code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; /** {@collect.stats} * <P>A thin wrapper around the <code>java.util.Date</code> class that allows the JDBC * API to identify this as an SQL <code>TIME</code> value. The <code>Time</code> * class adds formatting and * parsing operations to support the JDBC escape syntax for time * values. * <p>The date components should be set to the "zero epoch" * value of January 1, 1970 and should not be accessed. */ public class Time extends java.util.Date { /** {@collect.stats} * Constructs a <code>Time</code> object initialized with the * given values for the hour, minute, and second. * The driver sets the date components to January 1, 1970. * Any method that attempts to access the date components of a * <code>Time</code> object will throw a * <code>java.lang.IllegalArgumentException</code>. * <P> * The result is undefined if a given argument is out of bounds. * * @param hour 0 to 23 * @param minute 0 to 59 * @param second 0 to 59 * * @deprecated Use the constructor that takes a milliseconds value * in place of this constructor */ @Deprecated public Time(int hour, int minute, int second) { super(70, 0, 1, hour, minute, second); } /** {@collect.stats} * Constructs a <code>Time</code> object using a milliseconds time value. * * @param time milliseconds since January 1, 1970, 00:00:00 GMT; * a negative number is milliseconds before * January 1, 1970, 00:00:00 GMT */ public Time(long time) { super(time); } /** {@collect.stats} * Sets a <code>Time</code> object using a milliseconds time value. * * @param time milliseconds since January 1, 1970, 00:00:00 GMT; * a negative number is milliseconds before * January 1, 1970, 00:00:00 GMT */ public void setTime(long time) { super.setTime(time); } /** {@collect.stats} * Converts a string in JDBC time escape format to a <code>Time</code> value. * * @param s time in format "hh:mm:ss" * @return a corresponding <code>Time</code> object */ public static Time valueOf(String s) { int hour; int minute; int second; int firstColon; int secondColon; if (s == null) throw new java.lang.IllegalArgumentException(); firstColon = s.indexOf(':'); secondColon = s.indexOf(':', firstColon+1); if ((firstColon > 0) & (secondColon > 0) & (secondColon < s.length()-1)) { hour = Integer.parseInt(s.substring(0, firstColon)); minute = Integer.parseInt(s.substring(firstColon+1, secondColon)); second = Integer.parseInt(s.substring(secondColon+1)); } else { throw new java.lang.IllegalArgumentException(); } return new Time(hour, minute, second); } /** {@collect.stats} * Formats a time in JDBC time escape format. * * @return a <code>String</code> in hh:mm:ss format */ public String toString () { int hour = super.getHours(); int minute = super.getMinutes(); int second = super.getSeconds(); String hourString; String minuteString; String secondString; if (hour < 10) { hourString = "0" + hour; } else { hourString = Integer.toString(hour); } if (minute < 10) { minuteString = "0" + minute; } else { minuteString = Integer.toString(minute); } if (second < 10) { secondString = "0" + second; } else { secondString = Integer.toString(second); } return (hourString + ":" + minuteString + ":" + secondString); } // Override all the date operations inherited from java.util.Date; /** {@collect.stats} * This method is deprecated and should not be used because SQL <code>TIME</code> * values do not have a year component. * * @deprecated * @exception java.lang.IllegalArgumentException if this * method is invoked * @see #setYear */ @Deprecated public int getYear() { throw new java.lang.IllegalArgumentException(); } /** {@collect.stats} * This method is deprecated and should not be used because SQL <code>TIME</code> * values do not have a month component. * * @deprecated * @exception java.lang.IllegalArgumentException if this * method is invoked * @see #setMonth */ @Deprecated public int getMonth() { throw new java.lang.IllegalArgumentException(); } /** {@collect.stats} * This method is deprecated and should not be used because SQL <code>TIME</code> * values do not have a day component. * * @deprecated * @exception java.lang.IllegalArgumentException if this * method is invoked */ @Deprecated public int getDay() { throw new java.lang.IllegalArgumentException(); } /** {@collect.stats} * This method is deprecated and should not be used because SQL <code>TIME</code> * values do not have a date component. * * @deprecated * @exception java.lang.IllegalArgumentException if this * method is invoked * @see #setDate */ @Deprecated public int getDate() { throw new java.lang.IllegalArgumentException(); } /** {@collect.stats} * This method is deprecated and should not be used because SQL <code>TIME</code> * values do not have a year component. * * @deprecated * @exception java.lang.IllegalArgumentException if this * method is invoked * @see #getYear */ @Deprecated public void setYear(int i) { throw new java.lang.IllegalArgumentException(); } /** {@collect.stats} * This method is deprecated and should not be used because SQL <code>TIME</code> * values do not have a month component. * * @deprecated * @exception java.lang.IllegalArgumentException if this * method is invoked * @see #getMonth */ @Deprecated public void setMonth(int i) { throw new java.lang.IllegalArgumentException(); } /** {@collect.stats} * This method is deprecated and should not be used because SQL <code>TIME</code> * values do not have a date component. * * @deprecated * @exception java.lang.IllegalArgumentException if this * method is invoked * @see #getDate */ @Deprecated public void setDate(int i) { throw new java.lang.IllegalArgumentException(); } /** {@collect.stats} * Private serial version unique ID to ensure serialization * compatibility. */ static final long serialVersionUID = 8397324403548013681L; }
Java
/* * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; /** {@collect.stats} * An input stream that contains a stream of values representing an * instance of an SQL structured type or an SQL distinct type. * This interface, used only for custom mapping, is used by the driver * behind the scenes, and a programmer never directly invokes * <code>SQLInput</code> methods. The <i>reader</i> methods * (<code>readLong</code>, <code>readBytes</code>, and so on) * provide a way for an implementation of the <code>SQLData</code> * interface to read the values in an <code>SQLInput</code> object. * And as described in <code>SQLData</code>, calls to reader methods must * be made in the order that their corresponding attributes appear in the * SQL definition of the type. * The method <code>wasNull</code> is used to determine whether * the last value read was SQL <code>NULL</code>. * <P>When the method <code>getObject</code> is called with an * object of a class implementing the interface <code>SQLData</code>, * the JDBC driver calls the method <code>SQLData.getSQLType</code> * to determine the SQL type of the user-defined type (UDT) * being custom mapped. The driver * creates an instance of <code>SQLInput</code>, populating it with the * attributes of the UDT. The driver then passes the input * stream to the method <code>SQLData.readSQL</code>, which in turn * calls the <code>SQLInput</code> reader methods * in its implementation for reading the * attributes from the input stream. * @since 1.2 */ public interface SQLInput { //================================================================ // Methods for reading attributes from the stream of SQL data. // These methods correspond to the column-accessor methods of // java.sql.ResultSet. //================================================================ /** {@collect.stats} * Reads the next attribute in the stream and returns it as a <code>String</code> * in the Java programming language. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>null</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ String readString() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as a <code>boolean</code> * in the Java programming language. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>false</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ boolean readBoolean() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as a <code>byte</code> * in the Java programming language. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>0</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ byte readByte() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as a <code>short</code> * in the Java programming language. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>0</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ short readShort() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as an <code>int</code> * in the Java programming language. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>0</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ int readInt() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as a <code>long</code> * in the Java programming language. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>0</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ long readLong() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as a <code>float</code> * in the Java programming language. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>0</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ float readFloat() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as a <code>double</code> * in the Java programming language. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>0</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ double readDouble() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as a <code>java.math.BigDecimal</code> * object in the Java programming language. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>null</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ java.math.BigDecimal readBigDecimal() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as an array of bytes * in the Java programming language. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>null</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ byte[] readBytes() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as a <code>java.sql.Date</code> object. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>null</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ java.sql.Date readDate() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as a <code>java.sql.Time</code> object. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>null</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ java.sql.Time readTime() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as a <code>java.sql.Timestamp</code> object. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>null</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ java.sql.Timestamp readTimestamp() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as a stream of Unicode characters. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>null</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ java.io.Reader readCharacterStream() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as a stream of ASCII characters. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>null</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ java.io.InputStream readAsciiStream() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as a stream of uninterpreted * bytes. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>null</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ java.io.InputStream readBinaryStream() throws SQLException; //================================================================ // Methods for reading items of SQL user-defined types from the stream. //================================================================ /** {@collect.stats} * Reads the datum at the head of the stream and returns it as an * <code>Object</code> in the Java programming language. The * actual type of the object returned is determined by the default type * mapping, and any customizations present in this stream's type map. * * <P>A type map is registered with the stream by the JDBC driver before the * stream is passed to the application. * * <P>When the datum at the head of the stream is an SQL <code>NULL</code>, * the method returns <code>null</code>. If the datum is an SQL structured or distinct * type, it determines the SQL type of the datum at the head of the stream. * If the stream's type map has an entry for that SQL type, the driver * constructs an object of the appropriate class and calls the method * <code>SQLData.readSQL</code> on that object, which reads additional data from the * stream, using the protocol described for that method. * * @return the datum at the head of the stream as an <code>Object</code> in the * Java programming language;<code>null</code> if the datum is SQL <code>NULL</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ Object readObject() throws SQLException; /** {@collect.stats} * Reads an SQL <code>REF</code> value from the stream and returns it as a * <code>Ref</code> object in the Java programming language. * * @return a <code>Ref</code> object representing the SQL <code>REF</code> value * at the head of the stream; <code>null</code> if the value read is * SQL <code>NULL</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ Ref readRef() throws SQLException; /** {@collect.stats} * Reads an SQL <code>BLOB</code> value from the stream and returns it as a * <code>Blob</code> object in the Java programming language. * * @return a <code>Blob</code> object representing data of the SQL <code>BLOB</code> value * at the head of the stream; <code>null</code> if the value read is * SQL <code>NULL</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ Blob readBlob() throws SQLException; /** {@collect.stats} * Reads an SQL <code>CLOB</code> value from the stream and returns it as a * <code>Clob</code> object in the Java programming language. * * @return a <code>Clob</code> object representing data of the SQL <code>CLOB</code> value * at the head of the stream; <code>null</code> if the value read is * SQL <code>NULL</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ Clob readClob() throws SQLException; /** {@collect.stats} * Reads an SQL <code>ARRAY</code> value from the stream and returns it as an * <code>Array</code> object in the Java programming language. * * @return an <code>Array</code> object representing data of the SQL * <code>ARRAY</code> value at the head of the stream; <code>null</code> * if the value read is SQL <code>NULL</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ Array readArray() throws SQLException; /** {@collect.stats} * Retrieves whether the last value read was SQL <code>NULL</code>. * * @return <code>true</code> if the most recently read SQL value was SQL * <code>NULL</code>; <code>false</code> otherwise * @exception SQLException if a database access error occurs * * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ boolean wasNull() throws SQLException; //---------------------------- JDBC 3.0 ------------------------- /** {@collect.stats} * Reads an SQL <code>DATALINK</code> value from the stream and returns it as a * <code>java.net.URL</code> object in the Java programming language. * * @return a <code>java.net.URL</code> object. * @exception SQLException if a database access error occurs, * or if a URL is malformed * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.4 */ java.net.URL readURL() throws SQLException; //---------------------------- JDBC 4.0 ------------------------- /** {@collect.stats} * Reads an SQL <code>NCLOB</code> value from the stream and returns it as a * <code>NClob</code> object in the Java programming language. * * @return a <code>NClob</code> object representing data of the SQL <code>NCLOB</code> value * at the head of the stream; <code>null</code> if the value read is * SQL <code>NULL</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.6 */ NClob readNClob() throws SQLException; /** {@collect.stats} * Reads the next attribute in the stream and returns it as a <code>String</code> * in the Java programming language. It is intended for use when * accessing <code>NCHAR</code>,<code>NVARCHAR</code> * and <code>LONGNVARCHAR</code> columns. * * @return the attribute; if the value is SQL <code>NULL</code>, returns <code>null</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.6 */ String readNString() throws SQLException; /** {@collect.stats} * Reads an SQL <code>XML</code> value from the stream and returns it as a * <code>SQLXML</code> object in the Java programming language. * * @return a <code>SQLXML</code> object representing data of the SQL <code>XML</code> value * at the head of the stream; <code>null</code> if the value read is * SQL <code>NULL</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.6 */ SQLXML readSQLXML() throws SQLException; /** {@collect.stats} * Reads an SQL <code>ROWID</code> value from the stream and returns it as a * <code>RowId</code> object in the Java programming language. * * @return a <code>RowId</code> object representing data of the SQL <code>ROWID</code> value * at the head of the stream; <code>null</code> if the value read is * SQL <code>NULL</code> * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.6 */ RowId readRowId() throws SQLException; }
Java
/* * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; /** {@collect.stats} * The subclass of {@link SQLException} thrown when an error * occurs during a batch update operation. In addition to the * information provided by {@link SQLException}, a * <code>BatchUpdateException</code> provides the update * counts for all commands that were executed successfully during the * batch update, that is, all commands that were executed before the error * occurred. The order of elements in an array of update counts * corresponds to the order in which commands were added to the batch. * <P> * After a command in a batch update fails to execute properly * and a <code>BatchUpdateException</code> is thrown, the driver * may or may not continue to process the remaining commands in * the batch. If the driver continues processing after a failure, * the array returned by the method * <code>BatchUpdateException.getUpdateCounts</code> will have * an element for every command in the batch rather than only * elements for the commands that executed successfully before * the error. In the case where the driver continues processing * commands, the array element for any command * that failed is <code>Statement.EXECUTE_FAILED</code>. * <P> * @since 1.2 */ public class BatchUpdateException extends SQLException { /** {@collect.stats} * Constructs a <code>BatchUpdateException</code> object initialized with a given * <code>reason</code>, <code>SQLState</code>, <code>vendorCode</code> and * <code>updateCounts</code>. * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * * @param reason a description of the error * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param vendorCode an exception code used by a particular * database vendor * @param updateCounts an array of <code>int</code>, with each element * indicating the update count, <code>Statement.SUCCESS_NO_INFO</code> or * <code>Statement.EXECUTE_FAILED</code> for each SQL command in * the batch for JDBC drivers that continue processing * after a command failure; an update count or * <code>Statement.SUCCESS_NO_INFO</code> for each SQL command in the batch * prior to the failure for JDBC drivers that stop processing after a command * failure * @since 1.2 */ public BatchUpdateException( String reason, String SQLState, int vendorCode, int[] updateCounts ) { super(reason, SQLState, vendorCode); this.updateCounts = updateCounts; } /** {@collect.stats} * Constructs a <code>BatchUpdateException</code> object initialized with a given * <code>reason</code>, <code>SQLState</code> and * <code>updateCounts</code>. * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. The vendor code * is intialized to 0. * <p> * * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param updateCounts an array of <code>int</code>, with each element * indicating the update count, <code>Statement.SUCCESS_NO_INFO</code> or * <code>Statement.EXECUTE_FAILED</code> for each SQL command in * the batch for JDBC drivers that continue processing * after a command failure; an update count or * <code>Statement.SUCCESS_NO_INFO</code> for each SQL command in the batch * prior to the failure for JDBC drivers that stop processing after a command * failure * @since 1.2 */ public BatchUpdateException(String reason, String SQLState, int[] updateCounts) { super(reason, SQLState); this.updateCounts = updateCounts; } /** {@collect.stats} * Constructs a <code>BatchUpdateException</code> object initialized with a given * <code>reason</code> and <code>updateCounts</code>. * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. The * <code>SQLState</code> is initialized to <code>null</code> * and the vender code is initialized to 0. * <p> * * * @param reason a description of the exception * @param updateCounts an array of <code>int</code>, with each element * indicating the update count, <code>Statement.SUCCESS_NO_INFO</code> or * <code>Statement.EXECUTE_FAILED</code> for each SQL command in * the batch for JDBC drivers that continue processing * after a command failure; an update count or * <code>Statement.SUCCESS_NO_INFO</code> for each SQL command in the batch * prior to the failure for JDBC drivers that stop processing after a command * failure * @since 1.2 */ public BatchUpdateException(String reason, int[] updateCounts) { super(reason); this.updateCounts = updateCounts; } /** {@collect.stats} * Constructs a <code>BatchUpdateException</code> object initialized with a given * <code>updateCounts</code>. * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. The <code>reason</code> * and <code>SQLState</code> are initialized to null and the vendor code * is initialized to 0. * <p> * * @param updateCounts an array of <code>int</code>, with each element * indicating the update count, <code>Statement.SUCCESS_NO_INFO</code> or * <code>Statement.EXECUTE_FAILED</code> for each SQL command in * the batch for JDBC drivers that continue processing * after a command failure; an update count or * <code>Statement.SUCCESS_NO_INFO</code> for each SQL command in the batch * prior to the failure for JDBC drivers that stop processing after a command * failure * @since 1.2 */ public BatchUpdateException(int[] updateCounts) { super(); this.updateCounts = updateCounts; } /** {@collect.stats} * Constructs a <code>BatchUpdateException</code> object. * The <code>reason</code>, <code>SQLState</code> and <code>updateCounts</code> * are initialized to <code>null</code> and the vendor code is initialized to 0. * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * * @since 1.2 */ public BatchUpdateException() { super(); this.updateCounts = null; } /** {@collect.stats} * Constructs a <code>BatchUpdateException</code> object initialized with * a given <code>cause</code>. * The <code>SQLState</code> and <code>updateCounts</code> * are initialized * to <code>null</code> and the vendor code is initialized to 0. * The <code>reason</code> is initialized to <code>null</code> if * <code>cause==null</code> or to <code>cause.toString()</code> if * <code>cause!=null</code>. * @param cause the underlying reason for this <code>SQLException</code> * (which is saved for later retrieval by the <code>getCause()</code> method); * may be null indicating the cause is non-existent or unknown. * @since 1.6 */ public BatchUpdateException(Throwable cause) { super(cause); this.updateCounts = null; } /** {@collect.stats} * Constructs a <code>BatchUpdateException</code> object initialized with a * given <code>cause</code> and <code>updateCounts</code>. * The <code>SQLState</code> is initialized * to <code>null</code> and the vendor code is initialized to 0. * The <code>reason</code> is initialized to <code>null</code> if * <code>cause==null</code> or to <code>cause.toString()</code> if * <code>cause!=null</code>. * * @param updateCounts an array of <code>int</code>, with each element * indicating the update count, <code>Statement.SUCCESS_NO_INFO</code> or * <code>Statement.EXECUTE_FAILED</code> for each SQL command in * the batch for JDBC drivers that continue processing * after a command failure; an update count or * <code>Statement.SUCCESS_NO_INFO</code> for each SQL command in the batch * prior to the failure for JDBC drivers that stop processing after a command * failure * @param cause the underlying reason for this <code>SQLException</code> * (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public BatchUpdateException(int []updateCounts , Throwable cause) { super(cause); this.updateCounts = updateCounts; } /** {@collect.stats} * Constructs a <code>BatchUpdateException</code> object initialized with * a given <code>reason</code>, <code>cause</code> * and <code>updateCounts</code>. The <code>SQLState</code> is initialized * to <code>null</code> and the vendor code is initialized to 0. * * @param reason a description of the exception * @param updateCounts an array of <code>int</code>, with each element *indicating the update count, <code>Statement.SUCCESS_NO_INFO</code> or * <code>Statement.EXECUTE_FAILED</code> for each SQL command in * the batch for JDBC drivers that continue processing * after a command failure; an update count or * <code>Statement.SUCCESS_NO_INFO</code> for each SQL command in the batch * prior to the failure for JDBC drivers that stop processing after a command * failure * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval by the <code>getCause()</code> method); * may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public BatchUpdateException(String reason, int []updateCounts, Throwable cause) { super(reason,cause); this.updateCounts = updateCounts; } /** {@collect.stats} * Constructs a <code>BatchUpdateException</code> object initialized with * a given <code>reason</code>, <code>SQLState</code>,<code>cause</code>, and * <code>updateCounts</code>. The vendor code is initialized to 0. * * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param updateCounts an array of <code>int</code>, with each element * indicating the update count, <code>Statement.SUCCESS_NO_INFO</code> or * <code>Statement.EXECUTE_FAILED</code> for each SQL command in * the batch for JDBC drivers that continue processing * after a command failure; an update count or * <code>Statement.SUCCESS_NO_INFO</code> for each SQL command in the batch * prior to the failure for JDBC drivers that stop processing after a command * failure * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval by the <code>getCause()</code> method); * may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public BatchUpdateException(String reason, String SQLState, int []updateCounts, Throwable cause) { super(reason,SQLState,cause); this.updateCounts = updateCounts; } /** {@collect.stats} * Constructs a <code>BatchUpdateException</code> object initialized with * a given <code>reason</code>, <code>SQLState</code>, <code>vendorCode</code> * <code>cause</code> and <code>updateCounts</code>. * * @param reason a description of the error * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param vendorCode an exception code used by a particular * database vendor * @param updateCounts an array of <code>int</code>, with each element *indicating the update count, <code>Statement.SUCCESS_NO_INFO</code> or * <code>Statement.EXECUTE_FAILED</code> for each SQL command in * the batch for JDBC drivers that continue processing * after a command failure; an update count or * <code>Statement.SUCCESS_NO_INFO</code> for each SQL command in the batch * prior to the failure for JDBC drivers that stop processing after a command * failure * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval by the <code>getCause()</code> method); * may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public BatchUpdateException(String reason, String SQLState, int vendorCode, int []updateCounts,Throwable cause) { super(reason,SQLState,vendorCode,cause); this.updateCounts = updateCounts; } /** {@collect.stats} * Retrieves the update count for each update statement in the batch * update that executed successfully before this exception occurred. * A driver that implements batch updates may or may not continue to * process the remaining commands in a batch when one of the commands * fails to execute properly. If the driver continues processing commands, * the array returned by this method will have as many elements as * there are commands in the batch; otherwise, it will contain an * update count for each command that executed successfully before * the <code>BatchUpdateException</code> was thrown. *<P> * The possible return values for this method were modified for * the Java 2 SDK, Standard Edition, version 1.3. This was done to * accommodate the new option of continuing to process commands * in a batch update after a <code>BatchUpdateException</code> object * has been thrown. * * @return an array of <code>int</code> containing the update counts * for the updates that were executed successfully before this error * occurred. Or, if the driver continues to process commands after an * error, one of the following for every command in the batch: * <OL> * <LI>an update count * <LI><code>Statement.SUCCESS_NO_INFO</code> to indicate that the command * executed successfully but the number of rows affected is unknown * <LI><code>Statement.EXECUTE_FAILED</code> to indicate that the command * failed to execute successfully * </OL> * @since 1.3 */ public int[] getUpdateCounts() { return updateCounts; } /** {@collect.stats} * The array that describes the outcome of a batch execution. * @serial * @since 1.2 */ private int[] updateCounts; private static final long serialVersionUID = 5977529877145521757L; }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; /** {@collect.stats} * <P>An exception that provides information on a database access * error or other errors. * * <P>Each <code>SQLException</code> provides several kinds of information: * <UL> * <LI> a string describing the error. This is used as the Java Exception * message, available via the method <code>getMesasge</code>. * <LI> a "SQLstate" string, which follows either the XOPEN SQLstate conventions * or the SQL:2003 conventions. * The values of the SQLState string are described in the appropriate spec. * The <code>DatabaseMetaData</code> method <code>getSQLStateType</code> * can be used to discover whether the driver returns the XOPEN type or * the SQL:2003 type. * <LI> an integer error code that is specific to each vendor. Normally this will * be the actual error code returned by the underlying database. * <LI> a chain to a next Exception. This can be used to provide additional * error information. * <LI> the causal relationship, if any for this <code>SQLException</code>. * </UL> */ public class SQLException extends java.lang.Exception implements Iterable<Throwable> { /** {@collect.stats} * Constructs a <code>SQLException</code> object with a given * <code>reason</code>, <code>SQLState</code> and * <code>vendorCode</code>. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param vendorCode a database vendor-specific exception code */ public SQLException(String reason, String SQLState, int vendorCode) { super(reason); this.SQLState = SQLState; this.vendorCode = vendorCode; if (!(this instanceof SQLWarning)) { if (DriverManager.getLogWriter() != null) { DriverManager.println("SQLState(" + SQLState + ") vendor code(" + vendorCode + ")"); printStackTrace(DriverManager.getLogWriter()); } } } /** {@collect.stats} * Constructs a <code>SQLException</code> object with a given * <code>reason</code> and <code>SQLState</code>. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. The vendor code * is initialized to 0. * <p> * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception */ public SQLException(String reason, String SQLState) { super(reason); this.SQLState = SQLState; this.vendorCode = 0; if (!(this instanceof SQLWarning)) { if (DriverManager.getLogWriter() != null) { printStackTrace(DriverManager.getLogWriter()); DriverManager.println("SQLException: SQLState(" + SQLState + ")"); } } } /** {@collect.stats} * Constructs a <code>SQLException</code> object with a given * <code>reason</code>. The <code>SQLState</code> is initialized to * <code>null</code> and the vender code is initialized to 0. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * @param reason a description of the exception */ public SQLException(String reason) { super(reason); this.SQLState = null; this.vendorCode = 0; if (!(this instanceof SQLWarning)) { if (DriverManager.getLogWriter() != null) { printStackTrace(DriverManager.getLogWriter()); } } } /** {@collect.stats} * Constructs a <code>SQLException</code> object. * The <code>reason</code>, <code>SQLState</code> are initialized * to <code>null</code> and the vendor code is initialized to 0. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> */ public SQLException() { super(); this.SQLState = null; this.vendorCode = 0; if (!(this instanceof SQLWarning)) { if (DriverManager.getLogWriter() != null) { printStackTrace(DriverManager.getLogWriter()); } } } /** {@collect.stats} * Constructs a <code>SQLException</code> object with a given * <code>cause</code>. * The <code>SQLState</code> is initialized * to <code>null</code> and the vendor code is initialized to 0. * The <code>reason</code> is initialized to <code>null</code> if * <code>cause==null</code> or to <code>cause.toString()</code> if * <code>cause!=null</code>. * <p> * @param cause the underlying reason for this <code>SQLException</code> * (which is saved for later retrieval by the <code>getCause()</code> method); * may be null indicating the cause is non-existent or unknown. * @since 1.6 */ public SQLException(Throwable cause) { super(cause); if (!(this instanceof SQLWarning)) { if (DriverManager.getLogWriter() != null) { printStackTrace(DriverManager.getLogWriter()); } } } /** {@collect.stats} * Constructs a <code>SQLException</code> object with a given * <code>reason</code> and <code>cause</code>. * The <code>SQLState</code> is initialized to <code>null</code> * and the vendor code is initialized to 0. * <p> * @param reason a description of the exception. * @param cause the underlying reason for this <code>SQLException</code> * (which is saved for later retrieval by the <code>getCause()</code> method); * may be null indicating the cause is non-existent or unknown. * @since 1.6 */ public SQLException(String reason, Throwable cause) { super(reason,cause); if (!(this instanceof SQLWarning)) { if (DriverManager.getLogWriter() != null) { printStackTrace(DriverManager.getLogWriter()); } } } /** {@collect.stats} * Constructs a <code>SQLException</code> object with a given * <code>reason</code>, <code>SQLState</code> and <code>cause</code>. * The vendor code is initialized to 0. * <p> * @param reason a description of the exception. * @param sqlState an XOPEN or SQL:2003 code identifying the exception * @param cause the underlying reason for this <code>SQLException</code> * (which is saved for later retrieval by the * <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLException(String reason, String sqlState, Throwable cause) { super(reason,cause); this.SQLState = sqlState; this.vendorCode = 0; if (!(this instanceof SQLWarning)) { if (DriverManager.getLogWriter() != null) { printStackTrace(DriverManager.getLogWriter()); DriverManager.println("SQLState(" + SQLState + ")"); } } } /** {@collect.stats} * Constructs a <code>SQLException</code> object with a given * <code>reason</code>, <code>SQLState</code>, <code>vendorCode</code> * and <code>cause</code>. * <p> * @param reason a description of the exception * @param sqlState an XOPEN or SQL:2003 code identifying the exception * @param vendorCode a database vendor-specific exception code * @param cause the underlying reason for this <code>SQLException</code> * (which is saved for later retrieval by the <code>getCause()</code> method); * may be null indicating the cause is non-existent or unknown. * @since 1.6 */ public SQLException(String reason, String sqlState, int vendorCode, Throwable cause) { super(reason,cause); this.SQLState = sqlState; this.vendorCode = vendorCode; if (!(this instanceof SQLWarning)) { if (DriverManager.getLogWriter() != null) { DriverManager.println("SQLState(" + SQLState + ") vendor code(" + vendorCode + ")"); printStackTrace(DriverManager.getLogWriter()); } } } /** {@collect.stats} * Retrieves the SQLState for this <code>SQLException</code> object. * * @return the SQLState value */ public String getSQLState() { return (SQLState); } /** {@collect.stats} * Retrieves the vendor-specific exception code * for this <code>SQLException</code> object. * * @return the vendor's error code */ public int getErrorCode() { return (vendorCode); } /** {@collect.stats} * Retrieves the exception chained to this * <code>SQLException</code> object by setNextException(SQLException ex). * * @return the next <code>SQLException</code> object in the chain; * <code>null</code> if there are none * @see #setNextException */ public SQLException getNextException() { return (next); } /** {@collect.stats} * Adds an <code>SQLException</code> object to the end of the chain. * * @param ex the new exception that will be added to the end of * the <code>SQLException</code> chain * @see #getNextException */ public void setNextException(SQLException ex) { SQLException current = this; for(;;) { SQLException next=current.next; if (next != null) { current = next; continue; } if (nextUpdater.compareAndSet(current,null,ex)) { return; } current=current.next; } } /** {@collect.stats} * Returns an iterator over the chained SQLExceptions. The iterator will * be used to iterate over each SQLException and its underlying cause * (if any). * * @return an iterator over the chained SQLExceptions and causes in the proper * order * * @since 1.6 */ public Iterator<Throwable> iterator() { return new Iterator<Throwable>() { SQLException firstException = SQLException.this; SQLException nextException = firstException.getNextException(); Throwable cause = firstException.getCause(); public boolean hasNext() { if(firstException != null || nextException != null || cause != null) return true; return false; } public Throwable next() { Throwable throwable = null; if(firstException != null){ throwable = firstException; firstException = null; } else if(cause != null){ throwable = cause; cause = cause.getCause(); } else if(nextException != null){ throwable = nextException; cause = nextException.getCause(); nextException = nextException.getNextException(); } else throw new NoSuchElementException(); return throwable; } public void remove() { throw new UnsupportedOperationException(); } }; } /** {@collect.stats} * @serial */ private String SQLState; /** {@collect.stats} * @serial */ private int vendorCode; /** {@collect.stats} * @serial */ private volatile SQLException next; private static final AtomicReferenceFieldUpdater<SQLException,SQLException> nextUpdater = AtomicReferenceFieldUpdater.newUpdater(SQLException.class,SQLException.class,"next"); private static final long serialVersionUID = 2135244094396331484L; }
Java
/* * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; import java.util.*; /** {@collect.stats} * Enumeration for status of the reason that a property could not be set * via a call to <code>Connection.setClientInfo</code> * @since 1.6 */ public enum ClientInfoStatus { /** {@collect.stats} * The client info property could not be set for some unknown reason * @since 1.6 */ REASON_UNKNOWN, /** {@collect.stats} * The client info property name specified was not a recognized property * name. * @since 1.6 */ REASON_UNKNOWN_PROPERTY, /** {@collect.stats} * The value specified for the client info property was not valid. * @since 1.6 */ REASON_VALUE_INVALID, /** {@collect.stats} * The value specified for the client info property was too large. * @since 1.6 */ REASON_VALUE_TRUNCATED }
Java
/* * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; /** {@collect.stats} * The representation of a savepoint, which is a point within * the current transaction that can be referenced from the * <code>Connection.rollback</code> method. When a transaction * is rolled back to a savepoint all changes made after that * savepoint are undone. * <p> * Savepoints can be either named or unnamed. Unnamed savepoints * are identified by an ID generated by the underlying data source. * * @since 1.4 */ public interface Savepoint { /** {@collect.stats} * Retrieves the generated ID for the savepoint that this * <code>Savepoint</code> object represents. * @return the numeric ID of this savepoint * @exception SQLException if this is a named savepoint * @since 1.4 */ int getSavepointId() throws SQLException; /** {@collect.stats} * Retrieves the name of the savepoint that this <code>Savepoint</code> * object represents. * @return the name of this savepoint * @exception SQLException if this is an un-named savepoint * @since 1.4 */ String getSavepointName() throws SQLException; }
Java
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; /** {@collect.stats} * The subclass of {@link SQLException} thrown when the SQLState class value is '<i>23</i>'. This indicates that an integrity * constraint (foreign key, primary key or unique key) has been violated. * * @since 1.6 */ public class SQLIntegrityConstraintViolationException extends SQLNonTransientException { /** {@collect.stats} * Constructs a <code>SQLIntegrityConstraintViolationException</code> object. * The <code>reason</code>, <code>SQLState</code> are initialized * to <code>null</code> and the vendor code is initialized to 0. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * @since 1.6 */ public SQLIntegrityConstraintViolationException() { super(); } /** {@collect.stats} * Constructs a <code>SQLIntegrityConstraintViolationException</code> * with a given <code>reason</code>. The <code>SQLState</code> * is initialized to <code>null</code> and the vender code is initialized * to 0. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * @param reason a description of the exception * @since 1.6 */ public SQLIntegrityConstraintViolationException(String reason) { super(reason); } /** {@collect.stats} * Constructs a <code>SQLIntegrityConstraintViolationException</code> * object with a given <code>reason</code> and <code>SQLState</code>. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. The vendor code * is initialized to 0. * <p> * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @since 1.6 */ public SQLIntegrityConstraintViolationException(String reason, String SQLState) { super(reason,SQLState); } /** {@collect.stats} * Constructs a <code>SQLIntegrityConstraintViolationException</code> object * with a given <code>reason</code>, <code>SQLState</code> and * <code>vendorCode</code>. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param vendorCode a database vendor specific exception code * @since 1.6 */ public SQLIntegrityConstraintViolationException(String reason, String SQLState, int vendorCode) { super(reason,SQLState,vendorCode); } /** {@collect.stats} * Constructs an <code>SQLIntegrityConstraintViolationException</code> object with * a given <code>cause</code>. * The <code>SQLState</code> is initialized * to <code>null</code> and the vendor code is initialized to 0. * The <code>reason</code> is initialized to <code>null</code> if * <code>cause==null</code> or to <code>cause.toString()</code> if * <code>cause!=null</code>. * <p> * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLIntegrityConstraintViolationException(Throwable cause) { super(cause); } /** {@collect.stats} * Constructs a <code>SQLIntegrityConstraintViolationException</code> object * with a given * <code>reason</code> and <code>cause</code>. * The <code>SQLState</code> is initialized to <code>null</code> * and the vendor code is initialized to 0. * <p> * @param reason a description of the exception. * @param cause the (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLIntegrityConstraintViolationException(String reason, Throwable cause) { super(reason,cause); } /** {@collect.stats} * Constructs a <code>SQLIntegrityConstraintViolationException</code> object * with a given * <code>reason</code>, <code>SQLState</code> and <code>cause</code>. * The vendor code is initialized to 0. * <p> * @param reason a description of the exception. * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLIntegrityConstraintViolationException(String reason, String SQLState, Throwable cause) { super(reason,SQLState, cause); } /** {@collect.stats} * Constructs a <code>SQLIntegrityConstraintViolationException</code> object * with a given * <code>reason</code>, <code>SQLState</code>, <code>vendorCode</code> * and <code>cause</code>. * <p> * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param vendorCode a database vendor-specific exception code * @param cause the (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLIntegrityConstraintViolationException(String reason, String SQLState, int vendorCode, Throwable cause) { super(reason,SQLState,vendorCode,cause); } private static final long serialVersionUID = 8033405298774849169L; }
Java
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; /** {@collect.stats} * The subclass of {@link SQLException} is thrown in situations where a * previoulsy failed operation might be able to succeed when the operation is * retried without any intervention by application-level functionality. *<p> * * @since 1.6 */ public class SQLTransientException extends java.sql.SQLException { /** {@collect.stats} * Constructs a <code>SQLTransientException</code> object. * The <code>reason</code>, <code>SQLState</code> are initialized * to <code>null</code> and the vendor code is initialized to 0. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * @since 1.6 */ public SQLTransientException() { super(); } /** {@collect.stats} * Constructs a <code>SQLTransientException</code> object * with a given <code>reason</code>. The <code>SQLState</code> * is initialized to <code>null</code> and the vender code is initialized * to 0. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * @param reason a description of the exception * @since 1.6 */ public SQLTransientException(String reason) { super(reason); } /** {@collect.stats} * Constructs a <code>SQLTransientException</code> object * with a given <code>reason</code> and <code>SQLState</code>. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. The vendor code * is initialized to 0. * <p> * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @since 1.6 */ public SQLTransientException(String reason, String SQLState) { super(reason,SQLState); } /** {@collect.stats} * Constructs a <code>SQLTransientException</code> object * with a given <code>reason</code>, <code>SQLState</code> and * <code>vendorCode</code>. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param vendorCode a database vendor specific exception code * @since 1.6 */ public SQLTransientException(String reason, String SQLState, int vendorCode) { super(reason,SQLState,vendorCode); } /** {@collect.stats} * Constructs a <code>SQLTransientException</code> object * with a given <code>cause</code>. * The <code>SQLState</code> is initialized * to <code>null</code> and the vendor code is initialized to 0. * The <code>reason</code> is initialized to <code>null</code> if * <code>cause==null</code> or to <code>cause.toString()</code> if * <code>cause!=null</code>. * <p> * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLTransientException(Throwable cause) { super(cause); } /** {@collect.stats} * Constructs a <code>SQLTransientException</code> object * with a given * <code>reason</code> and <code>cause</code>. * The <code>SQLState</code> is initialized to <code>null</code> * and the vendor code is initialized to 0. * <p> * @param reason a description of the exception. * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLTransientException(String reason, Throwable cause) { super(reason,cause); } /** {@collect.stats} * Constructs a <code>SQLTransientException</code> object * with a given * <code>reason</code>, <code>SQLState</code> and <code>cause</code>. * The vendor code is initialized to 0. * <p> * @param reason a description of the exception. * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLTransientException(String reason, String SQLState, Throwable cause) { super(reason,SQLState,cause); } /** {@collect.stats} * Constructs a <code>SQLTransientException</code> object * with a given * <code>reason</code>, <code>SQLState</code>, <code>vendorCode</code> * and <code>cause</code>. * <p> * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param vendorCode a database vendor-specific exception code * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLTransientException(String reason, String SQLState, int vendorCode, Throwable cause) { super(reason,SQLState,vendorCode,cause); } private static final long serialVersionUID = -9042733978262274539L; }
Java
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; /** {@collect.stats} * The subclass of {@link SQLException} thrown when the SQLState class value is '<i>28</i>'. This indicated that the * authorization credentials presented during connection establishment are not valid. * * @since 1.6 */ public class SQLInvalidAuthorizationSpecException extends SQLNonTransientException { /** {@collect.stats} * Constructs a <code>SQLInvalidAuthorizationSpecException</code> object. * The <code>reason</code>, <code>SQLState</code> are initialized * to <code>null</code> and the vendor code is initialized to 0. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * @since 1.6 */ public SQLInvalidAuthorizationSpecException() { super(); } /** {@collect.stats} * Constructs a <code>SQLInvalidAuthorizationSpecException</code> object * with a given <code>reason</code>. The <code>SQLState</code> * is initialized to <code>null</code> and the vender code is initialized * to 0. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * @param reason a description of the exception * @since 1.6 */ public SQLInvalidAuthorizationSpecException(String reason) { super(reason); } /** {@collect.stats} * Constructs a <code>SQLInvalidAuthorizationSpecException</code> object * with a given <code>reason</code> and <code>SQLState</code>. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. The vendor code * is initialized to 0. * <p> * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @since 1.6 */ public SQLInvalidAuthorizationSpecException(String reason, String SQLState) { super(reason,SQLState); } /** {@collect.stats} * Constructs a <code>SQLInvalidAuthorizationSpecException</code> object * with a given <code>reason</code>, <code>SQLState</code> and * <code>vendorCode</code>. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param vendorCode a database vendor specific exception code * @since 1.6 */ public SQLInvalidAuthorizationSpecException(String reason, String SQLState, int vendorCode) { super(reason,SQLState,vendorCode); } /** {@collect.stats} * Constructs a <code>SQLInvalidAuthorizationSpecException</code> object * with a given <code>cause</code>. * The <code>SQLState</code> is initialized * to <code>null</code> and the vendor code is initialized to 0. * The <code>reason</code> is initialized to <code>null</code> if * <code>cause==null</code> or to <code>cause.toString()</code> if * <code>cause!=null</code>. * <p> * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLInvalidAuthorizationSpecException(Throwable cause) { super(cause); } /** {@collect.stats} * Constructs a <code>SQLInvalidAuthorizationSpecException</code> object * with a given * <code>reason</code> and <code>cause</code>. * The <code>SQLState</code> is initialized to <code>null</code> * and the vendor code is initialized to 0. * <p> * @param reason a description of the exception. * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLInvalidAuthorizationSpecException(String reason, Throwable cause) { super(reason,cause); } /** {@collect.stats} * Constructs a <code>SQLInvalidAuthorizationSpecException</code> object * with a given * <code>reason</code>, <code>SQLState</code> and <code>cause</code>. * The vendor code is initialized to 0. * <p> * @param reason a description of the exception. * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLInvalidAuthorizationSpecException(String reason, String SQLState, Throwable cause) { super(reason,SQLState,cause); } /** {@collect.stats} * Constructs a <code>SQLInvalidAuthorizationSpecException</code> object * with a given * <code>reason</code>, <code>SQLState</code>, <code>vendorCode</code> * and <code>cause</code>. * <p> * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param vendorCode a database vendor-specific exception code * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLInvalidAuthorizationSpecException(String reason, String SQLState, int vendorCode, Throwable cause) { super(reason,SQLState,vendorCode,cause); } private static final long serialVersionUID = -64105250450891498L; }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; import java.util.Iterator; import java.sql.Driver; import java.util.ServiceLoader; import java.security.AccessController; import java.security.PrivilegedAction; /** {@collect.stats} * <P>The basic service for managing a set of JDBC drivers.<br> * <B>NOTE:</B> The {@link <code>DataSource</code>} interface, new in the * JDBC 2.0 API, provides another way to connect to a data source. * The use of a <code>DataSource</code> object is the preferred means of * connecting to a data source. * * <P>As part of its initialization, the <code>DriverManager</code> class will * attempt to load the driver classes referenced in the "jdbc.drivers" * system property. This allows a user to customize the JDBC Drivers * used by their applications. For example in your * ~/.hotjava/properties file you might specify: * <pre> * <CODE>jdbc.drivers=foo.bah.Driver:wombat.sql.Driver:bad.taste.ourDriver</CODE> * </pre> *<P> The <code>DriverManager</code> methods <code>getConnection</code> and * <code>getDrivers</code> have been enhanced to support the Java Standard Edition * <a href="../../../technotes/guides/jar/jar.html#Service%20Provider">Service Provider</a> mechanism. JDBC 4.0 Drivers must * include the file <code>META-INF/services/java.sql.Driver</code>. This file contains the name of the JDBC drivers * implementation of <code>java.sql.Driver</code>. For example, to load the <code>my.sql.Driver</code> class, * the <code>META-INF/services/java.sql.Driver</code> file would contain the entry: * <pre> * <code>my.sql.Driver</code> * </pre> * * <P>Applications no longer need to explictly load JDBC drivers using <code>Class.forName()</code>. Existing programs * which currently load JDBC drivers using <code>Class.forName()</code> will continue to work without * modification. * * <P>When the method <code>getConnection</code> is called, * the <code>DriverManager</code> will attempt to * locate a suitable driver from amongst those loaded at * initialization and those loaded explicitly using the same classloader * as the current applet or application. * * <P> * Starting with the Java 2 SDK, Standard Edition, version 1.3, a * logging stream can be set only if the proper * permission has been granted. Normally this will be done with * the tool PolicyTool, which can be used to grant <code>permission * java.sql.SQLPermission "setLog"</code>. * @see Driver * @see Connection */ public class DriverManager { /** {@collect.stats} * The <code>SQLPermission</code> constant that allows the * setting of the logging stream. * @since 1.3 */ final static SQLPermission SET_LOG_PERMISSION = new SQLPermission("setLog"); //--------------------------JDBC 2.0----------------------------- /** {@collect.stats} * Retrieves the log writer. * * The <code>getLogWriter</code> and <code>setLogWriter</code> * methods should be used instead * of the <code>get/setlogStream</code> methods, which are deprecated. * @return a <code>java.io.PrintWriter</code> object * @see #setLogWriter * @since 1.2 */ public static java.io.PrintWriter getLogWriter() { return logWriter; } /** {@collect.stats} * Sets the logging/tracing <code>PrintWriter</code> object * that is used by the <code>DriverManager</code> and all drivers. * <P> * There is a minor versioning problem created by the introduction * of the method <code>setLogWriter</code>. The * method <code>setLogWriter</code> cannot create a <code>PrintStream</code> object * that will be returned by <code>getLogStream</code>---the Java platform does * not provide a backward conversion. As a result, a new application * that uses <code>setLogWriter</code> and also uses a JDBC 1.0 driver that uses * <code>getLogStream</code> will likely not see debugging information written * by that driver. *<P> * Starting with the Java 2 SDK, Standard Edition, version 1.3 release, this method checks * to see that there is an <code>SQLPermission</code> object before setting * the logging stream. If a <code>SecurityManager</code> exists and its * <code>checkPermission</code> method denies setting the log writer, this * method throws a <code>java.lang.SecurityException</code>. * * @param out the new logging/tracing <code>PrintStream</code> object; * <code>null</code> to disable logging and tracing * @throws SecurityException * if a security manager exists and its * <code>checkPermission</code> method denies * setting the log writer * * @see SecurityManager#checkPermission * @see #getLogWriter * @since 1.2 */ public static void setLogWriter(java.io.PrintWriter out) { SecurityManager sec = System.getSecurityManager(); if (sec != null) { sec.checkPermission(SET_LOG_PERMISSION); } logStream = null; logWriter = out; } //--------------------------------------------------------------- /** {@collect.stats} * Attempts to establish a connection to the given database URL. * The <code>DriverManager</code> attempts to select an appropriate driver from * the set of registered JDBC drivers. * * @param url a database url of the form * <code> jdbc:<em>subprotocol</em>:<em>subname</em></code> * @param info a list of arbitrary string tag/value pairs as * connection arguments; normally at least a "user" and * "password" property should be included * @return a Connection to the URL * @exception SQLException if a database access error occurs */ public static Connection getConnection(String url, java.util.Properties info) throws SQLException { // Gets the classloader of the code that called this method, may // be null. ClassLoader callerCL = DriverManager.getCallerClassLoader(); return (getConnection(url, info, callerCL)); } /** {@collect.stats} * Attempts to establish a connection to the given database URL. * The <code>DriverManager</code> attempts to select an appropriate driver from * the set of registered JDBC drivers. * * @param url a database url of the form * <code>jdbc:<em>subprotocol</em>:<em>subname</em></code> * @param user the database user on whose behalf the connection is being * made * @param password the user's password * @return a connection to the URL * @exception SQLException if a database access error occurs */ public static Connection getConnection(String url, String user, String password) throws SQLException { java.util.Properties info = new java.util.Properties(); // Gets the classloader of the code that called this method, may // be null. ClassLoader callerCL = DriverManager.getCallerClassLoader(); if (user != null) { info.put("user", user); } if (password != null) { info.put("password", password); } return (getConnection(url, info, callerCL)); } /** {@collect.stats} * Attempts to establish a connection to the given database URL. * The <code>DriverManager</code> attempts to select an appropriate driver from * the set of registered JDBC drivers. * * @param url a database url of the form * <code> jdbc:<em>subprotocol</em>:<em>subname</em></code> * @return a connection to the URL * @exception SQLException if a database access error occurs */ public static Connection getConnection(String url) throws SQLException { java.util.Properties info = new java.util.Properties(); // Gets the classloader of the code that called this method, may // be null. ClassLoader callerCL = DriverManager.getCallerClassLoader(); return (getConnection(url, info, callerCL)); } /** {@collect.stats} * Attempts to locate a driver that understands the given URL. * The <code>DriverManager</code> attempts to select an appropriate driver from * the set of registered JDBC drivers. * * @param url a database URL of the form * <code>jdbc:<em>subprotocol</em>:<em>subname</em></code> * @return a <code>Driver</code> object representing a driver * that can connect to the given URL * @exception SQLException if a database access error occurs */ public static Driver getDriver(String url) throws SQLException { java.util.Vector drivers = null; println("DriverManager.getDriver(\"" + url + "\")"); if (!initialized) { initialize(); } synchronized (DriverManager.class){ // use the read copy of the drivers vector drivers = readDrivers; } // Gets the classloader of the code that called this method, may // be null. ClassLoader callerCL = DriverManager.getCallerClassLoader(); // Walk through the loaded drivers attempting to locate someone // who understands the given URL. for (int i = 0; i < drivers.size(); i++) { DriverInfo di = (DriverInfo)drivers.elementAt(i); // If the caller does not have permission to load the driver then // skip it. if ( getCallerClass(callerCL, di.driverClassName ) != di.driverClass ) { println(" skipping: " + di); continue; } try { println(" trying " + di); if (di.driver.acceptsURL(url)) { // Success! println("getDriver returning " + di); return (di.driver); } } catch (SQLException ex) { // Drop through and try the next driver. } } println("getDriver: no suitable driver"); throw new SQLException("No suitable driver", "08001"); } /** {@collect.stats} * Registers the given driver with the <code>DriverManager</code>. * A newly-loaded driver class should call * the method <code>registerDriver</code> to make itself * known to the <code>DriverManager</code>. * * @param driver the new JDBC Driver that is to be registered with the * <code>DriverManager</code> * @exception SQLException if a database access error occurs */ public static synchronized void registerDriver(java.sql.Driver driver) throws SQLException { if (!initialized) { initialize(); } DriverInfo di = new DriverInfo(); di.driver = driver; di.driverClass = driver.getClass(); di.driverClassName = di.driverClass.getName(); // Not Required -- drivers.addElement(di); writeDrivers.addElement(di); println("registerDriver: " + di); /* update the read copy of drivers vector */ readDrivers = (java.util.Vector) writeDrivers.clone(); } /** {@collect.stats} * Drops a driver from the <code>DriverManager</code>'s list. * Applets can only deregister drivers from their own classloaders. * * @param driver the JDBC Driver to drop * @exception SQLException if a database access error occurs */ public static synchronized void deregisterDriver(Driver driver) throws SQLException { // Gets the classloader of the code that called this method, // may be null. ClassLoader callerCL = DriverManager.getCallerClassLoader(); println("DriverManager.deregisterDriver: " + driver); // Walk through the loaded drivers. int i; DriverInfo di = null; for (i = 0; i < writeDrivers.size(); i++) { di = (DriverInfo)writeDrivers.elementAt(i); if (di.driver == driver) { break; } } // If we can't find the driver just return. if (i >= writeDrivers.size()) { println(" couldn't find driver to unload"); return; } // If the caller does not have permission to load the driver then // throw a security exception. if (getCallerClass(callerCL, di.driverClassName ) != di.driverClass ) { throw new SecurityException(); } // Remove the driver. Other entries in drivers get shuffled down. writeDrivers.removeElementAt(i); /* update the read copy of drivers vector */ readDrivers = (java.util.Vector) writeDrivers.clone(); } /** {@collect.stats} * Retrieves an Enumeration with all of the currently loaded JDBC drivers * to which the current caller has access. * * <P><B>Note:</B> The classname of a driver can be found using * <CODE>d.getClass().getName()</CODE> * * @return the list of JDBC Drivers loaded by the caller's class loader */ public static java.util.Enumeration<Driver> getDrivers() { java.util.Vector<Driver> result = new java.util.Vector<Driver>(); java.util.Vector drivers = null; if (!initialized) { initialize(); } synchronized (DriverManager.class){ // use the readcopy of drivers drivers = readDrivers; } // Gets the classloader of the code that called this method, may // be null. ClassLoader callerCL = DriverManager.getCallerClassLoader(); // Walk through the loaded drivers. for (int i = 0; i < drivers.size(); i++) { DriverInfo di = (DriverInfo)drivers.elementAt(i); // If the caller does not have permission to load the driver then // skip it. if ( getCallerClass(callerCL, di.driverClassName ) != di.driverClass ) { println(" skipping: " + di); continue; } result.addElement(di.driver); } return (result.elements()); } /** {@collect.stats} * Sets the maximum time in seconds that a driver will wait * while attempting to connect to a database. * * @param seconds the login time limit in seconds; zero means there is no limit * @see #getLoginTimeout */ public static void setLoginTimeout(int seconds) { loginTimeout = seconds; } /** {@collect.stats} * Gets the maximum time in seconds that a driver can wait * when attempting to log in to a database. * * @return the driver login time limit in seconds * @see #setLoginTimeout */ public static int getLoginTimeout() { return (loginTimeout); } /** {@collect.stats} * Sets the logging/tracing PrintStream that is used * by the <code>DriverManager</code> * and all drivers. *<P> * In the Java 2 SDK, Standard Edition, version 1.3 release, this method checks * to see that there is an <code>SQLPermission</code> object before setting * the logging stream. If a <code>SecurityManager</code> exists and its * <code>checkPermission</code> method denies setting the log writer, this * method throws a <code>java.lang.SecurityException</code>. * * @param out the new logging/tracing PrintStream; to disable, set to <code>null</code> * @deprecated * @throws SecurityException if a security manager exists and its * <code>checkPermission</code> method denies setting the log stream * * @see SecurityManager#checkPermission * @see #getLogStream */ public static void setLogStream(java.io.PrintStream out) { SecurityManager sec = System.getSecurityManager(); if (sec != null) { sec.checkPermission(SET_LOG_PERMISSION); } logStream = out; if ( out != null ) logWriter = new java.io.PrintWriter(out); else logWriter = null; } /** {@collect.stats} * Retrieves the logging/tracing PrintStream that is used by the <code>DriverManager</code> * and all drivers. * * @return the logging/tracing PrintStream; if disabled, is <code>null</code> * @deprecated * @see #setLogStream */ public static java.io.PrintStream getLogStream() { return logStream; } /** {@collect.stats} * Prints a message to the current JDBC log stream. * * @param message a log or tracing message */ public static void println(String message) { synchronized (logSync) { if (logWriter != null) { logWriter.println(message); // automatic flushing is never enabled, so we must do it ourselves logWriter.flush(); } } } //------------------------------------------------------------------------ // Returns the class object that would be created if the code calling the // driver manager had loaded the driver class, or null if the class // is inaccessible. private static Class getCallerClass(ClassLoader callerClassLoader, String driverClassName) { Class callerC = null; try { callerC = Class.forName(driverClassName, true, callerClassLoader); } catch (Exception ex) { callerC = null; // being very careful } return callerC; } private static void loadInitialDrivers() { String drivers; try { drivers = (String) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return System.getProperty("jdbc.drivers"); } }); } catch (Exception ex) { drivers = null; } // If the driver is packaged as a Service Provider, load it. // Get all the drivers through the classloader // exposed as a java.sql.Driver.class service. // ServiceLoader.load() replaces the sun.misc.Providers() AccessController.doPrivileged(new PrivilegedAction() { public Object run() { ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class); Iterator driversIterator = loadedDrivers.iterator(); /* Load these drivers, so that they can be instantiated. * It may be the case that the driver class may not be there * i.e. there may be a packaged driver with the service class * as implementation of java.sql.Driver but the actual class * may be missing. In that case a java.util.ServiceConfigurationError * will be thrown at runtime by the VM trying to locate * and load the service. * * Adding a try catch block to catch those runtime errors * if driver not available in classpath but it's * packaged as service and that service is there in classpath. */ try{ while(driversIterator.hasNext()) { println(" Loading done by the java.util.ServiceLoader : "+driversIterator.next()); } } catch(Throwable t) { // Do nothing } return null; } }); println("DriverManager.initialize: jdbc.drivers = " + drivers); if (drivers == null) { return; } while (drivers.length() != 0) { int x = drivers.indexOf(':'); String driver; if (x < 0) { driver = drivers; drivers = ""; } else { driver = drivers.substring(0, x); drivers = drivers.substring(x+1); } if (driver.length() == 0) { continue; } try { println("DriverManager.Initialize: loading " + driver); Class.forName(driver, true, ClassLoader.getSystemClassLoader()); } catch (Exception ex) { println("DriverManager.Initialize: load failed: " + ex); } } } // Worker method called by the public getConnection() methods. private static Connection getConnection( String url, java.util.Properties info, ClassLoader callerCL) throws SQLException { java.util.Vector drivers = null; /* * When callerCl is null, we should check the application's * (which is invoking this class indirectly) * classloader, so that the JDBC driver class outside rt.jar * can be loaded from here. */ synchronized(DriverManager.class) { // synchronize loading of the correct classloader. if(callerCL == null) { callerCL = Thread.currentThread().getContextClassLoader(); } } if(url == null) { throw new SQLException("The url cannot be null", "08001"); } println("DriverManager.getConnection(\"" + url + "\")"); if (!initialized) { initialize(); } synchronized (DriverManager.class){ // use the readcopy of drivers drivers = readDrivers; } // Walk through the loaded drivers attempting to make a connection. // Remember the first exception that gets raised so we can reraise it. SQLException reason = null; for (int i = 0; i < drivers.size(); i++) { DriverInfo di = (DriverInfo)drivers.elementAt(i); // If the caller does not have permission to load the driver then // skip it. if ( getCallerClass(callerCL, di.driverClassName ) != di.driverClass ) { println(" skipping: " + di); continue; } try { println(" trying " + di); Connection result = di.driver.connect(url, info); if (result != null) { // Success! println("getConnection returning " + di); return (result); } } catch (SQLException ex) { if (reason == null) { reason = ex; } } } // if we got here nobody could connect. if (reason != null) { println("getConnection failed: " + reason); throw reason; } println("getConnection: no suitable driver found for "+ url); throw new SQLException("No suitable driver found for "+ url, "08001"); } // Class initialization. static void initialize() { if (initialized) { return; } initialized = true; loadInitialDrivers(); println("JDBC DriverManager initialized"); } /* Prevent the DriverManager class from being instantiated. */ private DriverManager(){} /* write copy of the drivers vector */ private static java.util.Vector writeDrivers = new java.util.Vector(); /* write copy of the drivers vector */ private static java.util.Vector readDrivers = new java.util.Vector(); private static int loginTimeout = 0; private static java.io.PrintWriter logWriter = null; private static java.io.PrintStream logStream = null; private static boolean initialized = false; private static Object logSync = new Object(); /* Returns the caller's class loader, or null if none */ private static native ClassLoader getCallerClassLoader(); } // DriverInfo is a package-private support class. class DriverInfo { Driver driver; Class driverClass; String driverClassName; public String toString() { return ("driver[className=" + driverClassName + "," + driver + "]"); } }
Java
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; /** {@collect.stats} * The subclass of {@link SQLException} thrown when the SQLState class value is '<i>0A</i>' * ( the value is 'zero' A). * This indicates that the JDBC driver does not support an optional JDBC feature. * Optional JDBC features can fall into the fallowing categories: *<p> *<UL> *<LI>no support for an optional feature *<LI>no support for an optional overloaded method *<LI>no support for an optional mode for a method. The mode for a method is *determined based on constants passed as parameter values to a method *</UL> * * @since 1.6 */ public class SQLFeatureNotSupportedException extends SQLNonTransientException { /** {@collect.stats} * Constructs a <code>SQLFeatureNotSupportedException</code> object. * The <code>reason</code>, <code>SQLState</code> are initialized * to <code>null</code> and the vendor code is initialized to 0. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * @since 1.6 */ public SQLFeatureNotSupportedException() { super(); } /** {@collect.stats} * Constructs a <code>SQLFeatureNotSupportedException</code> object * with a given <code>reason</code>. The <code>SQLState</code> * is initialized to <code>null</code> and the vender code is initialized * to 0. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * @param reason a description of the exception * @since 1.6 */ public SQLFeatureNotSupportedException(String reason) { super(reason); } /** {@collect.stats} * Constructs a <code>SQLFeatureNotSupportedException</code> object * with a given <code>reason</code> and <code>SQLState</code>. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. The vendor code * is initialized to 0. * <p> * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @since 1.6 */ public SQLFeatureNotSupportedException(String reason, String SQLState) { super(reason,SQLState); } /** {@collect.stats} * Constructs a <code>SQLFeatureNotSupportedException</code> object * with a given <code>reason</code>, <code>SQLState</code> and * <code>vendorCode</code>. * * The <code>cause</code> is not initialized, and may subsequently be * initialized by a call to the * {@link Throwable#initCause(java.lang.Throwable)} method. * <p> * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param vendorCode a database vendor specific exception code * @since 1.6 */ public SQLFeatureNotSupportedException(String reason, String SQLState, int vendorCode) { super(reason,SQLState,vendorCode); } /** {@collect.stats} * Constructs a <code>SQLFeatureNotSupportedException</code> object * with a given <code>cause</code>. * The <code>SQLState</code> is initialized * to <code>null</code> and the vendor code is initialized to 0. * The <code>reason</code> is initialized to <code>null</code> if * <code>cause==null</code> or to <code>cause.toString()</code> if * <code>cause!=null</code>. * <p> * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval bythe <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLFeatureNotSupportedException(Throwable cause) { super(cause); } /** {@collect.stats} * Constructs a <code>SQLFeatureNotSupportedException</code> object * with a given * <code>reason</code> and <code>cause</code>. * The <code>SQLState</code> is initialized to <code>null</code> * and the vendor code is initialized to 0. * <p> * @param reason a description of the exception. * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLFeatureNotSupportedException(String reason, Throwable cause) { super(reason,cause); } /** {@collect.stats} * Constructs a <code>SQLFeatureNotSupportedException</code> object * with a given * <code>reason</code>, <code>SQLState</code> and <code>cause</code>. * The vendor code is initialized to 0. * <p> * @param reason a description of the exception. * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param cause the (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLFeatureNotSupportedException(String reason, String SQLState, Throwable cause) { super(reason,SQLState,cause); } /** {@collect.stats} * Constructs a <code>SQLFeatureNotSupportedException</code> object * with a given * <code>reason</code>, <code>SQLState</code>, <code>vendorCode</code> * and <code>cause</code>. * <p> * @param reason a description of the exception * @param SQLState an XOPEN or SQL:2003 code identifying the exception * @param vendorCode a database vendor-specific exception code * @param cause the underlying reason for this <code>SQLException</code> (which is saved for later retrieval by the <code>getCause()</code> method); may be null indicating * the cause is non-existent or unknown. * @since 1.6 */ public SQLFeatureNotSupportedException(String reason, String SQLState, int vendorCode, Throwable cause) { super(reason,SQLState,vendorCode,cause); } private static final long serialVersionUID = -1026510870282316051L; }
Java
/* * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; /** {@collect.stats} * <p>Driver properties for making a connection. The * <code>DriverPropertyInfo</code> class is of interest only to advanced programmers * who need to interact with a Driver via the method * <code>getDriverProperties</code> to discover * and supply properties for connections. */ public class DriverPropertyInfo { /** {@collect.stats} * Constructs a <code>DriverPropertyInfo</code> object with a given * name and value. The <code>description</code> and <code>choices</code> * are intialized to <code>null</code> and <code>required</code> is initialized * to <code>false</code>. * * @param name the name of the property * @param value the current value, which may be null */ public DriverPropertyInfo(String name, String value) { this.name = name; this.value = value; } /** {@collect.stats} * The name of the property. */ public String name; /** {@collect.stats} * A brief description of the property, which may be null. */ public String description = null; /** {@collect.stats} * The <code>required</code> field is <code>true</code> if a value must be * supplied for this property * during <code>Driver.connect</code> and <code>false</code> otherwise. */ public boolean required = false; /** {@collect.stats} * The <code>value</code> field specifies the current value of * the property, based on a combination of the information * supplied to the method <code>getPropertyInfo</code>, the * Java environment, and the driver-supplied default values. This field * may be null if no value is known. */ public String value = null; /** {@collect.stats} * An array of possible values if the value for the field * <code>DriverPropertyInfo.value</code> may be selected * from a particular set of values; otherwise null. */ public String[] choices = null; }
Java
/* * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; /** {@collect.stats} * The interface used for the custom mapping of an SQL user-defined type (UDT) to * a class in the Java programming language. The class object for a class * implementing the <code>SQLData</code> interface will be entered in the * appropriate <code>Connection</code> object's type map along with the SQL * name of the UDT for which it is a custom mapping. * <P> * Typically, a <code>SQLData</code> implementation * will define a field for each attribute of an SQL structured type or a * single field for an SQL <code>DISTINCT</code> type. When the UDT is * retrieved from a data source with the <code>ResultSet.getObject</code> * method, it will be mapped as an instance of this class. A programmer * can operate on this class instance just as on any other object in the * Java programming language and then store any changes made to it by * calling the <code>PreparedStatement.setObject</code> method, * which will map it back to the SQL type. * <p> * It is expected that the implementation of the class for a custom * mapping will be done by a tool. In a typical implementation, the * programmer would simply supply the name of the SQL UDT, the name of * the class to which it is being mapped, and the names of the fields to * which each of the attributes of the UDT is to be mapped. The tool will use * this information to implement the <code>SQLData.readSQL</code> and * <code>SQLData.writeSQL</code> methods. The <code>readSQL</code> method * calls the appropriate <code>SQLInput</code> methods to read * each attribute from an <code>SQLInput</code> object, and the * <code>writeSQL</code> method calls <code>SQLOutput</code> methods * to write each attribute back to the data source via an * <code>SQLOutput</code> object. * <P> * An application programmer will not normally call <code>SQLData</code> methods * directly, and the <code>SQLInput</code> and <code>SQLOutput</code> methods * are called internally by <code>SQLData</code> methods, not by application code. * * @since 1.2 */ public interface SQLData { /** {@collect.stats} * Returns the fully-qualified * name of the SQL user-defined type that this object represents. * This method is called by the JDBC driver to get the name of the * UDT instance that is being mapped to this instance of * <code>SQLData</code>. * * @return the type name that was passed to the method <code>readSQL</code> * when this object was constructed and populated * @exception SQLException if there is a database access error * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ String getSQLTypeName() throws SQLException; /** {@collect.stats} * Populates this object with data read from the database. * The implementation of the method must follow this protocol: * <UL> * <LI>It must read each of the attributes or elements of the SQL * type from the given input stream. This is done * by calling a method of the input stream to read each * item, in the order that they appear in the SQL definition * of the type. * <LI>The method <code>readSQL</code> then * assigns the data to appropriate fields or * elements (of this or other objects). * Specifically, it must call the appropriate <i>reader</i> method * (<code>SQLInput.readString</code>, <code>SQLInput.readBigDecimal</code>, * and so on) method(s) to do the following: * for a distinct type, read its single data element; * for a structured type, read a value for each attribute of the SQL type. * </UL> * The JDBC driver initializes the input stream with a type map * before calling this method, which is used by the appropriate * <code>SQLInput</code> reader method on the stream. * * @param stream the <code>SQLInput</code> object from which to read the data for * the value that is being custom mapped * @param typeName the SQL type name of the value on the data stream * @exception SQLException if there is a database access error * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @see SQLInput * @since 1.2 */ void readSQL (SQLInput stream, String typeName) throws SQLException; /** {@collect.stats} * Writes this object to the given SQL data stream, converting it back to * its SQL value in the data source. * The implementation of the method must follow this protocol:<BR> * It must write each of the attributes of the SQL type * to the given output stream. This is done by calling a * method of the output stream to write each item, in the order that * they appear in the SQL definition of the type. * Specifically, it must call the appropriate <code>SQLOutput</code> writer * method(s) (<code>writeInt</code>, <code>writeString</code>, and so on) * to do the following: for a Distinct Type, write its single data element; * for a Structured Type, write a value for each attribute of the SQL type. * * @param stream the <code>SQLOutput</code> object to which to write the data for * the value that was custom mapped * @exception SQLException if there is a database access error * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @see SQLOutput * @since 1.2 */ void writeSQL (SQLOutput stream) throws SQLException; }
Java
/* * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; import java.io.Reader; /** {@collect.stats} * The mapping in the Java<sup><font size=-2>TM</font></sup> programming language * for the SQL <code>CLOB</code> type. * An SQL <code>CLOB</code> is a built-in type * that stores a Character Large Object as a column value in a row of * a database table. * By default drivers implement a <code>Clob</code> object using an SQL * <code>locator(CLOB)</code>, which means that a <code>Clob</code> object * contains a logical pointer to the SQL <code>CLOB</code> data rather than * the data itself. A <code>Clob</code> object is valid for the duration * of the transaction in which it was created. * <P>The <code>Clob</code> interface provides methods for getting the * length of an SQL <code>CLOB</code> (Character Large Object) value, * for materializing a <code>CLOB</code> value on the client, and for * searching for a substring or <code>CLOB</code> object within a * <code>CLOB</code> value. * Methods in the interfaces {@link ResultSet}, * {@link CallableStatement}, and {@link PreparedStatement}, such as * <code>getClob</code> and <code>setClob</code> allow a programmer to * access an SQL <code>CLOB</code> value. In addition, this interface * has methods for updating a <code>CLOB</code> value. * <p> * All methods on the <code>Clob</code> interface must be fully implemented if the * JDBC driver supports the data type. * * @since 1.2 */ public interface Clob { /** {@collect.stats} * Retrieves the number of characters * in the <code>CLOB</code> value * designated by this <code>Clob</code> object. * * @return length of the <code>CLOB</code> in characters * @exception SQLException if there is an error accessing the * length of the <code>CLOB</code> value * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ long length() throws SQLException; /** {@collect.stats} * Retrieves a copy of the specified substring * in the <code>CLOB</code> value * designated by this <code>Clob</code> object. * The substring begins at position * <code>pos</code> and has up to <code>length</code> consecutive * characters. * * @param pos the first character of the substring to be extracted. * The first character is at position 1. * @param length the number of consecutive characters to be copied; * the value for length must be 0 or greater * @return a <code>String</code> that is the specified substring in * the <code>CLOB</code> value designated by this <code>Clob</code> object * @exception SQLException if there is an error accessing the * <code>CLOB</code> value; if pos is less than 1 or length is * less than 0 * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ String getSubString(long pos, int length) throws SQLException; /** {@collect.stats} * Retrieves the <code>CLOB</code> value designated by this <code>Clob</code> * object as a <code>java.io.Reader</code> object (or as a stream of * characters). * * @return a <code>java.io.Reader</code> object containing the * <code>CLOB</code> data * @exception SQLException if there is an error accessing the * <code>CLOB</code> value * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @see #setCharacterStream * @since 1.2 */ java.io.Reader getCharacterStream() throws SQLException; /** {@collect.stats} * Retrieves the <code>CLOB</code> value designated by this <code>Clob</code> * object as an ascii stream. * * @return a <code>java.io.InputStream</code> object containing the * <code>CLOB</code> data * @exception SQLException if there is an error accessing the * <code>CLOB</code> value * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @see #setAsciiStream * @since 1.2 */ java.io.InputStream getAsciiStream() throws SQLException; /** {@collect.stats} * Retrieves the character position at which the specified substring * <code>searchstr</code> appears in the SQL <code>CLOB</code> value * represented by this <code>Clob</code> object. The search * begins at position <code>start</code>. * * @param searchstr the substring for which to search * @param start the position at which to begin searching; the first position * is 1 * @return the position at which the substring appears or -1 if it is not * present; the first position is 1 * @exception SQLException if there is an error accessing the * <code>CLOB</code> value or if pos is less than 1 * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ long position(String searchstr, long start) throws SQLException; /** {@collect.stats} * Retrieves the character position at which the specified * <code>Clob</code> object <code>searchstr</code> appears in this * <code>Clob</code> object. The search begins at position * <code>start</code>. * * @param searchstr the <code>Clob</code> object for which to search * @param start the position at which to begin searching; the first * position is 1 * @return the position at which the <code>Clob</code> object appears * or -1 if it is not present; the first position is 1 * @exception SQLException if there is an error accessing the * <code>CLOB</code> value or if start is less than 1 * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ long position(Clob searchstr, long start) throws SQLException; //---------------------------- jdbc 3.0 ----------------------------------- /** {@collect.stats} * Writes the given Java <code>String</code> to the <code>CLOB</code> * value that this <code>Clob</code> object designates at the position * <code>pos</code>. The string will overwrite the existing characters * in the <code>Clob</code> object starting at the position * <code>pos</code>. If the end of the <code>Clob</code> value is reached * while writing the given string, then the length of the <code>Clob</code> * value will be increased to accomodate the extra characters. * <p> * <b>Note:</b> If the value specified for <code>pos</code> * is greater then the length+1 of the <code>CLOB</code> value then the * behavior is undefined. Some JDBC drivers may throw a * <code>SQLException</code> while other drivers may support this * operation. * * @param pos the position at which to start writing to the <code>CLOB</code> * value that this <code>Clob</code> object represents; * The first position is 1 * @param str the string to be written to the <code>CLOB</code> * value that this <code>Clob</code> designates * @return the number of characters written * @exception SQLException if there is an error accessing the * <code>CLOB</code> value or if pos is less than 1 * * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.4 */ int setString(long pos, String str) throws SQLException; /** {@collect.stats} * Writes <code>len</code> characters of <code>str</code>, starting * at character <code>offset</code>, to the <code>CLOB</code> value * that this <code>Clob</code> represents. The string will overwrite the existing characters * in the <code>Clob</code> object starting at the position * <code>pos</code>. If the end of the <code>Clob</code> value is reached * while writing the given string, then the length of the <code>Clob</code> * value will be increased to accomodate the extra characters. * <p> * <b>Note:</b> If the value specified for <code>pos</code> * is greater then the length+1 of the <code>CLOB</code> value then the * behavior is undefined. Some JDBC drivers may throw a * <code>SQLException</code> while other drivers may support this * operation. * * @param pos the position at which to start writing to this * <code>CLOB</code> object; The first position is 1 * @param str the string to be written to the <code>CLOB</code> * value that this <code>Clob</code> object represents * @param offset the offset into <code>str</code> to start reading * the characters to be written * @param len the number of characters to be written * @return the number of characters written * @exception SQLException if there is an error accessing the * <code>CLOB</code> value or if pos is less than 1 * * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.4 */ int setString(long pos, String str, int offset, int len) throws SQLException; /** {@collect.stats} * Retrieves a stream to be used to write Ascii characters to the * <code>CLOB</code> value that this <code>Clob</code> object represents, * starting at position <code>pos</code>. Characters written to the stream * will overwrite the existing characters * in the <code>Clob</code> object starting at the position * <code>pos</code>. If the end of the <code>Clob</code> value is reached * while writing characters to the stream, then the length of the <code>Clob</code> * value will be increased to accomodate the extra characters. * <p> * <b>Note:</b> If the value specified for <code>pos</code> * is greater then the length+1 of the <code>CLOB</code> value then the * behavior is undefined. Some JDBC drivers may throw a * <code>SQLException</code> while other drivers may support this * operation. * * @param pos the position at which to start writing to this * <code>CLOB</code> object; The first position is 1 * @return the stream to which ASCII encoded characters can be written * @exception SQLException if there is an error accessing the * <code>CLOB</code> value or if pos is less than 1 * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @see #getAsciiStream * * @since 1.4 */ java.io.OutputStream setAsciiStream(long pos) throws SQLException; /** {@collect.stats} * Retrieves a stream to be used to write a stream of Unicode characters * to the <code>CLOB</code> value that this <code>Clob</code> object * represents, at position <code>pos</code>. Characters written to the stream * will overwrite the existing characters * in the <code>Clob</code> object starting at the position * <code>pos</code>. If the end of the <code>Clob</code> value is reached * while writing characters to the stream, then the length of the <code>Clob</code> * value will be increased to accomodate the extra characters. * <p> * <b>Note:</b> If the value specified for <code>pos</code> * is greater then the length+1 of the <code>CLOB</code> value then the * behavior is undefined. Some JDBC drivers may throw a * <code>SQLException</code> while other drivers may support this * operation. * * @param pos the position at which to start writing to the * <code>CLOB</code> value; The first position is 1 * * @return a stream to which Unicode encoded characters can be written * @exception SQLException if there is an error accessing the * <code>CLOB</code> value or if pos is less than 1 * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @see #getCharacterStream * * @since 1.4 */ java.io.Writer setCharacterStream(long pos) throws SQLException; /** {@collect.stats} * Truncates the <code>CLOB</code> value that this <code>Clob</code> * designates to have a length of <code>len</code> * characters. * <p> * <b>Note:</b> If the value specified for <code>pos</code> * is greater then the length+1 of the <code>CLOB</code> value then the * behavior is undefined. Some JDBC drivers may throw a * <code>SQLException</code> while other drivers may support this * operation. * * @param len the length, in characters, to which the <code>CLOB</code> value * should be truncated * @exception SQLException if there is an error accessing the * <code>CLOB</code> value or if len is less than 0 * * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.4 */ void truncate(long len) throws SQLException; /** {@collect.stats} * This method frees the <code>Clob</code> object and releases the resources the resources * that it holds. The object is invalid once the <code>free</code> method * is called. * <p> * After <code>free</code> has been called, any attempt to invoke a * method other than <code>free</code> will result in a <code>SQLException</code> * being thrown. If <code>free</code> is called multiple times, the subsequent * calls to <code>free</code> are treated as a no-op. * <p> * @throws SQLException if an error occurs releasing * the Clob's resources * * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.6 */ void free() throws SQLException; /** {@collect.stats} * Returns a <code>Reader</code> object that contains a partial <code>Clob</code> value, starting * with the character specified by pos, which is length characters in length. * * @param pos the offset to the first character of the partial value to * be retrieved. The first character in the Clob is at position 1. * @param length the length in characters of the partial value to be retrieved. * @return <code>Reader</code> through which the partial <code>Clob</code> value can be read. * @throws SQLException if pos is less than 1 or if pos is greater than the number of * characters in the <code>Clob</code> or if pos + length is greater than the number of * characters in the <code>Clob</code> * * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.6 */ Reader getCharacterStream(long pos, long length) throws SQLException; }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; import java.util.StringTokenizer; /** {@collect.stats} * <P>A thin wrapper around <code>java.util.Date</code> that allows * the JDBC API to identify this as an SQL <code>TIMESTAMP</code> value. * It adds the ability * to hold the SQL <code>TIMESTAMP</code> fractional seconds value, by allowing * the specification of fractional seconds to a precision of nanoseconds. * A Timestamp also provides formatting and * parsing operations to support the JDBC escape syntax for timestamp values. * * <p>The precision of a Timestamp object is calculated to be either: * <ul> * <li><code>19 </code>, which is the number of characters in yyyy-mm-dd hh:mm:ss * <li> <code> 20 + s </code>, which is the number * of characters in the yyyy-mm-dd hh:mm:ss.[fff...] and <code>s</code> represents the scale of the given Timestamp, * its fractional seconds precision. *</ul> * * <P><B>Note:</B> This type is a composite of a <code>java.util.Date</code> and a * separate nanoseconds value. Only integral seconds are stored in the * <code>java.util.Date</code> component. The fractional seconds - the nanos - are * separate. The <code>Timestamp.equals(Object)</code> method never returns * <code>true</code> when passed an object * that isn't an instance of <code>java.sql.Timestamp</code>, * because the nanos component of a date is unknown. * As a result, the <code>Timestamp.equals(Object)</code> * method is not symmetric with respect to the * <code>java.util.Date.equals(Object)</code> * method. Also, the <code>hashcode</code> method uses the underlying * <code>java.util.Date</code> * implementation and therefore does not include nanos in its computation. * <P> * Due to the differences between the <code>Timestamp</code> class * and the <code>java.util.Date</code> * class mentioned above, it is recommended that code not view * <code>Timestamp</code> values generically as an instance of * <code>java.util.Date</code>. The * inheritance relationship between <code>Timestamp</code> * and <code>java.util.Date</code> really * denotes implementation inheritance, and not type inheritance. */ public class Timestamp extends java.util.Date { /** {@collect.stats} * Constructs a <code>Timestamp</code> object initialized * with the given values. * * @param year the year minus 1900 * @param month 0 to 11 * @param date 1 to 31 * @param hour 0 to 23 * @param minute 0 to 59 * @param second 0 to 59 * @param nano 0 to 999,999,999 * @deprecated instead use the constructor <code>Timestamp(long millis)</code> * @exception IllegalArgumentException if the nano argument is out of bounds */ @Deprecated public Timestamp(int year, int month, int date, int hour, int minute, int second, int nano) { super(year, month, date, hour, minute, second); if (nano > 999999999 || nano < 0) { throw new IllegalArgumentException("nanos > 999999999 or < 0"); } nanos = nano; } /** {@collect.stats} * Constructs a <code>Timestamp</code> object * using a milliseconds time value. The * integral seconds are stored in the underlying date value; the * fractional seconds are stored in the <code>nanos</code> field of * the <code>Timestamp</code> object. * * @param time milliseconds since January 1, 1970, 00:00:00 GMT. * A negative number is the number of milliseconds before * January 1, 1970, 00:00:00 GMT. * @see java.util.Calendar */ public Timestamp(long time) { super((time/1000)*1000); nanos = (int)((time%1000) * 1000000); if (nanos < 0) { nanos = 1000000000 + nanos; super.setTime(((time/1000)-1)*1000); } } /** {@collect.stats} * Sets this <code>Timestamp</code> object to represent a point in time that is * <tt>time</tt> milliseconds after January 1, 1970 00:00:00 GMT. * * @param time the number of milliseconds. * @see #getTime * @see #Timestamp(long time) * @see java.util.Calendar */ public void setTime(long time) { super.setTime((time/1000)*1000); nanos = (int)((time%1000) * 1000000); if (nanos < 0) { nanos = 1000000000 + nanos; super.setTime(((time/1000)-1)*1000); } } /** {@collect.stats} * Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT * represented by this <code>Timestamp</code> object. * * @return the number of milliseconds since January 1, 1970, 00:00:00 GMT * represented by this date. * @see #setTime */ public long getTime() { long time = super.getTime(); return (time + (nanos / 1000000)); } /** {@collect.stats} * @serial */ private int nanos; /** {@collect.stats} * Converts a <code>String</code> object in JDBC timestamp escape format to a * <code>Timestamp</code> value. * * @param s timestamp in format <code>yyyy-mm-dd hh:mm:ss[.f...]</code>. The * fractional seconds may be omitted. * @return corresponding <code>Timestamp</code> value * @exception java.lang.IllegalArgumentException if the given argument * does not have the format <code>yyyy-mm-dd hh:mm:ss[.f...]</code> */ public static Timestamp valueOf(String s) { String date_s; String time_s; String nanos_s; int year; int month; int day; int hour; int minute; int second; int a_nanos = 0; int firstDash; int secondDash; int dividingSpace; int firstColon = 0; int secondColon = 0; int period = 0; String formatError = "Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]"; String zeros = "000000000"; String delimiterDate = "-"; String delimiterTime = ":"; StringTokenizer stringTokeninzerDate; StringTokenizer stringTokeninzerTime; if (s == null) throw new java.lang.IllegalArgumentException("null string"); int counterD = 0; int intDate[] = {4,2,2}; int counterT = 0; int intTime[] = {2,2,12}; // Split the string into date and time components s = s.trim(); dividingSpace = s.indexOf(' '); if (dividingSpace > 0) { date_s = s.substring(0,dividingSpace); time_s = s.substring(dividingSpace+1); } else { throw new java.lang.IllegalArgumentException(formatError); } stringTokeninzerTime = new StringTokenizer(time_s, delimiterTime); stringTokeninzerDate = new StringTokenizer(date_s, delimiterDate); while(stringTokeninzerDate.hasMoreTokens()) { String tokenDate = stringTokeninzerDate.nextToken(); if(tokenDate.length() != intDate[counterD] ) { throw new java.lang.IllegalArgumentException(formatError); } counterD++; } /* //Commenting this portion out for checking of time while(stringTokeninzerTime.hasMoreTokens()) { String tokenTime = stringTokeninzerTime.nextToken(); if (counterT < 2 && tokenTime.length() != intTime[counterT] ) { throw new java.lang.IllegalArgumentException(formatError); } counterT++; } */ // Parse the date firstDash = date_s.indexOf('-'); secondDash = date_s.indexOf('-', firstDash+1); // Parse the time if (time_s == null) throw new java.lang.IllegalArgumentException(formatError); firstColon = time_s.indexOf(':'); secondColon = time_s.indexOf(':', firstColon+1); period = time_s.indexOf('.', secondColon+1); // Convert the date if ((firstDash > 0) && (secondDash > 0) && (secondDash < date_s.length()-1)) { year = Integer.parseInt(date_s.substring(0, firstDash)) - 1900; month = Integer.parseInt(date_s.substring (firstDash+1, secondDash)) - 1; day = Integer.parseInt(date_s.substring(secondDash+1)); } else { throw new java.lang.IllegalArgumentException(formatError); } // Convert the time; default missing nanos if ((firstColon > 0) & (secondColon > 0) & (secondColon < time_s.length()-1)) { hour = Integer.parseInt(time_s.substring(0, firstColon)); minute = Integer.parseInt(time_s.substring(firstColon+1, secondColon)); if ((period > 0) & (period < time_s.length()-1)) { second = Integer.parseInt(time_s.substring(secondColon+1, period)); nanos_s = time_s.substring(period+1); if (nanos_s.length() > 9) throw new java.lang.IllegalArgumentException(formatError); if (!Character.isDigit(nanos_s.charAt(0))) throw new java.lang.IllegalArgumentException(formatError); nanos_s = nanos_s + zeros.substring(0,9-nanos_s.length()); a_nanos = Integer.parseInt(nanos_s); } else if (period > 0) { throw new java.lang.IllegalArgumentException(formatError); } else { second = Integer.parseInt(time_s.substring(secondColon+1)); } } else { throw new java.lang.IllegalArgumentException(); } return new Timestamp(year, month, day, hour, minute, second, a_nanos); } /** {@collect.stats} * Formats a timestamp in JDBC timestamp escape format. * <code>yyyy-mm-dd hh:mm:ss.fffffffff</code>, * where <code>ffffffffff</code> indicates nanoseconds. * <P> * @return a <code>String</code> object in * <code>yyyy-mm-dd hh:mm:ss.fffffffff</code> format */ public String toString () { int year = super.getYear() + 1900; int month = super.getMonth() + 1; int day = super.getDate(); int hour = super.getHours(); int minute = super.getMinutes(); int second = super.getSeconds(); String yearString; String monthString; String dayString; String hourString; String minuteString; String secondString; String nanosString; String zeros = "000000000"; String yearZeros = "0000"; StringBuffer timestampBuf; if (year < 1000) { // Add leading zeros yearString = "" + year; yearString = yearZeros.substring(0, (4-yearString.length())) + yearString; } else { yearString = "" + year; } if (month < 10) { monthString = "0" + month; } else { monthString = Integer.toString(month); } if (day < 10) { dayString = "0" + day; } else { dayString = Integer.toString(day); } if (hour < 10) { hourString = "0" + hour; } else { hourString = Integer.toString(hour); } if (minute < 10) { minuteString = "0" + minute; } else { minuteString = Integer.toString(minute); } if (second < 10) { secondString = "0" + second; } else { secondString = Integer.toString(second); } if (nanos == 0) { nanosString = "0"; } else { nanosString = Integer.toString(nanos); // Add leading zeros nanosString = zeros.substring(0, (9-nanosString.length())) + nanosString; // Truncate trailing zeros char[] nanosChar = new char[nanosString.length()]; nanosString.getChars(0, nanosString.length(), nanosChar, 0); int truncIndex = 8; while (nanosChar[truncIndex] == '0') { truncIndex--; } nanosString = new String(nanosChar, 0, truncIndex + 1); } // do a string buffer here instead. timestampBuf = new StringBuffer(20+nanosString.length()); timestampBuf.append(yearString); timestampBuf.append("-"); timestampBuf.append(monthString); timestampBuf.append("-"); timestampBuf.append(dayString); timestampBuf.append(" "); timestampBuf.append(hourString); timestampBuf.append(":"); timestampBuf.append(minuteString); timestampBuf.append(":"); timestampBuf.append(secondString); timestampBuf.append("."); timestampBuf.append(nanosString); return (timestampBuf.toString()); } /** {@collect.stats} * Gets this <code>Timestamp</code> object's <code>nanos</code> value. * * @return this <code>Timestamp</code> object's fractional seconds component * @see #setNanos */ public int getNanos() { return nanos; } /** {@collect.stats} * Sets this <code>Timestamp</code> object's <code>nanos</code> field * to the given value. * * @param n the new fractional seconds component * @exception java.lang.IllegalArgumentException if the given argument * is greater than 999999999 or less than 0 * @see #getNanos */ public void setNanos(int n) { if (n > 999999999 || n < 0) { throw new IllegalArgumentException("nanos > 999999999 or < 0"); } nanos = n; } /** {@collect.stats} * Tests to see if this <code>Timestamp</code> object is * equal to the given <code>Timestamp</code> object. * * @param ts the <code>Timestamp</code> value to compare with * @return <code>true</code> if the given <code>Timestamp</code> * object is equal to this <code>Timestamp</code> object; * <code>false</code> otherwise */ public boolean equals(Timestamp ts) { if (super.equals(ts)) { if (nanos == ts.nanos) { return true; } else { return false; } } else { return false; } } /** {@collect.stats} * Tests to see if this <code>Timestamp</code> object is * equal to the given object. * * This version of the method <code>equals</code> has been added * to fix the incorrect * signature of <code>Timestamp.equals(Timestamp)</code> and to preserve backward * compatibility with existing class files. * * Note: This method is not symmetric with respect to the * <code>equals(Object)</code> method in the base class. * * @param ts the <code>Object</code> value to compare with * @return <code>true</code> if the given <code>Object</code> is an instance * of a <code>Timestamp</code> that * is equal to this <code>Timestamp</code> object; * <code>false</code> otherwise */ public boolean equals(java.lang.Object ts) { if (ts instanceof Timestamp) { return this.equals((Timestamp)ts); } else { return false; } } /** {@collect.stats} * Indicates whether this <code>Timestamp</code> object is * earlier than the given <code>Timestamp</code> object. * * @param ts the <code>Timestamp</code> value to compare with * @return <code>true</code> if this <code>Timestamp</code> object is earlier; * <code>false</code> otherwise */ public boolean before(Timestamp ts) { return compareTo(ts) < 0; } /** {@collect.stats} * Indicates whether this <code>Timestamp</code> object is * later than the given <code>Timestamp</code> object. * * @param ts the <code>Timestamp</code> value to compare with * @return <code>true</code> if this <code>Timestamp</code> object is later; * <code>false</code> otherwise */ public boolean after(Timestamp ts) { return compareTo(ts) > 0; } /** {@collect.stats} * Compares this <code>Timestamp</code> object to the given * <code>Timestamp</code> object. * * @param ts the <code>Timestamp</code> object to be compared to * this <code>Timestamp</code> object * @return the value <code>0</code> if the two <code>Timestamp</code> * objects are equal; a value less than <code>0</code> if this * <code>Timestamp</code> object is before the given argument; * and a value greater than <code>0</code> if this * <code>Timestamp</code> object is after the given argument. * @since 1.4 */ public int compareTo(Timestamp ts) { long thisTime = this.getTime(); long anotherTime = ts.getTime(); int i = (thisTime<anotherTime ? -1 :(thisTime==anotherTime?0 :1)); if (i == 0) { if (nanos > ts.nanos) { return 1; } else if (nanos < ts.nanos) { return -1; } } return i; } /** {@collect.stats} * Compares this <code>Timestamp</code> object to the given * <code>Date</code>, which must be a <code>Timestamp</code> * object. If the argument is not a <code>Timestamp</code> object, * this method throws a <code>ClassCastException</code> object. * (<code>Timestamp</code> objects are * comparable only to other <code>Timestamp</code> objects.) * * @param o the <code>Date</code> to be compared, which must be a * <code>Timestamp</code> object * @return the value <code>0</code> if this <code>Timestamp</code> object * and the given object are equal; a value less than <code>0</code> * if this <code>Timestamp</code> object is before the given argument; * and a value greater than <code>0</code> if this * <code>Timestamp</code> object is after the given argument. * * @since 1.5 */ public int compareTo(java.util.Date o) { if(o instanceof Timestamp) { // When Timestamp instance compare it with a Timestamp // Hence it is basically calling this.compareTo((Timestamp))o); // Note typecasting is safe because o is instance of Timestamp return compareTo((Timestamp)o); } else { // When Date doing a o.compareTo(this) // will give wrong results. Timestamp ts = new Timestamp(o.getTime()); return this.compareTo(ts); } } static final long serialVersionUID = 2745179027874758501L; }
Java
/* * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; /** {@collect.stats} * The output stream for writing the attributes of a user-defined * type back to the database. This interface, used * only for custom mapping, is used by the driver, and its * methods are never directly invoked by a programmer. * <p>When an object of a class implementing the interface * <code>SQLData</code> is passed as an argument to an SQL statement, the * JDBC driver calls the method <code>SQLData.getSQLType</code> to * determine the kind of SQL * datum being passed to the database. * The driver then creates an instance of <code>SQLOutput</code> and * passes it to the method <code>SQLData.writeSQL</code>. * The method <code>writeSQL</code> in turn calls the * appropriate <code>SQLOutput</code> <i>writer</i> methods * <code>writeBoolean</code>, <code>writeCharacterStream</code>, and so on) * to write data from the <code>SQLData</code> object to * the <code>SQLOutput</code> output stream as the * representation of an SQL user-defined type. * @since 1.2 */ public interface SQLOutput { //================================================================ // Methods for writing attributes to the stream of SQL data. // These methods correspond to the column-accessor methods of // java.sql.ResultSet. //================================================================ /** {@collect.stats} * Writes the next attribute to the stream as a <code>String</code> * in the Java programming language. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeString(String x) throws SQLException; /** {@collect.stats} * Writes the next attribute to the stream as a Java boolean. * Writes the next attribute to the stream as a <code>String</code> * in the Java programming language. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeBoolean(boolean x) throws SQLException; /** {@collect.stats} * Writes the next attribute to the stream as a Java byte. * Writes the next attribute to the stream as a <code>String</code> * in the Java programming language. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeByte(byte x) throws SQLException; /** {@collect.stats} * Writes the next attribute to the stream as a Java short. * Writes the next attribute to the stream as a <code>String</code> * in the Java programming language. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeShort(short x) throws SQLException; /** {@collect.stats} * Writes the next attribute to the stream as a Java int. * Writes the next attribute to the stream as a <code>String</code> * in the Java programming language. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeInt(int x) throws SQLException; /** {@collect.stats} * Writes the next attribute to the stream as a Java long. * Writes the next attribute to the stream as a <code>String</code> * in the Java programming language. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeLong(long x) throws SQLException; /** {@collect.stats} * Writes the next attribute to the stream as a Java float. * Writes the next attribute to the stream as a <code>String</code> * in the Java programming language. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeFloat(float x) throws SQLException; /** {@collect.stats} * Writes the next attribute to the stream as a Java double. * Writes the next attribute to the stream as a <code>String</code> * in the Java programming language. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeDouble(double x) throws SQLException; /** {@collect.stats} * Writes the next attribute to the stream as a java.math.BigDecimal object. * Writes the next attribute to the stream as a <code>String</code> * in the Java programming language. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeBigDecimal(java.math.BigDecimal x) throws SQLException; /** {@collect.stats} * Writes the next attribute to the stream as an array of bytes. * Writes the next attribute to the stream as a <code>String</code> * in the Java programming language. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeBytes(byte[] x) throws SQLException; /** {@collect.stats} * Writes the next attribute to the stream as a java.sql.Date object. * Writes the next attribute to the stream as a <code>java.sql.Date</code> object * in the Java programming language. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeDate(java.sql.Date x) throws SQLException; /** {@collect.stats} * Writes the next attribute to the stream as a java.sql.Time object. * Writes the next attribute to the stream as a <code>java.sql.Date</code> object * in the Java programming language. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeTime(java.sql.Time x) throws SQLException; /** {@collect.stats} * Writes the next attribute to the stream as a java.sql.Timestamp object. * Writes the next attribute to the stream as a <code>java.sql.Date</code> object * in the Java programming language. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeTimestamp(java.sql.Timestamp x) throws SQLException; /** {@collect.stats} * Writes the next attribute to the stream as a stream of Unicode characters. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeCharacterStream(java.io.Reader x) throws SQLException; /** {@collect.stats} * Writes the next attribute to the stream as a stream of ASCII characters. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeAsciiStream(java.io.InputStream x) throws SQLException; /** {@collect.stats} * Writes the next attribute to the stream as a stream of uninterpreted * bytes. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeBinaryStream(java.io.InputStream x) throws SQLException; //================================================================ // Methods for writing items of SQL user-defined types to the stream. // These methods pass objects to the database as values of SQL // Structured Types, Distinct Types, Constructed Types, and Locator // Types. They decompose the Java object(s) and write leaf data // items using the methods above. //================================================================ /** {@collect.stats} * Writes to the stream the data contained in the given * <code>SQLData</code> object. * When the <code>SQLData</code> object is <code>null</code>, this * method writes an SQL <code>NULL</code> to the stream. * Otherwise, it calls the <code>SQLData.writeSQL</code> * method of the given object, which * writes the object's attributes to the stream. * The implementation of the method <code>SQLData.writeSQ</code> * calls the appropriate <code>SQLOutput</code> writer method(s) * for writing each of the object's attributes in order. * The attributes must be read from an <code>SQLInput</code> * input stream and written to an <code>SQLOutput</code> * output stream in the same order in which they were * listed in the SQL definition of the user-defined type. * * @param x the object representing data of an SQL structured or * distinct type * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeObject(SQLData x) throws SQLException; /** {@collect.stats} * Writes an SQL <code>REF</code> value to the stream. * * @param x a <code>Ref</code> object representing data of an SQL * <code>REF</code> value * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeRef(Ref x) throws SQLException; /** {@collect.stats} * Writes an SQL <code>BLOB</code> value to the stream. * * @param x a <code>Blob</code> object representing data of an SQL * <code>BLOB</code> value * * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeBlob(Blob x) throws SQLException; /** {@collect.stats} * Writes an SQL <code>CLOB</code> value to the stream. * * @param x a <code>Clob</code> object representing data of an SQL * <code>CLOB</code> value * * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeClob(Clob x) throws SQLException; /** {@collect.stats} * Writes an SQL structured type value to the stream. * * @param x a <code>Struct</code> object representing data of an SQL * structured type * * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeStruct(Struct x) throws SQLException; /** {@collect.stats} * Writes an SQL <code>ARRAY</code> value to the stream. * * @param x an <code>Array</code> object representing data of an SQL * <code>ARRAY</code> type * * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ void writeArray(Array x) throws SQLException; //--------------------------- JDBC 3.0 ------------------------ /** {@collect.stats} * Writes a SQL <code>DATALINK</code> value to the stream. * * @param x a <code>java.net.URL</code> object representing the data * of SQL DATALINK type * * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.4 */ void writeURL(java.net.URL x) throws SQLException; //--------------------------- JDBC 4.0 ------------------------ /** {@collect.stats} * Writes the next attribute to the stream as a <code>String</code> * in the Java programming language. The driver converts this to a * SQL <code>NCHAR</code> or * <code>NVARCHAR</code> or <code>LONGNVARCHAR</code> value * (depending on the argument's * size relative to the driver's limits on <code>NVARCHAR</code> values) * when it sends it to the stream. * * @param x the value to pass to the database * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.6 */ void writeNString(String x) throws SQLException; /** {@collect.stats} * Writes an SQL <code>NCLOB</code> value to the stream. * * @param x a <code>NClob</code> object representing data of an SQL * <code>NCLOB</code> value * * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.6 */ void writeNClob(NClob x) throws SQLException; /** {@collect.stats} * Writes an SQL <code>ROWID</code> value to the stream. * * @param x a <code>RowId</code> object representing data of an SQL * <code>ROWID</code> value * * @exception SQLException if a database access error occurs * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.6 */ void writeRowId(RowId x) throws SQLException; /** {@collect.stats} * Writes an SQL <code>XML</code> value to the stream. * * @param x a <code>SQLXML</code> object representing data of an SQL * <code>XML</code> value * * @throws SQLException if a database access error occurs, * the <code>java.xml.transform.Result</code>, * <code>Writer</code> or <code>OutputStream</code> has not been closed for the <code>SQLXML</code> object or * if there is an error processing the XML value. The <code>getCause</code> method * of the exception may provide a more detailed exception, for example, if the * stream does not contain valid XML. * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.6 */ void writeSQLXML(SQLXML x) throws SQLException; }
Java
/* * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; import java.io.InputStream; /** {@collect.stats} * The representation (mapping) in * the Java<sup><font size=-2>TM</font></sup> programming * language of an SQL * <code>BLOB</code> value. An SQL <code>BLOB</code> is a built-in type * that stores a Binary Large Object as a column value in a row of * a database table. By default drivers implement <code>Blob</code> using * an SQL <code>locator(BLOB)</code>, which means that a * <code>Blob</code> object contains a logical pointer to the * SQL <code>BLOB</code> data rather than the data itself. * A <code>Blob</code> object is valid for the duration of the * transaction in which is was created. * * <P>Methods in the interfaces {@link ResultSet}, * {@link CallableStatement}, and {@link PreparedStatement}, such as * <code>getBlob</code> and <code>setBlob</code> allow a programmer to * access an SQL <code>BLOB</code> value. * The <code>Blob</code> interface provides methods for getting the * length of an SQL <code>BLOB</code> (Binary Large Object) value, * for materializing a <code>BLOB</code> value on the client, and for * determining the position of a pattern of bytes within a * <code>BLOB</code> value. In addition, this interface has methods for updating * a <code>BLOB</code> value. * <p> * All methods on the <code>Blob</code> interface must be fully implemented if the * JDBC driver supports the data type. * * @since 1.2 */ public interface Blob { /** {@collect.stats} * Returns the number of bytes in the <code>BLOB</code> value * designated by this <code>Blob</code> object. * @return length of the <code>BLOB</code> in bytes * @exception SQLException if there is an error accessing the * length of the <code>BLOB</code> * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ long length() throws SQLException; /** {@collect.stats} * Retrieves all or part of the <code>BLOB</code> * value that this <code>Blob</code> object represents, as an array of * bytes. This <code>byte</code> array contains up to <code>length</code> * consecutive bytes starting at position <code>pos</code>. * * @param pos the ordinal position of the first byte in the * <code>BLOB</code> value to be extracted; the first byte is at * position 1 * @param length the number of consecutive bytes to be copied; the value * for length must be 0 or greater * @return a byte array containing up to <code>length</code> * consecutive bytes from the <code>BLOB</code> value designated * by this <code>Blob</code> object, starting with the * byte at position <code>pos</code> * @exception SQLException if there is an error accessing the * <code>BLOB</code> value; if pos is less than 1 or length is * less than 0 * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @see #setBytes * @since 1.2 */ byte[] getBytes(long pos, int length) throws SQLException; /** {@collect.stats} * Retrieves the <code>BLOB</code> value designated by this * <code>Blob</code> instance as a stream. * * @return a stream containing the <code>BLOB</code> data * @exception SQLException if there is an error accessing the * <code>BLOB</code> value * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @see #setBinaryStream * @since 1.2 */ java.io.InputStream getBinaryStream () throws SQLException; /** {@collect.stats} * Retrieves the byte position at which the specified byte array * <code>pattern</code> begins within the <code>BLOB</code> * value that this <code>Blob</code> object represents. The * search for <code>pattern</code> begins at position * <code>start</code>. * * @param pattern the byte array for which to search * @param start the position at which to begin searching; the * first position is 1 * @return the position at which the pattern appears, else -1 * @exception SQLException if there is an error accessing the * <code>BLOB</code> or if start is less than 1 * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ long position(byte pattern[], long start) throws SQLException; /** {@collect.stats} * Retrieves the byte position in the <code>BLOB</code> value * designated by this <code>Blob</code> object at which * <code>pattern</code> begins. The search begins at position * <code>start</code>. * * @param pattern the <code>Blob</code> object designating * the <code>BLOB</code> value for which to search * @param start the position in the <code>BLOB</code> value * at which to begin searching; the first position is 1 * @return the position at which the pattern begins, else -1 * @exception SQLException if there is an error accessing the * <code>BLOB</code> value or if start is less than 1 * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.2 */ long position(Blob pattern, long start) throws SQLException; // -------------------------- JDBC 3.0 ----------------------------------- /** {@collect.stats} * Writes the given array of bytes to the <code>BLOB</code> value that * this <code>Blob</code> object represents, starting at position * <code>pos</code>, and returns the number of bytes written. * The array of bytes will overwrite the existing bytes * in the <code>Blob</code> object starting at the position * <code>pos</code>. If the end of the <code>Blob</code> value is reached * while writing the array of bytes, then the length of the <code>Blob</code> * value will be increased to accomodate the extra bytes. * <p> * <b>Note:</b> If the value specified for <code>pos</code> * is greater then the length+1 of the <code>BLOB</code> value then the * behavior is undefined. Some JDBC drivers may throw a * <code>SQLException</code> while other drivers may support this * operation. * * @param pos the position in the <code>BLOB</code> object at which * to start writing; the first position is 1 * @param bytes the array of bytes to be written to the <code>BLOB</code> * value that this <code>Blob</code> object represents * @return the number of bytes written * @exception SQLException if there is an error accessing the * <code>BLOB</code> value or if pos is less than 1 * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @see #getBytes * @since 1.4 */ int setBytes(long pos, byte[] bytes) throws SQLException; /** {@collect.stats} * Writes all or part of the given <code>byte</code> array to the * <code>BLOB</code> value that this <code>Blob</code> object represents * and returns the number of bytes written. * Writing starts at position <code>pos</code> in the <code>BLOB</code> * value; <code>len</code> bytes from the given byte array are written. * The array of bytes will overwrite the existing bytes * in the <code>Blob</code> object starting at the position * <code>pos</code>. If the end of the <code>Blob</code> value is reached * while writing the array of bytes, then the length of the <code>Blob</code> * value will be increased to accomodate the extra bytes. * <p> * <b>Note:</b> If the value specified for <code>pos</code> * is greater then the length+1 of the <code>BLOB</code> value then the * behavior is undefined. Some JDBC drivers may throw a * <code>SQLException</code> while other drivers may support this * operation. * * @param pos the position in the <code>BLOB</code> object at which * to start writing; the first position is 1 * @param bytes the array of bytes to be written to this <code>BLOB</code> * object * @param offset the offset into the array <code>bytes</code> at which * to start reading the bytes to be set * @param len the number of bytes to be written to the <code>BLOB</code> * value from the array of bytes <code>bytes</code> * @return the number of bytes written * @exception SQLException if there is an error accessing the * <code>BLOB</code> value or if pos is less than 1 * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @see #getBytes * @since 1.4 */ int setBytes(long pos, byte[] bytes, int offset, int len) throws SQLException; /** {@collect.stats} * Retrieves a stream that can be used to write to the <code>BLOB</code> * value that this <code>Blob</code> object represents. The stream begins * at position <code>pos</code>. * The bytes written to the stream will overwrite the existing bytes * in the <code>Blob</code> object starting at the position * <code>pos</code>. If the end of the <code>Blob</code> value is reached * while writing to the stream, then the length of the <code>Blob</code> * value will be increased to accomodate the extra bytes. * <p> * <b>Note:</b> If the value specified for <code>pos</code> * is greater then the length+1 of the <code>BLOB</code> value then the * behavior is undefined. Some JDBC drivers may throw a * <code>SQLException</code> while other drivers may support this * operation. * * @param pos the position in the <code>BLOB</code> value at which * to start writing; the first position is 1 * @return a <code>java.io.OutputStream</code> object to which data can * be written * @exception SQLException if there is an error accessing the * <code>BLOB</code> value or if pos is less than 1 * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @see #getBinaryStream * @since 1.4 */ java.io.OutputStream setBinaryStream(long pos) throws SQLException; /** {@collect.stats} * Truncates the <code>BLOB</code> value that this <code>Blob</code> * object represents to be <code>len</code> bytes in length. * <p> * <b>Note:</b> If the value specified for <code>pos</code> * is greater then the length+1 of the <code>BLOB</code> value then the * behavior is undefined. Some JDBC drivers may throw a * <code>SQLException</code> while other drivers may support this * operation. * * @param len the length, in bytes, to which the <code>BLOB</code> value * that this <code>Blob</code> object represents should be truncated * @exception SQLException if there is an error accessing the * <code>BLOB</code> value or if len is less than 0 * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.4 */ void truncate(long len) throws SQLException; /** {@collect.stats} * This method frees the <code>Blob</code> object and releases the resources that * it holds. The object is invalid once the <code>free</code> * method is called. *<p> * After <code>free</code> has been called, any attempt to invoke a * method other than <code>free</code> will result in a <code>SQLException</code> * being thrown. If <code>free</code> is called multiple times, the subsequent * calls to <code>free</code> are treated as a no-op. *<p> * * @throws SQLException if an error occurs releasing * the Blob's resources * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.6 */ void free() throws SQLException; /** {@collect.stats} * Returns an <code>InputStream</code> object that contains a partial <code>Blob</code> value, * starting with the byte specified by pos, which is length bytes in length. * * @param pos the offset to the first byte of the partial value to be retrieved. * The first byte in the <code>Blob</code> is at position 1 * @param length the length in bytes of the partial value to be retrieved * @return <code>InputStream</code> through which the partial <code>Blob</code> value can be read. * @throws SQLException if pos is less than 1 or if pos is greater than the number of bytes * in the <code>Blob</code> or if pos + length is greater than the number of bytes * in the <code>Blob</code> * * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since 1.6 */ InputStream getBinaryStream(long pos, long length) throws SQLException; }
Java
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.sql; import java.sql.Clob; /** {@collect.stats} * The mapping in the Java<sup><font size=-2>TM</font></sup> programming language * for the SQL <code>NCLOB</code> type. * An SQL <code>NCLOB</code> is a built-in type * that stores a Character Large Object using the National Character Set * as a column value in a row of a database table. * <P>The <code>NClob</code> interface extends the <code>Clob</code> interface * which provides provides methods for getting the * length of an SQL <code>NCLOB</code> value, * for materializing a <code>NCLOB</code> value on the client, and for * searching for a substring or <code>NCLOB</code> object within a * <code>NCLOB</code> value. A <code>NClob</code> object, just like a <code>Clob</code> object, is valid for the duration * of the transaction in which it was created. * Methods in the interfaces {@link ResultSet}, * {@link CallableStatement}, and {@link PreparedStatement}, such as * <code>getNClob</code> and <code>setNClob</code> allow a programmer to * access an SQL <code>NCLOB</code> value. In addition, this interface * has methods for updating a <code>NCLOB</code> value. * <p> * All methods on the <code>NClob</code> interface must be fully implemented if the * JDBC driver supports the data type. * * @since 1.6 */ public interface NClob extends Clob { }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.io.*; import java.util.*; import java.lang.reflect.*; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.UnsupportedCharsetException; /** {@collect.stats} * The <code>XMLEncoder</code> class is a complementary alternative to * the <code>ObjectOutputStream</code> and can used to generate * a textual representation of a <em>JavaBean</em> in the same * way that the <code>ObjectOutputStream</code> can * be used to create binary representation of <code>Serializable</code> * objects. For example, the following fragment can be used to create * a textual representation the supplied <em>JavaBean</em> * and all its properties: * <pre> * XMLEncoder e = new XMLEncoder( * new BufferedOutputStream( * new FileOutputStream("Test.xml"))); * e.writeObject(new JButton("Hello, world")); * e.close(); * </pre> * Despite the similarity of their APIs, the <code>XMLEncoder</code> * class is exclusively designed for the purpose of archiving graphs * of <em>JavaBean</em>s as textual representations of their public * properties. Like Java source files, documents written this way * have a natural immunity to changes in the implementations of the classes * involved. The <code>ObjectOutputStream</code> continues to be recommended * for interprocess communication and general purpose serialization. * <p> * The <code>XMLEncoder</code> class provides a default denotation for * <em>JavaBean</em>s in which they are represented as XML documents * complying with version 1.0 of the XML specification and the * UTF-8 character encoding of the Unicode/ISO 10646 character set. * The XML documents produced by the <code>XMLEncoder</code> class are: * <ul> * <li> * <em>Portable and version resilient</em>: they have no dependencies * on the private implementation of any class and so, like Java source * files, they may be exchanged between environments which may have * different versions of some of the classes and between VMs from * different vendors. * <li> * <em>Structurally compact</em>: The <code>XMLEncoder</code> class * uses a <em>redundancy elimination</em> algorithm internally so that the * default values of a Bean's properties are not written to the stream. * <li> * <em>Fault tolerant</em>: Non-structural errors in the file, * caused either by damage to the file or by API changes * made to classes in an archive remain localized * so that a reader can report the error and continue to load the parts * of the document which were not affected by the error. * </ul> * <p> * Below is an example of an XML archive containing * some user interface components from the <em>swing</em> toolkit: * <pre> * &lt;?xml version="1.0" encoding="UTF-8"?&gt; * &lt;java version="1.0" class="java.beans.XMLDecoder"&gt; * &lt;object class="javax.swing.JFrame"&gt; * &lt;void property="name"&gt; * &lt;string&gt;frame1&lt;/string&gt; * &lt;/void&gt; * &lt;void property="bounds"&gt; * &lt;object class="java.awt.Rectangle"&gt; * &lt;int&gt;0&lt;/int&gt; * &lt;int&gt;0&lt;/int&gt; * &lt;int&gt;200&lt;/int&gt; * &lt;int&gt;200&lt;/int&gt; * &lt;/object&gt; * &lt;/void&gt; * &lt;void property="contentPane"&gt; * &lt;void method="add"&gt; * &lt;object class="javax.swing.JButton"&gt; * &lt;void property="label"&gt; * &lt;string&gt;Hello&lt;/string&gt; * &lt;/void&gt; * &lt;/object&gt; * &lt;/void&gt; * &lt;/void&gt; * &lt;void property="visible"&gt; * &lt;boolean&gt;true&lt;/boolean&gt; * &lt;/void&gt; * &lt;/object&gt; * &lt;/java&gt; * </pre> * The XML syntax uses the following conventions: * <ul> * <li> * Each element represents a method call. * <li> * The "object" tag denotes an <em>expression</em> whose value is * to be used as the argument to the enclosing element. * <li> * The "void" tag denotes a <em>statement</em> which will * be executed, but whose result will not be used as an * argument to the enclosing method. * <li> * Elements which contain elements use those elements as arguments, * unless they have the tag: "void". * <li> * The name of the method is denoted by the "method" attribute. * <li> * XML's standard "id" and "idref" attributes are used to make * references to previous expressions - so as to deal with * circularities in the object graph. * <li> * The "class" attribute is used to specify the target of a static * method or constructor explicitly; its value being the fully * qualified name of the class. * <li> * Elements with the "void" tag are executed using * the outer context as the target if no target is defined * by a "class" attribute. * <li> * Java's String class is treated specially and is * written &lt;string&gt;Hello, world&lt;/string&gt; where * the characters of the string are converted to bytes * using the UTF-8 character encoding. * </ul> * <p> * Although all object graphs may be written using just these three * tags, the following definitions are included so that common * data structures can be expressed more concisely: * <p> * <ul> * <li> * The default method name is "new". * <li> * A reference to a java class is written in the form * &lt;class&gt;javax.swing.JButton&lt;/class&gt;. * <li> * Instances of the wrapper classes for Java's primitive types are written * using the name of the primitive type as the tag. For example, an * instance of the <code>Integer</code> class could be written: * &lt;int&gt;123&lt;/int&gt;. Note that the <code>XMLEncoder</code> class * uses Java's reflection package in which the conversion between * Java's primitive types and their associated "wrapper classes" * is handled internally. The API for the <code>XMLEncoder</code> class * itself deals only with <code>Object</code>s. * <li> * In an element representing a nullary method whose name * starts with "get", the "method" attribute is replaced * with a "property" attribute whose value is given by removing * the "get" prefix and decapitalizing the result. * <li> * In an element representing a monadic method whose name * starts with "set", the "method" attribute is replaced * with a "property" attribute whose value is given by removing * the "set" prefix and decapitalizing the result. * <li> * In an element representing a method named "get" taking one * integer argument, the "method" attribute is replaced * with an "index" attribute whose value the value of the * first argument. * <li> * In an element representing a method named "set" taking two arguments, * the first of which is an integer, the "method" attribute is replaced * with an "index" attribute whose value the value of the * first argument. * <li> * A reference to an array is written using the "array" * tag. The "class" and "length" attributes specify the * sub-type of the array and its length respectively. * </ul> * *<p> * For more information you might also want to check out * <a href="http://java.sun.com/products/jfc/tsc/articles/persistence4">Using XMLEncoder</a>, * an article in <em>The Swing Connection.</em> * @see XMLDecoder * @see java.io.ObjectOutputStream * * @since 1.4 * * @author Philip Milne */ public class XMLEncoder extends Encoder { private static String encoding = "UTF-8"; private OutputStream out; private Object owner; private int indentation = 0; private boolean internal = false; private Map valueToExpression; private Map targetToStatementList; private boolean preambleWritten = false; private NameGenerator nameGenerator; private class ValueData { public int refs = 0; public boolean marked = false; // Marked -> refs > 0 unless ref was a target. public String name = null; public Expression exp = null; } /** {@collect.stats} * Creates a new output stream for sending <em>JavaBeans</em> * to the stream <code>out</code> using an XML encoding. * * @param out The stream to which the XML representation of * the objects will be sent. * * @see XMLDecoder#XMLDecoder(InputStream) */ public XMLEncoder(OutputStream out) { this.out = out; valueToExpression = new IdentityHashMap(); targetToStatementList = new IdentityHashMap(); nameGenerator = new NameGenerator(); } /** {@collect.stats} * Sets the owner of this encoder to <code>owner</code>. * * @param owner The owner of this encoder. * * @see #getOwner */ public void setOwner(Object owner) { this.owner = owner; writeExpression(new Expression(this, "getOwner", new Object[0])); } /** {@collect.stats} * Gets the owner of this encoder. * * @return The owner of this encoder. * * @see #setOwner */ public Object getOwner() { return owner; } /** {@collect.stats} * Write an XML representation of the specified object to the output. * * @param o The object to be written to the stream. * * @see XMLDecoder#readObject */ public void writeObject(Object o) { if (internal) { super.writeObject(o); } else { writeStatement(new Statement(this, "writeObject", new Object[]{o})); } } private Vector statementList(Object target) { Vector list = (Vector)targetToStatementList.get(target); if (list != null) { return list; } list = new Vector(); targetToStatementList.put(target, list); return list; } private void mark(Object o, boolean isArgument) { if (o == null || o == this) { return; } ValueData d = getValueData(o); Expression exp = d.exp; // Do not mark liternal strings. Other strings, which might, // for example, come from resource bundles should still be marked. if (o.getClass() == String.class && exp == null) { return; } // Bump the reference counts of all arguments if (isArgument) { d.refs++; } if (d.marked) { return; } d.marked = true; Object target = exp.getTarget(); if (!(target instanceof Class)) { statementList(target).add(exp); // Pending: Why does the reference count need to // be incremented here? d.refs++; } mark(exp); } private void mark(Statement stm) { Object[] args = stm.getArguments(); for (int i = 0; i < args.length; i++) { Object arg = args[i]; mark(arg, true); } mark(stm.getTarget(), false); } /** {@collect.stats} * Records the Statement so that the Encoder will * produce the actual output when the stream is flushed. * <P> * This method should only be invoked within the context * of initializing a persistence delegate. * * @param oldStm The statement that will be written * to the stream. * @see java.beans.PersistenceDelegate#initialize */ public void writeStatement(Statement oldStm) { // System.out.println("XMLEncoder::writeStatement: " + oldStm); boolean internal = this.internal; this.internal = true; try { super.writeStatement(oldStm); /* Note we must do the mark first as we may require the results of previous values in this context for this statement. Test case is: os.setOwner(this); os.writeObject(this); */ mark(oldStm); statementList(oldStm.getTarget()).add(oldStm); } catch (Exception e) { getExceptionListener().exceptionThrown(new Exception("XMLEncoder: discarding statement " + oldStm, e)); } this.internal = internal; } /** {@collect.stats} * Records the Expression so that the Encoder will * produce the actual output when the stream is flushed. * <P> * This method should only be invoked within the context of * initializing a persistence delegate or setting up an encoder to * read from a resource bundle. * <P> * For more information about using resource bundles with the * XMLEncoder, see * http://java.sun.com/products/jfc/tsc/articles/persistence4/#i18n * * @param oldExp The expression that will be written * to the stream. * @see java.beans.PersistenceDelegate#initialize */ public void writeExpression(Expression oldExp) { boolean internal = this.internal; this.internal = true; Object oldValue = getValue(oldExp); if (get(oldValue) == null || (oldValue instanceof String && !internal)) { getValueData(oldValue).exp = oldExp; super.writeExpression(oldExp); } this.internal = internal; } /** {@collect.stats} * This method writes out the preamble associated with the * XML encoding if it has not been written already and * then writes out all of the values that been * written to the stream since the last time <code>flush</code> * was called. After flushing, all internal references to the * values that were written to this stream are cleared. */ public void flush() { if (!preambleWritten) { // Don't do this in constructor - it throws ... pending. writeln("<?xml version=" + quote("1.0") + " encoding=" + quote(encoding) + "?>"); writeln("<java version=" + quote(System.getProperty("java.version")) + " class=" + quote(XMLDecoder.class.getName()) + ">"); preambleWritten = true; } indentation++; Vector roots = statementList(this); for(int i = 0; i < roots.size(); i++) { Statement s = (Statement)roots.get(i); if ("writeObject".equals(s.getMethodName())) { outputValue(s.getArguments()[0], this, true); } else { outputStatement(s, this, false); } } indentation--; try { out.flush(); } catch (IOException e) { getExceptionListener().exceptionThrown(e); } clear(); } void clear() { super.clear(); nameGenerator.clear(); valueToExpression.clear(); targetToStatementList.clear(); } /** {@collect.stats} * This method calls <code>flush</code>, writes the closing * postamble and then closes the output stream associated * with this stream. */ public void close() { flush(); writeln("</java>"); try { out.close(); } catch (IOException e) { getExceptionListener().exceptionThrown(e); } } private String quote(String s) { return "\"" + s + "\""; } private ValueData getValueData(Object o) { ValueData d = (ValueData)valueToExpression.get(o); if (d == null) { d = new ValueData(); valueToExpression.put(o, d); } return d; } /** {@collect.stats} * Returns <code>true</code> if the argument, * a Unicode code point, is valid in XML documents. * Unicode characters fit into the low sixteen bits of a Unicode code point, * and pairs of Unicode <em>surrogate characters</em> can be combined * to encode Unicode code point in documents containing only Unicode. * (The <code>char</code> datatype in the Java Programming Language * represents Unicode characters, including unpaired surrogates.) * <par> * [2] Char ::= #x0009 | #x000A | #x000D * | [#x0020-#xD7FF] * | [#xE000-#xFFFD] * | [#x10000-#x10ffff] * </par> * * @param code the 32-bit Unicode code point being tested * @return <code>true</code> if the Unicode code point is valid, * <code>false</code> otherwise */ private static boolean isValidCharCode(int code) { return (0x0020 <= code && code <= 0xD7FF) || (0x000A == code) || (0x0009 == code) || (0x000D == code) || (0xE000 <= code && code <= 0xFFFD) || (0x10000 <= code && code <= 0x10ffff); } private void writeln(String exp) { try { StringBuilder sb = new StringBuilder(); for(int i = 0; i < indentation; i++) { sb.append(' '); } sb.append(exp); sb.append('\n'); this.out.write(sb.toString().getBytes(encoding)); } catch (IOException e) { getExceptionListener().exceptionThrown(e); } } private void outputValue(Object value, Object outer, boolean isArgument) { if (value == null) { writeln("<null/>"); return; } if (value instanceof Class) { writeln("<class>" + ((Class)value).getName() + "</class>"); return; } ValueData d = getValueData(value); if (d.exp != null) { Object target = d.exp.getTarget(); String methodName = d.exp.getMethodName(); if (target == null || methodName == null) { throw new NullPointerException((target == null ? "target" : "methodName") + " should not be null"); } if (target instanceof Field && methodName.equals("get")) { Field f = (Field)target; writeln("<object class=" + quote(f.getDeclaringClass().getName()) + " field=" + quote(f.getName()) + "/>"); return; } Class primitiveType = ReflectionUtils.primitiveTypeFor(value.getClass()); if (primitiveType != null && target == value.getClass() && methodName.equals("new")) { String primitiveTypeName = primitiveType.getName(); // Make sure that character types are quoted correctly. if (primitiveType == Character.TYPE) { char code = ((Character) value).charValue(); if (!isValidCharCode(code)) { writeln(createString(code)); return; } value = quoteCharCode(code); if (value == null) { value = Character.valueOf(code); } } writeln("<" + primitiveTypeName + ">" + value + "</" + primitiveTypeName + ">"); return; } } else if (value instanceof String) { writeln(createString((String) value)); return; } if (d.name != null) { writeln("<object idref=" + quote(d.name) + "/>"); return; } outputStatement(d.exp, outer, isArgument); } private static String quoteCharCode(int code) { switch(code) { case '&': return "&amp;"; case '<': return "&lt;"; case '>': return "&gt;"; case '"': return "&quot;"; case '\'': return "&apos;"; case '\r': return "&#13;"; default: return null; } } private static String createString(int code) { return "<char code=\"#" + Integer.toString(code, 16) + "\"/>"; } private String createString(String string) { CharsetEncoder encoder = Charset.forName(encoding).newEncoder(); StringBuilder sb = new StringBuilder(); sb.append("<string>"); int index = 0; while (index < string.length()) { int point = string.codePointAt(index); int count = Character.charCount(point); if (isValidCharCode(point) && encoder.canEncode(string.substring(index, index + count))) { String value = quoteCharCode(point); if (value != null) { sb.append(value); } else { sb.appendCodePoint(point); } index += count; } else { sb.append(createString(string.charAt(index))); index++; } /* String value = isValidCharCode(point) && encoder.canEncode(string.substring(index, index + count)) ? quoteCharCode(point) : createString(point); if (value != null) { sb.append(value); } else { sb.appendCodePoint(point); } index += count; */ } sb.append("</string>"); return sb.toString(); } private void outputStatement(Statement exp, Object outer, boolean isArgument) { Object target = exp.getTarget(); String methodName = exp.getMethodName(); if (target == null || methodName == null) { throw new NullPointerException((target == null ? "target" : "methodName") + " should not be null"); } Object[] args = exp.getArguments(); boolean expression = exp.getClass() == Expression.class; Object value = (expression) ? getValue((Expression)exp) : null; String tag = (expression && isArgument) ? "object" : "void"; String attributes = ""; ValueData d = getValueData(value); if (expression) { if (d.refs > 1) { String instanceName = nameGenerator.instanceName(value); d.name = instanceName; attributes = attributes + " id=" + quote(instanceName); } } // Special cases for targets. if (target == outer) { } else if (target == Array.class && methodName.equals("newInstance")) { tag = "array"; attributes = attributes + " class=" + quote(((Class)args[0]).getName()); attributes = attributes + " length=" + quote(args[1].toString()); args = new Object[]{}; } else if (target.getClass() == Class.class) { attributes = attributes + " class=" + quote(((Class)target).getName()); } else { d.refs = 2; getValueData(target).refs++; outputValue(target, outer, false); if (isArgument) { outputValue(value, outer, false); } return; } // Special cases for methods. if ((!expression && methodName.equals("set") && args.length == 2 && args[0] instanceof Integer) || (expression && methodName.equals("get") && args.length == 1 && args[0] instanceof Integer)) { attributes = attributes + " index=" + quote(args[0].toString()); args = (args.length == 1) ? new Object[]{} : new Object[]{args[1]}; } else if ((!expression && methodName.startsWith("set") && args.length == 1) || (expression && methodName.startsWith("get") && args.length == 0)) { attributes = attributes + " property=" + quote(Introspector.decapitalize(methodName.substring(3))); } else if (!methodName.equals("new") && !methodName.equals("newInstance")) { attributes = attributes + " method=" + quote(methodName); } Vector statements = statementList(value); // Use XML's short form when there is no body. if (args.length == 0 && statements.size() == 0) { writeln("<" + tag + attributes + "/>"); return; } writeln("<" + tag + attributes + ">"); indentation++; for(int i = 0; i < args.length; i++) { outputValue(args[i], null, true); } for(int i = 0; i < statements.size(); i++) { Statement s = (Statement)statements.get(i); outputStatement(s, value, false); } indentation--; writeln("</" + tag + ">"); } }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.io.Serializable; import java.io.ObjectStreamField; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.IOException; import java.util.Hashtable; import java.util.Map.Entry; /** {@collect.stats} * This is a utility class that can be used by beans that support constrained * properties. You can use an instance of this class as a member field * of your bean and delegate various work to it. * * This class is serializable. When it is serialized it will save * (and restore) any listeners that are themselves serializable. Any * non-serializable listeners will be skipped during serialization. */ public class VetoableChangeSupport implements Serializable { private VetoableChangeListenerMap map = new VetoableChangeListenerMap(); /** {@collect.stats} * Constructs a <code>VetoableChangeSupport</code> object. * * @param sourceBean The bean to be given as the source for any events. */ public VetoableChangeSupport(Object sourceBean) { if (sourceBean == null) { throw new NullPointerException(); } source = sourceBean; } /** {@collect.stats} * Add a VetoableChangeListener to the listener list. * The listener is registered for all properties. * The same listener object may be added more than once, and will be called * as many times as it is added. * If <code>listener</code> is null, no exception is thrown and no action * is taken. * * @param listener The VetoableChangeListener to be added */ public void addVetoableChangeListener(VetoableChangeListener listener) { if (listener == null) { return; } if (listener instanceof VetoableChangeListenerProxy) { VetoableChangeListenerProxy proxy = (VetoableChangeListenerProxy)listener; // Call two argument add method. addVetoableChangeListener(proxy.getPropertyName(), (VetoableChangeListener)proxy.getListener()); } else { this.map.add(null, listener); } } /** {@collect.stats} * Remove a VetoableChangeListener from the listener list. * This removes a VetoableChangeListener that was registered * for all properties. * If <code>listener</code> was added more than once to the same event * source, it will be notified one less time after being removed. * If <code>listener</code> is null, or was never added, no exception is * thrown and no action is taken. * * @param listener The VetoableChangeListener to be removed */ public void removeVetoableChangeListener(VetoableChangeListener listener) { if (listener == null) { return; } if (listener instanceof VetoableChangeListenerProxy) { VetoableChangeListenerProxy proxy = (VetoableChangeListenerProxy)listener; // Call two argument remove method. removeVetoableChangeListener(proxy.getPropertyName(), (VetoableChangeListener)proxy.getListener()); } else { this.map.remove(null, listener); } } /** {@collect.stats} * Returns the list of VetoableChangeListeners. If named vetoable change listeners * were added, then VetoableChangeListenerProxy wrappers will returned * <p> * @return List of VetoableChangeListeners and VetoableChangeListenerProxys * if named property change listeners were added. * @since 1.4 */ public VetoableChangeListener[] getVetoableChangeListeners(){ return this.map.getListeners(); } /** {@collect.stats} * Add a VetoableChangeListener for a specific property. The listener * will be invoked only when a call on fireVetoableChange names that * specific property. * The same listener object may be added more than once. For each * property, the listener will be invoked the number of times it was added * for that property. * If <code>propertyName</code> or <code>listener</code> is null, no * exception is thrown and no action is taken. * * @param propertyName The name of the property to listen on. * @param listener The VetoableChangeListener to be added */ public void addVetoableChangeListener( String propertyName, VetoableChangeListener listener) { if (listener == null || propertyName == null) { return; } listener = this.map.extract(listener); if (listener != null) { this.map.add(propertyName, listener); } } /** {@collect.stats} * Remove a VetoableChangeListener for a specific property. * If <code>listener</code> was added more than once to the same event * source for the specified property, it will be notified one less time * after being removed. * If <code>propertyName</code> is null, no exception is thrown and no * action is taken. * If <code>listener</code> is null, or was never added for the specified * property, no exception is thrown and no action is taken. * * @param propertyName The name of the property that was listened on. * @param listener The VetoableChangeListener to be removed */ public void removeVetoableChangeListener( String propertyName, VetoableChangeListener listener) { if (listener == null || propertyName == null) { return; } listener = this.map.extract(listener); if (listener != null) { this.map.remove(propertyName, listener); } } /** {@collect.stats} * Returns an array of all the listeners which have been associated * with the named property. * * @param propertyName The name of the property being listened to * @return all the <code>VetoableChangeListeners</code> associated with * the named property. If no such listeners have been added, * or if <code>propertyName</code> is null, an empty array is * returned. * @since 1.4 */ public VetoableChangeListener[] getVetoableChangeListeners(String propertyName) { return this.map.getListeners(propertyName); } /** {@collect.stats} * Report a vetoable property update to any registered listeners. If * anyone vetos the change, then fire a new event reverting everyone to * the old value and then rethrow the PropertyVetoException. * <p> * No event is fired if old and new are equal and non-null. * * @param propertyName The programmatic name of the property * that is about to change.. * @param oldValue The old value of the property. * @param newValue The new value of the property. * @exception PropertyVetoException if the recipient wishes the property * change to be rolled back. */ public void fireVetoableChange(String propertyName, Object oldValue, Object newValue) throws PropertyVetoException { if (oldValue != null && newValue != null && oldValue.equals(newValue)) { return; } PropertyChangeEvent evt = new PropertyChangeEvent(source, propertyName, oldValue, newValue); fireVetoableChange(evt); } /** {@collect.stats} * Report a int vetoable property update to any registered listeners. * No event is fired if old and new are equal. * <p> * This is merely a convenience wrapper around the more general * fireVetoableChange method that takes Object values. * * @param propertyName The programmatic name of the property * that is about to change. * @param oldValue The old value of the property. * @param newValue The new value of the property. */ public void fireVetoableChange(String propertyName, int oldValue, int newValue) throws PropertyVetoException { if (oldValue == newValue) { return; } fireVetoableChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } /** {@collect.stats} * Report a boolean vetoable property update to any registered listeners. * No event is fired if old and new are equal. * <p> * This is merely a convenience wrapper around the more general * fireVetoableChange method that takes Object values. * * @param propertyName The programmatic name of the property * that is about to change. * @param oldValue The old value of the property. * @param newValue The new value of the property. */ public void fireVetoableChange(String propertyName, boolean oldValue, boolean newValue) throws PropertyVetoException { if (oldValue == newValue) { return; } fireVetoableChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } /** {@collect.stats} * Fire a vetoable property update to any registered listeners. If * anyone vetos the change, then fire a new event reverting everyone to * the old value and then rethrow the PropertyVetoException. * <p> * No event is fired if old and new are equal and non-null. * * @param evt The PropertyChangeEvent to be fired. * @exception PropertyVetoException if the recipient wishes the property * change to be rolled back. */ public void fireVetoableChange(PropertyChangeEvent evt) throws PropertyVetoException { Object oldValue = evt.getOldValue(); Object newValue = evt.getNewValue(); String propertyName = evt.getPropertyName(); if (oldValue != null && newValue != null && oldValue.equals(newValue)) { return; } VetoableChangeListener[] common = this.map.get(null); VetoableChangeListener[] named = (propertyName != null) ? this.map.get(propertyName) : null; fire(common, evt); fire(named, evt); } private void fire(VetoableChangeListener[] listeners, PropertyChangeEvent event) throws PropertyVetoException { if (listeners != null) { VetoableChangeListener current = null; try { for (VetoableChangeListener listener : listeners) { current = listener; listener.vetoableChange(event); } } catch (PropertyVetoException veto) { // Create an event to revert everyone to the old value. event = new PropertyChangeEvent( this.source, event.getPropertyName(), event.getNewValue(), event.getOldValue() ); for (VetoableChangeListener listener : listeners) { try { listener.vetoableChange(event); } catch (PropertyVetoException ex) { // We just ignore exceptions that occur during reversions. } } // And now rethrow the PropertyVetoException. throw veto; } } } /** {@collect.stats} * Check if there are any listeners for a specific property, including * those registered on all properties. If <code>propertyName</code> * is null, only check for listeners registered on all properties. * * @param propertyName the property name. * @return true if there are one or more listeners for the given property */ public boolean hasListeners(String propertyName) { return this.map.hasListeners(propertyName); } /** {@collect.stats} * @serialData Null terminated list of <code>VetoableChangeListeners</code>. * <p> * At serialization time we skip non-serializable listeners and * only serialize the serializable listeners. */ private void writeObject(ObjectOutputStream s) throws IOException { Hashtable<String, VetoableChangeSupport> children = null; VetoableChangeListener[] listeners = null; synchronized (this.map) { for (Entry<String, VetoableChangeListener[]> entry : this.map.getEntries()) { String property = entry.getKey(); if (property == null) { listeners = entry.getValue(); } else { if (children == null) { children = new Hashtable<String, VetoableChangeSupport>(); } VetoableChangeSupport vcs = new VetoableChangeSupport(this.source); vcs.map.set(null, entry.getValue()); children.put(property, vcs); } } } ObjectOutputStream.PutField fields = s.putFields(); fields.put("children", children); fields.put("source", this.source); fields.put("vetoableChangeSupportSerializedDataVersion", 2); s.writeFields(); if (listeners != null) { for (VetoableChangeListener l : listeners) { if (l instanceof Serializable) { s.writeObject(l); } } } s.writeObject(null); } private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { this.map = new VetoableChangeListenerMap(); ObjectInputStream.GetField fields = s.readFields(); Hashtable<String, VetoableChangeSupport> children = (Hashtable<String, VetoableChangeSupport>) fields.get("children", null); this.source = fields.get("source", null); fields.get("vetoableChangeSupportSerializedDataVersion", 2); Object listenerOrNull; while (null != (listenerOrNull = s.readObject())) { this.map.add(null, (VetoableChangeListener)listenerOrNull); } if (children != null) { for (Entry<String, VetoableChangeSupport> entry : children.entrySet()) { for (VetoableChangeListener listener : entry.getValue().getVetoableChangeListeners()) { this.map.add(entry.getKey(), listener); } } } } /** {@collect.stats} * The object to be provided as the "source" for any generated events. */ private Object source; /** {@collect.stats} * @serialField children Hashtable * @serialField source Object * @serialField propertyChangeSupportSerializedDataVersion int */ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField("children", Hashtable.class), new ObjectStreamField("source", Object.class), new ObjectStreamField("vetoableChangeSupportSerializedDataVersion", Integer.TYPE) }; /** {@collect.stats} * Serialization version ID, so we're compatible with JDK 1.1 */ static final long serialVersionUID = -5090210921595982017L; /** {@collect.stats} * This is a {@link ChangeListenerMap ChangeListenerMap} implementation * that works with {@link VetoableChangeListener VetoableChangeListener} objects. */ private static final class VetoableChangeListenerMap extends ChangeListenerMap<VetoableChangeListener> { private static final VetoableChangeListener[] EMPTY = {}; /** {@collect.stats} * Creates an array of {@link VetoableChangeListener VetoableChangeListener} objects. * This method uses the same instance of the empty array * when {@code length} equals {@code 0}. * * @param length the array length * @return an array with specified length */ @Override protected VetoableChangeListener[] newArray(int length) { return (0 < length) ? new VetoableChangeListener[length] : EMPTY; } /** {@collect.stats} * Creates a {@link VetoableChangeListenerProxy VetoableChangeListenerProxy} * object for the specified property. * * @param name the name of the property to listen on * @param listener the listener to process events * @return a {@code VetoableChangeListenerProxy} object */ @Override protected VetoableChangeListener newProxy(String name, VetoableChangeListener listener) { return new VetoableChangeListenerProxy(name, listener); } } }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * Thrown when an exception happens during Introspection. * <p> * Typical causes include not being able to map a string class name * to a Class object, not being able to resolve a string method name, * or specifying a method name that has the wrong type signature for * its intended use. */ public class IntrospectionException extends Exception { /** {@collect.stats} * Constructs an <code>IntrospectionException</code> with a * detailed message. * * @param mess Descriptive message */ public IntrospectionException(String mess) { super(mess); } }
Java
/* * Copyright (c) 1996, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * A customizer class provides a complete custom GUI for customizing * a target Java Bean. * <P> * Each customizer should inherit from the java.awt.Component class so * it can be instantiated inside an AWT dialog or panel. * <P> * Each customizer should have a null constructor. */ public interface Customizer { /** {@collect.stats} * Set the object to be customized. This method should be called only * once, before the Customizer has been added to any parent AWT container. * @param bean The object to be customized. */ void setObject(Object bean); /** {@collect.stats} * Register a listener for the PropertyChange event. The customizer * should fire a PropertyChange event whenever it changes the target * bean in a way that might require the displayed properties to be * refreshed. * * @param listener An object to be invoked when a PropertyChange * event is fired. */ void addPropertyChangeListener(PropertyChangeListener listener); /** {@collect.stats} * Remove a listener for the PropertyChange event. * * @param listener The PropertyChange listener to be removed. */ void removePropertyChangeListener(PropertyChangeListener listener); }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * The PersistenceDelegate class takes the responsibility * for expressing the state of an instance of a given class * in terms of the methods in the class's public API. Instead * of associating the responsibility of persistence with * the class itself as is done, for example, by the * <code>readObject</code> and <code>writeObject</code> * methods used by the <code>ObjectOutputStream</code>, streams like * the <code>XMLEncoder</code> which * use this delegation model can have their behavior controlled * independently of the classes themselves. Normally, the class * is the best place to put such information and conventions * can easily be expressed in this delegation scheme to do just that. * Sometimes however, it is the case that a minor problem * in a single class prevents an entire object graph from * being written and this can leave the application * developer with no recourse but to attempt to shadow * the problematic classes locally or use alternative * persistence techniques. In situations like these, the * delegation model gives a relatively clean mechanism for * the application developer to intervene in all parts of the * serialization process without requiring that modifications * be made to the implementation of classes which are not part * of the application itself. * <p> * In addition to using a delegation model, this persistence * scheme differs from traditional serialization schemes * in requiring an analog of the <code>writeObject</code> * method without a corresponding <code>readObject</code> * method. The <code>writeObject</code> analog encodes each * instance in terms of its public API and there is no need to * define a <code>readObject</code> analog * since the procedure for reading the serialized form * is defined by the semantics of method invocation as laid * out in the Java Language Specification. * Breaking the dependency between <code>writeObject</code> * and <code>readObject</code> implementations, which may * change from version to version, is the key factor * in making the archives produced by this technique immune * to changes in the private implementations of the classes * to which they refer. * <p> * A persistence delegate, may take control of all * aspects of the persistence of an object including: * <ul> * <li> * Deciding whether or not an instance can be mutated * into another instance of the same class. * <li> * Instantiating the object, either by calling a * public constructor or a public factory method. * <li> * Performing the initialization of the object. * </ul> * @see XMLEncoder * * @since 1.4 * * @author Philip Milne */ public abstract class PersistenceDelegate { /** {@collect.stats} * The <code>writeObject</code> is a single entry point to the persistence * and is used by a <code>Encoder</code> in the traditional * mode of delegation. Although this method is not final, * it should not need to be subclassed under normal circumstances. * <p> * This implementation first checks to see if the stream * has already encountered this object. Next the * <code>mutatesTo</code> method is called to see if * that candidate returned from the stream can * be mutated into an accurate copy of <code>oldInstance</code>. * If it can, the <code>initialize</code> method is called to * perform the initialization. If not, the candidate is removed * from the stream, and the <code>instantiate</code> method * is called to create a new candidate for this object. * * @param oldInstance The instance that will be created by this expression. * @param out The stream to which this expression will be written. */ public void writeObject(Object oldInstance, Encoder out) { Object newInstance = out.get(oldInstance); if (!mutatesTo(oldInstance, newInstance)) { out.remove(oldInstance); out.writeExpression(instantiate(oldInstance, out)); } else { initialize(oldInstance.getClass(), oldInstance, newInstance, out); } } /** {@collect.stats} * Returns true if an <em>equivalent</em> copy of <code>oldInstance</code> may be * created by applying a series of statements to <code>newInstance</code>. * In the specification of this method, we mean by equivalent that the modified instance * is indistinguishable from <code>oldInstance</code> in the behavior * of the relevant methods in its public API. [Note: we use the * phrase <em>relevant</em> methods rather than <em>all</em> methods * here only because, to be strictly correct, methods like <code>hashCode</code> * and <code>toString</code> prevent most classes from producing truly * indistinguishable copies of their instances]. * <p> * The default behavior returns <code>true</code> * if the classes of the two instances are the same. * * @param oldInstance The instance to be copied. * @param newInstance The instance that is to be modified. * @return True if an equivalent copy of <code>newInstance</code> may be * created by applying a series of mutations to <code>oldInstance</code>. */ protected boolean mutatesTo(Object oldInstance, Object newInstance) { return (newInstance != null && oldInstance != null && oldInstance.getClass() == newInstance.getClass()); } /** {@collect.stats} * Returns an expression whose value is <code>oldInstance</code>. * This method is used to characterize the constructor * or factory method that should be used to create the given object. * For example, the <code>instantiate</code> method of the persistence * delegate for the <code>Field</code> class could be defined as follows: * <pre> * Field f = (Field)oldInstance; * return new Expression(f, f.getDeclaringClass(), "getField", new Object[]{f.getName()}); * </pre> * Note that we declare the value of the returned expression so that * the value of the expression (as returned by <code>getValue</code>) * will be identical to <code>oldInstance</code>. * * @param oldInstance The instance that will be created by this expression. * @param out The stream to which this expression will be written. * @return An expression whose value is <code>oldInstance</code>. */ protected abstract Expression instantiate(Object oldInstance, Encoder out); /** {@collect.stats} * Produce a series of statements with side effects on <code>newInstance</code> * so that the new instance becomes <em>equivalent</em> to <code>oldInstance</code>. * In the specification of this method, we mean by equivalent that, after the method * returns, the modified instance is indistinguishable from * <code>newInstance</code> in the behavior of all methods in its * public API. * <p> * The implementation typically achieves this goal by producing a series of * "what happened" statements involving the <code>oldInstance</code> * and its publicly available state. These statements are sent * to the output stream using its <code>writeExpression</code> * method which returns an expression involving elements in * a cloned environment simulating the state of an input stream during * reading. Each statement returned will have had all instances * the old environment replaced with objects which exist in the new * one. In particular, references to the target of these statements, * which start out as references to <code>oldInstance</code> are returned * as references to the <code>newInstance</code> instead. * Executing these statements effects an incremental * alignment of the state of the two objects as a series of * modifications to the objects in the new environment. * By the time the initialize method returns it should be impossible * to tell the two instances apart by using their public APIs. * Most importantly, the sequence of steps that were used to make * these objects appear equivalent will have been recorded * by the output stream and will form the actual output when * the stream is flushed. * <p> * The default implementation, calls the <code>initialize</code> * method of the type's superclass. * * @param oldInstance The instance to be copied. * @param newInstance The instance that is to be modified. * @param out The stream to which any initialization statements should be written. */ protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { Class superType = type.getSuperclass(); PersistenceDelegate info = out.getPersistenceDelegate(superType); info.initialize(superType, oldInstance, newInstance, out); } }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.io.Serializable; import java.io.ObjectStreamField; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.IOException; import java.util.Hashtable; import java.util.Map.Entry; /** {@collect.stats} * This is a utility class that can be used by beans that support bound * properties. You can use an instance of this class as a member field * of your bean and delegate various work to it. * * This class is serializable. When it is serialized it will save * (and restore) any listeners that are themselves serializable. Any * non-serializable listeners will be skipped during serialization. */ public class PropertyChangeSupport implements Serializable { private PropertyChangeListenerMap map = new PropertyChangeListenerMap(); /** {@collect.stats} * Constructs a <code>PropertyChangeSupport</code> object. * * @param sourceBean The bean to be given as the source for any events. */ public PropertyChangeSupport(Object sourceBean) { if (sourceBean == null) { throw new NullPointerException(); } source = sourceBean; } /** {@collect.stats} * Add a PropertyChangeListener to the listener list. * The listener is registered for all properties. * The same listener object may be added more than once, and will be called * as many times as it is added. * If <code>listener</code> is null, no exception is thrown and no action * is taken. * * @param listener The PropertyChangeListener to be added */ public void addPropertyChangeListener(PropertyChangeListener listener) { if (listener == null) { return; } if (listener instanceof PropertyChangeListenerProxy) { PropertyChangeListenerProxy proxy = (PropertyChangeListenerProxy)listener; // Call two argument add method. addPropertyChangeListener(proxy.getPropertyName(), (PropertyChangeListener)proxy.getListener()); } else { this.map.add(null, listener); } } /** {@collect.stats} * Remove a PropertyChangeListener from the listener list. * This removes a PropertyChangeListener that was registered * for all properties. * If <code>listener</code> was added more than once to the same event * source, it will be notified one less time after being removed. * If <code>listener</code> is null, or was never added, no exception is * thrown and no action is taken. * * @param listener The PropertyChangeListener to be removed */ public void removePropertyChangeListener(PropertyChangeListener listener) { if (listener == null) { return; } if (listener instanceof PropertyChangeListenerProxy) { PropertyChangeListenerProxy proxy = (PropertyChangeListenerProxy)listener; // Call two argument remove method. removePropertyChangeListener(proxy.getPropertyName(), (PropertyChangeListener)proxy.getListener()); } else { this.map.remove(null, listener); } } /** {@collect.stats} * Returns an array of all the listeners that were added to the * PropertyChangeSupport object with addPropertyChangeListener(). * <p> * If some listeners have been added with a named property, then * the returned array will be a mixture of PropertyChangeListeners * and <code>PropertyChangeListenerProxy</code>s. If the calling * method is interested in distinguishing the listeners then it must * test each element to see if it's a * <code>PropertyChangeListenerProxy</code>, perform the cast, and examine * the parameter. * * <pre> * PropertyChangeListener[] listeners = bean.getPropertyChangeListeners(); * for (int i = 0; i < listeners.length; i++) { * if (listeners[i] instanceof PropertyChangeListenerProxy) { * PropertyChangeListenerProxy proxy = * (PropertyChangeListenerProxy)listeners[i]; * if (proxy.getPropertyName().equals("foo")) { * // proxy is a PropertyChangeListener which was associated * // with the property named "foo" * } * } * } *</pre> * * @see PropertyChangeListenerProxy * @return all of the <code>PropertyChangeListeners</code> added or an * empty array if no listeners have been added * @since 1.4 */ public PropertyChangeListener[] getPropertyChangeListeners() { return this.map.getListeners(); } /** {@collect.stats} * Add a PropertyChangeListener for a specific property. The listener * will be invoked only when a call on firePropertyChange names that * specific property. * The same listener object may be added more than once. For each * property, the listener will be invoked the number of times it was added * for that property. * If <code>propertyName</code> or <code>listener</code> is null, no * exception is thrown and no action is taken. * * @param propertyName The name of the property to listen on. * @param listener The PropertyChangeListener to be added */ public void addPropertyChangeListener( String propertyName, PropertyChangeListener listener) { if (listener == null || propertyName == null) { return; } listener = this.map.extract(listener); if (listener != null) { this.map.add(propertyName, listener); } } /** {@collect.stats} * Remove a PropertyChangeListener for a specific property. * If <code>listener</code> was added more than once to the same event * source for the specified property, it will be notified one less time * after being removed. * If <code>propertyName</code> is null, no exception is thrown and no * action is taken. * If <code>listener</code> is null, or was never added for the specified * property, no exception is thrown and no action is taken. * * @param propertyName The name of the property that was listened on. * @param listener The PropertyChangeListener to be removed */ public void removePropertyChangeListener( String propertyName, PropertyChangeListener listener) { if (listener == null || propertyName == null) { return; } listener = this.map.extract(listener); if (listener != null) { this.map.remove(propertyName, listener); } } /** {@collect.stats} * Returns an array of all the listeners which have been associated * with the named property. * * @param propertyName The name of the property being listened to * @return all of the <code>PropertyChangeListeners</code> associated with * the named property. If no such listeners have been added, * or if <code>propertyName</code> is null, an empty array is * returned. * @since 1.4 */ public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) { return this.map.getListeners(propertyName); } /** {@collect.stats} * Report a bound property update to any registered listeners. * No event is fired if old and new are equal and non-null. * * <p> * This is merely a convenience wrapper around the more general * firePropertyChange method that takes {@code * PropertyChangeEvent} value. * * @param propertyName The programmatic name of the property * that was changed. * @param oldValue The old value of the property. * @param newValue The new value of the property. */ public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { if (oldValue != null && newValue != null && oldValue.equals(newValue)) { return; } firePropertyChange(new PropertyChangeEvent(source, propertyName, oldValue, newValue)); } /** {@collect.stats} * Report an int bound property update to any registered listeners. * No event is fired if old and new are equal. * <p> * This is merely a convenience wrapper around the more general * firePropertyChange method that takes Object values. * * @param propertyName The programmatic name of the property * that was changed. * @param oldValue The old value of the property. * @param newValue The new value of the property. */ public void firePropertyChange(String propertyName, int oldValue, int newValue) { if (oldValue == newValue) { return; } firePropertyChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } /** {@collect.stats} * Report a boolean bound property update to any registered listeners. * No event is fired if old and new are equal. * <p> * This is merely a convenience wrapper around the more general * firePropertyChange method that takes Object values. * * @param propertyName The programmatic name of the property * that was changed. * @param oldValue The old value of the property. * @param newValue The new value of the property. */ public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { if (oldValue == newValue) { return; } firePropertyChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } /** {@collect.stats} * Fire an existing PropertyChangeEvent to any registered listeners. * No event is fired if the given event's old and new values are * equal and non-null. * @param evt The PropertyChangeEvent object. */ public void firePropertyChange(PropertyChangeEvent evt) { Object oldValue = evt.getOldValue(); Object newValue = evt.getNewValue(); String propertyName = evt.getPropertyName(); if (oldValue != null && newValue != null && oldValue.equals(newValue)) { return; } PropertyChangeListener[] common = this.map.get(null); PropertyChangeListener[] named = (propertyName != null) ? this.map.get(propertyName) : null; fire(common, evt); fire(named, evt); } private void fire(PropertyChangeListener[] listeners, PropertyChangeEvent event) { if (listeners != null) { for (PropertyChangeListener listener : listeners) { listener.propertyChange(event); } } } /** {@collect.stats} * Report a bound indexed property update to any registered * listeners. * <p> * No event is fired if old and new values are equal * and non-null. * * <p> * This is merely a convenience wrapper around the more general * firePropertyChange method that takes {@code PropertyChangeEvent} value. * * @param propertyName The programmatic name of the property that * was changed. * @param index index of the property element that was changed. * @param oldValue The old value of the property. * @param newValue The new value of the property. * @since 1.5 */ public void fireIndexedPropertyChange(String propertyName, int index, Object oldValue, Object newValue) { firePropertyChange(new IndexedPropertyChangeEvent (source, propertyName, oldValue, newValue, index)); } /** {@collect.stats} * Report an <code>int</code> bound indexed property update to any registered * listeners. * <p> * No event is fired if old and new values are equal. * <p> * This is merely a convenience wrapper around the more general * fireIndexedPropertyChange method which takes Object values. * * @param propertyName The programmatic name of the property that * was changed. * @param index index of the property element that was changed. * @param oldValue The old value of the property. * @param newValue The new value of the property. * @since 1.5 */ public void fireIndexedPropertyChange(String propertyName, int index, int oldValue, int newValue) { if (oldValue == newValue) { return; } fireIndexedPropertyChange(propertyName, index, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } /** {@collect.stats} * Report a <code>boolean</code> bound indexed property update to any * registered listeners. * <p> * No event is fired if old and new values are equal. * <p> * This is merely a convenience wrapper around the more general * fireIndexedPropertyChange method which takes Object values. * * @param propertyName The programmatic name of the property that * was changed. * @param index index of the property element that was changed. * @param oldValue The old value of the property. * @param newValue The new value of the property. * @since 1.5 */ public void fireIndexedPropertyChange(String propertyName, int index, boolean oldValue, boolean newValue) { if (oldValue == newValue) { return; } fireIndexedPropertyChange(propertyName, index, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } /** {@collect.stats} * Check if there are any listeners for a specific property, including * those registered on all properties. If <code>propertyName</code> * is null, only check for listeners registered on all properties. * * @param propertyName the property name. * @return true if there are one or more listeners for the given property */ public boolean hasListeners(String propertyName) { return this.map.hasListeners(propertyName); } /** {@collect.stats} * @serialData Null terminated list of <code>PropertyChangeListeners</code>. * <p> * At serialization time we skip non-serializable listeners and * only serialize the serializable listeners. */ private void writeObject(ObjectOutputStream s) throws IOException { Hashtable<String, PropertyChangeSupport> children = null; PropertyChangeListener[] listeners = null; synchronized (this.map) { for (Entry<String, PropertyChangeListener[]> entry : this.map.getEntries()) { String property = entry.getKey(); if (property == null) { listeners = entry.getValue(); } else { if (children == null) { children = new Hashtable<String, PropertyChangeSupport>(); } PropertyChangeSupport pcs = new PropertyChangeSupport(this.source); pcs.map.set(null, entry.getValue()); children.put(property, pcs); } } } ObjectOutputStream.PutField fields = s.putFields(); fields.put("children", children); fields.put("source", this.source); fields.put("propertyChangeSupportSerializedDataVersion", 2); s.writeFields(); if (listeners != null) { for (PropertyChangeListener l : listeners) { if (l instanceof Serializable) { s.writeObject(l); } } } s.writeObject(null); } private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { this.map = new PropertyChangeListenerMap(); ObjectInputStream.GetField fields = s.readFields(); Hashtable<String, PropertyChangeSupport> children = (Hashtable<String, PropertyChangeSupport>) fields.get("children", null); this.source = fields.get("source", null); fields.get("propertyChangeSupportSerializedDataVersion", 2); Object listenerOrNull; while (null != (listenerOrNull = s.readObject())) { this.map.add(null, (PropertyChangeListener)listenerOrNull); } if (children != null) { for (Entry<String, PropertyChangeSupport> entry : children.entrySet()) { for (PropertyChangeListener listener : entry.getValue().getPropertyChangeListeners()) { this.map.add(entry.getKey(), listener); } } } } /** {@collect.stats} * The object to be provided as the "source" for any generated events. */ private Object source; /** {@collect.stats} * @serialField children Hashtable * @serialField source Object * @serialField propertyChangeSupportSerializedDataVersion int */ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField("children", Hashtable.class), new ObjectStreamField("source", Object.class), new ObjectStreamField("propertyChangeSupportSerializedDataVersion", Integer.TYPE) }; /** {@collect.stats} * Serialization version ID, so we're compatible with JDK 1.1 */ static final long serialVersionUID = 6401253773779951803L; /** {@collect.stats} * This is a {@link ChangeListenerMap ChangeListenerMap} implementation * that works with {@link PropertyChangeListener PropertyChangeListener} objects. */ private static final class PropertyChangeListenerMap extends ChangeListenerMap<PropertyChangeListener> { private static final PropertyChangeListener[] EMPTY = {}; /** {@collect.stats} * Creates an array of {@link PropertyChangeListener PropertyChangeListener} objects. * This method uses the same instance of the empty array * when {@code length} equals {@code 0}. * * @param length the array length * @return an array with specified length */ @Override protected PropertyChangeListener[] newArray(int length) { return (0 < length) ? new PropertyChangeListener[length] : EMPTY; } /** {@collect.stats} * Creates a {@link PropertyChangeListenerProxy PropertyChangeListenerProxy} * object for the specified property. * * @param name the name of the property to listen on * @param listener the listener to process events * @return a {@code PropertyChangeListenerProxy} object */ @Override protected PropertyChangeListener newProxy(String name, PropertyChangeListener listener) { return new PropertyChangeListenerProxy(name, listener); } } }
Java
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.lang.ref.Reference; /** {@collect.stats} * A BeanDescriptor provides global information about a "bean", * including its Java class, its displayName, etc. * <p> * This is one of the kinds of descriptor returned by a BeanInfo object, * which also returns descriptors for properties, method, and events. */ public class BeanDescriptor extends FeatureDescriptor { private Reference<Class> beanClassRef; private Reference<Class> customizerClassRef; /** {@collect.stats} * Create a BeanDescriptor for a bean that doesn't have a customizer. * * @param beanClass The Class object of the Java class that implements * the bean. For example sun.beans.OurButton.class. */ public BeanDescriptor(Class<?> beanClass) { this(beanClass, null); } /** {@collect.stats} * Create a BeanDescriptor for a bean that has a customizer. * * @param beanClass The Class object of the Java class that implements * the bean. For example sun.beans.OurButton.class. * @param customizerClass The Class object of the Java class that implements * the bean's Customizer. For example sun.beans.OurButtonCustomizer.class. */ public BeanDescriptor(Class<?> beanClass, Class<?> customizerClass) { this.beanClassRef = getWeakReference((Class)beanClass); this.customizerClassRef = getWeakReference((Class)customizerClass); String name = beanClass.getName(); while (name.indexOf('.') >= 0) { name = name.substring(name.indexOf('.')+1); } setName(name); } /** {@collect.stats} * Gets the bean's Class object. * * @return The Class object for the bean. */ public Class<?> getBeanClass() { return (this.beanClassRef != null) ? this.beanClassRef.get() : null; } /** {@collect.stats} * Gets the Class object for the bean's customizer. * * @return The Class object for the bean's customizer. This may * be null if the bean doesn't have a customizer. */ public Class<?> getCustomizerClass() { return (this.customizerClassRef != null) ? this.customizerClassRef.get() : null; } /* * Package-private dup constructor * This must isolate the new object from any changes to the old object. */ BeanDescriptor(BeanDescriptor old) { super(old); beanClassRef = old.beanClassRef; customizerClassRef = old.customizerClassRef; } }
Java
/* * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.util.ArrayList; import java.util.Collections; import java.util.EventListener; import java.util.EventListenerProxy; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** {@collect.stats} * This is an abstract class that provides base functionality * for the {@link PropertyChangeSupport PropertyChangeSupport} class * and the {@link VetoableChangeSupport VetoableChangeSupport} class. * * @see PropertyChangeListenerMap * @see VetoableChangeListenerMap * * @author Sergey A. Malenkov */ abstract class ChangeListenerMap<L extends EventListener> { private Map<String, L[]> map; /** {@collect.stats} * Creates an array of listeners. * This method can be optimized by using * the same instance of the empty array * when {@code length} is equal to {@code 0}. * * @param length the array length * @return an array with specified length */ protected abstract L[] newArray(int length); /** {@collect.stats} * Creates a proxy listener for the specified property. * * @param name the name of the property to listen on * @param listener the listener to process events * @return a proxy listener */ protected abstract L newProxy(String name, L listener); /** {@collect.stats} * Adds a listener to the list of listeners for the specified property. * This listener is called as many times as it was added. * * @param name the name of the property to listen on * @param listener the listener to process events */ public final synchronized void add(String name, L listener) { if (this.map == null) { this.map = new HashMap<String, L[]>(); } L[] array = this.map.get(name); int size = (array != null) ? array.length : 0; L[] clone = newArray(size + 1); clone[size] = listener; if (array != null) { System.arraycopy(array, 0, clone, 0, size); } this.map.put(name, clone); } /** {@collect.stats} * Removes a listener from the list of listeners for the specified property. * If the listener was added more than once to the same event source, * this listener will be notified one less time after being removed. * * @param name the name of the property to listen on * @param listener the listener to process events */ public final synchronized void remove(String name, L listener) { if (this.map != null) { L[] array = this.map.get(name); if (array != null) { for (int i = 0; i < array.length; i++) { if (listener.equals(array[i])) { int size = array.length - 1; if (size > 0) { L[] clone = newArray(size); System.arraycopy(array, 0, clone, 0, i); System.arraycopy(array, i + 1, clone, i, size - i); this.map.put(name, clone); } else { this.map.remove(name); if (this.map.isEmpty()) { this.map = null; } } break; } } } } } /** {@collect.stats} * Returns the list of listeners for the specified property. * * @param name the name of the property * @return the corresponding list of listeners */ public final synchronized L[] get(String name) { return (this.map != null) ? this.map.get(name) : null; } /** {@collect.stats} * Sets new list of listeners for the specified property. * * @param name the name of the property * @param listeners new list of listeners */ public final void set(String name, L[] listeners) { if (listeners != null) { if (this.map == null) { this.map = new HashMap<String, L[]>(); } this.map.put(name, listeners); } else if (this.map != null) { this.map.remove(name); if (this.map.isEmpty()) { this.map = null; } } } /** {@collect.stats} * Returns all listeners in the map. * * @return an array of all listeners */ public final synchronized L[] getListeners() { if (this.map == null) { return newArray(0); } List<L> list = new ArrayList<L>(); L[] listeners = this.map.get(null); if (listeners != null) { for (L listener : listeners) { list.add(listener); } } for (Entry<String, L[]> entry : this.map.entrySet()) { String name = entry.getKey(); if (name != null) { for (L listener : entry.getValue()) { list.add(newProxy(name, listener)); } } } return list.toArray(newArray(list.size())); } /** {@collect.stats} * Returns listeners that have been associated with the named property. * * @param name the name of the property * @return an array of listeners for the named property */ public final L[] getListeners(String name) { if (name != null) { L[] listeners = get(name); if (listeners != null) { return listeners.clone(); } } return newArray(0); } /** {@collect.stats} * Indicates whether the map contains * at least one listener to be notified. * * @param name the name of the property * @return {@code true} if at least one listener exists or * {@code false} otherwise */ public final synchronized boolean hasListeners(String name) { if (this.map == null) { return false; } L[] array = this.map.get(null); return (array != null) || ((name != null) && (null != this.map.get(name))); } /** {@collect.stats} * Returns a set of entries from the map. * Each entry is a pair consisted of the property name * and the corresponding list of listeners. * * @return a set of entries from the map */ public final Set<Entry<String, L[]>> getEntries() { return (this.map != null) ? this.map.entrySet() : Collections.<Entry<String, L[]>>emptySet(); } /** {@collect.stats} * Extracts a real listener from the proxy listener. * It is necessary because default proxy class is not serializable. * * @return a real listener */ public final L extract(L listener) { while (listener instanceof EventListenerProxy) { EventListenerProxy proxy = (EventListenerProxy) listener; listener = (L) proxy.getListener(); } return listener; } }
Java
/* * Copyright (c) 1996, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * A "PropertyChange" event gets fired whenever a bean changes a "bound" * property. You can register a PropertyChangeListener with a source * bean so as to be notified of any bound property updates. */ public interface PropertyChangeListener extends java.util.EventListener { /** {@collect.stats} * This method gets called when a bound property is changed. * @param evt A PropertyChangeEvent object describing the event source * and the property that has changed. */ void propertyChange(PropertyChangeEvent evt); }
Java
/* * Copyright (c) 1996, 1997, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * A VetoableChange event gets fired whenever a bean changes a "constrained" * property. You can register a VetoableChangeListener with a source bean * so as to be notified of any constrained property updates. */ public interface VetoableChangeListener extends java.util.EventListener { /** {@collect.stats} * This method gets called when a constrained property is changed. * * @param evt a <code>PropertyChangeEvent</code> object describing the * event source and the property that has changed. * @exception PropertyVetoException if the recipient wishes the property * change to be rolled back. */ void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException; }
Java
/* * Copyright (c) 2000, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import com.sun.beans.finder.ClassFinder; import sun.reflect.misc.MethodUtil; /** {@collect.stats} * A <code>Statement</code> object represents a primitive statement * in which a single method is applied to a target and * a set of arguments - as in <code>"a.setFoo(b)"</code>. * Note that where this example uses names * to denote the target and its argument, a statement * object does not require a name space and is constructed with * the values themselves. * The statement object associates the named method * with its environment as a simple set of values: * the target and an array of argument values. * * @since 1.4 * * @author Philip Milne */ public class Statement { private static Object[] emptyArray = new Object[]{}; static ExceptionListener defaultExceptionListener = new ExceptionListener() { public void exceptionThrown(Exception e) { System.err.println(e); // e.printStackTrace(); System.err.println("Continuing ..."); } }; private final AccessControlContext acc = AccessController.getContext(); private final Object target; private final String methodName; private final Object[] arguments; /** {@collect.stats} * Creates a new <code>Statement</code> object with a <code>target</code>, * <code>methodName</code> and <code>arguments</code> as per the parameters. * * @param target The target of this statement. * @param methodName The methodName of this statement. * @param arguments The arguments of this statement. If <code>null</code> then an empty array will be used. * */ public Statement(Object target, String methodName, Object[] arguments) { this.target = target; this.methodName = methodName; this.arguments = (arguments == null) ? emptyArray : arguments; } /** {@collect.stats} * Returns the target of this statement. * * @return The target of this statement. */ public Object getTarget() { return target; } /** {@collect.stats} * Returns the name of the method. * * @return The name of the method. */ public String getMethodName() { return methodName; } /** {@collect.stats} * Returns the arguments of this statement. * * @return the arguments of this statement. */ public Object[] getArguments() { return arguments; } /** {@collect.stats} * The execute method finds a method whose name is the same * as the methodName property, and invokes the method on * the target. * * When the target's class defines many methods with the given name * the implementation should choose the most specific method using * the algorithm specified in the Java Language Specification * (15.11). The dynamic class of the target and arguments are used * in place of the compile-time type information and, like the * <code>java.lang.reflect.Method</code> class itself, conversion between * primitive values and their associated wrapper classes is handled * internally. * <p> * The following method types are handled as special cases: * <ul> * <li> * Static methods may be called by using a class object as the target. * <li> * The reserved method name "new" may be used to call a class's constructor * as if all classes defined static "new" methods. Constructor invocations * are typically considered <code>Expression</code>s rather than <code>Statement</code>s * as they return a value. * <li> * The method names "get" and "set" defined in the <code>java.util.List</code> * interface may also be applied to array instances, mapping to * the static methods of the same name in the <code>Array</code> class. * </ul> */ public void execute() throws Exception { invoke(); } Object invoke() throws Exception { AccessControlContext acc = this.acc; if ((acc == null) && (System.getSecurityManager() != null)) { throw new SecurityException("AccessControlContext is not set"); } try { return AccessController.doPrivileged( new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { return invokeInternal(); } }, acc ); } catch (PrivilegedActionException exception) { throw exception.getException(); } } private Object invokeInternal() throws Exception { Object target = getTarget(); String methodName = getMethodName(); if (target == null || methodName == null) { throw new NullPointerException((target == null ? "target" : "methodName") + " should not be null"); } Object[] arguments = getArguments(); // Class.forName() won't load classes outside // of core from a class inside core. Special // case this method. if (target == Class.class && methodName.equals("forName")) { return ClassFinder.resolveClass((String)arguments[0]); } Class[] argClasses = new Class[arguments.length]; for(int i = 0; i < arguments.length; i++) { argClasses[i] = (arguments[i] == null) ? null : arguments[i].getClass(); } AccessibleObject m = null; if (target instanceof Class) { /* For class methods, simluate the effect of a meta class by taking the union of the static methods of the actual class, with the instance methods of "Class.class" and the overloaded "newInstance" methods defined by the constructors. This way "System.class", for example, will perform both the static method getProperties() and the instance method getSuperclass() defined in "Class.class". */ if (methodName.equals("new")) { methodName = "newInstance"; } // Provide a short form for array instantiation by faking an nary-constructor. if (methodName.equals("newInstance") && ((Class)target).isArray()) { Object result = Array.newInstance(((Class)target).getComponentType(), arguments.length); for(int i = 0; i < arguments.length; i++) { Array.set(result, i, arguments[i]); } return result; } if (methodName.equals("newInstance") && arguments.length != 0) { // The Character class, as of 1.4, does not have a constructor // which takes a String. All of the other "wrapper" classes // for Java's primitive types have a String constructor so we // fake such a constructor here so that this special case can be // ignored elsewhere. if (target == Character.class && arguments.length == 1 && argClasses[0] == String.class) { return new Character(((String)arguments[0]).charAt(0)); } m = ReflectionUtils.getConstructor((Class)target, argClasses); } if (m == null && target != Class.class) { m = ReflectionUtils.getMethod((Class)target, methodName, argClasses); } if (m == null) { m = ReflectionUtils.getMethod(Class.class, methodName, argClasses); } } else { /* This special casing of arrays is not necessary, but makes files involving arrays much shorter and simplifies the archiving infrastrcure. The Array.set() method introduces an unusual idea - that of a static method changing the state of an instance. Normally statements with side effects on objects are instance methods of the objects themselves and we reinstate this rule (perhaps temporarily) by special-casing arrays. */ if (target.getClass().isArray() && (methodName.equals("set") || methodName.equals("get"))) { int index = ((Integer)arguments[0]).intValue(); if (methodName.equals("get")) { return Array.get(target, index); } else { Array.set(target, index, arguments[1]); return null; } } m = ReflectionUtils.getMethod(target.getClass(), methodName, argClasses); } if (m != null) { try { if (m instanceof Method) { return MethodUtil.invoke((Method)m, target, arguments); } else { return ((Constructor)m).newInstance(arguments); } } catch (IllegalAccessException iae) { throw new Exception("Statement cannot invoke: " + methodName + " on " + target.getClass(), iae); } catch (InvocationTargetException ite) { Throwable te = ite.getTargetException(); if (te instanceof Exception) { throw (Exception)te; } else { throw ite; } } } throw new NoSuchMethodException(toString()); } String instanceName(Object instance) { if (instance == null) { return "null"; } else if (instance.getClass() == String.class) { return "\""+(String)instance + "\""; } else { // Note: there is a minor problem with using the non-caching // NameGenerator method. The return value will not have // specific information about the inner class name. For example, // In 1.4.2 an inner class would be represented as JList$1 now // would be named Class. return NameGenerator.unqualifiedClassName(instance.getClass()); } } /** {@collect.stats} * Prints the value of this statement using a Java-style syntax. */ public String toString() { // Respect a subclass's implementation here. Object target = getTarget(); String methodName = getMethodName(); Object[] arguments = getArguments(); StringBuffer result = new StringBuffer(instanceName(target) + "." + methodName + "("); int n = arguments.length; for(int i = 0; i < n; i++) { result.append(instanceName(arguments[i])); if (i != n -1) { result.append(", "); } } result.append(");"); return result.toString(); } }
Java
/* * Copyright (c) 1997, 2000, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.applet.Applet; import java.beans.beancontext.BeanContext; /** {@collect.stats} * <p> * This interface is designed to work in collusion with java.beans.Beans.instantiate. * The interafce is intended to provide mechanism to allow the proper * initialization of JavaBeans that are also Applets, during their * instantiation by java.beans.Beans.instantiate(). * </p> * * @see java.beans.Beans#instantiate * * @since 1.2 * */ public interface AppletInitializer { /** {@collect.stats} * <p> * If passed to the appropriate variant of java.beans.Beans.instantiate * this method will be called in order to associate the newly instantiated * Applet (JavaBean) with its AppletContext, AppletStub, and Container. * </p> * <p> * Conformant implementations shall: * <ol> * <li> Associate the newly instantiated Applet with the appropriate * AppletContext. * * <li> Instantiate an AppletStub() and associate that AppletStub with * the Applet via an invocation of setStub(). * * <li> If BeanContext parameter is null, then it shall associate the * Applet with its appropriate Container by adding that Applet to its * Container via an invocation of add(). If the BeanContext parameter is * non-null, then it is the responsibility of the BeanContext to associate * the Applet with its Container during the subsequent invocation of its * addChildren() method. * </ol> * </p> * * @param newAppletBean The newly instantiated JavaBean * @param bCtxt The BeanContext intended for this Applet, or * null. */ void initialize(Applet newAppletBean, BeanContext bCtxt); /** {@collect.stats} * <p> * Activate, and/or mark Applet active. Implementors of this interface * shall mark this Applet as active, and optionally invoke its start() * method. * </p> * * @param newApplet The newly instantiated JavaBean */ void activate(Applet newApplet); }
Java
/* * Copyright (c) 1996, 1997, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * The ParameterDescriptor class allows bean implementors to provide * additional information on each of their parameters, beyond the * low level type information provided by the java.lang.reflect.Method * class. * <p> * Currently all our state comes from the FeatureDescriptor base class. */ public class ParameterDescriptor extends FeatureDescriptor { /** {@collect.stats} * Public default constructor. */ public ParameterDescriptor() { } /** {@collect.stats} * Package private dup constructor. * This must isolate the new object from any changes to the old object. */ ParameterDescriptor(ParameterDescriptor old) { super(old); } }
Java
/* * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import com.sun.beans.finder.ClassFinder; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collections; import java.util.Map; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.EventListener; import java.util.List; import java.util.WeakHashMap; import java.util.TreeMap; import sun.awt.AppContext; import sun.reflect.misc.ReflectUtil; /** {@collect.stats} * The Introspector class provides a standard way for tools to learn about * the properties, events, and methods supported by a target Java Bean. * <p> * For each of those three kinds of information, the Introspector will * separately analyze the bean's class and superclasses looking for * either explicit or implicit information and use that information to * build a BeanInfo object that comprehensively describes the target bean. * <p> * For each class "Foo", explicit information may be available if there exists * a corresponding "FooBeanInfo" class that provides a non-null value when * queried for the information. We first look for the BeanInfo class by * taking the full package-qualified name of the target bean class and * appending "BeanInfo" to form a new class name. If this fails, then * we take the final classname component of this name, and look for that * class in each of the packages specified in the BeanInfo package search * path. * <p> * Thus for a class such as "sun.xyz.OurButton" we would first look for a * BeanInfo class called "sun.xyz.OurButtonBeanInfo" and if that failed we'd * look in each package in the BeanInfo search path for an OurButtonBeanInfo * class. With the default search path, this would mean looking for * "sun.beans.infos.OurButtonBeanInfo". * <p> * If a class provides explicit BeanInfo about itself then we add that to * the BeanInfo information we obtained from analyzing any derived classes, * but we regard the explicit information as being definitive for the current * class and its base classes, and do not proceed any further up the superclass * chain. * <p> * If we don't find explicit BeanInfo on a class, we use low-level * reflection to study the methods of the class and apply standard design * patterns to identify property accessors, event sources, or public * methods. We then proceed to analyze the class's superclass and add * in the information from it (and possibly on up the superclass chain). * * <p> * Because the Introspector caches BeanInfo classes for better performance, * take care if you use it in an application that uses * multiple class loaders. * In general, when you destroy a <code>ClassLoader</code> * that has been used to introspect classes, * you should use the * {@link #flushCaches <code>Introspector.flushCaches</code>} * or * {@link #flushFromCaches <code>Introspector.flushFromCaches</code>} method * to flush all of the introspected classes out of the cache. * * <P> * For more information about introspection and design patterns, please * consult the * <a href="http://java.sun.com/products/javabeans/docs/index.html">JavaBeans specification</a>. */ public class Introspector { // Flags that can be used to control getBeanInfo: public final static int USE_ALL_BEANINFO = 1; public final static int IGNORE_IMMEDIATE_BEANINFO = 2; public final static int IGNORE_ALL_BEANINFO = 3; // Static Caches to speed up introspection. private static Map declaredMethodCache = Collections.synchronizedMap(new WeakHashMap()); private static final Object BEANINFO_CACHE = new Object(); private Class beanClass; private BeanInfo explicitBeanInfo; private BeanInfo superBeanInfo; private BeanInfo additionalBeanInfo[]; private boolean propertyChangeSource = false; private static Class eventListenerType = EventListener.class; // These should be removed. private String defaultEventName; private String defaultPropertyName; private int defaultEventIndex = -1; private int defaultPropertyIndex = -1; // Methods maps from Method objects to MethodDescriptors private Map methods; // properties maps from String names to PropertyDescriptors private Map properties; // events maps from String names to EventSetDescriptors private Map events; private final static String DEFAULT_INFO_PATH = "sun.beans.infos"; private static String[] searchPath = { DEFAULT_INFO_PATH }; private final static EventSetDescriptor[] EMPTY_EVENTSETDESCRIPTORS = new EventSetDescriptor[0]; static final String ADD_PREFIX = "add"; static final String REMOVE_PREFIX = "remove"; static final String GET_PREFIX = "get"; static final String SET_PREFIX = "set"; static final String IS_PREFIX = "is"; private static final String BEANINFO_SUFFIX = "BeanInfo"; //====================================================================== // Public methods //====================================================================== /** {@collect.stats} * Introspect on a Java Bean and learn about all its properties, exposed * methods, and events. * <p> * If the BeanInfo class for a Java Bean has been previously Introspected * then the BeanInfo class is retrieved from the BeanInfo cache. * * @param beanClass The bean class to be analyzed. * @return A BeanInfo object describing the target bean. * @exception IntrospectionException if an exception occurs during * introspection. * @see #flushCaches * @see #flushFromCaches */ public static BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException { if (!ReflectUtil.isPackageAccessible(beanClass)) { return (new Introspector(beanClass, null, USE_ALL_BEANINFO)).getBeanInfo(); } Map<Class<?>, BeanInfo> map; synchronized (BEANINFO_CACHE) { map = (Map<Class<?>, BeanInfo>) AppContext.getAppContext().get(BEANINFO_CACHE); if (map == null) { map = Collections.synchronizedMap(new WeakHashMap<Class<?>, BeanInfo>()); AppContext.getAppContext().put(BEANINFO_CACHE, map); } } BeanInfo bi = map.get(beanClass); if (bi == null) { bi = (new Introspector(beanClass, null, USE_ALL_BEANINFO)).getBeanInfo(); map.put(beanClass, bi); } return bi; } /** {@collect.stats} * Introspect on a Java bean and learn about all its properties, exposed * methods, and events, subject to some control flags. * <p> * If the BeanInfo class for a Java Bean has been previously Introspected * based on the same arguments then the BeanInfo class is retrieved * from the BeanInfo cache. * * @param beanClass The bean class to be analyzed. * @param flags Flags to control the introspection. * If flags == USE_ALL_BEANINFO then we use all of the BeanInfo * classes we can discover. * If flags == IGNORE_IMMEDIATE_BEANINFO then we ignore any * BeanInfo associated with the specified beanClass. * If flags == IGNORE_ALL_BEANINFO then we ignore all BeanInfo * associated with the specified beanClass or any of its * parent classes. * @return A BeanInfo object describing the target bean. * @exception IntrospectionException if an exception occurs during * introspection. */ public static BeanInfo getBeanInfo(Class<?> beanClass, int flags) throws IntrospectionException { return getBeanInfo(beanClass, null, flags); } /** {@collect.stats} * Introspect on a Java bean and learn all about its properties, exposed * methods, below a given "stop" point. * <p> * If the BeanInfo class for a Java Bean has been previously Introspected * based on the same arguments, then the BeanInfo class is retrieved * from the BeanInfo cache. * * @param beanClass The bean class to be analyzed. * @param stopClass The baseclass at which to stop the analysis. Any * methods/properties/events in the stopClass or in its baseclasses * will be ignored in the analysis. * @exception IntrospectionException if an exception occurs during * introspection. */ public static BeanInfo getBeanInfo(Class<?> beanClass, Class<?> stopClass) throws IntrospectionException { return getBeanInfo(beanClass, stopClass, USE_ALL_BEANINFO); } /** {@collect.stats} * Only called from the public getBeanInfo methods. This method caches * the Introspected BeanInfo based on the arguments. */ private static BeanInfo getBeanInfo(Class beanClass, Class stopClass, int flags) throws IntrospectionException { BeanInfo bi; if (stopClass == null && flags == USE_ALL_BEANINFO) { // Same parameters to take advantage of caching. bi = getBeanInfo(beanClass); } else { bi = (new Introspector(beanClass, stopClass, flags)).getBeanInfo(); } return bi; // Old behaviour: Make an independent copy of the BeanInfo. //return new GenericBeanInfo(bi); } /** {@collect.stats} * Utility method to take a string and convert it to normal Java variable * name capitalization. This normally means converting the first * character from upper case to lower case, but in the (unusual) special * case when there is more than one character and both the first and * second characters are upper case, we leave it alone. * <p> * Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays * as "URL". * * @param name The string to be decapitalized. * @return The decapitalized version of the string. */ public static String decapitalize(String name) { if (name == null || name.length() == 0) { return name; } if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) && Character.isUpperCase(name.charAt(0))){ return name; } char chars[] = name.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); return new String(chars); } /** {@collect.stats} * Gets the list of package names that will be used for * finding BeanInfo classes. * * @return The array of package names that will be searched in * order to find BeanInfo classes. The default value * for this array is implementation-dependent; e.g. * Sun implementation initially sets to {"sun.beans.infos"}. */ public static synchronized String[] getBeanInfoSearchPath() { // Return a copy of the searchPath. String result[] = new String[searchPath.length]; for (int i = 0; i < searchPath.length; i++) { result[i] = searchPath[i]; } return result; } /** {@collect.stats} * Change the list of package names that will be used for * finding BeanInfo classes. The behaviour of * this method is undefined if parameter path * is null. * * <p>First, if there is a security manager, its <code>checkPropertiesAccess</code> * method is called. This could result in a SecurityException. * * @param path Array of package names. * @exception SecurityException if a security manager exists and its * <code>checkPropertiesAccess</code> method doesn't allow setting * of system properties. * @see SecurityManager#checkPropertiesAccess */ public static synchronized void setBeanInfoSearchPath(String path[]) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } searchPath = path; } /** {@collect.stats} * Flush all of the Introspector's internal caches. This method is * not normally required. It is normally only needed by advanced * tools that update existing "Class" objects in-place and need * to make the Introspector re-analyze existing Class objects. */ public static void flushCaches() { Map map = (Map) AppContext.getAppContext().get(BEANINFO_CACHE); if (map != null) { map.clear(); } declaredMethodCache.clear(); } /** {@collect.stats} * Flush the Introspector's internal cached information for a given class. * This method is not normally required. It is normally only needed * by advanced tools that update existing "Class" objects in-place * and need to make the Introspector re-analyze an existing Class object. * * Note that only the direct state associated with the target Class * object is flushed. We do not flush state for other Class objects * with the same name, nor do we flush state for any related Class * objects (such as subclasses), even though their state may include * information indirectly obtained from the target Class object. * * @param clz Class object to be flushed. * @throws NullPointerException If the Class object is null. */ public static void flushFromCaches(Class<?> clz) { if (clz == null) { throw new NullPointerException(); } Map map = (Map) AppContext.getAppContext().get(BEANINFO_CACHE); if (map != null) { map.remove(clz); } declaredMethodCache.remove(clz); } //====================================================================== // Private implementation methods //====================================================================== private Introspector(Class beanClass, Class stopClass, int flags) throws IntrospectionException { this.beanClass = beanClass; // Check stopClass is a superClass of startClass. if (stopClass != null) { boolean isSuper = false; for (Class c = beanClass.getSuperclass(); c != null; c = c.getSuperclass()) { if (c == stopClass) { isSuper = true; } } if (!isSuper) { throw new IntrospectionException(stopClass.getName() + " not superclass of " + beanClass.getName()); } } if (flags == USE_ALL_BEANINFO) { explicitBeanInfo = findExplicitBeanInfo(beanClass); } Class superClass = beanClass.getSuperclass(); if (superClass != stopClass) { int newFlags = flags; if (newFlags == IGNORE_IMMEDIATE_BEANINFO) { newFlags = USE_ALL_BEANINFO; } superBeanInfo = getBeanInfo(superClass, stopClass, newFlags); } if (explicitBeanInfo != null) { additionalBeanInfo = explicitBeanInfo.getAdditionalBeanInfo(); } if (additionalBeanInfo == null) { additionalBeanInfo = new BeanInfo[0]; } } /** {@collect.stats} * Constructs a GenericBeanInfo class from the state of the Introspector */ private BeanInfo getBeanInfo() throws IntrospectionException { // the evaluation order here is import, as we evaluate the // event sets and locate PropertyChangeListeners before we // look for properties. BeanDescriptor bd = getTargetBeanDescriptor(); MethodDescriptor mds[] = getTargetMethodInfo(); EventSetDescriptor esds[] = getTargetEventInfo(); PropertyDescriptor pds[] = getTargetPropertyInfo(); int defaultEvent = getTargetDefaultEventIndex(); int defaultProperty = getTargetDefaultPropertyIndex(); return new GenericBeanInfo(bd, esds, defaultEvent, pds, defaultProperty, mds, explicitBeanInfo); } /** {@collect.stats} * Looks for an explicit BeanInfo class that corresponds to the Class. * First it looks in the existing package that the Class is defined in, * then it checks to see if the class is its own BeanInfo. Finally, * the BeanInfo search path is prepended to the class and searched. * * @return Instance of an explicit BeanInfo class or null if one isn't found. */ private static synchronized BeanInfo findExplicitBeanInfo(Class beanClass) { String name = beanClass.getName() + BEANINFO_SUFFIX; try { return (java.beans.BeanInfo)instantiate(beanClass, name); } catch (Exception ex) { // Just drop through } // Now try checking if the bean is its own BeanInfo. try { if (isSubclass(beanClass, java.beans.BeanInfo.class)) { return (java.beans.BeanInfo)beanClass.newInstance(); } } catch (Exception ex) { // Just drop through } // Now try looking for <searchPath>.fooBeanInfo name = name.substring(name.lastIndexOf('.')+1); for (int i = 0; i < searchPath.length; i++) { // This optimization will only use the BeanInfo search path if is has changed // from the original or trying to get the ComponentBeanInfo. if (!DEFAULT_INFO_PATH.equals(searchPath[i]) || DEFAULT_INFO_PATH.equals(searchPath[i]) && "ComponentBeanInfo".equals(name)) { try { String fullName = searchPath[i] + "." + name; java.beans.BeanInfo bi = (java.beans.BeanInfo)instantiate(beanClass, fullName); // Make sure that the returned BeanInfo matches the class. if (bi.getBeanDescriptor() != null) { if (bi.getBeanDescriptor().getBeanClass() == beanClass) { return bi; } } else if (bi.getPropertyDescriptors() != null) { PropertyDescriptor[] pds = bi.getPropertyDescriptors(); for (int j = 0; j < pds.length; j++) { Method method = pds[j].getReadMethod(); if (method == null) { method = pds[j].getWriteMethod(); } if (method != null && method.getDeclaringClass() == beanClass) { return bi; } } } else if (bi.getMethodDescriptors() != null) { MethodDescriptor[] mds = bi.getMethodDescriptors(); for (int j = 0; j < mds.length; j++) { Method method = mds[j].getMethod(); if (method != null && method.getDeclaringClass() == beanClass) { return bi; } } } } catch (Exception ex) { // Silently ignore any errors. } } } return null; } /** {@collect.stats} * @return An array of PropertyDescriptors describing the editable * properties supported by the target bean. */ private PropertyDescriptor[] getTargetPropertyInfo() { // Check if the bean has its own BeanInfo that will provide // explicit information. PropertyDescriptor[] explicitProperties = null; if (explicitBeanInfo != null) { explicitProperties = getPropertyDescriptors(this.explicitBeanInfo); } if (explicitProperties == null && superBeanInfo != null) { // We have no explicit BeanInfo properties. Check with our parent. addPropertyDescriptors(getPropertyDescriptors(this.superBeanInfo)); } for (int i = 0; i < additionalBeanInfo.length; i++) { addPropertyDescriptors(additionalBeanInfo[i].getPropertyDescriptors()); } if (explicitProperties != null) { // Add the explicit BeanInfo data to our results. addPropertyDescriptors(explicitProperties); } else { // Apply some reflection to the current class. // First get an array of all the public methods at this level Method methodList[] = getPublicDeclaredMethods(beanClass); // Now analyze each method. for (int i = 0; i < methodList.length; i++) { Method method = methodList[i]; if (method == null || method.isSynthetic()) { continue; } // skip static methods. int mods = method.getModifiers(); if (Modifier.isStatic(mods)) { continue; } String name = method.getName(); Class argTypes[] = method.getParameterTypes(); Class resultType = method.getReturnType(); int argCount = argTypes.length; PropertyDescriptor pd = null; if (name.length() <= 3 && !name.startsWith(IS_PREFIX)) { // Optimization. Don't bother with invalid propertyNames. continue; } try { if (argCount == 0) { if (name.startsWith(GET_PREFIX)) { // Simple getter pd = new PropertyDescriptor(this.beanClass, name.substring(3), method, null); } else if (resultType == boolean.class && name.startsWith(IS_PREFIX)) { // Boolean getter pd = new PropertyDescriptor(this.beanClass, name.substring(2), method, null); } } else if (argCount == 1) { if (argTypes[0] == int.class && name.startsWith(GET_PREFIX)) { pd = new IndexedPropertyDescriptor(this.beanClass, name.substring(3), null, null, method, null); } else if (resultType == void.class && name.startsWith(SET_PREFIX)) { // Simple setter pd = new PropertyDescriptor(this.beanClass, name.substring(3), null, method); if (throwsException(method, PropertyVetoException.class)) { pd.setConstrained(true); } } } else if (argCount == 2) { if (argTypes[0] == int.class && name.startsWith(SET_PREFIX)) { pd = new IndexedPropertyDescriptor(this.beanClass, name.substring(3), null, null, null, method); if (throwsException(method, PropertyVetoException.class)) { pd.setConstrained(true); } } } } catch (IntrospectionException ex) { // This happens if a PropertyDescriptor or IndexedPropertyDescriptor // constructor fins that the method violates details of the deisgn // pattern, e.g. by having an empty name, or a getter returning // void , or whatever. pd = null; } if (pd != null) { // If this class or one of its base classes is a PropertyChange // source, then we assume that any properties we discover are "bound". if (propertyChangeSource) { pd.setBound(true); } addPropertyDescriptor(pd); } } } processPropertyDescriptors(); // Allocate and populate the result array. PropertyDescriptor result[] = new PropertyDescriptor[properties.size()]; result = (PropertyDescriptor[])properties.values().toArray(result); // Set the default index. if (defaultPropertyName != null) { for (int i = 0; i < result.length; i++) { if (defaultPropertyName.equals(result[i].getName())) { defaultPropertyIndex = i; } } } return result; } private HashMap pdStore = new HashMap(); /** {@collect.stats} * Adds the property descriptor to the list store. */ private void addPropertyDescriptor(PropertyDescriptor pd) { String propName = pd.getName(); List list = (List)pdStore.get(propName); if (list == null) { list = new ArrayList(); pdStore.put(propName, list); } if (this.beanClass != pd.getClass0()) { // replace existing property descriptor // only if we have types to resolve // in the context of this.beanClass try { String name = pd.getName(); Method read = pd.getReadMethod(); Method write = pd.getWriteMethod(); boolean cls = true; if (read != null) cls = cls && read.getGenericReturnType() instanceof Class; if (write != null) cls = cls && write.getGenericParameterTypes()[0] instanceof Class; if (pd instanceof IndexedPropertyDescriptor) { IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor)pd; Method readI = ipd.getIndexedReadMethod(); Method writeI = ipd.getIndexedWriteMethod(); if (readI != null) cls = cls && readI.getGenericReturnType() instanceof Class; if (writeI != null) cls = cls && writeI.getGenericParameterTypes()[1] instanceof Class; if (!cls) { pd = new IndexedPropertyDescriptor(this.beanClass, name, read, write, readI, writeI); } } else if (!cls) { pd = new PropertyDescriptor(this.beanClass, name, read, write); } } catch ( IntrospectionException e ) { } } list.add(pd); } private void addPropertyDescriptors(PropertyDescriptor[] descriptors) { if (descriptors != null) { for (PropertyDescriptor descriptor : descriptors) { addPropertyDescriptor(descriptor); } } } private PropertyDescriptor[] getPropertyDescriptors(BeanInfo info) { PropertyDescriptor[] descriptors = info.getPropertyDescriptors(); int index = info.getDefaultPropertyIndex(); if ((0 <= index) && (index < descriptors.length)) { this.defaultPropertyName = descriptors[index].getName(); } return descriptors; } /** {@collect.stats} * Populates the property descriptor table by merging the * lists of Property descriptors. */ private void processPropertyDescriptors() { if (properties == null) { properties = new TreeMap(); } List list; PropertyDescriptor pd, gpd, spd; IndexedPropertyDescriptor ipd, igpd, ispd; Iterator it = pdStore.values().iterator(); while (it.hasNext()) { pd = null; gpd = null; spd = null; ipd = null; igpd = null; ispd = null; list = (List)it.next(); // First pass. Find the latest getter method. Merge properties // of previous getter methods. for (int i = 0; i < list.size(); i++) { pd = (PropertyDescriptor)list.get(i); if (pd instanceof IndexedPropertyDescriptor) { ipd = (IndexedPropertyDescriptor)pd; if (ipd.getIndexedReadMethod() != null) { if (igpd != null) { igpd = new IndexedPropertyDescriptor(igpd, ipd); } else { igpd = ipd; } } } else { if (pd.getReadMethod() != null) { if (gpd != null) { // Don't replace the existing read // method if it starts with "is" Method method = gpd.getReadMethod(); if (!method.getName().startsWith(IS_PREFIX)) { gpd = new PropertyDescriptor(gpd, pd); } } else { gpd = pd; } } } } // Second pass. Find the latest setter method which // has the same type as the getter method. for (int i = 0; i < list.size(); i++) { pd = (PropertyDescriptor)list.get(i); if (pd instanceof IndexedPropertyDescriptor) { ipd = (IndexedPropertyDescriptor)pd; if (ipd.getIndexedWriteMethod() != null) { if (igpd != null) { if (igpd.getIndexedPropertyType() == ipd.getIndexedPropertyType()) { if (ispd != null) { ispd = new IndexedPropertyDescriptor(ispd, ipd); } else { ispd = ipd; } } } else { if (ispd != null) { ispd = new IndexedPropertyDescriptor(ispd, ipd); } else { ispd = ipd; } } } } else { if (pd.getWriteMethod() != null) { if (gpd != null) { if (gpd.getPropertyType() == pd.getPropertyType()) { if (spd != null) { spd = new PropertyDescriptor(spd, pd); } else { spd = pd; } } } else { if (spd != null) { spd = new PropertyDescriptor(spd, pd); } else { spd = pd; } } } } } // At this stage we should have either PDs or IPDs for the // representative getters and setters. The order at which the // property descriptors are determined represent the // precedence of the property ordering. pd = null; ipd = null; if (igpd != null && ispd != null) { // Complete indexed properties set // Merge any classic property descriptors if (gpd != null) { PropertyDescriptor tpd = mergePropertyDescriptor(igpd, gpd); if (tpd instanceof IndexedPropertyDescriptor) { igpd = (IndexedPropertyDescriptor)tpd; } } if (spd != null) { PropertyDescriptor tpd = mergePropertyDescriptor(ispd, spd); if (tpd instanceof IndexedPropertyDescriptor) { ispd = (IndexedPropertyDescriptor)tpd; } } if (igpd == ispd) { pd = igpd; } else { pd = mergePropertyDescriptor(igpd, ispd); } } else if (gpd != null && spd != null) { // Complete simple properties set if (gpd == spd) { pd = gpd; } else { pd = mergePropertyDescriptor(gpd, spd); } } else if (ispd != null) { // indexed setter pd = ispd; // Merge any classic property descriptors if (spd != null) { pd = mergePropertyDescriptor(ispd, spd); } if (gpd != null) { pd = mergePropertyDescriptor(ispd, gpd); } } else if (igpd != null) { // indexed getter pd = igpd; // Merge any classic property descriptors if (gpd != null) { pd = mergePropertyDescriptor(igpd, gpd); } if (spd != null) { pd = mergePropertyDescriptor(igpd, spd); } } else if (spd != null) { // simple setter pd = spd; } else if (gpd != null) { // simple getter pd = gpd; } // Very special case to ensure that an IndexedPropertyDescriptor // doesn't contain less information than the enclosed // PropertyDescriptor. If it does, then recreate as a // PropertyDescriptor. See 4168833 if (pd instanceof IndexedPropertyDescriptor) { ipd = (IndexedPropertyDescriptor)pd; if (ipd.getIndexedReadMethod() == null && ipd.getIndexedWriteMethod() == null) { pd = new PropertyDescriptor(ipd); } } // Find the first property descriptor // which does not have getter and setter methods. // See regression bug 4984912. if ( (pd == null) && (list.size() > 0) ) { pd = (PropertyDescriptor) list.get(0); } if (pd != null) { properties.put(pd.getName(), pd); } } } /** {@collect.stats} * Adds the property descriptor to the indexedproperty descriptor only if the * types are the same. * * The most specific property descriptor will take precedence. */ private PropertyDescriptor mergePropertyDescriptor(IndexedPropertyDescriptor ipd, PropertyDescriptor pd) { PropertyDescriptor result = null; Class propType = pd.getPropertyType(); Class ipropType = ipd.getIndexedPropertyType(); if (propType.isArray() && propType.getComponentType() == ipropType) { if (pd.getClass0().isAssignableFrom(ipd.getClass0())) { result = new IndexedPropertyDescriptor(pd, ipd); } else { result = new IndexedPropertyDescriptor(ipd, pd); } } else { // Cannot merge the pd because of type mismatch // Return the most specific pd if (pd.getClass0().isAssignableFrom(ipd.getClass0())) { result = ipd; } else { result = pd; // Try to add methods which may have been lost in the type change // See 4168833 Method write = result.getWriteMethod(); Method read = result.getReadMethod(); if (read == null && write != null) { read = findMethod(result.getClass0(), GET_PREFIX + NameGenerator.capitalize(result.getName()), 0); if (read != null) { try { result.setReadMethod(read); } catch (IntrospectionException ex) { // no consequences for failure. } } } if (write == null && read != null) { write = findMethod(result.getClass0(), SET_PREFIX + NameGenerator.capitalize(result.getName()), 1, new Class[] { FeatureDescriptor.getReturnType(result.getClass0(), read) }); if (write != null) { try { result.setWriteMethod(write); } catch (IntrospectionException ex) { // no consequences for failure. } } } } } return result; } // Handle regular pd merge private PropertyDescriptor mergePropertyDescriptor(PropertyDescriptor pd1, PropertyDescriptor pd2) { if (pd1.getClass0().isAssignableFrom(pd2.getClass0())) { return new PropertyDescriptor(pd1, pd2); } else { return new PropertyDescriptor(pd2, pd1); } } // Handle regular ipd merge private PropertyDescriptor mergePropertyDescriptor(IndexedPropertyDescriptor ipd1, IndexedPropertyDescriptor ipd2) { if (ipd1.getClass0().isAssignableFrom(ipd2.getClass0())) { return new IndexedPropertyDescriptor(ipd1, ipd2); } else { return new IndexedPropertyDescriptor(ipd2, ipd1); } } /** {@collect.stats} * @return An array of EventSetDescriptors describing the kinds of * events fired by the target bean. */ private EventSetDescriptor[] getTargetEventInfo() throws IntrospectionException { if (events == null) { events = new HashMap(); } // Check if the bean has its own BeanInfo that will provide // explicit information. EventSetDescriptor[] explicitEvents = null; if (explicitBeanInfo != null) { explicitEvents = explicitBeanInfo.getEventSetDescriptors(); int ix = explicitBeanInfo.getDefaultEventIndex(); if (ix >= 0 && ix < explicitEvents.length) { defaultEventName = explicitEvents[ix].getName(); } } if (explicitEvents == null && superBeanInfo != null) { // We have no explicit BeanInfo events. Check with our parent. EventSetDescriptor supers[] = superBeanInfo.getEventSetDescriptors(); for (int i = 0 ; i < supers.length; i++) { addEvent(supers[i]); } int ix = superBeanInfo.getDefaultEventIndex(); if (ix >= 0 && ix < supers.length) { defaultEventName = supers[ix].getName(); } } for (int i = 0; i < additionalBeanInfo.length; i++) { EventSetDescriptor additional[] = additionalBeanInfo[i].getEventSetDescriptors(); if (additional != null) { for (int j = 0 ; j < additional.length; j++) { addEvent(additional[j]); } } } if (explicitEvents != null) { // Add the explicit explicitBeanInfo data to our results. for (int i = 0 ; i < explicitEvents.length; i++) { addEvent(explicitEvents[i]); } } else { // Apply some reflection to the current class. // Get an array of all the public beans methods at this level Method methodList[] = getPublicDeclaredMethods(beanClass); // Find all suitable "add", "remove" and "get" Listener methods // The name of the listener type is the key for these hashtables // i.e, ActionListener Map adds = null; Map removes = null; Map gets = null; for (int i = 0; i < methodList.length; i++) { Method method = methodList[i]; if (method == null) { continue; } // skip static methods. int mods = method.getModifiers(); if (Modifier.isStatic(mods)) { continue; } String name = method.getName(); // Optimization avoid getParameterTypes if (!name.startsWith(ADD_PREFIX) && !name.startsWith(REMOVE_PREFIX) && !name.startsWith(GET_PREFIX)) { continue; } Class argTypes[] = FeatureDescriptor.getParameterTypes(beanClass, method); Class resultType = FeatureDescriptor.getReturnType(beanClass, method); if (name.startsWith(ADD_PREFIX) && argTypes.length == 1 && resultType == Void.TYPE && Introspector.isSubclass(argTypes[0], eventListenerType)) { String listenerName = name.substring(3); if (listenerName.length() > 0 && argTypes[0].getName().endsWith(listenerName)) { if (adds == null) { adds = new HashMap(); } adds.put(listenerName, method); } } else if (name.startsWith(REMOVE_PREFIX) && argTypes.length == 1 && resultType == Void.TYPE && Introspector.isSubclass(argTypes[0], eventListenerType)) { String listenerName = name.substring(6); if (listenerName.length() > 0 && argTypes[0].getName().endsWith(listenerName)) { if (removes == null) { removes = new HashMap(); } removes.put(listenerName, method); } } else if (name.startsWith(GET_PREFIX) && argTypes.length == 0 && resultType.isArray() && Introspector.isSubclass(resultType.getComponentType(), eventListenerType)) { String listenerName = name.substring(3, name.length() - 1); if (listenerName.length() > 0 && resultType.getComponentType().getName().endsWith(listenerName)) { if (gets == null) { gets = new HashMap(); } gets.put(listenerName, method); } } } if (adds != null && removes != null) { // Now look for matching addFooListener+removeFooListener pairs. // Bonus if there is a matching getFooListeners method as well. Iterator keys = adds.keySet().iterator(); while (keys.hasNext()) { String listenerName = (String) keys.next(); // Skip any "add" which doesn't have a matching "remove" or // a listener name that doesn't end with Listener if (removes.get(listenerName) == null || !listenerName.endsWith("Listener")) { continue; } String eventName = decapitalize(listenerName.substring(0, listenerName.length()-8)); Method addMethod = (Method)adds.get(listenerName); Method removeMethod = (Method)removes.get(listenerName); Method getMethod = null; if (gets != null) { getMethod = (Method)gets.get(listenerName); } Class argType = FeatureDescriptor.getParameterTypes(beanClass, addMethod)[0]; // generate a list of Method objects for each of the target methods: Method allMethods[] = getPublicDeclaredMethods(argType); List validMethods = new ArrayList(allMethods.length); for (int i = 0; i < allMethods.length; i++) { if (allMethods[i] == null) { continue; } if (isEventHandler(allMethods[i])) { validMethods.add(allMethods[i]); } } Method[] methods = (Method[])validMethods.toArray(new Method[validMethods.size()]); EventSetDescriptor esd = new EventSetDescriptor(eventName, argType, methods, addMethod, removeMethod, getMethod); // If the adder method throws the TooManyListenersException then it // is a Unicast event source. if (throwsException(addMethod, java.util.TooManyListenersException.class)) { esd.setUnicast(true); } addEvent(esd); } } // if (adds != null ... } EventSetDescriptor[] result; if (events.size() == 0) { result = EMPTY_EVENTSETDESCRIPTORS; } else { // Allocate and populate the result array. result = new EventSetDescriptor[events.size()]; result = (EventSetDescriptor[])events.values().toArray(result); // Set the default index. if (defaultEventName != null) { for (int i = 0; i < result.length; i++) { if (defaultEventName.equals(result[i].getName())) { defaultEventIndex = i; } } } } return result; } private void addEvent(EventSetDescriptor esd) { String key = esd.getName(); if (esd.getName().equals("propertyChange")) { propertyChangeSource = true; } EventSetDescriptor old = (EventSetDescriptor)events.get(key); if (old == null) { events.put(key, esd); return; } EventSetDescriptor composite = new EventSetDescriptor(old, esd); events.put(key, composite); } /** {@collect.stats} * @return An array of MethodDescriptors describing the private * methods supported by the target bean. */ private MethodDescriptor[] getTargetMethodInfo() { if (methods == null) { methods = new HashMap(100); } // Check if the bean has its own BeanInfo that will provide // explicit information. MethodDescriptor[] explicitMethods = null; if (explicitBeanInfo != null) { explicitMethods = explicitBeanInfo.getMethodDescriptors(); } if (explicitMethods == null && superBeanInfo != null) { // We have no explicit BeanInfo methods. Check with our parent. MethodDescriptor supers[] = superBeanInfo.getMethodDescriptors(); for (int i = 0 ; i < supers.length; i++) { addMethod(supers[i]); } } for (int i = 0; i < additionalBeanInfo.length; i++) { MethodDescriptor additional[] = additionalBeanInfo[i].getMethodDescriptors(); if (additional != null) { for (int j = 0 ; j < additional.length; j++) { addMethod(additional[j]); } } } if (explicitMethods != null) { // Add the explicit explicitBeanInfo data to our results. for (int i = 0 ; i < explicitMethods.length; i++) { addMethod(explicitMethods[i]); } } else { // Apply some reflection to the current class. // First get an array of all the beans methods at this level Method methodList[] = getPublicDeclaredMethods(beanClass); // Now analyze each method. for (int i = 0; i < methodList.length; i++) { Method method = methodList[i]; if (method == null) { continue; } MethodDescriptor md = new MethodDescriptor(method); addMethod(md); } } // Allocate and populate the result array. MethodDescriptor result[] = new MethodDescriptor[methods.size()]; result = (MethodDescriptor[])methods.values().toArray(result); return result; } private void addMethod(MethodDescriptor md) { // We have to be careful here to distinguish method by both name // and argument lists. // This method gets called a *lot, so we try to be efficient. String name = md.getName(); MethodDescriptor old = (MethodDescriptor)methods.get(name); if (old == null) { // This is the common case. methods.put(name, md); return; } // We have a collision on method names. This is rare. // Check if old and md have the same type. String[] p1 = md.getParamNames(); String[] p2 = old.getParamNames(); boolean match = false; if (p1.length == p2.length) { match = true; for (int i = 0; i < p1.length; i++) { if (p1[i] != p2[i]) { match = false; break; } } } if (match) { MethodDescriptor composite = new MethodDescriptor(old, md); methods.put(name, composite); return; } // We have a collision on method names with different type signatures. // This is very rare. String longKey = makeQualifiedMethodName(name, p1); old = (MethodDescriptor)methods.get(longKey); if (old == null) { methods.put(longKey, md); return; } MethodDescriptor composite = new MethodDescriptor(old, md); methods.put(longKey, composite); } /** {@collect.stats} * Creates a key for a method in a method cache. */ private static String makeQualifiedMethodName(String name, String[] params) { StringBuffer sb = new StringBuffer(name); sb.append('='); for (int i = 0; i < params.length; i++) { sb.append(':'); sb.append(params[i]); } return sb.toString(); } private int getTargetDefaultEventIndex() { return defaultEventIndex; } private int getTargetDefaultPropertyIndex() { return defaultPropertyIndex; } private BeanDescriptor getTargetBeanDescriptor() { // Use explicit info, if available, if (explicitBeanInfo != null) { BeanDescriptor bd = explicitBeanInfo.getBeanDescriptor(); if (bd != null) { return (bd); } } // OK, fabricate a default BeanDescriptor. return (new BeanDescriptor(beanClass)); } private boolean isEventHandler(Method m) { // We assume that a method is an event handler if it has a single // argument, whose type inherit from java.util.Event. Class argTypes[] = FeatureDescriptor.getParameterTypes(beanClass, m); if (argTypes.length != 1) { return false; } if (isSubclass(argTypes[0], java.util.EventObject.class)) { return true; } return false; } /* * Internal method to return *public* methods within a class. */ private static synchronized Method[] getPublicDeclaredMethods(Class clz) { // Looking up Class.getDeclaredMethods is relatively expensive, // so we cache the results. Method[] result = null; if (!ReflectUtil.isPackageAccessible(clz)) { return new Method[0]; } final Class fclz = clz; Reference ref = (Reference)declaredMethodCache.get(fclz); if (ref != null) { result = (Method[])ref.get(); if (result != null) { return result; } } // We have to raise privilege for getDeclaredMethods result = (Method[]) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return fclz.getDeclaredMethods(); } }); // Null out any non-public methods. for (int i = 0; i < result.length; i++) { Method method = result[i]; int mods = method.getModifiers(); if (!Modifier.isPublic(mods)) { result[i] = null; } } // Add it to the cache. declaredMethodCache.put(fclz, new SoftReference(result)); return result; } //====================================================================== // Package private support methods. //====================================================================== /** {@collect.stats} * Internal support for finding a target methodName with a given * parameter list on a given class. */ private static Method internalFindMethod(Class start, String methodName, int argCount, Class args[]) { // For overriden methods we need to find the most derived version. // So we start with the given class and walk up the superclass chain. Method method = null; for (Class cl = start; cl != null; cl = cl.getSuperclass()) { Method methods[] = getPublicDeclaredMethods(cl); for (int i = 0; i < methods.length; i++) { method = methods[i]; if (method == null) { continue; } // make sure method signature matches. Class params[] = FeatureDescriptor.getParameterTypes(start, method); if (method.getName().equals(methodName) && params.length == argCount) { if (args != null) { boolean different = false; if (argCount > 0) { for (int j = 0; j < argCount; j++) { if (params[j] != args[j]) { different = true; continue; } } if (different) { continue; } } } return method; } } } method = null; // Now check any inherited interfaces. This is necessary both when // the argument class is itself an interface, and when the argument // class is an abstract class. Class ifcs[] = start.getInterfaces(); for (int i = 0 ; i < ifcs.length; i++) { // Note: The original implementation had both methods calling // the 3 arg method. This is preserved but perhaps it should // pass the args array instead of null. method = internalFindMethod(ifcs[i], methodName, argCount, null); if (method != null) { break; } } return method; } /** {@collect.stats} * Find a target methodName on a given class. */ static Method findMethod(Class cls, String methodName, int argCount) { return findMethod(cls, methodName, argCount, null); } /** {@collect.stats} * Find a target methodName with specific parameter list on a given class. * <p> * Used in the contructors of the EventSetDescriptor, * PropertyDescriptor and the IndexedPropertyDescriptor. * <p> * @param cls The Class object on which to retrieve the method. * @param methodName Name of the method. * @param argCount Number of arguments for the desired method. * @param args Array of argument types for the method. * @return the method or null if not found */ static Method findMethod(Class cls, String methodName, int argCount, Class args[]) { if (methodName == null) { return null; } return internalFindMethod(cls, methodName, argCount, args); } /** {@collect.stats} * Return true if class a is either equivalent to class b, or * if class a is a subclass of class b, i.e. if a either "extends" * or "implements" b. * Note tht either or both "Class" objects may represent interfaces. */ static boolean isSubclass(Class a, Class b) { // We rely on the fact that for any given java class or // primtitive type there is a unqiue Class object, so // we can use object equivalence in the comparisons. if (a == b) { return true; } if (a == null || b == null) { return false; } for (Class x = a; x != null; x = x.getSuperclass()) { if (x == b) { return true; } if (b.isInterface()) { Class interfaces[] = x.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (isSubclass(interfaces[i], b)) { return true; } } } } return false; } /** {@collect.stats} * Return true iff the given method throws the given exception. */ private boolean throwsException(Method method, Class exception) { Class exs[] = method.getExceptionTypes(); for (int i = 0; i < exs.length; i++) { if (exs[i] == exception) { return true; } } return false; } /** {@collect.stats} * Try to create an instance of a named class. * First try the classloader of "sibling", then try the system * classloader then the class loader of the current Thread. */ static Object instantiate(Class sibling, String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException { // First check with sibling's classloader (if any). ClassLoader cl = sibling.getClassLoader(); Class cls = ClassFinder.findClass(className, cl); return cls.newInstance(); } } // end class Introspector //=========================================================================== /** {@collect.stats} * Package private implementation support class for Introspector's * internal use. * <p> * Mostly this is used as a placeholder for the descriptors. */ class GenericBeanInfo extends SimpleBeanInfo { private BeanDescriptor beanDescriptor; private EventSetDescriptor[] events; private int defaultEvent; private PropertyDescriptor[] properties; private int defaultProperty; private MethodDescriptor[] methods; private BeanInfo targetBeanInfo; public GenericBeanInfo(BeanDescriptor beanDescriptor, EventSetDescriptor[] events, int defaultEvent, PropertyDescriptor[] properties, int defaultProperty, MethodDescriptor[] methods, BeanInfo targetBeanInfo) { this.beanDescriptor = beanDescriptor; this.events = events; this.defaultEvent = defaultEvent; this.properties = properties; this.defaultProperty = defaultProperty; this.methods = methods; this.targetBeanInfo = targetBeanInfo; } /** {@collect.stats} * Package-private dup constructor * This must isolate the new object from any changes to the old object. */ GenericBeanInfo(GenericBeanInfo old) { beanDescriptor = new BeanDescriptor(old.beanDescriptor); if (old.events != null) { int len = old.events.length; events = new EventSetDescriptor[len]; for (int i = 0; i < len; i++) { events[i] = new EventSetDescriptor(old.events[i]); } } defaultEvent = old.defaultEvent; if (old.properties != null) { int len = old.properties.length; properties = new PropertyDescriptor[len]; for (int i = 0; i < len; i++) { PropertyDescriptor oldp = old.properties[i]; if (oldp instanceof IndexedPropertyDescriptor) { properties[i] = new IndexedPropertyDescriptor( (IndexedPropertyDescriptor) oldp); } else { properties[i] = new PropertyDescriptor(oldp); } } } defaultProperty = old.defaultProperty; if (old.methods != null) { int len = old.methods.length; methods = new MethodDescriptor[len]; for (int i = 0; i < len; i++) { methods[i] = new MethodDescriptor(old.methods[i]); } } targetBeanInfo = old.targetBeanInfo; } public PropertyDescriptor[] getPropertyDescriptors() { return properties; } public int getDefaultPropertyIndex() { return defaultProperty; } public EventSetDescriptor[] getEventSetDescriptors() { return events; } public int getDefaultEventIndex() { return defaultEvent; } public MethodDescriptor[] getMethodDescriptors() { return methods; } public BeanDescriptor getBeanDescriptor() { return beanDescriptor; } public java.awt.Image getIcon(int iconKind) { if (targetBeanInfo != null) { return targetBeanInfo.getIcon(iconKind); } return super.getIcon(iconKind); } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; /** {@collect.stats} * An <code>Encoder</code> is a class which can be used to create * files or streams that encode the state of a collection of * JavaBeans in terms of their public APIs. The <code>Encoder</code>, * in conjunction with its persistence delegates, is responsible for * breaking the object graph down into a series of <code>Statements</code>s * and <code>Expression</code>s which can be used to create it. * A subclass typically provides a syntax for these expressions * using some human readable form - like Java source code or XML. * * @since 1.4 * * @author Philip Milne */ public class Encoder { private final Map<Class<?>, PersistenceDelegate> delegates = Collections.synchronizedMap(new HashMap<Class<?>, PersistenceDelegate>()); private Map bindings = new IdentityHashMap(); private ExceptionListener exceptionListener; boolean executeStatements = true; private Map attributes; /** {@collect.stats} * Write the specified object to the output stream. * The serialized form will denote a series of * expressions, the combined effect of which will create * an equivalent object when the input stream is read. * By default, the object is assumed to be a <em>JavaBean</em> * with a nullary constructor, whose state is defined by * the matching pairs of "setter" and "getter" methods * returned by the Introspector. * * @param o The object to be written to the stream. * * @see XMLDecoder#readObject */ protected void writeObject(Object o) { if (o == this) { return; } PersistenceDelegate info = getPersistenceDelegate(o == null ? null : o.getClass()); info.writeObject(o, this); } /** {@collect.stats} * Sets the exception handler for this stream to <code>exceptionListener</code>. * The exception handler is notified when this stream catches recoverable * exceptions. * * @param exceptionListener The exception handler for this stream; * if <code>null</code> the default exception listener will be used. * * @see #getExceptionListener */ public void setExceptionListener(ExceptionListener exceptionListener) { this.exceptionListener = exceptionListener; } /** {@collect.stats} * Gets the exception handler for this stream. * * @return The exception handler for this stream; * Will return the default exception listener if this has not explicitly been set. * * @see #setExceptionListener */ public ExceptionListener getExceptionListener() { return (exceptionListener != null) ? exceptionListener : Statement.defaultExceptionListener; } Object getValue(Expression exp) { try { return (exp == null) ? null : exp.getValue(); } catch (Exception e) { getExceptionListener().exceptionThrown(e); throw new RuntimeException("failed to evaluate: " + exp.toString()); } } /** {@collect.stats} * Returns the persistence delegate for the given type. * The persistence delegate is calculated * by applying the following of rules in order: * <ul> * <li> * If the type is an array, an internal persistence * delegate is returned which will instantiate an * array of the appropriate type and length, initializing * each of its elements as if they are properties. * <li> * If the type is a proxy, an internal persistence * delegate is returned which will instantiate a * new proxy instance using the static * "newProxyInstance" method defined in the * Proxy class. * <li> * If the BeanInfo for this type has a <code>BeanDescriptor</code> * which defined a "persistenceDelegate" property, this * value is returned. * <li> * In all other cases the default persistence delegate * is returned. The default persistence delegate assumes * the type is a <em>JavaBean</em>, implying that it has a default constructor * and that its state may be characterized by the matching pairs * of "setter" and "getter" methods returned by the Introspector. * The default constructor is the constructor with the greatest number * of parameters that has the {@link ConstructorProperties} annotation. * If none of the constructors have the {@code ConstructorProperties} annotation, * then the nullary constructor (constructor with no parameters) will be used. * For example, in the following the nullary constructor * for {@code Foo} will be used, while the two parameter constructor * for {@code Bar} will be used. * <code> * public class Foo { * public Foo() { ... } * public Foo(int x) { ... } * } * public class Bar { * public Bar() { ... } * &#64;ConstructorProperties({"x"}) * public Bar(int x) { ... } * &#64;ConstructorProperties({"x", "y"}) * public Bar(int x, int y) { ... } * } * </code> * </ul> * * @param type The type of the object. * @return The persistence delegate for this type of object. * * @see #setPersistenceDelegate * @see java.beans.Introspector#getBeanInfo * @see java.beans.BeanInfo#getBeanDescriptor */ public PersistenceDelegate getPersistenceDelegate(Class<?> type) { PersistenceDelegate pd = this.delegates.get(type); return (pd != null) ? pd : MetaData.getPersistenceDelegate(type); } /** {@collect.stats} * Sets the persistence delegate associated with this <code>type</code> to * <code>persistenceDelegate</code>. * * @param type The class of objects that <code>persistenceDelegate</code> applies to. * @param persistenceDelegate The persistence delegate for instances of <code>type</code>. * * @see #getPersistenceDelegate * @see java.beans.Introspector#getBeanInfo * @see java.beans.BeanInfo#getBeanDescriptor */ public void setPersistenceDelegate(Class<?> type, PersistenceDelegate persistenceDelegate) { if (persistenceDelegate != null) { this.delegates.put(type, persistenceDelegate); } else { this.delegates.remove(type); } } /** {@collect.stats} * Removes the entry for this instance, returning the old entry. * * @param oldInstance The entry that should be removed. * @return The entry that was removed. * * @see #get */ public Object remove(Object oldInstance) { Expression exp = (Expression)bindings.remove(oldInstance); return getValue(exp); } /** {@collect.stats} * Returns a tentative value for <code>oldInstance</code> in * the environment created by this stream. A persistence * delegate can use its <code>mutatesTo</code> method to * determine whether this value may be initialized to * form the equivalent object at the output or whether * a new object must be instantiated afresh. If the * stream has not yet seen this value, null is returned. * * @param oldInstance The instance to be looked up. * @return The object, null if the object has not been seen before. */ public Object get(Object oldInstance) { if (oldInstance == null || oldInstance == this || oldInstance.getClass() == String.class) { return oldInstance; } Expression exp = (Expression)bindings.get(oldInstance); return getValue(exp); } private Object writeObject1(Object oldInstance) { Object o = get(oldInstance); if (o == null) { writeObject(oldInstance); o = get(oldInstance); } return o; } private Statement cloneStatement(Statement oldExp) { Object oldTarget = oldExp.getTarget(); Object newTarget = writeObject1(oldTarget); Object[] oldArgs = oldExp.getArguments(); Object[] newArgs = new Object[oldArgs.length]; for (int i = 0; i < oldArgs.length; i++) { newArgs[i] = writeObject1(oldArgs[i]); } if (oldExp.getClass() == Statement.class) { return new Statement(newTarget, oldExp.getMethodName(), newArgs); } else { return new Expression(newTarget, oldExp.getMethodName(), newArgs); } } /** {@collect.stats} * Writes statement <code>oldStm</code> to the stream. * The <code>oldStm</code> should be written entirely * in terms of the callers environment, i.e. the * target and all arguments should be part of the * object graph being written. These expressions * represent a series of "what happened" expressions * which tell the output stream how to produce an * object graph like the original. * <p> * The implementation of this method will produce * a second expression to represent the same expression in * an environment that will exist when the stream is read. * This is achieved simply by calling <code>writeObject</code> * on the target and all the arguments and building a new * expression with the results. * * @param oldStm The expression to be written to the stream. */ public void writeStatement(Statement oldStm) { // System.out.println("writeStatement: " + oldExp); Statement newStm = cloneStatement(oldStm); if (oldStm.getTarget() != this && executeStatements) { try { newStm.execute(); } catch (Exception e) { getExceptionListener().exceptionThrown(new Exception("Encoder: discarding statement " + newStm, e)); } } } /** {@collect.stats} * The implementation first checks to see if an * expression with this value has already been written. * If not, the expression is cloned, using * the same procedure as <code>writeStatement</code>, * and the value of this expression is reconciled * with the value of the cloned expression * by calling <code>writeObject</code>. * * @param oldExp The expression to be written to the stream. */ public void writeExpression(Expression oldExp) { // System.out.println("Encoder::writeExpression: " + oldExp); Object oldValue = getValue(oldExp); if (get(oldValue) != null) { return; } bindings.put(oldValue, (Expression)cloneStatement(oldExp)); writeObject(oldValue); } void clear() { bindings.clear(); } // Package private method for setting an attributes table for the encoder void setAttribute(Object key, Object value) { if (attributes == null) { attributes = new HashMap(); } attributes.put(key, value); } Object getAttribute(Object key) { if (attributes == null) { return null; } return attributes.get(key); } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.util.*; import java.lang.reflect.*; import sun.reflect.misc.*; /** {@collect.stats} * The <code>DefaultPersistenceDelegate</code> is a concrete implementation of * the abstract <code>PersistenceDelegate</code> class and * is the delegate used by default for classes about * which no information is available. The <code>DefaultPersistenceDelegate</code> * provides, version resilient, public API-based persistence for * classes that follow the JavaBeans conventions without any class specific * configuration. * <p> * The key assumptions are that the class has a nullary constructor * and that its state is accurately represented by matching pairs * of "setter" and "getter" methods in the order they are returned * by the Introspector. * In addition to providing code-free persistence for JavaBeans, * the <code>DefaultPersistenceDelegate</code> provides a convenient means * to effect persistent storage for classes that have a constructor * that, while not nullary, simply requires some property values * as arguments. * * @see #DefaultPersistenceDelegate(String[]) * @see java.beans.Introspector * * @since 1.4 * * @author Philip Milne */ public class DefaultPersistenceDelegate extends PersistenceDelegate { private String[] constructor; private Boolean definesEquals; /** {@collect.stats} * Creates a persistence delegate for a class with a nullary constructor. * * @see #DefaultPersistenceDelegate(java.lang.String[]) */ public DefaultPersistenceDelegate() { this(new String[0]); } /** {@collect.stats} * Creates a default persistence delegate for a class with a * constructor whose arguments are the values of the property * names as specified by <code>constructorPropertyNames</code>. * The constructor arguments are created by * evaluating the property names in the order they are supplied. * To use this class to specify a single preferred constructor for use * in the serialization of a particular type, we state the * names of the properties that make up the constructor's * arguments. For example, the <code>Font</code> class which * does not define a nullary constructor can be handled * with the following persistence delegate: * * <pre> * new DefaultPersistenceDelegate(new String[]{"name", "style", "size"}); * </pre> * * @param constructorPropertyNames The property names for the arguments of this constructor. * * @see #instantiate */ public DefaultPersistenceDelegate(String[] constructorPropertyNames) { this.constructor = constructorPropertyNames; } private static boolean definesEquals(Class type) { try { return type == type.getMethod("equals", Object.class).getDeclaringClass(); } catch(NoSuchMethodException e) { return false; } } private boolean definesEquals(Object instance) { if (definesEquals != null) { return (definesEquals == Boolean.TRUE); } else { boolean result = definesEquals(instance.getClass()); definesEquals = result ? Boolean.TRUE : Boolean.FALSE; return result; } } /** {@collect.stats} * If the number of arguments in the specified constructor is non-zero and * the class of <code>oldInstance</code> explicitly declares an "equals" method * this method returns the value of <code>oldInstance.equals(newInstance)</code>. * Otherwise, this method uses the superclass's definition which returns true if the * classes of the two instances are equal. * * @param oldInstance The instance to be copied. * @param newInstance The instance that is to be modified. * @return True if an equivalent copy of <code>newInstance</code> may be * created by applying a series of mutations to <code>oldInstance</code>. * * @see #DefaultPersistenceDelegate(String[]) */ protected boolean mutatesTo(Object oldInstance, Object newInstance) { // Assume the instance is either mutable or a singleton // if it has a nullary constructor. return (constructor.length == 0) || !definesEquals(oldInstance) ? super.mutatesTo(oldInstance, newInstance) : oldInstance.equals(newInstance); } /** {@collect.stats} * This default implementation of the <code>instantiate</code> method returns * an expression containing the predefined method name "new" which denotes a * call to a constructor with the arguments as specified in * the <code>DefaultPersistenceDelegate</code>'s constructor. * * @param oldInstance The instance to be instantiated. * @param out The code output stream. * @return An expression whose value is <code>oldInstance</code>. * * @see #DefaultPersistenceDelegate(String[]) */ protected Expression instantiate(Object oldInstance, Encoder out) { int nArgs = constructor.length; Class type = oldInstance.getClass(); Object[] constructorArgs = new Object[nArgs]; for(int i = 0; i < nArgs; i++) { try { Method method = findMethod(type, this.constructor[i]); constructorArgs[i] = MethodUtil.invoke(method, oldInstance, new Object[0]); } catch (Exception e) { out.getExceptionListener().exceptionThrown(e); } } return new Expression(oldInstance, oldInstance.getClass(), "new", constructorArgs); } private Method findMethod(Class type, String property) throws IntrospectionException { if (property == null) { throw new IllegalArgumentException("Property name is null"); } BeanInfo info = Introspector.getBeanInfo(type); for (PropertyDescriptor pd : info.getPropertyDescriptors()) { if (property.equals(pd.getName())) { Method method = pd.getReadMethod(); if (method != null) { return method; } throw new IllegalStateException("Could not find getter for the property " + property); } } throw new IllegalStateException("Could not find property by the name " + property); } // This is a workaround for a bug in the introspector. // PropertyDescriptors are not shared amongst subclasses. private boolean isTransient(Class type, PropertyDescriptor pd) { if (type == null) { return false; } // This code was mistakenly deleted - it may be fine and // is more efficient than the code below. This should // all disappear anyway when property descriptors are shared // by the introspector. /* Method getter = pd.getReadMethod(); Class declaringClass = getter.getDeclaringClass(); if (declaringClass == type) { return Boolean.TRUE.equals(pd.getValue("transient")); } */ String pName = pd.getName(); BeanInfo info = MetaData.getBeanInfo(type); PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; ++i ) { PropertyDescriptor pd2 = propertyDescriptors[i]; if (pName.equals(pd2.getName())) { Object value = pd2.getValue("transient"); if (value != null) { return Boolean.TRUE.equals(value); } } } return isTransient(type.getSuperclass(), pd); } private static boolean equals(Object o1, Object o2) { return (o1 == null) ? (o2 == null) : o1.equals(o2); } private void doProperty(Class type, PropertyDescriptor pd, Object oldInstance, Object newInstance, Encoder out) throws Exception { Method getter = pd.getReadMethod(); Method setter = pd.getWriteMethod(); if (getter != null && setter != null && !isTransient(type, pd)) { Expression oldGetExp = new Expression(oldInstance, getter.getName(), new Object[]{}); Expression newGetExp = new Expression(newInstance, getter.getName(), new Object[]{}); Object oldValue = oldGetExp.getValue(); Object newValue = newGetExp.getValue(); out.writeExpression(oldGetExp); if (!equals(newValue, out.get(oldValue))) { // Search for a static constant with this value; Object e = (Object[])pd.getValue("enumerationValues"); if (e instanceof Object[] && Array.getLength(e) % 3 == 0) { Object[] a = (Object[])e; for(int i = 0; i < a.length; i = i + 3) { try { Field f = type.getField((String)a[i]); if (f.get(null).equals(oldValue)) { out.remove(oldValue); out.writeExpression(new Expression(oldValue, f, "get", new Object[]{null})); } } catch (Exception ex) {} } } invokeStatement(oldInstance, setter.getName(), new Object[]{oldValue}, out); } } } static void invokeStatement(Object instance, String methodName, Object[] args, Encoder out) { out.writeStatement(new Statement(instance, methodName, args)); } // Write out the properties of this instance. private void initBean(Class type, Object oldInstance, Object newInstance, Encoder out) { // System.out.println("initBean: " + oldInstance); BeanInfo info = MetaData.getBeanInfo(type); // Properties PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; ++i ) { try { doProperty(type, propertyDescriptors[i], oldInstance, newInstance, out); } catch (Exception e) { out.getExceptionListener().exceptionThrown(e); } } // Listeners /* Pending(milne). There is a general problem with the archival of listeners which is unresolved as of 1.4. Many of the methods which install one object inside another (typically "add" methods or setters) automatically install a listener on the "child" object so that its "parent" may respond to changes that are made to it. For example the JTable:setModel() method automatically adds a TableModelListener (the JTable itself in this case) to the supplied table model. We do not need to explictly add these listeners to the model in an archive as they will be added automatically by, in the above case, the JTable's "setModel" method. In some cases, we must specifically avoid trying to do this since the listener may be an inner class that cannot be instantiated using public API. No general mechanism currently exists for differentiating between these kind of listeners and those which were added explicitly by the user. A mechanism must be created to provide a general means to differentiate these special cases so as to provide reliable persistence of listeners for the general case. */ if (!java.awt.Component.class.isAssignableFrom(type)) { return; // Just handle the listeners of Components for now. } EventSetDescriptor[] eventSetDescriptors = info.getEventSetDescriptors(); for (int e = 0; e < eventSetDescriptors.length; e++) { EventSetDescriptor d = eventSetDescriptors[e]; Class listenerType = d.getListenerType(); // The ComponentListener is added automatically, when // Contatiner:add is called on the parent. if (listenerType == java.awt.event.ComponentListener.class) { continue; } // JMenuItems have a change listener added to them in // their "add" methods to enable accessibility support - // see the add method in JMenuItem for details. We cannot // instantiate this instance as it is a private inner class // and do not need to do this anyway since it will be created // and installed by the "add" method. Special case this for now, // ignoring all change listeners on JMenuItems. if (listenerType == javax.swing.event.ChangeListener.class && type == javax.swing.JMenuItem.class) { continue; } EventListener[] oldL = new EventListener[0]; EventListener[] newL = new EventListener[0]; try { Method m = d.getGetListenerMethod(); oldL = (EventListener[])MethodUtil.invoke(m, oldInstance, new Object[]{}); newL = (EventListener[])MethodUtil.invoke(m, newInstance, new Object[]{}); } catch (Throwable e2) { try { Method m = type.getMethod("getListeners", new Class[]{Class.class}); oldL = (EventListener[])MethodUtil.invoke(m, oldInstance, new Object[]{listenerType}); newL = (EventListener[])MethodUtil.invoke(m, newInstance, new Object[]{listenerType}); } catch (Exception e3) { return; } } // Asssume the listeners are in the same order and that there are no gaps. // Eventually, this may need to do true differencing. String addListenerMethodName = d.getAddListenerMethod().getName(); for (int i = newL.length; i < oldL.length; i++) { // System.out.println("Adding listener: " + addListenerMethodName + oldL[i]); invokeStatement(oldInstance, addListenerMethodName, new Object[]{oldL[i]}, out); } String removeListenerMethodName = d.getRemoveListenerMethod().getName(); for (int i = oldL.length; i < newL.length; i++) { invokeStatement(oldInstance, removeListenerMethodName, new Object[]{newL[i]}, out); } } } /** {@collect.stats} * This default implementation of the <code>initialize</code> method assumes * all state held in objects of this type is exposed via the * matching pairs of "setter" and "getter" methods in the order * they are returned by the Introspector. If a property descriptor * defines a "transient" attribute with a value equal to * <code>Boolean.TRUE</code> the property is ignored by this * default implementation. Note that this use of the word * "transient" is quite independent of the field modifier * that is used by the <code>ObjectOutputStream</code>. * <p> * For each non-transient property, an expression is created * in which the nullary "getter" method is applied * to the <code>oldInstance</code>. The value of this * expression is the value of the property in the instance that is * being serialized. If the value of this expression * in the cloned environment <code>mutatesTo</code> the * target value, the new value is initialized to make it * equivalent to the old value. In this case, because * the property value has not changed there is no need to * call the corresponding "setter" method and no statement * is emitted. If not however, the expression for this value * is replaced with another expression (normally a constructor) * and the corresponding "setter" method is called to install * the new property value in the object. This scheme removes * default information from the output produced by streams * using this delegate. * <p> * In passing these statements to the output stream, where they * will be executed, side effects are made to the <code>newInstance</code>. * In most cases this allows the problem of properties * whose values depend on each other to actually help the * serialization process by making the number of statements * that need to be written to the output smaller. In general, * the problem of handling interdependent properties is reduced to * that of finding an order for the properties in * a class such that no property value depends on the value of * a subsequent property. * * @param oldInstance The instance to be copied. * @param newInstance The instance that is to be modified. * @param out The stream to which any initialization statements should be written. * * @see java.beans.Introspector#getBeanInfo * @see java.beans.PropertyDescriptor */ protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { // System.out.println("DefulatPD:initialize" + type); super.initialize(type, oldInstance, newInstance, out); if (oldInstance.getClass() == type) { // !type.isInterface()) { initBean(type, oldInstance, newInstance, out); } } }
Java
/* * Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.util.EventListenerProxy; /** {@collect.stats} * A class which extends the <code>EventListenerProxy</code> specifically * for associating a <code>VetoableChangeListener</code> with a "constrained" * property. Instances of this class can be added as a * <code>VetoableChangeListener</code> to a bean which supports firing * VetoableChange events. * <p> * If the object has a <code>getVetoableChangeListeners()</code> * method then the array returned could be a mixture of * <code>VetoableChangeListener</code> and * <code>VetoableChangeListenerProxy</code> objects. * <p> * @see java.util.EventListenerProxy * @see VetoableChangeListener * @see VetoableChangeSupport#getVetoableChangeListeners * @since 1.4 */ public class VetoableChangeListenerProxy extends EventListenerProxy implements VetoableChangeListener { private String propertyName; /** {@collect.stats} * @param propertyName The name of the property to listen on. * @param listener The listener object */ public VetoableChangeListenerProxy(String propertyName, VetoableChangeListener listener) { super(listener); this.propertyName = propertyName; } /** {@collect.stats} * Forwards the property change event to the listener delegate. * * @param evt the property change event * * @exception PropertyVetoException if the recipient wishes the property * change to be rolled back. */ public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException{ ((VetoableChangeListener)getListener()).vetoableChange(evt); } /** {@collect.stats} * Returns the name of the named property associated with the * listener. */ public String getPropertyName() { return propertyName; } }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * This is a support class to make it easier for people to provide * BeanInfo classes. * <p> * It defaults to providing "noop" information, and can be selectively * overriden to provide more explicit information on chosen topics. * When the introspector sees the "noop" values, it will apply low * level introspection and design patterns to automatically analyze * the target bean. */ public class SimpleBeanInfo implements BeanInfo { /** {@collect.stats} * Deny knowledge about the class and customizer of the bean. * You can override this if you wish to provide explicit info. */ public BeanDescriptor getBeanDescriptor() { return null; } /** {@collect.stats} * Deny knowledge of properties. You can override this * if you wish to provide explicit property info. */ public PropertyDescriptor[] getPropertyDescriptors() { return null; } /** {@collect.stats} * Deny knowledge of a default property. You can override this * if you wish to define a default property for the bean. */ public int getDefaultPropertyIndex() { return -1; } /** {@collect.stats} * Deny knowledge of event sets. You can override this * if you wish to provide explicit event set info. */ public EventSetDescriptor[] getEventSetDescriptors() { return null; } /** {@collect.stats} * Deny knowledge of a default event. You can override this * if you wish to define a default event for the bean. */ public int getDefaultEventIndex() { return -1; } /** {@collect.stats} * Deny knowledge of methods. You can override this * if you wish to provide explicit method info. */ public MethodDescriptor[] getMethodDescriptors() { return null; } /** {@collect.stats} * Claim there are no other relevant BeanInfo objects. You * may override this if you want to (for example) return a * BeanInfo for a base class. */ public BeanInfo[] getAdditionalBeanInfo() { return null; } /** {@collect.stats} * Claim there are no icons available. You can override * this if you want to provide icons for your bean. */ public java.awt.Image getIcon(int iconKind) { return null; } /** {@collect.stats} * This is a utility method to help in loading icon images. * It takes the name of a resource file associated with the * current object's class file and loads an image object * from that file. Typically images will be GIFs. * <p> * @param resourceName A pathname relative to the directory * holding the class file of the current class. For example, * "wombat.gif". * @return an image object. May be null if the load failed. */ public java.awt.Image loadImage(final String resourceName) { try { final Class c = getClass(); java.awt.image.ImageProducer ip = (java.awt.image.ImageProducer) java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Object run() { java.net.URL url; if ((url = c.getResource(resourceName)) == null) { return null; } else { try { return url.getContent(); } catch (java.io.IOException ioe) { return null; } } } }); if (ip == null) return null; java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit(); return tk.createImage(ip); } catch (Exception ex) { return null; } } }
Java
/* * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.lang.ref.Reference; import java.lang.reflect.Method; /** {@collect.stats} * An EventSetDescriptor describes a group of events that a given Java * bean fires. * <P> * The given group of events are all delivered as method calls on a single * event listener interface, and an event listener object can be registered * via a call on a registration method supplied by the event source. */ public class EventSetDescriptor extends FeatureDescriptor { private MethodDescriptor[] listenerMethodDescriptors; private MethodDescriptor addMethodDescriptor; private MethodDescriptor removeMethodDescriptor; private MethodDescriptor getMethodDescriptor; private Reference<Method[]> listenerMethodsRef; private Reference<Class> listenerTypeRef; private boolean unicast; private boolean inDefaultEventSet = true; /** {@collect.stats} * Creates an <TT>EventSetDescriptor</TT> assuming that you are * following the most simple standard design pattern where a named * event &quot;fred&quot; is (1) delivered as a call on the single method of * interface FredListener, (2) has a single argument of type FredEvent, * and (3) where the FredListener may be registered with a call on an * addFredListener method of the source component and removed with a * call on a removeFredListener method. * * @param sourceClass The class firing the event. * @param eventSetName The programmatic name of the event. E.g. &quot;fred&quot;. * Note that this should normally start with a lower-case character. * @param listenerType The target interface that events * will get delivered to. * @param listenerMethodName The method that will get called when the event gets * delivered to its target listener interface. * @exception IntrospectionException if an exception occurs during * introspection. */ public EventSetDescriptor(Class<?> sourceClass, String eventSetName, Class<?> listenerType, String listenerMethodName) throws IntrospectionException { this(sourceClass, eventSetName, listenerType, new String[] { listenerMethodName }, Introspector.ADD_PREFIX + getListenerClassName(listenerType), Introspector.REMOVE_PREFIX + getListenerClassName(listenerType), Introspector.GET_PREFIX + getListenerClassName(listenerType) + "s"); String eventName = NameGenerator.capitalize(eventSetName) + "Event"; Method[] listenerMethods = getListenerMethods(); if (listenerMethods.length > 0) { Class[] args = getParameterTypes(getClass0(), listenerMethods[0]); // Check for EventSet compliance. Special case for vetoableChange. See 4529996 if (!"vetoableChange".equals(eventSetName) && !args[0].getName().endsWith(eventName)) { throw new IntrospectionException("Method \"" + listenerMethodName + "\" should have argument \"" + eventName + "\""); } } } private static String getListenerClassName(Class cls) { String className = cls.getName(); return className.substring(className.lastIndexOf('.') + 1); } /** {@collect.stats} * Creates an <TT>EventSetDescriptor</TT> from scratch using * string names. * * @param sourceClass The class firing the event. * @param eventSetName The programmatic name of the event set. * Note that this should normally start with a lower-case character. * @param listenerType The Class of the target interface that events * will get delivered to. * @param listenerMethodNames The names of the methods that will get called * when the event gets delivered to its target listener interface. * @param addListenerMethodName The name of the method on the event source * that can be used to register an event listener object. * @param removeListenerMethodName The name of the method on the event source * that can be used to de-register an event listener object. * @exception IntrospectionException if an exception occurs during * introspection. */ public EventSetDescriptor(Class<?> sourceClass, String eventSetName, Class<?> listenerType, String listenerMethodNames[], String addListenerMethodName, String removeListenerMethodName) throws IntrospectionException { this(sourceClass, eventSetName, listenerType, listenerMethodNames, addListenerMethodName, removeListenerMethodName, null); } /** {@collect.stats} * This constructor creates an EventSetDescriptor from scratch using * string names. * * @param sourceClass The class firing the event. * @param eventSetName The programmatic name of the event set. * Note that this should normally start with a lower-case character. * @param listenerType The Class of the target interface that events * will get delivered to. * @param listenerMethodNames The names of the methods that will get called * when the event gets delivered to its target listener interface. * @param addListenerMethodName The name of the method on the event source * that can be used to register an event listener object. * @param removeListenerMethodName The name of the method on the event source * that can be used to de-register an event listener object. * @param getListenerMethodName The method on the event source that * can be used to access the array of event listener objects. * @exception IntrospectionException if an exception occurs during * introspection. * @since 1.4 */ public EventSetDescriptor(Class<?> sourceClass, String eventSetName, Class<?> listenerType, String listenerMethodNames[], String addListenerMethodName, String removeListenerMethodName, String getListenerMethodName) throws IntrospectionException { if (sourceClass == null || eventSetName == null || listenerType == null) { throw new NullPointerException(); } setName(eventSetName); setClass0(sourceClass); setListenerType(listenerType); Method[] listenerMethods = new Method[listenerMethodNames.length]; for (int i = 0; i < listenerMethodNames.length; i++) { // Check for null names if (listenerMethodNames[i] == null) { throw new NullPointerException(); } listenerMethods[i] = getMethod(listenerType, listenerMethodNames[i], 1); } setListenerMethods(listenerMethods); setAddListenerMethod(getMethod(sourceClass, addListenerMethodName, 1)); setRemoveListenerMethod(getMethod(sourceClass, removeListenerMethodName, 1)); // Be more forgiving of not finding the getListener method. Method method = Introspector.findMethod(sourceClass, getListenerMethodName, 0); if (method != null) { setGetListenerMethod(method); } } private static Method getMethod(Class cls, String name, int args) throws IntrospectionException { if (name == null) { return null; } Method method = Introspector.findMethod(cls, name, args); if (method == null) { throw new IntrospectionException("Method not found: " + name + " on class " + cls.getName()); } return method; } /** {@collect.stats} * Creates an <TT>EventSetDescriptor</TT> from scratch using * <TT>java.lang.reflect.Method</TT> and <TT>java.lang.Class</TT> objects. * * @param eventSetName The programmatic name of the event set. * @param listenerType The Class for the listener interface. * @param listenerMethods An array of Method objects describing each * of the event handling methods in the target listener. * @param addListenerMethod The method on the event source * that can be used to register an event listener object. * @param removeListenerMethod The method on the event source * that can be used to de-register an event listener object. * @exception IntrospectionException if an exception occurs during * introspection. */ public EventSetDescriptor(String eventSetName, Class<?> listenerType, Method listenerMethods[], Method addListenerMethod, Method removeListenerMethod) throws IntrospectionException { this(eventSetName, listenerType, listenerMethods, addListenerMethod, removeListenerMethod, null); } /** {@collect.stats} * This constructor creates an EventSetDescriptor from scratch using * java.lang.reflect.Method and java.lang.Class objects. * * @param eventSetName The programmatic name of the event set. * @param listenerType The Class for the listener interface. * @param listenerMethods An array of Method objects describing each * of the event handling methods in the target listener. * @param addListenerMethod The method on the event source * that can be used to register an event listener object. * @param removeListenerMethod The method on the event source * that can be used to de-register an event listener object. * @param getListenerMethod The method on the event source * that can be used to access the array of event listener objects. * @exception IntrospectionException if an exception occurs during * introspection. * @since 1.4 */ public EventSetDescriptor(String eventSetName, Class<?> listenerType, Method listenerMethods[], Method addListenerMethod, Method removeListenerMethod, Method getListenerMethod) throws IntrospectionException { setName(eventSetName); setListenerMethods(listenerMethods); setAddListenerMethod(addListenerMethod); setRemoveListenerMethod( removeListenerMethod); setGetListenerMethod(getListenerMethod); setListenerType(listenerType); } /** {@collect.stats} * Creates an <TT>EventSetDescriptor</TT> from scratch using * <TT>java.lang.reflect.MethodDescriptor</TT> and <TT>java.lang.Class</TT> * objects. * * @param eventSetName The programmatic name of the event set. * @param listenerType The Class for the listener interface. * @param listenerMethodDescriptors An array of MethodDescriptor objects * describing each of the event handling methods in the * target listener. * @param addListenerMethod The method on the event source * that can be used to register an event listener object. * @param removeListenerMethod The method on the event source * that can be used to de-register an event listener object. * @exception IntrospectionException if an exception occurs during * introspection. */ public EventSetDescriptor(String eventSetName, Class<?> listenerType, MethodDescriptor listenerMethodDescriptors[], Method addListenerMethod, Method removeListenerMethod) throws IntrospectionException { setName(eventSetName); this.listenerMethodDescriptors = listenerMethodDescriptors; setAddListenerMethod(addListenerMethod); setRemoveListenerMethod(removeListenerMethod); setListenerType(listenerType); } /** {@collect.stats} * Gets the <TT>Class</TT> object for the target interface. * * @return The Class object for the target interface that will * get invoked when the event is fired. */ public Class<?> getListenerType() { return (this.listenerTypeRef != null) ? this.listenerTypeRef.get() : null; } private void setListenerType(Class cls) { this.listenerTypeRef = getWeakReference(cls); } /** {@collect.stats} * Gets the methods of the target listener interface. * * @return An array of <TT>Method</TT> objects for the target methods * within the target listener interface that will get called when * events are fired. */ public synchronized Method[] getListenerMethods() { Method[] methods = getListenerMethods0(); if (methods == null) { if (listenerMethodDescriptors != null) { methods = new Method[listenerMethodDescriptors.length]; for (int i = 0; i < methods.length; i++) { methods[i] = listenerMethodDescriptors[i].getMethod(); } } setListenerMethods(methods); } return methods; } private void setListenerMethods(Method[] methods) { if (methods == null) { return; } if (listenerMethodDescriptors == null) { listenerMethodDescriptors = new MethodDescriptor[methods.length]; for (int i = 0; i < methods.length; i++) { listenerMethodDescriptors[i] = new MethodDescriptor(methods[i]); } } this.listenerMethodsRef = getSoftReference(methods); } private Method[] getListenerMethods0() { return (this.listenerMethodsRef != null) ? this.listenerMethodsRef.get() : null; } /** {@collect.stats} * Gets the <code>MethodDescriptor</code>s of the target listener interface. * * @return An array of <code>MethodDescriptor</code> objects for the target methods * within the target listener interface that will get called when * events are fired. */ public synchronized MethodDescriptor[] getListenerMethodDescriptors() { return listenerMethodDescriptors; } /** {@collect.stats} * Gets the method used to add event listeners. * * @return The method used to register a listener at the event source. */ public synchronized Method getAddListenerMethod() { return (addMethodDescriptor != null ? addMethodDescriptor.getMethod() : null); } private synchronized void setAddListenerMethod(Method method) { if (method == null) { return; } if (getClass0() == null) { setClass0(method.getDeclaringClass()); } addMethodDescriptor = new MethodDescriptor(method); } /** {@collect.stats} * Gets the method used to remove event listeners. * * @return The method used to remove a listener at the event source. */ public synchronized Method getRemoveListenerMethod() { return (removeMethodDescriptor != null ? removeMethodDescriptor.getMethod() : null); } private synchronized void setRemoveListenerMethod(Method method) { if (method == null) { return; } if (getClass0() == null) { setClass0(method.getDeclaringClass()); } removeMethodDescriptor = new MethodDescriptor(method); } /** {@collect.stats} * Gets the method used to access the registered event listeners. * * @return The method used to access the array of listeners at the event * source or null if it doesn't exist. * @since 1.4 */ public synchronized Method getGetListenerMethod() { return (getMethodDescriptor != null ? getMethodDescriptor.getMethod() : null); } private synchronized void setGetListenerMethod(Method method) { if (method == null) { return; } if (getClass0() == null) { setClass0(method.getDeclaringClass()); } getMethodDescriptor = new MethodDescriptor(method); } /** {@collect.stats} * Mark an event set as unicast (or not). * * @param unicast True if the event set is unicast. */ public void setUnicast(boolean unicast) { this.unicast = unicast; } /** {@collect.stats} * Normally event sources are multicast. However there are some * exceptions that are strictly unicast. * * @return <TT>true</TT> if the event set is unicast. * Defaults to <TT>false</TT>. */ public boolean isUnicast() { return unicast; } /** {@collect.stats} * Marks an event set as being in the &quot;default&quot; set (or not). * By default this is <TT>true</TT>. * * @param inDefaultEventSet <code>true</code> if the event set is in * the &quot;default&quot; set, * <code>false</code> if not */ public void setInDefaultEventSet(boolean inDefaultEventSet) { this.inDefaultEventSet = inDefaultEventSet; } /** {@collect.stats} * Reports if an event set is in the &quot;default&quot; set. * * @return <TT>true</TT> if the event set is in * the &quot;default&quot; set. Defaults to <TT>true</TT>. */ public boolean isInDefaultEventSet() { return inDefaultEventSet; } /* * Package-private constructor * Merge two event set descriptors. Where they conflict, give the * second argument (y) priority over the first argument (x). * * @param x The first (lower priority) EventSetDescriptor * @param y The second (higher priority) EventSetDescriptor */ EventSetDescriptor(EventSetDescriptor x, EventSetDescriptor y) { super(x,y); listenerMethodDescriptors = x.listenerMethodDescriptors; if (y.listenerMethodDescriptors != null) { listenerMethodDescriptors = y.listenerMethodDescriptors; } listenerTypeRef = x.listenerTypeRef; if (y.listenerTypeRef != null) { listenerTypeRef = y.listenerTypeRef; } addMethodDescriptor = x.addMethodDescriptor; if (y.addMethodDescriptor != null) { addMethodDescriptor = y.addMethodDescriptor; } removeMethodDescriptor = x.removeMethodDescriptor; if (y.removeMethodDescriptor != null) { removeMethodDescriptor = y.removeMethodDescriptor; } getMethodDescriptor = x.getMethodDescriptor; if (y.getMethodDescriptor != null) { getMethodDescriptor = y.getMethodDescriptor; } unicast = y.unicast; if (!x.inDefaultEventSet || !y.inDefaultEventSet) { inDefaultEventSet = false; } } /* * Package-private dup constructor * This must isolate the new object from any changes to the old object. */ EventSetDescriptor(EventSetDescriptor old) { super(old); if (old.listenerMethodDescriptors != null) { int len = old.listenerMethodDescriptors.length; listenerMethodDescriptors = new MethodDescriptor[len]; for (int i = 0; i < len; i++) { listenerMethodDescriptors[i] = new MethodDescriptor( old.listenerMethodDescriptors[i]); } } listenerTypeRef = old.listenerTypeRef; addMethodDescriptor = old.addMethodDescriptor; removeMethodDescriptor = old.removeMethodDescriptor; getMethodDescriptor = old.getMethodDescriptor; unicast = old.unicast; inDefaultEventSet = old.inDefaultEventSet; } }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import com.sun.beans.finder.ClassFinder; import java.applet.*; import java.awt.*; import java.beans.AppletInitializer; import java.beans.beancontext.BeanContext; import java.io.*; import java.lang.reflect.Constructor; import java.net.URL; import java.lang.reflect.Array; /** {@collect.stats} * This class provides some general purpose beans control methods. */ public class Beans { /** {@collect.stats} * <p> * Instantiate a JavaBean. * </p> * * @param cls the class-loader from which we should create * the bean. If this is null, then the system * class-loader is used. * @param beanName the name of the bean within the class-loader. * For example "sun.beanbox.foobah" * * @exception java.lang.ClassNotFoundException if the class of a serialized * object could not be found. * @exception java.io.IOException if an I/O error occurs. */ public static Object instantiate(ClassLoader cls, String beanName) throws java.io.IOException, ClassNotFoundException { return Beans.instantiate(cls, beanName, null, null); } /** {@collect.stats} * <p> * Instantiate a JavaBean. * </p> * * @param cls the class-loader from which we should create * the bean. If this is null, then the system * class-loader is used. * @param beanName the name of the bean within the class-loader. * For example "sun.beanbox.foobah" * @param beanContext The BeanContext in which to nest the new bean * * @exception java.lang.ClassNotFoundException if the class of a serialized * object could not be found. * @exception java.io.IOException if an I/O error occurs. */ public static Object instantiate(ClassLoader cls, String beanName, BeanContext beanContext) throws java.io.IOException, ClassNotFoundException { return Beans.instantiate(cls, beanName, beanContext, null); } /** {@collect.stats} * Instantiate a bean. * <p> * The bean is created based on a name relative to a class-loader. * This name should be a dot-separated name such as "a.b.c". * <p> * In Beans 1.0 the given name can indicate either a serialized object * or a class. Other mechanisms may be added in the future. In * beans 1.0 we first try to treat the beanName as a serialized object * name then as a class name. * <p> * When using the beanName as a serialized object name we convert the * given beanName to a resource pathname and add a trailing ".ser" suffix. * We then try to load a serialized object from that resource. * <p> * For example, given a beanName of "x.y", Beans.instantiate would first * try to read a serialized object from the resource "x/y.ser" and if * that failed it would try to load the class "x.y" and create an * instance of that class. * <p> * If the bean is a subtype of java.applet.Applet, then it is given * some special initialization. First, it is supplied with a default * AppletStub and AppletContext. Second, if it was instantiated from * a classname the applet's "init" method is called. (If the bean was * deserialized this step is skipped.) * <p> * Note that for beans which are applets, it is the caller's responsiblity * to call "start" on the applet. For correct behaviour, this should be done * after the applet has been added into a visible AWT container. * <p> * Note that applets created via beans.instantiate run in a slightly * different environment than applets running inside browsers. In * particular, bean applets have no access to "parameters", so they may * wish to provide property get/set methods to set parameter values. We * advise bean-applet developers to test their bean-applets against both * the JDK appletviewer (for a reference browser environment) and the * BDK BeanBox (for a reference bean container). * * @param cls the class-loader from which we should create * the bean. If this is null, then the system * class-loader is used. * @param beanName the name of the bean within the class-loader. * For example "sun.beanbox.foobah" * @param beanContext The BeanContext in which to nest the new bean * @param initializer The AppletInitializer for the new bean * * @exception java.lang.ClassNotFoundException if the class of a serialized * object could not be found. * @exception java.io.IOException if an I/O error occurs. */ public static Object instantiate(ClassLoader cls, String beanName, BeanContext beanContext, AppletInitializer initializer) throws java.io.IOException, ClassNotFoundException { java.io.InputStream ins; java.io.ObjectInputStream oins = null; Object result = null; boolean serialized = false; java.io.IOException serex = null; // If the given classloader is null, we check if an // system classloader is available and (if so) // use that instead. // Note that calls on the system class loader will // look in the bootstrap class loader first. if (cls == null) { try { cls = ClassLoader.getSystemClassLoader(); } catch (SecurityException ex) { // We're not allowed to access the system class loader. // Drop through. } } // Try to find a serialized object with this name final String serName = beanName.replace('.','/').concat(".ser"); final ClassLoader loader = cls; ins = (InputStream)java.security.AccessController.doPrivileged (new java.security.PrivilegedAction() { public Object run() { if (loader == null) return ClassLoader.getSystemResourceAsStream(serName); else return loader.getResourceAsStream(serName); } }); if (ins != null) { try { if (cls == null) { oins = new ObjectInputStream(ins); } else { oins = new ObjectInputStreamWithLoader(ins, cls); } result = oins.readObject(); serialized = true; oins.close(); } catch (java.io.IOException ex) { ins.close(); // Drop through and try opening the class. But remember // the exception in case we can't find the class either. serex = ex; } catch (ClassNotFoundException ex) { ins.close(); throw ex; } } if (result == null) { // No serialized object, try just instantiating the class Class cl; try { cl = ClassFinder.findClass(beanName, cls); } catch (ClassNotFoundException ex) { // There is no appropriate class. If we earlier tried to // deserialize an object and got an IO exception, throw that, // otherwise rethrow the ClassNotFoundException. if (serex != null) { throw serex; } throw ex; } /* * Try to instantiate the class. */ try { result = cl.newInstance(); } catch (Exception ex) { // We have to remap the exception to one in our signature. // But we pass extra information in the detail message. throw new ClassNotFoundException("" + cl + " : " + ex, ex); } } if (result != null) { // Ok, if the result is an applet initialize it. AppletStub stub = null; if (result instanceof Applet) { Applet applet = (Applet) result; boolean needDummies = initializer == null; if (needDummies) { // Figure our the codebase and docbase URLs. We do this // by locating the URL for a known resource, and then // massaging the URL. // First find the "resource name" corresponding to the bean // itself. So a serialzied bean "a.b.c" would imply a // resource name of "a/b/c.ser" and a classname of "x.y" // would imply a resource name of "x/y.class". final String resourceName; if (serialized) { // Serialized bean resourceName = beanName.replace('.','/').concat(".ser"); } else { // Regular class resourceName = beanName.replace('.','/').concat(".class"); } URL objectUrl = null; URL codeBase = null; URL docBase = null; // Now get the URL correponding to the resource name. final ClassLoader cloader = cls; objectUrl = (URL) java.security.AccessController.doPrivileged (new java.security.PrivilegedAction() { public Object run() { if (cloader == null) return ClassLoader.getSystemResource (resourceName); else return cloader.getResource(resourceName); } }); // If we found a URL, we try to locate the docbase by taking // of the final path name component, and the code base by taking // of the complete resourceName. // So if we had a resourceName of "a/b/c.class" and we got an // objectURL of "file://bert/classes/a/b/c.class" then we would // want to set the codebase to "file://bert/classes/" and the // docbase to "file://bert/classes/a/b/" if (objectUrl != null) { String s = objectUrl.toExternalForm(); if (s.endsWith(resourceName)) { int ix = s.length() - resourceName.length(); codeBase = new URL(s.substring(0,ix)); docBase = codeBase; ix = s.lastIndexOf('/'); if (ix >= 0) { docBase = new URL(s.substring(0,ix+1)); } } } // Setup a default context and stub. BeansAppletContext context = new BeansAppletContext(applet); stub = (AppletStub)new BeansAppletStub(applet, context, codeBase, docBase); applet.setStub(stub); } else { initializer.initialize(applet, beanContext); } // now, if there is a BeanContext, add the bean, if applicable. if (beanContext != null) { beanContext.add(result); } // If it was deserialized then it was already init-ed. // Otherwise we need to initialize it. if (!serialized) { // We need to set a reasonable initial size, as many // applets are unhappy if they are started without // having been explicitly sized. applet.setSize(100,100); applet.init(); } if (needDummies) { ((BeansAppletStub)stub).active = true; } else initializer.activate(applet); } else if (beanContext != null) beanContext.add(result); } return result; } /** {@collect.stats} * From a given bean, obtain an object representing a specified * type view of that source object. * <p> * The result may be the same object or a different object. If * the requested target view isn't available then the given * bean is returned. * <p> * This method is provided in Beans 1.0 as a hook to allow the * addition of more flexible bean behaviour in the future. * * @param bean Object from which we want to obtain a view. * @param targetType The type of view we'd like to get. * */ public static Object getInstanceOf(Object bean, Class<?> targetType) { return bean; } /** {@collect.stats} * Check if a bean can be viewed as a given target type. * The result will be true if the Beans.getInstanceof method * can be used on the given bean to obtain an object that * represents the specified targetType type view. * * @param bean Bean from which we want to obtain a view. * @param targetType The type of view we'd like to get. * @return "true" if the given bean supports the given targetType. * */ public static boolean isInstanceOf(Object bean, Class<?> targetType) { return Introspector.isSubclass(bean.getClass(), targetType); } /** {@collect.stats} * Test if we are in design-mode. * * @return True if we are running in an application construction * environment. * * @see java.beans.DesignMode */ public static boolean isDesignTime() { return designTime; } /** {@collect.stats} * Determines whether beans can assume a GUI is available. * * @return True if we are running in an environment where beans * can assume that an interactive GUI is available, so they * can pop up dialog boxes, etc. This will normally return * true in a windowing environment, and will normally return * false in a server environment or if an application is * running as part of a batch job. * * @see java.beans.Visibility * */ public static boolean isGuiAvailable() { return guiAvailable; } /** {@collect.stats} * Used to indicate whether of not we are running in an application * builder environment. * * <p>Note that this method is security checked * and is not available to (for example) untrusted applets. * More specifically, if there is a security manager, * its <code>checkPropertiesAccess</code> * method is called. This could result in a SecurityException. * * @param isDesignTime True if we're in an application builder tool. * @exception SecurityException if a security manager exists and its * <code>checkPropertiesAccess</code> method doesn't allow setting * of system properties. * @see SecurityManager#checkPropertiesAccess */ public static void setDesignTime(boolean isDesignTime) throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } designTime = isDesignTime; } /** {@collect.stats} * Used to indicate whether of not we are running in an environment * where GUI interaction is available. * * <p>Note that this method is security checked * and is not available to (for example) untrusted applets. * More specifically, if there is a security manager, * its <code>checkPropertiesAccess</code> * method is called. This could result in a SecurityException. * * @param isGuiAvailable True if GUI interaction is available. * @exception SecurityException if a security manager exists and its * <code>checkPropertiesAccess</code> method doesn't allow setting * of system properties. * @see SecurityManager#checkPropertiesAccess */ public static void setGuiAvailable(boolean isGuiAvailable) throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } guiAvailable = isGuiAvailable; } private static boolean designTime; private static boolean guiAvailable; static { guiAvailable = !GraphicsEnvironment.isHeadless(); } } /** {@collect.stats} * This subclass of ObjectInputStream delegates loading of classes to * an existing ClassLoader. */ class ObjectInputStreamWithLoader extends ObjectInputStream { private ClassLoader loader; /** {@collect.stats} * Loader must be non-null; */ public ObjectInputStreamWithLoader(InputStream in, ClassLoader loader) throws IOException, StreamCorruptedException { super(in); if (loader == null) { throw new IllegalArgumentException("Illegal null argument to ObjectInputStreamWithLoader"); } this.loader = loader; } /** {@collect.stats} * Use the given ClassLoader rather than using the system class */ protected Class resolveClass(ObjectStreamClass classDesc) throws IOException, ClassNotFoundException { String cname = classDesc.getName(); return ClassFinder.resolveClass(cname, this.loader); } } /** {@collect.stats} * Package private support class. This provides a default AppletContext * for beans which are applets. */ class BeansAppletContext implements AppletContext { Applet target; java.util.Hashtable imageCache = new java.util.Hashtable(); BeansAppletContext(Applet target) { this.target = target; } public AudioClip getAudioClip(URL url) { // We don't currently support audio clips in the Beans.instantiate // applet context, unless by some luck there exists a URL content // class that can generate an AudioClip from the audio URL. try { return (AudioClip) url.getContent(); } catch (Exception ex) { return null; } } public synchronized Image getImage(URL url) { Object o = imageCache.get(url); if (o != null) { return (Image)o; } try { o = url.getContent(); if (o == null) { return null; } if (o instanceof Image) { imageCache.put(url, o); return (Image) o; } // Otherwise it must be an ImageProducer. Image img = target.createImage((java.awt.image.ImageProducer)o); imageCache.put(url, img); return img; } catch (Exception ex) { return null; } } public Applet getApplet(String name) { return null; } public java.util.Enumeration getApplets() { java.util.Vector applets = new java.util.Vector(); applets.addElement(target); return applets.elements(); } public void showDocument(URL url) { // We do nothing. } public void showDocument(URL url, String target) { // We do nothing. } public void showStatus(String status) { // We do nothing. } public void setStream(String key, InputStream stream)throws IOException{ // We do nothing. } public InputStream getStream(String key){ // We do nothing. return null; } public java.util.Iterator getStreamKeys(){ // We do nothing. return null; } } /** {@collect.stats} * Package private support class. This provides an AppletStub * for beans which are applets. */ class BeansAppletStub implements AppletStub { transient boolean active; transient Applet target; transient AppletContext context; transient URL codeBase; transient URL docBase; BeansAppletStub(Applet target, AppletContext context, URL codeBase, URL docBase) { this.target = target; this.context = context; this.codeBase = codeBase; this.docBase = docBase; } public boolean isActive() { return active; } public URL getDocumentBase() { // use the root directory of the applet's class-loader return docBase; } public URL getCodeBase() { // use the directory where we found the class or serialized object. return codeBase; } public String getParameter(String name) { return null; } public AppletContext getAppletContext() { return context; } public void appletResize(int width, int height) { // we do nothing. } }
Java
/* * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * An "IndexedPropertyChange" event gets delivered whenever a component that * conforms to the JavaBeans<TM> specification (a "bean") changes a bound * indexed property. This class is an extension of <code>PropertyChangeEvent</code> * but contains the index of the property that has changed. * <P> * Null values may be provided for the old and the new values if their * true values are not known. * <P> * An event source may send a null object as the name to indicate that an * arbitrary set of if its properties have changed. In this case the * old and new values should also be null. * * @since 1.5 * @author Mark Davidson */ public class IndexedPropertyChangeEvent extends PropertyChangeEvent { private int index; /** {@collect.stats} * Constructs a new <code>IndexedPropertyChangeEvent</code> object. * * @param source The bean that fired the event. * @param propertyName The programmatic name of the property that * was changed. * @param oldValue The old value of the property. * @param newValue The new value of the property. * @param index index of the property element that was changed. */ public IndexedPropertyChangeEvent(Object source, String propertyName, Object oldValue, Object newValue, int index) { super (source, propertyName, oldValue, newValue); this.index = index; } /** {@collect.stats} * Gets the index of the property that was changed. * * @return The index specifying the property element that was * changed. */ public int getIndex() { return index; } }
Java
/* * Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * An ExceptionListener is notified of internal exceptions. * * @since 1.4 * * @author Philip Milne */ public interface ExceptionListener { /** {@collect.stats} * This method is called when a recoverable exception has * been caught. * * @param e The exception that was caught. * */ public void exceptionThrown(Exception e); }
Java
/* * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * A PropertyEditor class provides support for GUIs that want to * allow users to edit a property value of a given type. * <p> * PropertyEditor supports a variety of different kinds of ways of * displaying and updating property values. Most PropertyEditors will * only need to support a subset of the different options available in * this API. * <P> * Simple PropertyEditors may only support the getAsText and setAsText * methods and need not support (say) paintValue or getCustomEditor. More * complex types may be unable to support getAsText and setAsText but will * instead support paintValue and getCustomEditor. * <p> * Every propertyEditor must support one or more of the three simple * display styles. Thus it can either (1) support isPaintable or (2) * both return a non-null String[] from getTags() and return a non-null * value from getAsText or (3) simply return a non-null String from * getAsText(). * <p> * Every property editor must support a call on setValue when the argument * object is of the type for which this is the corresponding propertyEditor. * In addition, each property editor must either support a custom editor, * or support setAsText. * <p> * Each PropertyEditor should have a null constructor. */ public interface PropertyEditor { /** {@collect.stats} * Set (or change) the object that is to be edited. Primitive types such * as "int" must be wrapped as the corresponding object type such as * "java.lang.Integer". * * @param value The new target object to be edited. Note that this * object should not be modified by the PropertyEditor, rather * the PropertyEditor should create a new object to hold any * modified value. */ void setValue(Object value); /** {@collect.stats} * Gets the property value. * * @return The value of the property. Primitive types such as "int" will * be wrapped as the corresponding object type such as "java.lang.Integer". */ Object getValue(); //---------------------------------------------------------------------- /** {@collect.stats} * Determines whether this property editor is paintable. * * @return True if the class will honor the paintValue method. */ boolean isPaintable(); /** {@collect.stats} * Paint a representation of the value into a given area of screen * real estate. Note that the propertyEditor is responsible for doing * its own clipping so that it fits into the given rectangle. * <p> * If the PropertyEditor doesn't honor paint requests (see isPaintable) * this method should be a silent noop. * <p> * The given Graphics object will have the default font, color, etc of * the parent container. The PropertyEditor may change graphics attributes * such as font and color and doesn't need to restore the old values. * * @param gfx Graphics object to paint into. * @param box Rectangle within graphics object into which we should paint. */ void paintValue(java.awt.Graphics gfx, java.awt.Rectangle box); //---------------------------------------------------------------------- /** {@collect.stats} * Returns a fragment of Java code that can be used to set a property * to match the editors current state. This method is intended * for use when generating Java code to reflect changes made through the * property editor. * <p> * The code fragment should be context free and must be a legal Java * expression as specified by the JLS. * <p> * Specifically, if the expression represents a computation then all * classes and static members should be fully qualified. This rule * applies to constructors, static methods and non primitive arguments. * <p> * Caution should be used when evaluating the expression as it may throw * exceptions. In particular, code generators must ensure that generated * code will compile in the presence of an expression that can throw * checked exceptions. * <p> * Example results are: * <ul> * <li>Primitive expresssion: <code>2</code> * <li>Class constructor: <code>new java.awt.Color(127,127,34)</code> * <li>Static field: <code>java.awt.Color.orange</code> * <li>Static method: <code>javax.swing.Box.createRigidArea(new * java.awt.Dimension(0, 5))</code> * </ul> * * @return a fragment of Java code representing an initializer for the * current value. It should not contain a semi-colon * ('<code>;</code>') to end the expression. */ String getJavaInitializationString(); //---------------------------------------------------------------------- /** {@collect.stats} * Gets the property value as text. * * @return The property value as a human editable string. * <p> Returns null if the value can't be expressed as an editable string. * <p> If a non-null value is returned, then the PropertyEditor should * be prepared to parse that string back in setAsText(). */ String getAsText(); /** {@collect.stats} * Set the property value by parsing a given String. May raise * java.lang.IllegalArgumentException if either the String is * badly formatted or if this kind of property can't be expressed * as text. * @param text The string to be parsed. */ void setAsText(String text) throws java.lang.IllegalArgumentException; //---------------------------------------------------------------------- /** {@collect.stats} * If the property value must be one of a set of known tagged values, * then this method should return an array of the tags. This can * be used to represent (for example) enum values. If a PropertyEditor * supports tags, then it should support the use of setAsText with * a tag value as a way of setting the value and the use of getAsText * to identify the current value. * * @return The tag values for this property. May be null if this * property cannot be represented as a tagged value. * */ String[] getTags(); //---------------------------------------------------------------------- /** {@collect.stats} * A PropertyEditor may choose to make available a full custom Component * that edits its property value. It is the responsibility of the * PropertyEditor to hook itself up to its editor Component itself and * to report property value changes by firing a PropertyChange event. * <P> * The higher-level code that calls getCustomEditor may either embed * the Component in some larger property sheet, or it may put it in * its own individual dialog, or ... * * @return A java.awt.Component that will allow a human to directly * edit the current property value. May be null if this is * not supported. */ java.awt.Component getCustomEditor(); /** {@collect.stats} * Determines whether this property editor supports a custom editor. * * @return True if the propertyEditor can provide a custom editor. */ boolean supportsCustomEditor(); //---------------------------------------------------------------------- /** {@collect.stats} * Register a listener for the PropertyChange event. When a * PropertyEditor changes its value it should fire a PropertyChange * event on all registered PropertyChangeListeners, specifying the * null value for the property name and itself as the source. * * @param listener An object to be invoked when a PropertyChange * event is fired. */ void addPropertyChangeListener(PropertyChangeListener listener); /** {@collect.stats} * Remove a listener for the PropertyChange event. * * @param listener The PropertyChange listener to be removed. */ void removePropertyChangeListener(PropertyChangeListener listener); }
Java
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.lang.ref.Reference; import java.lang.reflect.Method; import java.lang.reflect.Constructor; /** {@collect.stats} * A PropertyDescriptor describes one property that a Java Bean * exports via a pair of accessor methods. */ public class PropertyDescriptor extends FeatureDescriptor { private Reference<Class> propertyTypeRef; private Reference<Method> readMethodRef; private Reference<Method> writeMethodRef; private Reference<Class> propertyEditorClassRef; private boolean bound; private boolean constrained; // The base name of the method name which will be prefixed with the // read and write method. If name == "foo" then the baseName is "Foo" private String baseName; private String writeMethodName; private String readMethodName; /** {@collect.stats} * Constructs a PropertyDescriptor for a property that follows * the standard Java convention by having getFoo and setFoo * accessor methods. Thus if the argument name is "fred", it will * assume that the writer method is "setFred" and the reader method * is "getFred" (or "isFred" for a boolean property). Note that the * property name should start with a lower case character, which will * be capitalized in the method names. * * @param propertyName The programmatic name of the property. * @param beanClass The Class object for the target bean. For * example sun.beans.OurButton.class. * @exception IntrospectionException if an exception occurs during * introspection. */ public PropertyDescriptor(String propertyName, Class<?> beanClass) throws IntrospectionException { this(propertyName, beanClass, Introspector.IS_PREFIX + NameGenerator.capitalize(propertyName), Introspector.SET_PREFIX + NameGenerator.capitalize(propertyName)); } /** {@collect.stats} * This constructor takes the name of a simple property, and method * names for reading and writing the property. * * @param propertyName The programmatic name of the property. * @param beanClass The Class object for the target bean. For * example sun.beans.OurButton.class. * @param readMethodName The name of the method used for reading the property * value. May be null if the property is write-only. * @param writeMethodName The name of the method used for writing the property * value. May be null if the property is read-only. * @exception IntrospectionException if an exception occurs during * introspection. */ public PropertyDescriptor(String propertyName, Class<?> beanClass, String readMethodName, String writeMethodName) throws IntrospectionException { if (beanClass == null) { throw new IntrospectionException("Target Bean class is null"); } if (propertyName == null || propertyName.length() == 0) { throw new IntrospectionException("bad property name"); } if ("".equals(readMethodName) || "".equals(writeMethodName)) { throw new IntrospectionException("read or write method name should not be the empty string"); } setName(propertyName); setClass0(beanClass); this.readMethodName = readMethodName; if (readMethodName != null && getReadMethod() == null) { throw new IntrospectionException("Method not found: " + readMethodName); } this.writeMethodName = writeMethodName; if (writeMethodName != null && getWriteMethod() == null) { throw new IntrospectionException("Method not found: " + writeMethodName); } // If this class or one of its base classes allow PropertyChangeListener, // then we assume that any properties we discover are "bound". // See Introspector.getTargetPropertyInfo() method. String name = "addPropertyChangeListener"; Class[] args = {PropertyChangeListener.class}; this.bound = (null != Introspector.findMethod(beanClass, name, args.length, args)); } /** {@collect.stats} * This constructor takes the name of a simple property, and Method * objects for reading and writing the property. * * @param propertyName The programmatic name of the property. * @param readMethod The method used for reading the property value. * May be null if the property is write-only. * @param writeMethod The method used for writing the property value. * May be null if the property is read-only. * @exception IntrospectionException if an exception occurs during * introspection. */ public PropertyDescriptor(String propertyName, Method readMethod, Method writeMethod) throws IntrospectionException { if (propertyName == null || propertyName.length() == 0) { throw new IntrospectionException("bad property name"); } setName(propertyName); setReadMethod(readMethod); setWriteMethod(writeMethod); } /** {@collect.stats} * Creates <code>PropertyDescriptor</code> for the specified bean * with the specified name and methods to read/write the property value. * * @param bean the type of the target bean * @param base the base name of the property (the rest of the method name) * @param read the method used for reading the property value * @param write the method used for writing the property value * @exception IntrospectionException if an exception occurs during introspection * * @since 1.7 */ PropertyDescriptor(Class<?> bean, String base, Method read, Method write) throws IntrospectionException { if (bean == null) { throw new IntrospectionException("Target Bean class is null"); } setClass0(bean); setName(Introspector.decapitalize(base)); setReadMethod(read); setWriteMethod(write); this.baseName = base; } /** {@collect.stats} * Gets the Class object for the property. * * @return The Java type info for the property. Note that * the "Class" object may describe a built-in Java type such as "int". * The result may be "null" if this is an indexed property that * does not support non-indexed access. * <p> * This is the type that will be returned by the ReadMethod. */ public synchronized Class<?> getPropertyType() { Class type = getPropertyType0(); if (type == null) { try { type = findPropertyType(getReadMethod(), getWriteMethod()); setPropertyType(type); } catch (IntrospectionException ex) { // Fall } } return type; } private void setPropertyType(Class type) { this.propertyTypeRef = getWeakReference(type); } private Class getPropertyType0() { return (this.propertyTypeRef != null) ? this.propertyTypeRef.get() : null; } /** {@collect.stats} * Gets the method that should be used to read the property value. * * @return The method that should be used to read the property value. * May return null if the property can't be read. */ public synchronized Method getReadMethod() { Method readMethod = getReadMethod0(); if (readMethod == null) { Class cls = getClass0(); if (cls == null || (readMethodName == null && readMethodRef == null)) { // The read method was explicitly set to null. return null; } if (readMethodName == null) { Class type = getPropertyType0(); if (type == boolean.class || type == null) { readMethodName = Introspector.IS_PREFIX + getBaseName(); } else { readMethodName = Introspector.GET_PREFIX + getBaseName(); } } // Since there can be multiple write methods but only one getter // method, find the getter method first so that you know what the // property type is. For booleans, there can be "is" and "get" // methods. If an "is" method exists, this is the official // reader method so look for this one first. readMethod = Introspector.findMethod(cls, readMethodName, 0); if (readMethod == null) { readMethodName = Introspector.GET_PREFIX + getBaseName(); readMethod = Introspector.findMethod(cls, readMethodName, 0); } try { setReadMethod(readMethod); } catch (IntrospectionException ex) { // fall } } return readMethod; } /** {@collect.stats} * Sets the method that should be used to read the property value. * * @param readMethod The new read method. */ public synchronized void setReadMethod(Method readMethod) throws IntrospectionException { if (readMethod == null) { readMethodName = null; readMethodRef = null; return; } // The property type is determined by the read method. setPropertyType(findPropertyType(readMethod, getWriteMethod0())); setClass0(readMethod.getDeclaringClass()); readMethodName = readMethod.getName(); this.readMethodRef = getSoftReference(readMethod); } /** {@collect.stats} * Gets the method that should be used to write the property value. * * @return The method that should be used to write the property value. * May return null if the property can't be written. */ public synchronized Method getWriteMethod() { Method writeMethod = getWriteMethod0(); if (writeMethod == null) { Class cls = getClass0(); if (cls == null || (writeMethodName == null && writeMethodRef == null)) { // The write method was explicitly set to null. return null; } // We need the type to fetch the correct method. Class type = getPropertyType0(); if (type == null) { try { // Can't use getPropertyType since it will lead to recursive loop. type = findPropertyType(getReadMethod(), null); setPropertyType(type); } catch (IntrospectionException ex) { // Without the correct property type we can't be guaranteed // to find the correct method. return null; } } if (writeMethodName == null) { writeMethodName = Introspector.SET_PREFIX + getBaseName(); } writeMethod = Introspector.findMethod(cls, writeMethodName, 1, (type == null) ? null : new Class[] { type }); try { setWriteMethod(writeMethod); } catch (IntrospectionException ex) { // fall through } } return writeMethod; } /** {@collect.stats} * Sets the method that should be used to write the property value. * * @param writeMethod The new write method. */ public synchronized void setWriteMethod(Method writeMethod) throws IntrospectionException { if (writeMethod == null) { writeMethodName = null; writeMethodRef = null; return; } // Set the property type - which validates the method setPropertyType(findPropertyType(getReadMethod(), writeMethod)); setClass0(writeMethod.getDeclaringClass()); writeMethodName = writeMethod.getName(); this.writeMethodRef = getSoftReference(writeMethod); } private Method getReadMethod0() { return (this.readMethodRef != null) ? this.readMethodRef.get() : null; } private Method getWriteMethod0() { return (this.writeMethodRef != null) ? this.writeMethodRef.get() : null; } /** {@collect.stats} * Overridden to ensure that a super class doesn't take precedent */ void setClass0(Class clz) { if (getClass0() != null && clz.isAssignableFrom(getClass0())) { // dont replace a subclass with a superclass return; } super.setClass0(clz); } /** {@collect.stats} * Updates to "bound" properties will cause a "PropertyChange" event to * get fired when the property is changed. * * @return True if this is a bound property. */ public boolean isBound() { return bound; } /** {@collect.stats} * Updates to "bound" properties will cause a "PropertyChange" event to * get fired when the property is changed. * * @param bound True if this is a bound property. */ public void setBound(boolean bound) { this.bound = bound; } /** {@collect.stats} * Attempted updates to "Constrained" properties will cause a "VetoableChange" * event to get fired when the property is changed. * * @return True if this is a constrained property. */ public boolean isConstrained() { return constrained; } /** {@collect.stats} * Attempted updates to "Constrained" properties will cause a "VetoableChange" * event to get fired when the property is changed. * * @param constrained True if this is a constrained property. */ public void setConstrained(boolean constrained) { this.constrained = constrained; } /** {@collect.stats} * Normally PropertyEditors will be found using the PropertyEditorManager. * However if for some reason you want to associate a particular * PropertyEditor with a given property, then you can do it with * this method. * * @param propertyEditorClass The Class for the desired PropertyEditor. */ public void setPropertyEditorClass(Class<?> propertyEditorClass) { this.propertyEditorClassRef = getWeakReference((Class)propertyEditorClass); } /** {@collect.stats} * Gets any explicit PropertyEditor Class that has been registered * for this property. * * @return Any explicit PropertyEditor Class that has been registered * for this property. Normally this will return "null", * indicating that no special editor has been registered, * so the PropertyEditorManager should be used to locate * a suitable PropertyEditor. */ public Class<?> getPropertyEditorClass() { return (this.propertyEditorClassRef != null) ? this.propertyEditorClassRef.get() : null; } /** {@collect.stats} * Constructs an instance of a property editor using the current * property editor class. * <p> * If the property editor class has a public constructor that takes an * Object argument then it will be invoked using the bean parameter * as the argument. Otherwise, the default constructor will be invoked. * * @param bean the source object * @return a property editor instance or null if a property editor has * not been defined or cannot be created * @since 1.5 */ public PropertyEditor createPropertyEditor(Object bean) { Object editor = null; Class cls = getPropertyEditorClass(); if (cls != null) { Constructor ctor = null; if (bean != null) { try { ctor = cls.getConstructor(new Class[] { Object.class }); } catch (Exception ex) { // Fall through } } try { if (ctor == null) { editor = cls.newInstance(); } else { editor = ctor.newInstance(new Object[] { bean }); } } catch (Exception ex) { // A serious error has occured. // Proably due to an invalid property editor. throw new RuntimeException("PropertyEditor not instantiated", ex); } } return (PropertyEditor)editor; } /** {@collect.stats} * Compares this <code>PropertyDescriptor</code> against the specified object. * Returns true if the objects are the same. Two <code>PropertyDescriptor</code>s * are the same if the read, write, property types, property editor and * flags are equivalent. * * @since 1.4 */ public boolean equals(Object obj) { if (this == obj) { return true; } if (obj != null && obj instanceof PropertyDescriptor) { PropertyDescriptor other = (PropertyDescriptor)obj; Method otherReadMethod = other.getReadMethod(); Method otherWriteMethod = other.getWriteMethod(); if (!compareMethods(getReadMethod(), otherReadMethod)) { return false; } if (!compareMethods(getWriteMethod(), otherWriteMethod)) { return false; } if (getPropertyType() == other.getPropertyType() && getPropertyEditorClass() == other.getPropertyEditorClass() && bound == other.isBound() && constrained == other.isConstrained() && writeMethodName == other.writeMethodName && readMethodName == other.readMethodName) { return true; } } return false; } /** {@collect.stats} * Package private helper method for Descriptor .equals methods. * * @param a first method to compare * @param b second method to compare * @return boolean to indicate that the methods are equivalent */ boolean compareMethods(Method a, Method b) { // Note: perhaps this should be a protected method in FeatureDescriptor if ((a == null) != (b == null)) { return false; } if (a != null && b != null) { if (!a.equals(b)) { return false; } } return true; } /** {@collect.stats} * Package-private constructor. * Merge two property descriptors. Where they conflict, give the * second argument (y) priority over the first argument (x). * * @param x The first (lower priority) PropertyDescriptor * @param y The second (higher priority) PropertyDescriptor */ PropertyDescriptor(PropertyDescriptor x, PropertyDescriptor y) { super(x,y); if (y.baseName != null) { baseName = y.baseName; } else { baseName = x.baseName; } if (y.readMethodName != null) { readMethodName = y.readMethodName; } else { readMethodName = x.readMethodName; } if (y.writeMethodName != null) { writeMethodName = y.writeMethodName; } else { writeMethodName = x.writeMethodName; } if (y.propertyTypeRef != null) { propertyTypeRef = y.propertyTypeRef; } else { propertyTypeRef = x.propertyTypeRef; } // Figure out the merged read method. Method xr = x.getReadMethod(); Method yr = y.getReadMethod(); // Normally give priority to y's readMethod. try { if (yr != null && yr.getDeclaringClass() == getClass0()) { setReadMethod(yr); } else { setReadMethod(xr); } } catch (IntrospectionException ex) { // fall through } // However, if both x and y reference read methods in the same class, // give priority to a boolean "is" method over a boolean "get" method. if (xr != null && yr != null && xr.getDeclaringClass() == yr.getDeclaringClass() && getReturnType(getClass0(), xr) == boolean.class && getReturnType(getClass0(), yr) == boolean.class && xr.getName().indexOf(Introspector.IS_PREFIX) == 0 && yr.getName().indexOf(Introspector.GET_PREFIX) == 0) { try { setReadMethod(xr); } catch (IntrospectionException ex) { // fall through } } Method xw = x.getWriteMethod(); Method yw = y.getWriteMethod(); try { if (yw != null && yw.getDeclaringClass() == getClass0()) { setWriteMethod(yw); } else { setWriteMethod(xw); } } catch (IntrospectionException ex) { // Fall through } if (y.getPropertyEditorClass() != null) { setPropertyEditorClass(y.getPropertyEditorClass()); } else { setPropertyEditorClass(x.getPropertyEditorClass()); } bound = x.bound | y.bound; constrained = x.constrained | y.constrained; } /* * Package-private dup constructor. * This must isolate the new object from any changes to the old object. */ PropertyDescriptor(PropertyDescriptor old) { super(old); propertyTypeRef = old.propertyTypeRef; readMethodRef = old.readMethodRef; writeMethodRef = old.writeMethodRef; propertyEditorClassRef = old.propertyEditorClassRef; writeMethodName = old.writeMethodName; readMethodName = old.readMethodName; baseName = old.baseName; bound = old.bound; constrained = old.constrained; } /** {@collect.stats} * Returns the property type that corresponds to the read and write method. * The type precedence is given to the readMethod. * * @return the type of the property descriptor or null if both * read and write methods are null. * @throws IntrospectionException if the read or write method is invalid */ private Class findPropertyType(Method readMethod, Method writeMethod) throws IntrospectionException { Class propertyType = null; try { if (readMethod != null) { Class[] params = getParameterTypes(getClass0(), readMethod); if (params.length != 0) { throw new IntrospectionException("bad read method arg count: " + readMethod); } propertyType = getReturnType(getClass0(), readMethod); if (propertyType == Void.TYPE) { throw new IntrospectionException("read method " + readMethod.getName() + " returns void"); } } if (writeMethod != null) { Class params[] = getParameterTypes(getClass0(), writeMethod); if (params.length != 1) { throw new IntrospectionException("bad write method arg count: " + writeMethod); } if (propertyType != null && propertyType != params[0]) { throw new IntrospectionException("type mismatch between read and write methods"); } propertyType = params[0]; } } catch (IntrospectionException ex) { throw ex; } return propertyType; } /** {@collect.stats} * Returns a hash code value for the object. * See {@link java.lang.Object#hashCode} for a complete description. * * @return a hash code value for this object. * @since 1.5 */ public int hashCode() { int result = 7; result = 37 * result + ((getPropertyType() == null) ? 0 : getPropertyType().hashCode()); result = 37 * result + ((getReadMethod() == null) ? 0 : getReadMethod().hashCode()); result = 37 * result + ((getWriteMethod() == null) ? 0 : getWriteMethod().hashCode()); result = 37 * result + ((getPropertyEditorClass() == null) ? 0 : getPropertyEditorClass().hashCode()); result = 37 * result + ((writeMethodName == null) ? 0 : writeMethodName.hashCode()); result = 37 * result + ((readMethodName == null) ? 0 : readMethodName.hashCode()); result = 37 * result + getName().hashCode(); result = 37 * result + ((bound == false) ? 0 : 1); result = 37 * result + ((constrained == false) ? 0 : 1); return result; } // Calculate once since capitalize() is expensive. String getBaseName() { if (baseName == null) { baseName = NameGenerator.capitalize(getName()); } return baseName; } /* public String toString() { String message = "name=" + getName(); message += ", class=" + getClass0(); message += ", type=" + getPropertyType(); message += ", writeMethod="; message += writeMethodName; message += ", readMethod="; message += readMethodName; message += ", bound=" + bound; message += ", constrained=" + constrained; return message; } */ }
Java
/* * Copyright (c) 2000, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Proxy; import java.lang.reflect.Method; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedAction; import sun.reflect.misc.MethodUtil; /** {@collect.stats} * The <code>EventHandler</code> class provides * support for dynamically generating event listeners whose methods * execute a simple statement involving an incoming event object * and a target object. * <p> * The <code>EventHandler</code> class is intended to be used by interactive tools, such as * application builders, that allow developers to make connections between * beans. Typically connections are made from a user interface bean * (the event <em>source</em>) * to an application logic bean (the <em>target</em>). The most effective * connections of this kind isolate the application logic from the user * interface. For example, the <code>EventHandler</code> for a * connection from a <code>JCheckBox</code> to a method * that accepts a boolean value can deal with extracting the state * of the check box and passing it directly to the method so that * the method is isolated from the user interface layer. * <p> * Inner classes are another, more general way to handle events from * user interfaces. The <code>EventHandler</code> class * handles only a subset of what is possible using inner * classes. However, <code>EventHandler</code> works better * with the long-term persistence scheme than inner classes. * Also, using <code>EventHandler</code> in large applications in * which the same interface is implemented many times can * reduce the disk and memory footprint of the application. * <p> * The reason that listeners created with <code>EventHandler</code> * have such a small * footprint is that the <code>Proxy</code> class, on which * the <code>EventHandler</code> relies, shares implementations * of identical * interfaces. For example, if you use * the <code>EventHandler</code> <code>create</code> methods to make * all the <code>ActionListener</code>s in an application, * all the action listeners will be instances of a single class * (one created by the <code>Proxy</code> class). * In general, listeners based on * the <code>Proxy</code> class require one listener class * to be created per <em>listener type</em> (interface), * whereas the inner class * approach requires one class to be created per <em>listener</em> * (object that implements the interface). * * <p> * You don't generally deal directly with <code>EventHandler</code> * instances. * Instead, you use one of the <code>EventHandler</code> * <code>create</code> methods to create * an object that implements a given listener interface. * This listener object uses an <code>EventHandler</code> object * behind the scenes to encapsulate information about the * event, the object to be sent a message when the event occurs, * the message (method) to be sent, and any argument * to the method. * The following section gives examples of how to create listener * objects using the <code>create</code> methods. * * <h2>Examples of Using EventHandler</h2> * * The simplest use of <code>EventHandler</code> is to install * a listener that calls a method on the target object with no arguments. * In the following example we create an <code>ActionListener</code> * that invokes the <code>toFront</code> method on an instance * of <code>javax.swing.JFrame</code>. * * <blockquote> *<pre> *myButton.addActionListener( * (ActionListener)EventHandler.create(ActionListener.class, frame, "toFront")); *</pre> * </blockquote> * * When <code>myButton</code> is pressed, the statement * <code>frame.toFront()</code> will be executed. One could get * the same effect, with some additional compile-time type safety, * by defining a new implementation of the <code>ActionListener</code> * interface and adding an instance of it to the button: * * <blockquote> *<pre> //Equivalent code using an inner class instead of EventHandler. *myButton.addActionListener(new ActionListener() { * public void actionPerformed(ActionEvent e) { * frame.toFront(); * } *}); *</pre> * </blockquote> * * The next simplest use of <code>EventHandler</code> is * to extract a property value from the first argument * of the method in the listener interface (typically an event object) * and use it to set the value of a property in the target object. * In the following example we create an <code>ActionListener</code> that * sets the <code>nextFocusableComponent</code> property of the target * (myButton) object to the value of the "source" property of the event. * * <blockquote> *<pre> *EventHandler.create(ActionListener.class, myButton, "nextFocusableComponent", "source") *</pre> * </blockquote> * * This would correspond to the following inner class implementation: * * <blockquote> *<pre> //Equivalent code using an inner class instead of EventHandler. *new ActionListener() { * public void actionPerformed(ActionEvent e) { * myButton.setNextFocusableComponent((Component)e.getSource()); * } *} *</pre> * </blockquote> * * It's also possible to create an <code>EventHandler</code> that * just passes the incoming event object to the target's action. * If the fourth <code>EventHandler.create</code> argument is * an empty string, then the event is just passed along: * * <blockquote> *<pre> *EventHandler.create(ActionListener.class, target, "doActionEvent", "") *</pre> * </blockquote> * * This would correspond to the following inner class implementation: * * <blockquote> *<pre> //Equivalent code using an inner class instead of EventHandler. *new ActionListener() { * public void actionPerformed(ActionEvent e) { * target.doActionEvent(e); * } *} *</pre> * </blockquote> * * Probably the most common use of <code>EventHandler</code> * is to extract a property value from the * <em>source</em> of the event object and set this value as * the value of a property of the target object. * In the following example we create an <code>ActionListener</code> that * sets the "label" property of the target * object to the value of the "text" property of the * source (the value of the "source" property) of the event. * * <blockquote> *<pre> *EventHandler.create(ActionListener.class, myButton, "label", "source.text") *</pre> * </blockquote> * * This would correspond to the following inner class implementation: * * <blockquote> *<pre> //Equivalent code using an inner class instead of EventHandler. *new ActionListener { * public void actionPerformed(ActionEvent e) { * myButton.setLabel(((JTextField)e.getSource()).getText()); * } *} *</pre> * </blockquote> * * The event property may be "qualified" with an arbitrary number * of property prefixes delimited with the "." character. The "qualifying" * names that appear before the "." characters are taken as the names of * properties that should be applied, left-most first, to * the event object. * <p> * For example, the following action listener * * <blockquote> *<pre> *EventHandler.create(ActionListener.class, target, "a", "b.c.d") *</pre> * </blockquote> * * might be written as the following inner class * (assuming all the properties had canonical getter methods and * returned the appropriate types): * * <blockquote> *<pre> //Equivalent code using an inner class instead of EventHandler. *new ActionListener { * public void actionPerformed(ActionEvent e) { * target.setA(e.getB().getC().isD()); * } *} *</pre> * </blockquote> * The target property may also be "qualified" with an arbitrary number * of property prefixs delimited with the "." character. For example, the * following action listener: * <pre> * EventHandler.create(ActionListener.class, target, "a.b", "c.d") * </pre> * might be written as the following inner class * (assuming all the properties had canonical getter methods and * returned the appropriate types): * <pre> * //Equivalent code using an inner class instead of EventHandler. * new ActionListener { * public void actionPerformed(ActionEvent e) { * target.getA().setB(e.getC().isD()); * } *} *</pre> * <p> * As <code>EventHandler</code> ultimately relies on reflection to invoke * a method we recommend against targeting an overloaded method. For example, * if the target is an instance of the class <code>MyTarget</code> which is * defined as: * <pre> * public class MyTarget { * public void doIt(String); * public void doIt(Object); * } * </pre> * Then the method <code>doIt</code> is overloaded. EventHandler will invoke * the method that is appropriate based on the source. If the source is * null, then either method is appropriate and the one that is invoked is * undefined. For that reason we recommend against targeting overloaded * methods. * * @see java.lang.reflect.Proxy * @see java.util.EventObject * * @since 1.4 * * @author Mark Davidson * @author Philip Milne * @author Hans Muller * */ public class EventHandler implements InvocationHandler { private Object target; private String action; private final String eventPropertyName; private final String listenerMethodName; private final AccessControlContext acc = AccessController.getContext(); /** {@collect.stats} * Creates a new <code>EventHandler</code> object; * you generally use one of the <code>create</code> methods * instead of invoking this constructor directly. Refer to * {@link java.beans.EventHandler#create(Class, Object, String, String) * the general version of create} for a complete description of * the <code>eventPropertyName</code> and <code>listenerMethodName</code> * parameter. * * @param target the object that will perform the action * @param action the name of a (possibly qualified) property or method on * the target * @param eventPropertyName the (possibly qualified) name of a readable property of the incoming event * @param listenerMethodName the name of the method in the listener interface that should trigger the action * * @throws NullPointerException if <code>target</code> is null * @throws NullPointerException if <code>action</code> is null * * @see EventHandler * @see #create(Class, Object, String, String, String) * @see #getTarget * @see #getAction * @see #getEventPropertyName * @see #getListenerMethodName */ public EventHandler(Object target, String action, String eventPropertyName, String listenerMethodName) { this.target = target; this.action = action; if (target == null) { throw new NullPointerException("target must be non-null"); } if (action == null) { throw new NullPointerException("action must be non-null"); } this.eventPropertyName = eventPropertyName; this.listenerMethodName = listenerMethodName; } /** {@collect.stats} * Returns the object to which this event handler will send a message. * * @return the target of this event handler * @see #EventHandler(Object, String, String, String) */ public Object getTarget() { return target; } /** {@collect.stats} * Returns the name of the target's writable property * that this event handler will set, * or the name of the method that this event handler * will invoke on the target. * * @return the action of this event handler * @see #EventHandler(Object, String, String, String) */ public String getAction() { return action; } /** {@collect.stats} * Returns the property of the event that should be * used in the action applied to the target. * * @return the property of the event * * @see #EventHandler(Object, String, String, String) */ public String getEventPropertyName() { return eventPropertyName; } /** {@collect.stats} * Returns the name of the method that will trigger the action. * A return value of <code>null</code> signifies that all methods in the * listener interface trigger the action. * * @return the name of the method that will trigger the action * * @see #EventHandler(Object, String, String, String) */ public String getListenerMethodName() { return listenerMethodName; } private Object applyGetters(Object target, String getters) { if (getters == null || getters.equals("")) { return target; } int firstDot = getters.indexOf('.'); if (firstDot == -1) { firstDot = getters.length(); } String first = getters.substring(0, firstDot); String rest = getters.substring(Math.min(firstDot + 1, getters.length())); try { Method getter = null; if (target != null) { getter = ReflectionUtils.getMethod(target.getClass(), "get" + NameGenerator.capitalize(first), new Class[]{}); if (getter == null) { getter = ReflectionUtils.getMethod(target.getClass(), "is" + NameGenerator.capitalize(first), new Class[]{}); } if (getter == null) { getter = ReflectionUtils.getMethod(target.getClass(), first, new Class[]{}); } } if (getter == null) { throw new RuntimeException("No method called: " + first + " defined on " + target); } Object newTarget = MethodUtil.invoke(getter, target, new Object[]{}); return applyGetters(newTarget, rest); } catch (Throwable e) { throw new RuntimeException("Failed to call method: " + first + " on " + target, e); } } /** {@collect.stats} * Extract the appropriate property value from the event and * pass it to the action associated with * this <code>EventHandler</code>. * * @param proxy the proxy object * @param method the method in the listener interface * @return the result of applying the action to the target * * @see EventHandler */ public Object invoke(final Object proxy, final Method method, final Object[] arguments) { AccessControlContext acc = this.acc; if ((acc == null) && (System.getSecurityManager() != null)) { throw new SecurityException("AccessControlContext is not set"); } return AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { return invokeInternal(proxy, method, arguments); } }, acc); } private Object invokeInternal(Object proxy, Method method, Object[] arguments) { String methodName = method.getName(); if (method.getDeclaringClass() == Object.class) { // Handle the Object public methods. if (methodName.equals("hashCode")) { return new Integer(System.identityHashCode(proxy)); } else if (methodName.equals("equals")) { return (proxy == arguments[0] ? Boolean.TRUE : Boolean.FALSE); } else if (methodName.equals("toString")) { return proxy.getClass().getName() + '@' + Integer.toHexString(proxy.hashCode()); } } if (listenerMethodName == null || listenerMethodName.equals(methodName)) { Class[] argTypes = null; Object[] newArgs = null; if (eventPropertyName == null) { // Nullary method. newArgs = new Object[]{}; argTypes = new Class[]{}; } else { Object input = applyGetters(arguments[0], getEventPropertyName()); newArgs = new Object[]{input}; argTypes = new Class[]{input == null ? null : input.getClass()}; } try { int lastDot = action.lastIndexOf('.'); if (lastDot != -1) { target = applyGetters(target, action.substring(0, lastDot)); action = action.substring(lastDot + 1); } Method targetMethod = ReflectionUtils.getMethod( target.getClass(), action, argTypes); if (targetMethod == null) { targetMethod = ReflectionUtils.getMethod(target.getClass(), "set" + NameGenerator.capitalize(action), argTypes); } if (targetMethod == null) { String argTypeString = (argTypes.length == 0) ? " with no arguments" : " with argument " + argTypes[0]; throw new RuntimeException( "No method called " + action + " on " + target.getClass() + argTypeString); } return MethodUtil.invoke(targetMethod, target, newArgs); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (InvocationTargetException ex) { Throwable th = ex.getTargetException(); throw (th instanceof RuntimeException) ? (RuntimeException) th : new RuntimeException(th); } } return null; } /** {@collect.stats} * Creates an implementation of <code>listenerInterface</code> in which * <em>all</em> of the methods in the listener interface apply * the handler's <code>action</code> to the <code>target</code>. This * method is implemented by calling the other, more general, * implementation of the <code>create</code> method with both * the <code>eventPropertyName</code> and the <code>listenerMethodName</code> * taking the value <code>null</code>. Refer to * {@link java.beans.EventHandler#create(Class, Object, String, String) * the general version of create} for a complete description of * the <code>action</code> parameter. * <p> * To create an <code>ActionListener</code> that shows a * <code>JDialog</code> with <code>dialog.show()</code>, * one can write: * *<blockquote> *<pre> *EventHandler.create(ActionListener.class, dialog, "show") *</pre> *</blockquote> * * @param listenerInterface the listener interface to create a proxy for * @param target the object that will perform the action * @param action the name of a (possibly qualified) property or method on * the target * @return an object that implements <code>listenerInterface</code> * * @throws NullPointerException if <code>listenerInterface</code> is null * @throws NullPointerException if <code>target</code> is null * @throws NullPointerException if <code>action</code> is null * * @see #create(Class, Object, String, String) */ public static <T> T create(Class<T> listenerInterface, Object target, String action) { return create(listenerInterface, target, action, null, null); } /** {@collect.stats} /** {@collect.stats} * Creates an implementation of <code>listenerInterface</code> in which * <em>all</em> of the methods pass the value of the event * expression, <code>eventPropertyName</code>, to the final method in the * statement, <code>action</code>, which is applied to the <code>target</code>. * This method is implemented by calling the * more general, implementation of the <code>create</code> method with * the <code>listenerMethodName</code> taking the value <code>null</code>. * Refer to * {@link java.beans.EventHandler#create(Class, Object, String, String) * the general version of create} for a complete description of * the <code>action</code> and <code>eventPropertyName</code> parameters. * <p> * To create an <code>ActionListener</code> that sets the * the text of a <code>JLabel</code> to the text value of * the <code>JTextField</code> source of the incoming event, * you can use the following code: * *<blockquote> *<pre> *EventHandler.create(ActionListener.class, label, "text", "source.text"); *</pre> *</blockquote> * * This is equivalent to the following code: *<blockquote> *<pre> //Equivalent code using an inner class instead of EventHandler. *new ActionListener() { * public void actionPerformed(ActionEvent event) { * label.setText(((JTextField)(event.getSource())).getText()); * } *}; *</pre> *</blockquote> * * @param listenerInterface the listener interface to create a proxy for * @param target the object that will perform the action * @param action the name of a (possibly qualified) property or method on * the target * @param eventPropertyName the (possibly qualified) name of a readable property of the incoming event * * @return an object that implements <code>listenerInterface</code> * * @throws NullPointerException if <code>listenerInterface</code> is null * @throws NullPointerException if <code>target</code> is null * @throws NullPointerException if <code>action</code> is null * * @see #create(Class, Object, String, String, String) */ public static <T> T create(Class<T> listenerInterface, Object target, String action, String eventPropertyName) { return create(listenerInterface, target, action, eventPropertyName, null); } /** {@collect.stats} * Creates an implementation of <code>listenerInterface</code> in which * the method named <code>listenerMethodName</code> * passes the value of the event expression, <code>eventPropertyName</code>, * to the final method in the statement, <code>action</code>, which * is applied to the <code>target</code>. All of the other listener * methods do nothing. * <p> * The <code>eventPropertyName</code> string is used to extract a value * from the incoming event object that is passed to the target * method. The common case is the target method takes no arguments, in * which case a value of null should be used for the * <code>eventPropertyName</code>. Alternatively if you want * the incoming event object passed directly to the target method use * the empty string. * The format of the <code>eventPropertyName</code> string is a sequence of * methods or properties where each method or * property is applied to the value returned by the preceeding method * starting from the incoming event object. * The syntax is: <code>propertyName{.propertyName}*</code> * where <code>propertyName</code> matches a method or * property. For example, to extract the <code>point</code> * property from a <code>MouseEvent</code>, you could use either * <code>"point"</code> or <code>"getPoint"</code> as the * <code>eventPropertyName</code>. To extract the "text" property from * a <code>MouseEvent</code> with a <code>JLabel</code> source use any * of the following as <code>eventPropertyName</code>: * <code>"source.text"</code>, * <code>"getSource.text"</code> <code>"getSource.getText"</code> or * <code>"source.getText"</code>. If a method can not be found, or an * exception is generated as part of invoking a method a * <code>RuntimeException</code> will be thrown at dispatch time. For * example, if the incoming event object is null, and * <code>eventPropertyName</code> is non-null and not empty, a * <code>RuntimeException</code> will be thrown. * <p> * The <code>action</code> argument is of the same format as the * <code>eventPropertyName</code> argument where the last property name * identifies either a method name or writable property. * <p> * If the <code>listenerMethodName</code> is <code>null</code> * <em>all</em> methods in the interface trigger the <code>action</code> to be * executed on the <code>target</code>. * <p> * For example, to create a <code>MouseListener</code> that sets the target * object's <code>origin</code> property to the incoming <code>MouseEvent</code>'s * location (that's the value of <code>mouseEvent.getPoint()</code>) each * time a mouse button is pressed, one would write: *<blockquote> *<pre> *EventHandler.create(MouseListener.class, "mousePressed", target, "origin", "point"); *</pre> *</blockquote> * * This is comparable to writing a <code>MouseListener</code> in which all * of the methods except <code>mousePressed</code> are no-ops: * *<blockquote> *<pre> //Equivalent code using an inner class instead of EventHandler. *new MouseAdapter() { * public void mousePressed(MouseEvent e) { * target.setOrigin(e.getPoint()); * } *}; * </pre> *</blockquote> * * @param listenerInterface the listener interface to create a proxy for * @param target the object that will perform the action * @param action the name of a (possibly qualified) property or method on * the target * @param eventPropertyName the (possibly qualified) name of a readable property of the incoming event * @param listenerMethodName the name of the method in the listener interface that should trigger the action * * @return an object that implements <code>listenerInterface</code> * * @throws NullPointerException if <code>listenerInterface</code> is null * @throws NullPointerException if <code>target</code> is null * @throws NullPointerException if <code>action</code> is null * * @see EventHandler */ public static <T> T create(Class<T> listenerInterface, Object target, String action, String eventPropertyName, String listenerMethodName) { // Create this first to verify target/action are non-null EventHandler eventHandler = new EventHandler(target, action, eventPropertyName, listenerMethodName); if (listenerInterface == null) { throw new NullPointerException( "listenerInterface must be non-null"); } return (T)Proxy.newProxyInstance(target.getClass().getClassLoader(), new Class[] {listenerInterface}, eventHandler); } }
Java
/* * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.util.Iterator; /** {@collect.stats} * <p> * One of the primary functions of a BeanContext is to act a as rendezvous * between JavaBeans, and BeanContextServiceProviders. * </p> * <p> * A JavaBean nested within a BeanContext, may ask that BeanContext to * provide an instance of a "service", based upon a reference to a Java * Class object that represents that service. * </p> * <p> * If such a service has been registered with the context, or one of its * nesting context's, in the case where a context delegate to its context * to satisfy a service request, then the BeanContextServiceProvider associated with * the service is asked to provide an instance of that service. * </p> * <p> * The ServcieProvider may always return the same instance, or it may * construct a new instance for each request. * </p> */ public interface BeanContextServiceProvider { /** {@collect.stats} * Invoked by <code>BeanContextServices</code>, this method * requests an instance of a * service from this <code>BeanContextServiceProvider</code>. * * @param bcs The <code>BeanContextServices</code> associated with this * particular request. This parameter enables the * <code>BeanContextServiceProvider</code> to distinguish service * requests from multiple sources. * * @param requestor The object requesting the service * * @param serviceClass The service requested * * @param serviceSelector the service dependent parameter * for a particular service, or <code>null</code> if not applicable. * * @return a reference to the requested service */ Object getService(BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector); /** {@collect.stats} * Invoked by <code>BeanContextServices</code>, * this method releases a nested <code>BeanContextChild</code>'s * (or any arbitrary object associated with a * <code>BeanContextChild</code>) reference to the specified service. * * @param bcs the <code>BeanContextServices</code> associated with this * particular release request * * @param requestor the object requesting the service to be released * * @param service the service that is to be released */ public void releaseService(BeanContextServices bcs, Object requestor, Object service); /** {@collect.stats} * Invoked by <code>BeanContextServices</code>, this method * gets the current service selectors for the specified service. * A service selector is a service specific parameter, * typical examples of which could include: a * parameter to a constructor for the service implementation class, * a value for a particular service's property, or a key into a * map of existing implementations. * * @param bcs the <code>BeanContextServices</code> for this request * @param serviceClass the specified service * @return the current service selectors for the specified serviceClass */ Iterator getCurrentServiceSelectors(BeanContextServices bcs, Class serviceClass); }
Java
/* * Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.awt.Component; import java.awt.Container; import java.beans.Beans; import java.beans.AppletInitializer; import java.beans.DesignMode; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.beans.VetoableChangeListener; import java.beans.VetoableChangeSupport; import java.beans.PropertyVetoException; import java.beans.Visibility; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; /** {@collect.stats} * This helper class provides a utility implementation of the * java.beans.beancontext.BeanContext interface. * </p> * <p> * Since this class directly implements the BeanContext interface, the class * can, and is intended to be used either by subclassing this implementation, * or via ad-hoc delegation of an instance of this class from another. * </p> * * @author Laurence P. G. Cable * @since 1.2 */ public class BeanContextSupport extends BeanContextChildSupport implements BeanContext, Serializable, PropertyChangeListener, VetoableChangeListener { // Fix for bug 4282900 to pass JCK regression test static final long serialVersionUID = -4879613978649577204L; /** {@collect.stats} * * Construct a BeanContextSupport instance * * * @param peer The peer <tt>BeanContext</tt> we are * supplying an implementation for, * or <tt>null</tt> * if this object is its own peer * @param lcle The current Locale for this BeanContext. If * <tt>lcle</tt> is <tt>null</tt>, the default locale * is assigned to the <tt>BeanContext</tt> instance. * @param dTime The initial state, * <tt>true</tt> if in design mode, * <tt>false</tt> if runtime. * @param visible The initial visibility. * @see java.util.Locale#getDefault() * @see java.util.Locale#setDefault(java.util.Locale) */ public BeanContextSupport(BeanContext peer, Locale lcle, boolean dTime, boolean visible) { super(peer); locale = lcle != null ? lcle : Locale.getDefault(); designTime = dTime; okToUseGui = visible; initialize(); } /** {@collect.stats} * Create an instance using the specified Locale and design mode. * * @param peer The peer <tt>BeanContext</tt> we * are supplying an implementation for, * or <tt>null</tt> if this object is its own peer * @param lcle The current Locale for this <tt>BeanContext</tt>. If * <tt>lcle</tt> is <tt>null</tt>, the default locale * is assigned to the <tt>BeanContext</tt> instance. * @param dtime The initial state, <tt>true</tt> * if in design mode, * <tt>false</tt> if runtime. * @see java.util.Locale#getDefault() * @see java.util.Locale#setDefault(java.util.Locale) */ public BeanContextSupport(BeanContext peer, Locale lcle, boolean dtime) { this (peer, lcle, dtime, true); } /** {@collect.stats} * Create an instance using the specified locale * * @param peer The peer BeanContext we are * supplying an implementation for, * or <tt>null</tt> if this object * is its own peer * @param lcle The current Locale for this * <tt>BeanContext</tt>. If * <tt>lcle</tt> is <tt>null</tt>, * the default locale * is assigned to the <tt>BeanContext</tt> * instance. * @see java.util.Locale#getDefault() * @see java.util.Locale#setDefault(java.util.Locale) */ public BeanContextSupport(BeanContext peer, Locale lcle) { this (peer, lcle, false, true); } /** {@collect.stats} * Create an instance using with a default locale * * @param peer The peer <tt>BeanContext</tt> we are * supplying an implementation for, * or <tt>null</tt> if this object * is its own peer */ public BeanContextSupport(BeanContext peer) { this (peer, null, false, true); } /** {@collect.stats} * Create an instance that is not a delegate of another object */ public BeanContextSupport() { this (null, null, false, true); } /** {@collect.stats} * Gets the instance of <tt>BeanContext</tt> that * this object is providing the implementation for. * @return the BeanContext instance */ public BeanContext getBeanContextPeer() { return (BeanContext)getBeanContextChildPeer(); } /** {@collect.stats} * <p> * The instantiateChild method is a convenience hook * in BeanContext to simplify * the task of instantiating a Bean, nested, * into a <tt>BeanContext</tt>. * </p> * <p> * The semantics of the beanName parameter are defined by java.beans.Beans.instantate. * </p> * * @param beanName the name of the Bean to instantiate within this BeanContext * @throws IOException if there is an I/O error when the bean is being deserialized * @throws ClassNotFoundException if the class * identified by the beanName parameter is not found * @return the new object */ public Object instantiateChild(String beanName) throws IOException, ClassNotFoundException { BeanContext bc = getBeanContextPeer(); return Beans.instantiate(bc.getClass().getClassLoader(), beanName, bc); } /** {@collect.stats} * Gets the number of children currently nested in * this BeanContext. * * @return number of children */ public int size() { synchronized(children) { return children.size(); } } /** {@collect.stats} * Reports whether or not this * <tt>BeanContext</tt> is empty. * A <tt>BeanContext</tt> is considered * empty when it contains zero * nested children. * @return if there are not children */ public boolean isEmpty() { synchronized(children) { return children.isEmpty(); } } /** {@collect.stats} * Determines whether or not the specified object * is currently a child of this <tt>BeanContext</tt>. * @param o the Object in question * @return if this object is a child */ public boolean contains(Object o) { synchronized(children) { return children.containsKey(o); } } /** {@collect.stats} * Determines whether or not the specified object * is currently a child of this <tt>BeanContext</tt>. * @param o the Object in question * @return if this object is a child */ public boolean containsKey(Object o) { synchronized(children) { return children.containsKey(o); } } /** {@collect.stats} * Gets all JavaBean or <tt>BeanContext</tt> instances * currently nested in this <tt>BeanContext</tt>. * @return an <tt>Iterator</tt> of the nested children */ public Iterator iterator() { synchronized(children) { return new BCSIterator(children.keySet().iterator()); } } /** {@collect.stats} * Gets all JavaBean or <tt>BeanContext</tt> * instances currently nested in this BeanContext. */ public Object[] toArray() { synchronized(children) { return children.keySet().toArray(); } } /** {@collect.stats} * Gets an array containing all children of * this <tt>BeanContext</tt> that match * the types contained in arry. * @param arry The array of object * types that are of interest. * @return an array of children */ public Object[] toArray(Object[] arry) { synchronized(children) { return children.keySet().toArray(arry); } } /** {@collect.stats} **********************************************************************/ /** {@collect.stats} * protected final subclass that encapsulates an iterator but implements * a noop remove() method. */ protected static final class BCSIterator implements Iterator { BCSIterator(Iterator i) { super(); src = i; } public boolean hasNext() { return src.hasNext(); } public Object next() { return src.next(); } public void remove() { /* do nothing */ } private Iterator src; } /** {@collect.stats} **********************************************************************/ /* * protected nested class containing per child information, an instance * of which is associated with each child in the "children" hashtable. * subclasses can extend this class to include their own per-child state. * * Note that this 'value' is serialized with the corresponding child 'key' * when the BeanContextSupport is serialized. */ protected class BCSChild implements Serializable { private static final long serialVersionUID = -5815286101609939109L; BCSChild(Object bcc, Object peer) { super(); child = bcc; proxyPeer = peer; } Object getChild() { return child; } void setRemovePending(boolean v) { removePending = v; } boolean isRemovePending() { return removePending; } boolean isProxyPeer() { return proxyPeer != null; } Object getProxyPeer() { return proxyPeer; } /* * fields */ private Object child; private Object proxyPeer; private transient boolean removePending; } /** {@collect.stats} * <p> * Subclasses can override this method to insert their own subclass * of Child without having to override add() or the other Collection * methods that add children to the set. * </p> * * @param targetChild the child to create the Child on behalf of * @param peer the peer if the tragetChild and the peer are related by an implementation of BeanContextProxy */ protected BCSChild createBCSChild(Object targetChild, Object peer) { return new BCSChild(targetChild, peer); } /** {@collect.stats} **********************************************************************/ /** {@collect.stats} * Adds/nests a child within this <tt>BeanContext</tt>. * <p> * Invoked as a side effect of java.beans.Beans.instantiate(). * If the child object is not valid for adding then this method * throws an IllegalStateException. * </p> * * * @param targetChild The child objects to nest * within this <tt>BeanContext</tt> * @return true if the child was added successfully. * @see #validatePendingAdd */ public boolean add(Object targetChild) { if (targetChild == null) throw new IllegalArgumentException(); // The specification requires that we do nothing if the child // is already nested herein. if (children.containsKey(targetChild)) return false; // test before locking synchronized(BeanContext.globalHierarchyLock) { if (children.containsKey(targetChild)) return false; // check again if (!validatePendingAdd(targetChild)) { throw new IllegalStateException(); } // The specification requires that we invoke setBeanContext() on the // newly added child if it implements the java.beans.beancontext.BeanContextChild interface BeanContextChild cbcc = getChildBeanContextChild(targetChild); BeanContextChild bccp = null; synchronized(targetChild) { if (targetChild instanceof BeanContextProxy) { bccp = ((BeanContextProxy)targetChild).getBeanContextProxy(); if (bccp == null) throw new NullPointerException("BeanContextPeer.getBeanContextProxy()"); } BCSChild bcsc = createBCSChild(targetChild, bccp); BCSChild pbcsc = null; synchronized (children) { children.put(targetChild, bcsc); if (bccp != null) children.put(bccp, pbcsc = createBCSChild(bccp, targetChild)); } if (cbcc != null) synchronized(cbcc) { try { cbcc.setBeanContext(getBeanContextPeer()); } catch (PropertyVetoException pve) { synchronized (children) { children.remove(targetChild); if (bccp != null) children.remove(bccp); } throw new IllegalStateException(); } cbcc.addPropertyChangeListener("beanContext", childPCL); cbcc.addVetoableChangeListener("beanContext", childVCL); } Visibility v = getChildVisibility(targetChild); if (v != null) { if (okToUseGui) v.okToUseGui(); else v.dontUseGui(); } if (getChildSerializable(targetChild) != null) serializable++; childJustAddedHook(targetChild, bcsc); if (bccp != null) { v = getChildVisibility(bccp); if (v != null) { if (okToUseGui) v.okToUseGui(); else v.dontUseGui(); } if (getChildSerializable(bccp) != null) serializable++; childJustAddedHook(bccp, pbcsc); } } // The specification requires that we fire a notification of the change fireChildrenAdded(new BeanContextMembershipEvent(getBeanContextPeer(), bccp == null ? new Object[] { targetChild } : new Object[] { targetChild, bccp } )); } return true; } /** {@collect.stats} * Removes a child from this BeanContext. If the child object is not * for adding then this method throws an IllegalStateException. * @param targetChild The child objects to remove * @see #validatePendingRemove */ public boolean remove(Object targetChild) { return remove(targetChild, true); } /** {@collect.stats} * internal remove used when removal caused by * unexpected <tt>setBeanContext</tt> or * by <tt>remove()</tt> invocation. * @param targetChild the JavaBean, BeanContext, or Object to be removed * @param callChildSetBC used to indicate that * the child should be notified that it is no * longer nested in this <tt>BeanContext</tt>. */ protected boolean remove(Object targetChild, boolean callChildSetBC) { if (targetChild == null) throw new IllegalArgumentException(); synchronized(BeanContext.globalHierarchyLock) { if (!containsKey(targetChild)) return false; if (!validatePendingRemove(targetChild)) { throw new IllegalStateException(); } BCSChild bcsc = (BCSChild)children.get(targetChild); BCSChild pbcsc = null; Object peer = null; // we are required to notify the child that it is no longer nested here if // it implements java.beans.beancontext.BeanContextChild synchronized(targetChild) { if (callChildSetBC) { BeanContextChild cbcc = getChildBeanContextChild(targetChild); if (cbcc != null) synchronized(cbcc) { cbcc.removePropertyChangeListener("beanContext", childPCL); cbcc.removeVetoableChangeListener("beanContext", childVCL); try { cbcc.setBeanContext(null); } catch (PropertyVetoException pve1) { cbcc.addPropertyChangeListener("beanContext", childPCL); cbcc.addVetoableChangeListener("beanContext", childVCL); throw new IllegalStateException(); } } } synchronized (children) { children.remove(targetChild); if (bcsc.isProxyPeer()) { pbcsc = (BCSChild)children.get(peer = bcsc.getProxyPeer()); children.remove(peer); } } if (getChildSerializable(targetChild) != null) serializable--; childJustRemovedHook(targetChild, bcsc); if (peer != null) { if (getChildSerializable(peer) != null) serializable--; childJustRemovedHook(peer, pbcsc); } } fireChildrenRemoved(new BeanContextMembershipEvent(getBeanContextPeer(), peer == null ? new Object[] { targetChild } : new Object[] { targetChild, peer } )); } return true; } /** {@collect.stats} * Tests to see if all objects in the * specified <tt>Collection</tt> are children of * this <tt>BeanContext</tt>. * @param c the specified <tt>Collection</tt> * * @return <tt>true</tt> if all objects * in the collection are children of * this <tt>BeanContext</tt>, false if not. */ public boolean containsAll(Collection c) { synchronized(children) { Iterator i = c.iterator(); while (i.hasNext()) if(!contains(i.next())) return false; return true; } } /** {@collect.stats} * add Collection to set of Children (Unsupported) * implementations must synchronized on the hierarchy lock and "children" protected field * @throws UnsupportedOperationException */ public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } /** {@collect.stats} * remove all specified children (Unsupported) * implementations must synchronized on the hierarchy lock and "children" protected field * @throws UnsupportedOperationException */ public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } /** {@collect.stats} * retain only specified children (Unsupported) * implementations must synchronized on the hierarchy lock and "children" protected field * @throws UnsupportedOperationException */ public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } /** {@collect.stats} * clear the children (Unsupported) * implementations must synchronized on the hierarchy lock and "children" protected field * @throws UnsupportedOperationException */ public void clear() { throw new UnsupportedOperationException(); } /** {@collect.stats} * Adds a BeanContextMembershipListener * * @param bcml the BeanContextMembershipListener to add * @throws NullPointerException */ public void addBeanContextMembershipListener(BeanContextMembershipListener bcml) { if (bcml == null) throw new NullPointerException("listener"); synchronized(bcmListeners) { if (bcmListeners.contains(bcml)) return; else bcmListeners.add(bcml); } } /** {@collect.stats} * Removes a BeanContextMembershipListener * * @param bcml the BeanContextMembershipListener to remove * @throws NullPointerException */ public void removeBeanContextMembershipListener(BeanContextMembershipListener bcml) { if (bcml == null) throw new NullPointerException("listener"); synchronized(bcmListeners) { if (!bcmListeners.contains(bcml)) return; else bcmListeners.remove(bcml); } } /** {@collect.stats} * @param name the name of the resource requested. * @param bcc the child object making the request. * * @return the requested resource as an InputStream * @throws NullPointerException */ public InputStream getResourceAsStream(String name, BeanContextChild bcc) { if (name == null) throw new NullPointerException("name"); if (bcc == null) throw new NullPointerException("bcc"); if (containsKey(bcc)) { ClassLoader cl = bcc.getClass().getClassLoader(); return cl != null ? cl.getResourceAsStream(name) : ClassLoader.getSystemResourceAsStream(name); } else throw new IllegalArgumentException("Not a valid child"); } /** {@collect.stats} * @param name the name of the resource requested. * @param bcc the child object making the request. * * @return the requested resource as an InputStream */ public URL getResource(String name, BeanContextChild bcc) { if (name == null) throw new NullPointerException("name"); if (bcc == null) throw new NullPointerException("bcc"); if (containsKey(bcc)) { ClassLoader cl = bcc.getClass().getClassLoader(); return cl != null ? cl.getResource(name) : ClassLoader.getSystemResource(name); } else throw new IllegalArgumentException("Not a valid child"); } /** {@collect.stats} * Sets the new design time value for this <tt>BeanContext</tt>. * @param dTime the new designTime value */ public synchronized void setDesignTime(boolean dTime) { if (designTime != dTime) { designTime = dTime; firePropertyChange("designMode", Boolean.valueOf(!dTime), Boolean.valueOf(dTime)); } } /** {@collect.stats} * Reports whether or not this object is in * currently in design time mode. * @return <tt>true</tt> if in design time mode, * <tt>false</tt> if not */ public synchronized boolean isDesignTime() { return designTime; } /** {@collect.stats} * Sets the locale of this BeanContext. * @param newLocale the new locale. This method call will have * no effect if newLocale is <CODE>null</CODE>. * @throws PropertyVetoException if the new value is rejected */ public synchronized void setLocale(Locale newLocale) throws PropertyVetoException { if ((locale != null && !locale.equals(newLocale)) && newLocale != null) { Locale old = locale; fireVetoableChange("locale", old, newLocale); // throws locale = newLocale; firePropertyChange("locale", old, newLocale); } } /** {@collect.stats} * Gets the locale for this <tt>BeanContext</tt>. * * @return the current Locale of the <tt>BeanContext</tt> */ public synchronized Locale getLocale() { return locale; } /** {@collect.stats} * <p> * This method is typically called from the environment in order to determine * if the implementor "needs" a GUI. * </p> * <p> * The algorithm used herein tests the BeanContextPeer, and its current children * to determine if they are either Containers, Components, or if they implement * Visibility and return needsGui() == true. * </p> * @return <tt>true</tt> if the implementor needs a GUI */ public synchronized boolean needsGui() { BeanContext bc = getBeanContextPeer(); if (bc != this) { if (bc instanceof Visibility) return ((Visibility)bc).needsGui(); if (bc instanceof Container || bc instanceof Component) return true; } synchronized(children) { for (Iterator i = children.keySet().iterator(); i.hasNext();) { Object c = i.next(); try { return ((Visibility)c).needsGui(); } catch (ClassCastException cce) { // do nothing ... } if (c instanceof Container || c instanceof Component) return true; } } return false; } /** {@collect.stats} * notify this instance that it may no longer render a GUI. */ public synchronized void dontUseGui() { if (okToUseGui) { okToUseGui = false; // lets also tell the Children that can that they may not use their GUI's synchronized(children) { for (Iterator i = children.keySet().iterator(); i.hasNext();) { Visibility v = getChildVisibility(i.next()); if (v != null) v.dontUseGui(); } } } } /** {@collect.stats} * Notify this instance that it may now render a GUI */ public synchronized void okToUseGui() { if (!okToUseGui) { okToUseGui = true; // lets also tell the Children that can that they may use their GUI's synchronized(children) { for (Iterator i = children.keySet().iterator(); i.hasNext();) { Visibility v = getChildVisibility(i.next()); if (v != null) v.okToUseGui(); } } } } /** {@collect.stats} * Used to determine if the <tt>BeanContext</tt> * child is avoiding using its GUI. * @return is this instance avoiding using its GUI? * @see Visibility */ public boolean avoidingGui() { return !okToUseGui && needsGui(); } /** {@collect.stats} * Is this <tt>BeanContext</tt> in the * process of being serialized? * @return if this <tt>BeanContext</tt> is * currently being serialized */ public boolean isSerializing() { return serializing; } /** {@collect.stats} * Returns an iterator of all children * of this <tt>BeanContext</tt>. * @return an iterator for all the current BCSChild values */ protected Iterator bcsChildren() { synchronized(children) { return children.values().iterator(); } } /** {@collect.stats} * called by writeObject after defaultWriteObject() but prior to * serialization of currently serializable children. * * This method may be overridden by subclasses to perform custom * serialization of their state prior to this superclass serializing * the children. * * This method should not however be used by subclasses to replace their * own implementation (if any) of writeObject(). */ protected void bcsPreSerializationHook(ObjectOutputStream oos) throws IOException { } /** {@collect.stats} * called by readObject after defaultReadObject() but prior to * deserialization of any children. * * This method may be overridden by subclasses to perform custom * deserialization of their state prior to this superclass deserializing * the children. * * This method should not however be used by subclasses to replace their * own implementation (if any) of readObject(). */ protected void bcsPreDeserializationHook(ObjectInputStream ois) throws IOException, ClassNotFoundException { } /** {@collect.stats} * Called by readObject with the newly deserialized child and BCSChild. * @param child the newly deserialized child * @param bcsc the newly deserialized BCSChild */ protected void childDeserializedHook(Object child, BCSChild bcsc) { synchronized(children) { children.put(child, bcsc); } } /** {@collect.stats} * Used by writeObject to serialize a Collection. * @param oos the <tt>ObjectOutputStream</tt> * to use during serialization * @param coll the <tt>Collection</tt> to serialize * @throws IOException if serialization failed */ protected final void serialize(ObjectOutputStream oos, Collection coll) throws IOException { int count = 0; Object[] objects = coll.toArray(); for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof Serializable) count++; else objects[i] = null; } oos.writeInt(count); // number of subsequent objects for (int i = 0; count > 0; i++) { Object o = objects[i]; if (o != null) { oos.writeObject(o); count--; } } } /** {@collect.stats} * used by readObject to deserialize a collection. * @param ois the ObjectInputStream to use * @param coll the Collection */ protected final void deserialize(ObjectInputStream ois, Collection coll) throws IOException, ClassNotFoundException { int count = 0; count = ois.readInt(); while (count-- > 0) { coll.add(ois.readObject()); } } /** {@collect.stats} * Used to serialize all children of * this <tt>BeanContext</tt>. * @param oos the <tt>ObjectOutputStream</tt> * to use during serialization * @throws IOException if serialization failed */ public final void writeChildren(ObjectOutputStream oos) throws IOException { if (serializable <= 0) return; boolean prev = serializing; serializing = true; int count = 0; synchronized(children) { Iterator i = children.entrySet().iterator(); while (i.hasNext() && count < serializable) { Map.Entry entry = (Map.Entry)i.next(); if (entry.getKey() instanceof Serializable) { try { oos.writeObject(entry.getKey()); // child oos.writeObject(entry.getValue()); // BCSChild } catch (IOException ioe) { serializing = prev; throw ioe; } count++; } } } serializing = prev; if (count != serializable) { throw new IOException("wrote different number of children than expected"); } } /** {@collect.stats} * Serialize the BeanContextSupport, if this instance has a distinct * peer (that is this object is acting as a delegate for another) then * the children of this instance are not serialized here due to a * 'chicken and egg' problem that occurs on deserialization of the * children at the same time as this instance. * * Therefore in situations where there is a distinct peer to this instance * it should always call writeObject() followed by writeChildren() and * readObject() followed by readChildren(). * * @param oos the ObjectOutputStream */ private synchronized void writeObject(ObjectOutputStream oos) throws IOException, ClassNotFoundException { serializing = true; synchronized (BeanContext.globalHierarchyLock) { try { oos.defaultWriteObject(); // serialize the BeanContextSupport object bcsPreSerializationHook(oos); if (serializable > 0 && this.equals(getBeanContextPeer())) writeChildren(oos); serialize(oos, (Collection)bcmListeners); } finally { serializing = false; } } } /** {@collect.stats} * When an instance of this class is used as a delegate for the * implementation of the BeanContext protocols (and its subprotocols) * there exists a 'chicken and egg' problem during deserialization */ public final void readChildren(ObjectInputStream ois) throws IOException, ClassNotFoundException { int count = serializable; while (count-- > 0) { Object child = null; BeanContextSupport.BCSChild bscc = null; try { child = ois.readObject(); bscc = (BeanContextSupport.BCSChild)ois.readObject(); } catch (IOException ioe) { continue; } catch (ClassNotFoundException cnfe) { continue; } synchronized(child) { BeanContextChild bcc = null; try { bcc = (BeanContextChild)child; } catch (ClassCastException cce) { // do nothing; } if (bcc != null) { try { bcc.setBeanContext(getBeanContextPeer()); bcc.addPropertyChangeListener("beanContext", childPCL); bcc.addVetoableChangeListener("beanContext", childVCL); } catch (PropertyVetoException pve) { continue; } } childDeserializedHook(child, bscc); } } } /** {@collect.stats} * deserialize contents ... if this instance has a distinct peer the * children are *not* serialized here, the peer's readObject() must call * readChildren() after deserializing this instance. */ private synchronized void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { synchronized(BeanContext.globalHierarchyLock) { ois.defaultReadObject(); initialize(); bcsPreDeserializationHook(ois); if (serializable > 0 && this.equals(getBeanContextPeer())) readChildren(ois); deserialize(ois, bcmListeners = new ArrayList(1)); } } /** {@collect.stats} * subclasses may envelope to monitor veto child property changes. */ public void vetoableChange(PropertyChangeEvent pce) throws PropertyVetoException { String propertyName = pce.getPropertyName(); Object source = pce.getSource(); synchronized(children) { if ("beanContext".equals(propertyName) && containsKey(source) && !getBeanContextPeer().equals(pce.getNewValue()) ) { if (!validatePendingRemove(source)) { throw new PropertyVetoException("current BeanContext vetoes setBeanContext()", pce); } else ((BCSChild)children.get(source)).setRemovePending(true); } } } /** {@collect.stats} * subclasses may envelope to monitor child property changes. */ public void propertyChange(PropertyChangeEvent pce) { String propertyName = pce.getPropertyName(); Object source = pce.getSource(); synchronized(children) { if ("beanContext".equals(propertyName) && containsKey(source) && ((BCSChild)children.get(source)).isRemovePending()) { BeanContext bc = getBeanContextPeer(); if (bc.equals(pce.getOldValue()) && !bc.equals(pce.getNewValue())) { remove(source, false); } else { ((BCSChild)children.get(source)).setRemovePending(false); } } } } /** {@collect.stats} * <p> * Subclasses of this class may override, or envelope, this method to * add validation behavior for the BeanContext to examine child objects * immediately prior to their being added to the BeanContext. * </p> * * @return true iff the child may be added to this BeanContext, otherwise false. */ protected boolean validatePendingAdd(Object targetChild) { return true; } /** {@collect.stats} * <p> * Subclasses of this class may override, or envelope, this method to * add validation behavior for the BeanContext to examine child objects * immediately prior to their being removed from the BeanContext. * </p> * * @return true iff the child may be removed from this BeanContext, otherwise false. */ protected boolean validatePendingRemove(Object targetChild) { return true; } /** {@collect.stats} * subclasses may override this method to simply extend add() semantics * after the child has been added and before the event notification has * occurred. The method is called with the child synchronized. */ protected void childJustAddedHook(Object child, BCSChild bcsc) { } /** {@collect.stats} * subclasses may override this method to simply extend remove() semantics * after the child has been removed and before the event notification has * occurred. The method is called with the child synchronized. */ protected void childJustRemovedHook(Object child, BCSChild bcsc) { } /** {@collect.stats} * Gets the Component (if any) associated with the specified child. * @param child the specified child * @return the Component (if any) associated with the specified child. */ protected static final Visibility getChildVisibility(Object child) { try { return (Visibility)child; } catch (ClassCastException cce) { return null; } } /** {@collect.stats} * Gets the Serializable (if any) associated with the specified Child * @param child the specified child * @return the Serializable (if any) associated with the specified Child */ protected static final Serializable getChildSerializable(Object child) { try { return (Serializable)child; } catch (ClassCastException cce) { return null; } } /** {@collect.stats} * Gets the PropertyChangeListener * (if any) of the specified child * @param child the specified child * @return the PropertyChangeListener (if any) of the specified child */ protected static final PropertyChangeListener getChildPropertyChangeListener(Object child) { try { return (PropertyChangeListener)child; } catch (ClassCastException cce) { return null; } } /** {@collect.stats} * Gets the VetoableChangeListener * (if any) of the specified child * @param child the specified child * @return the VetoableChangeListener (if any) of the specified child */ protected static final VetoableChangeListener getChildVetoableChangeListener(Object child) { try { return (VetoableChangeListener)child; } catch (ClassCastException cce) { return null; } } /** {@collect.stats} * Gets the BeanContextMembershipListener * (if any) of the specified child * @param child the specified child * @return the BeanContextMembershipListener (if any) of the specified child */ protected static final BeanContextMembershipListener getChildBeanContextMembershipListener(Object child) { try { return (BeanContextMembershipListener)child; } catch (ClassCastException cce) { return null; } } /** {@collect.stats} * Gets the BeanContextChild (if any) of the specified child * @param child the specified child * @return the BeanContextChild (if any) of the specified child * @throws IllegalArgumentException if child implements both BeanContextChild and BeanContextProxy */ protected static final BeanContextChild getChildBeanContextChild(Object child) { try { BeanContextChild bcc = (BeanContextChild)child; if (child instanceof BeanContextChild && child instanceof BeanContextProxy) throw new IllegalArgumentException("child cannot implement both BeanContextChild and BeanContextProxy"); else return bcc; } catch (ClassCastException cce) { try { return ((BeanContextProxy)child).getBeanContextProxy(); } catch (ClassCastException cce1) { return null; } } } /** {@collect.stats} * Fire a BeanContextshipEvent on the BeanContextMembershipListener interface */ protected final void fireChildrenAdded(BeanContextMembershipEvent bcme) { Object[] copy; synchronized(bcmListeners) { copy = bcmListeners.toArray(); } for (int i = 0; i < copy.length; i++) ((BeanContextMembershipListener)copy[i]).childrenAdded(bcme); } /** {@collect.stats} * Fire a BeanContextshipEvent on the BeanContextMembershipListener interface */ protected final void fireChildrenRemoved(BeanContextMembershipEvent bcme) { Object[] copy; synchronized(bcmListeners) { copy = bcmListeners.toArray(); } for (int i = 0; i < copy.length; i++) ((BeanContextMembershipListener)copy[i]).childrenRemoved(bcme); } /** {@collect.stats} * protected method called from constructor and readObject to initialize * transient state of BeanContextSupport instance. * * This class uses this method to instantiate inner class listeners used * to monitor PropertyChange and VetoableChange events on children. * * subclasses may envelope this method to add their own initialization * behavior */ protected synchronized void initialize() { children = new HashMap(serializable + 1); bcmListeners = new ArrayList(1); childPCL = new PropertyChangeListener() { /* * this adaptor is used by the BeanContextSupport class to forward * property changes from a child to the BeanContext, avoiding * accidential serialization of the BeanContext by a badly * behaved Serializable child. */ public void propertyChange(PropertyChangeEvent pce) { BeanContextSupport.this.propertyChange(pce); } }; childVCL = new VetoableChangeListener() { /* * this adaptor is used by the BeanContextSupport class to forward * vetoable changes from a child to the BeanContext, avoiding * accidential serialization of the BeanContext by a badly * behaved Serializable child. */ public void vetoableChange(PropertyChangeEvent pce) throws PropertyVetoException { BeanContextSupport.this.vetoableChange(pce); } }; } /** {@collect.stats} * Gets a copy of the this BeanContext's children. * @return a copy of the current nested children */ protected final Object[] copyChildren() { synchronized(children) { return children.keySet().toArray(); } } /** {@collect.stats} * Tests to see if two class objects, * or their names are equal. * @param first the first object * @param second the second object * @return true if equal, false if not */ protected static final boolean classEquals(Class first, Class second) { return first.equals(second) || first.getName().equals(second.getName()); } /* * fields */ /** {@collect.stats} * all accesses to the <code> protected HashMap children </code> field * shall be synchronized on that object. */ protected transient HashMap children; private int serializable = 0; // children serializable /** {@collect.stats} * all accesses to the <code> protected ArrayList bcmListeners </code> field * shall be synchronized on that object. */ protected transient ArrayList bcmListeners; // /** {@collect.stats} * The current locale of this BeanContext. */ protected Locale locale; /** {@collect.stats} * A <tt>boolean</tt> indicating if this * instance may now render a GUI. */ protected boolean okToUseGui; /** {@collect.stats} * A <tt>boolean</tt> indicating whether or not * this object is currently in design time mode. */ protected boolean designTime; /* * transient */ private transient PropertyChangeListener childPCL; private transient VetoableChangeListener childVCL; private transient boolean serializing; }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.beans.DesignMode; import java.beans.Visibility; import java.io.InputStream; import java.io.IOException; import java.net.URL; import java.util.Collection; import java.util.Locale; /** {@collect.stats} * <p> * The BeanContext acts a logical hierarchical container for JavaBeans. * </p> * * @author Laurence P. G. Cable * @since 1.2 * * @see java.beans.Beans * @see java.beans.beancontext.BeanContextChild * @see java.beans.beancontext.BeanContextMembershipListener * @see java.beans.PropertyChangeEvent * @see java.beans.DesignMode * @see java.beans.Visibility * @see java.util.Collection */ public interface BeanContext extends BeanContextChild, Collection, DesignMode, Visibility { /** {@collect.stats} * Instantiate the javaBean named as a * child of this <code>BeanContext</code>. * The implementation of the JavaBean is * derived from the value of the beanName parameter, * and is defined by the * <code>java.beans.Beans.instantiate()</code> method. * * @param beanName The name of the JavaBean to instantiate * as a child of this <code>BeanContext</code> * @throws <code>IOException</code> * @throws <code>ClassNotFoundException</code> if the class identified * by the beanName parameter is not found */ Object instantiateChild(String beanName) throws IOException, ClassNotFoundException; /** {@collect.stats} * Analagous to <code>java.lang.ClassLoader.getResourceAsStream()</code>, * this method allows a <code>BeanContext</code> implementation * to interpose behavior between the child <code>Component</code> * and underlying <code>ClassLoader</code>. * * @param name the resource name * @param bcc the specified child * @return an <code>InputStream</code> for reading the resource, * or <code>null</code> if the resource could not * be found. * @throws <code>IllegalArgumentException</code> if * the resource is not valid */ InputStream getResourceAsStream(String name, BeanContextChild bcc) throws IllegalArgumentException; /** {@collect.stats} * Analagous to <code>java.lang.ClassLoader.getResource()</code>, this * method allows a <code>BeanContext</code> implementation to interpose * behavior between the child <code>Component</code> * and underlying <code>ClassLoader</code>. * * @param name the resource name * @param bcc the specified child * @return a <code>URL</code> for the named * resource for the specified child * @throws <code>IllegalArgumentException</code> * if the resource is not valid */ URL getResource(String name, BeanContextChild bcc) throws IllegalArgumentException; /** {@collect.stats} * Adds the specified <code>BeanContextMembershipListener</code> * to receive <code>BeanContextMembershipEvents</code> from * this <code>BeanContext</code> whenever it adds * or removes a child <code>Component</code>(s). * * @param bcml the <code>BeanContextMembershipListener</code> to be added */ void addBeanContextMembershipListener(BeanContextMembershipListener bcml); /** {@collect.stats} * Removes the specified <code>BeanContextMembershipListener</code> * so that it no longer receives <code>BeanContextMembershipEvent</code>s * when the child <code>Component</code>(s) are added or removed. * * @param bcml the <code>BeanContextMembershipListener</code> * to be removed */ void removeBeanContextMembershipListener(BeanContextMembershipListener bcml); /** {@collect.stats} * This global lock is used by both <code>BeanContext</code> * and <code>BeanContextServices</code> implementors * to serialize changes in a <code>BeanContext</code> * hierarchy and any service requests etc. */ public static final Object globalHierarchyLock = new Object(); }
Java
/* * Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.beans.beancontext.BeanContextServiceAvailableEvent; import java.beans.beancontext.BeanContextServiceRevokedEvent; import java.beans.beancontext.BeanContextServiceRevokedListener; /** {@collect.stats} * The listener interface for receiving * <code>BeanContextServiceAvailableEvent</code> objects. * A class that is interested in processing a * <code>BeanContextServiceAvailableEvent</code> implements this interface. */ public interface BeanContextServicesListener extends BeanContextServiceRevokedListener { /** {@collect.stats} * The service named has been registered. getService requests for * this service may now be made. * @param bcsae the <code>BeanContextServiceAvailableEvent</code> */ void serviceAvailable(BeanContextServiceAvailableEvent bcsae); }
Java
/* * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.beans.beancontext.BeanContextEvent; import java.beans.beancontext.BeanContextServices; /** {@collect.stats} * <p> * This event type is used by the * <code>BeanContextServiceRevokedListener</code> in order to * identify the service being revoked. * </p> */ public class BeanContextServiceRevokedEvent extends BeanContextEvent { /** {@collect.stats} * Construct a <code>BeanContextServiceEvent</code>. * @param bcs the <code>BeanContextServices</code> * from which this service is being revoked * @param sc the service that is being revoked * @param invalidate <code>true</code> for immediate revocation */ public BeanContextServiceRevokedEvent(BeanContextServices bcs, Class sc, boolean invalidate) { super((BeanContext)bcs); serviceClass = sc; invalidateRefs = invalidate; } /** {@collect.stats} * Gets the source as a reference of type <code>BeanContextServices</code> * @return the <code>BeanContextServices</code> from which * this service is being revoked */ public BeanContextServices getSourceAsBeanContextServices() { return (BeanContextServices)getBeanContext(); } /** {@collect.stats} * Gets the service class that is the subject of this notification * @return A <code>Class</code> reference to the * service that is being revoked */ public Class getServiceClass() { return serviceClass; } /** {@collect.stats} * Checks this event to determine whether or not * the service being revoked is of a particular class. * @param service the service of interest (should be non-null) * @return <code>true</code> if the service being revoked is of the * same class as the specified service */ public boolean isServiceClass(Class service) { return serviceClass.equals(service); } /** {@collect.stats} * Reports if the current service is being forcibly revoked, * in which case the references are now invalidated and unusable. * @return <code>true</code> if current service is being forcibly revoked */ public boolean isCurrentServiceInvalidNow() { return invalidateRefs; } /** {@collect.stats} * fields */ /** {@collect.stats} * A <code>Class</code> reference to the service that is being revoked. */ protected Class serviceClass; private boolean invalidateRefs; }
Java
/* * Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.util.EventObject; import java.beans.beancontext.BeanContext; import java.beans.beancontext.BeanContextEvent; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; /** {@collect.stats} * A <code>BeanContextMembershipEvent</code> encapsulates * the list of children added to, or removed from, * the membership of a particular <code>BeanContext</code>. * An instance of this event is fired whenever a successful * add(), remove(), retainAll(), removeAll(), or clear() is * invoked on a given <code>BeanContext</code> instance. * Objects interested in receiving events of this type must * implement the <code>BeanContextMembershipListener</code> * interface, and must register their intent via the * <code>BeanContext</code>'s * <code>addBeanContextMembershipListener(BeanContextMembershipListener bcml) * </code> method. * * @author Laurence P. G. Cable * @since 1.2 * @see java.beans.beancontext.BeanContext * @see java.beans.beancontext.BeanContextEvent * @see java.beans.beancontext.BeanContextMembershipListener */ public class BeanContextMembershipEvent extends BeanContextEvent { /** {@collect.stats} * Contruct a BeanContextMembershipEvent * * @param bc The BeanContext source * @param changes The Children affected * @throws NullPointerException if <CODE>changes</CODE> is <CODE>null</CODE> */ public BeanContextMembershipEvent(BeanContext bc, Collection changes) { super(bc); if (changes == null) throw new NullPointerException( "BeanContextMembershipEvent constructor: changes is null."); children = changes; } /** {@collect.stats} * Contruct a BeanContextMembershipEvent * * @param bc The BeanContext source * @param changes The Children effected * @exception NullPointerException if changes associated with this * event are null. */ public BeanContextMembershipEvent(BeanContext bc, Object[] changes) { super(bc); if (changes == null) throw new NullPointerException( "BeanContextMembershipEvent: changes is null."); children = Arrays.asList(changes); } /** {@collect.stats} * Gets the number of children affected by the notification. * @return the number of children affected by the notification */ public int size() { return children.size(); } /** {@collect.stats} * Is the child specified affected by the event? * @return <code>true</code> if affected, <code>false</code> * if not */ public boolean contains(Object child) { return children.contains(child); } /** {@collect.stats} * Gets the array of children affected by this event. * @return the array of children affected */ public Object[] toArray() { return children.toArray(); } /** {@collect.stats} * Gets the array of children affected by this event. * @return the array of children effected */ public Iterator iterator() { return children.iterator(); } /* * fields */ /** {@collect.stats} * The list of children affected by this * event notification. */ protected Collection children; }
Java
/* * Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.beans.BeanInfo; /** {@collect.stats} * A BeanContextServiceProvider implementor who wishes to provide explicit * information about the services their bean may provide shall implement a * BeanInfo class that implements this BeanInfo subinterface and provides * explicit information about the methods, properties, events, etc, of their * services. */ public interface BeanContextServiceProviderBeanInfo extends BeanInfo { /** {@collect.stats} * Gets a <code>BeanInfo</code> array, one for each * service class or interface statically available * from this ServiceProvider. * @return the <code>BeanInfo</code> array */ BeanInfo[] getServicesBeanInfo(); }
Java
/* * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.beans.VetoableChangeListener; import java.beans.VetoableChangeSupport; import java.beans.PropertyVetoException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** {@collect.stats} * <p> * This is a general support class to provide support for implementing the * BeanContextChild protocol. * * This class may either be directly subclassed, or encapsulated and delegated * to in order to implement this interface for a given component. * </p> * * @author Laurence P. G. Cable * @since 1.2 * * @see java.beans.beancontext.BeanContext * @see java.beans.beancontext.BeanContextServices * @see java.beans.beancontext.BeanContextChild */ public class BeanContextChildSupport implements BeanContextChild, BeanContextServicesListener, Serializable { static final long serialVersionUID = 6328947014421475877L; /** {@collect.stats} * construct a BeanContextChildSupport where this class has been * subclassed in order to implement the JavaBean component itself. */ public BeanContextChildSupport() { super(); beanContextChildPeer = this; pcSupport = new PropertyChangeSupport(beanContextChildPeer); vcSupport = new VetoableChangeSupport(beanContextChildPeer); } /** {@collect.stats} * construct a BeanContextChildSupport where the JavaBean component * itself implements BeanContextChild, and encapsulates this, delegating * that interface to this implementation */ public BeanContextChildSupport(BeanContextChild bcc) { super(); beanContextChildPeer = (bcc != null) ? bcc : this; pcSupport = new PropertyChangeSupport(beanContextChildPeer); vcSupport = new VetoableChangeSupport(beanContextChildPeer); } /** {@collect.stats} * Sets the <code>BeanContext</code> for * this <code>BeanContextChildSupport</code>. * @param bc the new value to be assigned to the <code>BeanContext</code> * property * @throws <code>PropertyVetoException</code> if the change is rejected */ public synchronized void setBeanContext(BeanContext bc) throws PropertyVetoException { if (bc == beanContext) return; BeanContext oldValue = beanContext; BeanContext newValue = bc; if (!rejectedSetBCOnce) { if (rejectedSetBCOnce = !validatePendingSetBeanContext(bc)) { throw new PropertyVetoException( "setBeanContext() change rejected:", new PropertyChangeEvent(beanContextChildPeer, "beanContext", oldValue, newValue) ); } try { fireVetoableChange("beanContext", oldValue, newValue ); } catch (PropertyVetoException pve) { rejectedSetBCOnce = true; throw pve; // re-throw } } if (beanContext != null) releaseBeanContextResources(); beanContext = newValue; rejectedSetBCOnce = false; firePropertyChange("beanContext", oldValue, newValue ); if (beanContext != null) initializeBeanContextResources(); } /** {@collect.stats} * Gets the nesting <code>BeanContext</code> * for this <code>BeanContextChildSupport</code>. * @return the nesting <code>BeanContext</code> for * this <code>BeanContextChildSupport</code>. */ public synchronized BeanContext getBeanContext() { return beanContext; } /** {@collect.stats} * Add a PropertyChangeListener for a specific property. * The same listener object may be added more than once. For each * property, the listener will be invoked the number of times it was added * for that property. * If <code>name</code> or <code>pcl</code> is null, no exception is thrown * and no action is taken. * * @param name The name of the property to listen on * @param pcl The <code>PropertyChangeListener</code> to be added */ public void addPropertyChangeListener(String name, PropertyChangeListener pcl) { pcSupport.addPropertyChangeListener(name, pcl); } /** {@collect.stats} * Remove a PropertyChangeListener for a specific property. * If <code>pcl</code> was added more than once to the same event * source for the specified property, it will be notified one less time * after being removed. * If <code>name</code> is null, no exception is thrown * and no action is taken. * If <code>pcl</code> is null, or was never added for the specified * property, no exception is thrown and no action is taken. * * @param name The name of the property that was listened on * @param pcl The PropertyChangeListener to be removed */ public void removePropertyChangeListener(String name, PropertyChangeListener pcl) { pcSupport.removePropertyChangeListener(name, pcl); } /** {@collect.stats} * Add a VetoableChangeListener for a specific property. * The same listener object may be added more than once. For each * property, the listener will be invoked the number of times it was added * for that property. * If <code>name</code> or <code>vcl</code> is null, no exception is thrown * and no action is taken. * * @param name The name of the property to listen on * @param vcl The <code>VetoableChangeListener</code> to be added */ public void addVetoableChangeListener(String name, VetoableChangeListener vcl) { vcSupport.addVetoableChangeListener(name, vcl); } /** {@collect.stats} * Removes a <code>VetoableChangeListener</code>. * If <code>pcl</code> was added more than once to the same event * source for the specified property, it will be notified one less time * after being removed. * If <code>name</code> is null, no exception is thrown * and no action is taken. * If <code>vcl</code> is null, or was never added for the specified * property, no exception is thrown and no action is taken. * * @param name The name of the property that was listened on * @param vcl The <code>VetoableChangeListener</code> to be removed */ public void removeVetoableChangeListener(String name, VetoableChangeListener vcl) { vcSupport.removeVetoableChangeListener(name, vcl); } /** {@collect.stats} * A service provided by the nesting BeanContext has been revoked. * * Subclasses may override this method in order to implement their own * behaviors. * @param bcsre The <code>BeanContextServiceRevokedEvent</code> fired as a * result of a service being revoked */ public void serviceRevoked(BeanContextServiceRevokedEvent bcsre) { } /** {@collect.stats} * A new service is available from the nesting BeanContext. * * Subclasses may override this method in order to implement their own * behaviors * @param bcsae The BeanContextServiceAvailableEvent fired as a * result of a service becoming available * */ public void serviceAvailable(BeanContextServiceAvailableEvent bcsae) { } /** {@collect.stats} * Gets the <tt>BeanContextChild</tt> associated with this * <tt>BeanContextChildSupport</tt>. * * @return the <tt>BeanContextChild</tt> peer of this class */ public BeanContextChild getBeanContextChildPeer() { return beanContextChildPeer; } /** {@collect.stats} * Reports whether or not this class is a delegate of another. * * @return true if this class is a delegate of another */ public boolean isDelegated() { return !this.equals(beanContextChildPeer); } /** {@collect.stats} * Report a bound property update to any registered listeners. No event is * fired if old and new are equal and non-null. * @param name The programmatic name of the property that was changed * @param oldValue The old value of the property * @param newValue The new value of the property */ public void firePropertyChange(String name, Object oldValue, Object newValue) { pcSupport.firePropertyChange(name, oldValue, newValue); } /** {@collect.stats} * Report a vetoable property update to any registered listeners. * If anyone vetos the change, then fire a new event * reverting everyone to the old value and then rethrow * the PropertyVetoException. <P> * * No event is fired if old and new are equal and non-null. * <P> * @param name The programmatic name of the property that is about to * change * * @param oldValue The old value of the property * @param newValue - The new value of the property * * @throws PropertyVetoException if the recipient wishes the property * change to be rolled back. */ public void fireVetoableChange(String name, Object oldValue, Object newValue) throws PropertyVetoException { vcSupport.fireVetoableChange(name, oldValue, newValue); } /** {@collect.stats} * Called from setBeanContext to validate (or otherwise) the * pending change in the nesting BeanContext property value. * Returning false will cause setBeanContext to throw * PropertyVetoException. * @param newValue the new value that has been requested for * the BeanContext property * @return <code>true</code> if the change operation is to be vetoed */ public boolean validatePendingSetBeanContext(BeanContext newValue) { return true; } /** {@collect.stats} * This method may be overridden by subclasses to provide their own * release behaviors. When invoked any resources held by this instance * obtained from its current BeanContext property should be released * since the object is no longer nested within that BeanContext. */ protected void releaseBeanContextResources() { // do nothing } /** {@collect.stats} * This method may be overridden by subclasses to provide their own * initialization behaviors. When invoked any resources requried by the * BeanContextChild should be obtained from the current BeanContext. */ protected void initializeBeanContextResources() { // do nothing } /** {@collect.stats} * Write the persistence state of the object. */ private void writeObject(ObjectOutputStream oos) throws IOException { /* * dont serialize if we are delegated and the delegator isnt also * serializable. */ if (!equals(beanContextChildPeer) && !(beanContextChildPeer instanceof Serializable)) throw new IOException("BeanContextChildSupport beanContextChildPeer not Serializable"); else oos.defaultWriteObject(); } /** {@collect.stats} * Restore a persistent object, must wait for subsequent setBeanContext() * to fully restore any resources obtained from the new nesting * BeanContext */ private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); } /* * fields */ /** {@collect.stats} * The <code>BeanContext</code> in which * this <code>BeanContextChild</code> is nested. */ public BeanContextChild beanContextChildPeer; /** {@collect.stats} * The <tt>PropertyChangeSupport</tt> associated with this * <tt>BeanContextChildSupport</tt>. */ protected PropertyChangeSupport pcSupport; /** {@collect.stats} * The <tt>VetoableChangeSupport</tt> associated with this * <tt>BeanContextChildSupport</tt>. */ protected VetoableChangeSupport vcSupport; protected transient BeanContext beanContext; /** {@collect.stats} * A flag indicating that there has been * at least one <code>PropertyChangeVetoException</code> * thrown for the attempted setBeanContext operation. */ protected transient boolean rejectedSetBCOnce; }
Java
/* * Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.beans.beancontext.BeanContextServiceRevokedEvent; import java.util.EventListener; /** {@collect.stats} * The listener interface for receiving * <code>BeanContextServiceRevokedEvent</code> objects. A class that is * interested in processing a <code>BeanContextServiceRevokedEvent</code> * implements this interface. */ public interface BeanContextServiceRevokedListener extends EventListener { /** {@collect.stats} * The service named has been revoked. getService requests for * this service will no longer be satisifed. * @param bcsre the <code>BeanContextServiceRevokedEvent</code> received * by this listener. */ void serviceRevoked(BeanContextServiceRevokedEvent bcsre); }
Java
/* * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.util.Iterator; import java.util.TooManyListenersException; import java.beans.beancontext.BeanContext; import java.beans.beancontext.BeanContextServiceProvider; import java.beans.beancontext.BeanContextServicesListener; /** {@collect.stats} * <p> * The BeanContextServices interface provides a mechanism for a BeanContext * to expose generic "services" to the BeanContextChild objects within. * </p> */ public interface BeanContextServices extends BeanContext, BeanContextServicesListener { /** {@collect.stats} * Adds a service to this BeanContext. * <code>BeanContextServiceProvider</code>s call this method * to register a particular service with this context. * If the service has not previously been added, the * <code>BeanContextServices</code> associates * the service with the <code>BeanContextServiceProvider</code> and * fires a <code>BeanContextServiceAvailableEvent</code> to all * currently registered <code>BeanContextServicesListeners</code>. * The method then returns <code>true</code>, indicating that * the addition of the service was successful. * If the given service has already been added, this method * simply returns <code>false</code>. * @param serviceClass the service to add * @param serviceProvider the <code>BeanContextServiceProvider</code> * associated with the service */ boolean addService(Class serviceClass, BeanContextServiceProvider serviceProvider); /** {@collect.stats} * BeanContextServiceProviders wishing to remove * a currently registered service from this context * may do so via invocation of this method. Upon revocation of * the service, the <code>BeanContextServices</code> fires a * <code>BeanContextServiceRevokedEvent</code> to its * list of currently registered * <code>BeanContextServiceRevokedListeners</code> and * <code>BeanContextServicesListeners</code>. * @param serviceClass the service to revoke from this BeanContextServices * @param serviceProvider the BeanContextServiceProvider associated with * this particular service that is being revoked * @param revokeCurrentServicesNow a value of <code>true</code> * indicates an exceptional circumstance where the * <code>BeanContextServiceProvider</code> or * <code>BeanContextServices</code> wishes to immediately * terminate service to all currently outstanding references * to the specified service. */ void revokeService(Class serviceClass, BeanContextServiceProvider serviceProvider, boolean revokeCurrentServicesNow); /** {@collect.stats} * Reports whether or not a given service is * currently available from this context. * @param serviceClass the service in question * @return true if the service is available */ boolean hasService(Class serviceClass); /** {@collect.stats} * A <code>BeanContextChild</code>, or any arbitrary object * associated with a <code>BeanContextChild</code>, may obtain * a reference to a currently registered service from its * nesting <code>BeanContextServices</code> * via invocation of this method. When invoked, this method * gets the service by calling the getService() method on the * underlying <code>BeanContextServiceProvider</code>. * @param child the <code>BeanContextChild</code> * associated with this request * @param requestor the object requesting the service * @param serviceClass class of the requested service * @param serviceSelector the service dependent parameter * @param bcsrl the * <code>BeanContextServiceRevokedListener</code> to notify * if the service should later become revoked * @throws TooManyListenersException * @return a reference to this context's named * Service as requested or <code>null</code> */ Object getService(BeanContextChild child, Object requestor, Class serviceClass, Object serviceSelector, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException; /** {@collect.stats} * Releases a <code>BeanContextChild</code>'s * (or any arbitrary object associated with a BeanContextChild) * reference to the specified service by calling releaseService() * on the underlying <code>BeanContextServiceProvider</code>. * @param child the <code>BeanContextChild</code> * @param requestor the requestor * @param service the service */ void releaseService(BeanContextChild child, Object requestor, Object service); /** {@collect.stats} * Gets the currently available services for this context. * @return an <code>Iterator</code> consisting of the * currently available services */ Iterator getCurrentServiceClasses(); /** {@collect.stats} * Gets the list of service dependent service parameters * (Service Selectors) for the specified service, by * calling getCurrentServiceSelectors() on the * underlying BeanContextServiceProvider. * @param serviceClass the specified service * @return the currently available service selectors * for the named serviceClass */ Iterator getCurrentServiceSelectors(Class serviceClass); /** {@collect.stats} * Adds a <code>BeanContextServicesListener</code> to this BeanContext * @param bcsl the <code>BeanContextServicesListener</code> to add */ void addBeanContextServicesListener(BeanContextServicesListener bcsl); /** {@collect.stats} * Removes a <code>BeanContextServicesListener</code> * from this <code>BeanContext</code> * @param bcsl the <code>BeanContextServicesListener</code> * to remove from this context */ void removeBeanContextServicesListener(BeanContextServicesListener bcsl); }
Java
/* * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.util.EventObject; import java.beans.beancontext.BeanContext; /** {@collect.stats} * <p> * <code>BeanContextEvent</code> is the abstract root event class * for all events emitted * from, and pertaining to the semantics of, a <code>BeanContext</code>. * This class introduces a mechanism to allow the propagation of * <code>BeanContextEvent</code> subclasses through a hierarchy of * <code>BeanContext</code>s. The <code>setPropagatedFrom()</code> * and <code>getPropagatedFrom()</code> methods allow a * <code>BeanContext</code> to identify itself as the source * of a propagated event. * </p> * * @author Laurence P. G. Cable * @since 1.2 * @see java.beans.beancontext.BeanContext */ public abstract class BeanContextEvent extends EventObject { /** {@collect.stats} * Contruct a BeanContextEvent * * @param bc The BeanContext source */ protected BeanContextEvent(BeanContext bc) { super(bc); } /** {@collect.stats} * Gets the <code>BeanContext</code> associated with this event. * @return the <code>BeanContext</code> associated with this event. */ public BeanContext getBeanContext() { return (BeanContext)getSource(); } /** {@collect.stats} * Sets the <code>BeanContext</code> from which this event was propagated. * @param bc the <code>BeanContext</code> from which this event * was propagated */ public synchronized void setPropagatedFrom(BeanContext bc) { propagatedFrom = bc; } /** {@collect.stats} * Gets the <code>BeanContext</code> from which this event was propagated. * @return the <code>BeanContext</code> from which this * event was propagated */ public synchronized BeanContext getPropagatedFrom() { return propagatedFrom; } /** {@collect.stats} * Reports whether or not this event is * propagated from some other <code>BeanContext</code>. * @return <code>true</code> if propagated, <code>false</code> * if not */ public synchronized boolean isPropagated() { return propagatedFrom != null; } /* * fields */ /** {@collect.stats} * The <code>BeanContext</code> from which this event was propagated */ protected BeanContext propagatedFrom; }
Java
/* * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.beans.beancontext.BeanContextChild; import java.beans.beancontext.BeanContextEvent; import java.beans.beancontext.BeanContextServices; import java.util.Iterator; /** {@collect.stats} * <p> * This event type is used by the BeanContextServicesListener in order to * identify the service being registered. * </p> */ public class BeanContextServiceAvailableEvent extends BeanContextEvent { /** {@collect.stats} * Construct a <code>BeanContextAvailableServiceEvent</code>. * @param bcs The context in which the service has become available * @param sc A <code>Class</code> reference to the newly available service */ public BeanContextServiceAvailableEvent(BeanContextServices bcs, Class sc) { super((BeanContext)bcs); serviceClass = sc; } /** {@collect.stats} * Gets the source as a reference of type <code>BeanContextServices</code>. * @return The context in which the service has become available */ public BeanContextServices getSourceAsBeanContextServices() { return (BeanContextServices)getBeanContext(); } /** {@collect.stats} * Gets the service class that is the subject of this notification. * @return A <code>Class</code> reference to the newly available service */ public Class getServiceClass() { return serviceClass; } /** {@collect.stats} * Gets the list of service dependent selectors. * @return the current selectors available from the service */ public Iterator getCurrentServiceSelectors() { return ((BeanContextServices)getSource()).getCurrentServiceSelectors(serviceClass); } /* * fields */ /** {@collect.stats} * A <code>Class</code> reference to the newly available service */ protected Class serviceClass; }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.beans.PropertyChangeListener; import java.beans.VetoableChangeListener; import java.beans.PropertyVetoException; import java.beans.beancontext.BeanContext; /** {@collect.stats} * <p> * JavaBeans wishing to be nested within, and obtain a reference to their * execution environment, or context, as defined by the BeanContext * sub-interface shall implement this interface. * </p> * <p> * Conformant BeanContexts shall as a side effect of adding a BeanContextChild * object shall pass a reference to itself via the setBeanContext() method of * this interface. * </p> * <p> * Note that a BeanContextChild may refuse a change in state by throwing * PropertyVetoedException in response. * </p> * <p> * In order for persistence mechanisms to function properly on BeanContextChild * instances across a broad variety of scenarios, implementing classes of this * interface are required to define as transient, any or all fields, or * instance variables, that may contain, or represent, references to the * nesting BeanContext instance or other resources obtained * from the BeanContext via any unspecified mechanisms. * </p> * * @author Laurence P. G. Cable * @since 1.2 * * @see java.beans.beancontext.BeanContext * @see java.beans.PropertyChangeEvent * @see java.beans.PropertyChangeListener * @see java.beans.PropertyVetoException * @see java.beans.VetoableChangeListener */ public interface BeanContextChild { /** {@collect.stats} * <p> * Objects that implement this interface, * shall fire a java.beans.PropertyChangeEvent, with parameters: * * propertyName "beanContext", oldValue (the previous nesting * <code>BeanContext</code> instance, or <code>null</code>), * newValue (the current nesting * <code>BeanContext</code> instance, or <code>null</code>). * <p> * A change in the value of the nesting BeanContext property of this * BeanContextChild may be vetoed by throwing the appropriate exception. * </p> * @param bc The <code>BeanContext</code> with which * to associate this <code>BeanContextChild</code>. * @throws <code>PropertyVetoException</code> if the * addition of the specified <code>BeanContext</code> is refused. */ void setBeanContext(BeanContext bc) throws PropertyVetoException; /** {@collect.stats} * Gets the <code>BeanContext</code> associated * with this <code>BeanContextChild</code>. * @return the <code>BeanContext</code> associated * with this <code>BeanContextChild</code>. */ BeanContext getBeanContext(); /** {@collect.stats} * Adds a <code>PropertyChangeListener</code> * to this <code>BeanContextChild</code> * in order to receive a <code>PropertyChangeEvent</code> * whenever the specified property has changed. * @param name the name of the property to listen on * @param pcl the <code>PropertyChangeListener</code> to add */ void addPropertyChangeListener(String name, PropertyChangeListener pcl); /** {@collect.stats} * Removes a <code>PropertyChangeListener</code> from this * <code>BeanContextChild</code> so that it no longer * receives <code>PropertyChangeEvents</code> when the * specified property is changed. * * @param name the name of the property that was listened on * @param pcl the <code>PropertyChangeListener</code> to remove */ void removePropertyChangeListener(String name, PropertyChangeListener pcl); /** {@collect.stats} * Adds a <code>VetoableChangeListener</code> to * this <code>BeanContextChild</code> * to receive events whenever the specified property changes. * @param name the name of the property to listen on * @param vcl the <code>VetoableChangeListener</code> to add */ void addVetoableChangeListener(String name, VetoableChangeListener vcl); /** {@collect.stats} * Removes a <code>VetoableChangeListener</code> from this * <code>BeanContextChild</code> so that it no longer receives * events when the specified property changes. * @param name the name of the property that was listened on. * @param vcl the <code>VetoableChangeListener</code> to remove. */ void removeVetoableChangeListener(String name, VetoableChangeListener vcl); }
Java
/* * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.beans.beancontext.BeanContextMembershipEvent; import java.util.EventListener; /** {@collect.stats} * <p> * Compliant BeanContexts fire events on this interface when the state of * the membership of the BeanContext changes. * </p> * * @author Laurence P. G. Cable * @since 1.2 * @see java.beans.beancontext.BeanContext */ public interface BeanContextMembershipListener extends EventListener { /** {@collect.stats} * Called when a child or list of children is added to a * <code>BeanContext</code> that this listener is registered with. * @param bcme The <code>BeanContextMembershipEvent</code> * describing the change that occurred. */ void childrenAdded(BeanContextMembershipEvent bcme); /** {@collect.stats} * Called when a child or list of children is removed * from a <code>BeanContext</code> that this listener * is registered with. * @param bcme The <code>BeanContextMembershipEvent</code> * describing the change that occurred. */ void childrenRemoved(BeanContextMembershipEvent bcme); }
Java
/* * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.TooManyListenersException; import java.util.Locale; /** {@collect.stats} * <p> * This helper class provides a utility implementation of the * java.beans.beancontext.BeanContextServices interface. * </p> * <p> * Since this class directly implements the BeanContextServices interface, * the class can, and is intended to be used either by subclassing this * implementation, or via delegation of an instance of this class * from another through the BeanContextProxy interface. * </p> * * @author Laurence P. G. Cable * @since 1.2 */ public class BeanContextServicesSupport extends BeanContextSupport implements BeanContextServices { /** {@collect.stats} * <p> * Construct a BeanContextServicesSupport instance * </p> * * @param peer The peer BeanContext we are supplying an implementation for, if null the this object is its own peer * @param lcle The current Locale for this BeanContext. * @param dTime The initial state, true if in design mode, false if runtime. * @param visible The initial visibility. * */ public BeanContextServicesSupport(BeanContextServices peer, Locale lcle, boolean dTime, boolean visible) { super(peer, lcle, dTime, visible); } /** {@collect.stats} * Create an instance using the specified Locale and design mode. * * @param peer The peer BeanContext we are supplying an implementation for, if null the this object is its own peer * @param lcle The current Locale for this BeanContext. * @param dtime The initial state, true if in design mode, false if runtime. */ public BeanContextServicesSupport(BeanContextServices peer, Locale lcle, boolean dtime) { this (peer, lcle, dtime, true); } /** {@collect.stats} * Create an instance using the specified locale * * @param peer The peer BeanContext we are supplying an implementation for, if null the this object is its own peer * @param lcle The current Locale for this BeanContext. */ public BeanContextServicesSupport(BeanContextServices peer, Locale lcle) { this (peer, lcle, false, true); } /** {@collect.stats} * Create an instance with a peer * * @param peer The peer BeanContext we are supplying an implementation for, if null the this object is its own peer */ public BeanContextServicesSupport(BeanContextServices peer) { this (peer, null, false, true); } /** {@collect.stats} * Create an instance that is not a delegate of another object */ public BeanContextServicesSupport() { this (null, null, false, true); } /** {@collect.stats} * called by BeanContextSupport superclass during construction and * deserialization to initialize subclass transient state. * * subclasses may envelope this method, but should not override it or * call it directly. */ public void initialize() { super.initialize(); services = new HashMap(serializable + 1); bcsListeners = new ArrayList(1); } /** {@collect.stats} * Gets the <tt>BeanContextServices</tt> associated with this * <tt>BeanContextServicesSupport</tt>. * * @return the instance of <tt>BeanContext</tt> * this object is providing the implementation for. */ public BeanContextServices getBeanContextServicesPeer() { return (BeanContextServices)getBeanContextChildPeer(); } /** {@collect.stats} **********************************************************************/ /* * protected nested class containing per child information, an instance * of which is associated with each child in the "children" hashtable. * subclasses can extend this class to include their own per-child state. * * Note that this 'value' is serialized with the corresponding child 'key' * when the BeanContextSupport is serialized. */ protected class BCSSChild extends BeanContextSupport.BCSChild { private static final long serialVersionUID = -3263851306889194873L; /* * private nested class to map serviceClass to Provider and requestors * listeners. */ class BCSSCServiceClassRef { // create an instance of a service ref BCSSCServiceClassRef(Class sc, BeanContextServiceProvider bcsp, boolean delegated) { super(); serviceClass = sc; if (delegated) delegateProvider = bcsp; else serviceProvider = bcsp; } // add a requestor and assoc listener void addRequestor(Object requestor, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException { BeanContextServiceRevokedListener cbcsrl = (BeanContextServiceRevokedListener)requestors.get(requestor); if (cbcsrl != null && !cbcsrl.equals(bcsrl)) throw new TooManyListenersException(); requestors.put(requestor, bcsrl); } // remove a requestor void removeRequestor(Object requestor) { requestors.remove(requestor); } // check a requestors listener void verifyRequestor(Object requestor, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException { BeanContextServiceRevokedListener cbcsrl = (BeanContextServiceRevokedListener)requestors.get(requestor); if (cbcsrl != null && !cbcsrl.equals(bcsrl)) throw new TooManyListenersException(); } void verifyAndMaybeSetProvider(BeanContextServiceProvider bcsp, boolean isDelegated) { BeanContextServiceProvider current; if (isDelegated) { // the provider is delegated current = delegateProvider; if (current == null || bcsp == null) { delegateProvider = bcsp; return; } } else { // the provider is registered with this BCS current = serviceProvider; if (current == null || bcsp == null) { serviceProvider = bcsp; return; } } if (!current.equals(bcsp)) throw new UnsupportedOperationException("existing service reference obtained from different BeanContextServiceProvider not supported"); } Iterator cloneOfEntries() { return ((HashMap)requestors.clone()).entrySet().iterator(); } Iterator entries() { return requestors.entrySet().iterator(); } boolean isEmpty() { return requestors.isEmpty(); } Class getServiceClass() { return serviceClass; } BeanContextServiceProvider getServiceProvider() { return serviceProvider; } BeanContextServiceProvider getDelegateProvider() { return delegateProvider; } boolean isDelegated() { return delegateProvider != null; } void addRef(boolean delegated) { if (delegated) { delegateRefs++; } else { serviceRefs++; } } void releaseRef(boolean delegated) { if (delegated) { if (--delegateRefs == 0) { delegateProvider = null; } } else { if (--serviceRefs <= 0) { serviceProvider = null; } } } int getRefs() { return serviceRefs + delegateRefs; } int getDelegateRefs() { return delegateRefs; } int getServiceRefs() { return serviceRefs; } /* * fields */ Class serviceClass; BeanContextServiceProvider serviceProvider; int serviceRefs; BeanContextServiceProvider delegateProvider; // proxy int delegateRefs; HashMap requestors = new HashMap(1); } /* * per service reference info ... */ class BCSSCServiceRef { BCSSCServiceRef(BCSSCServiceClassRef scref, boolean isDelegated) { serviceClassRef = scref; delegated = isDelegated; } void addRef() { refCnt++; } int release() { return --refCnt; } BCSSCServiceClassRef getServiceClassRef() { return serviceClassRef; } boolean isDelegated() { return delegated; } /* * fields */ BCSSCServiceClassRef serviceClassRef; int refCnt = 1; boolean delegated = false; } BCSSChild(Object bcc, Object peer) { super(bcc, peer); } // note usage of service per requestor, per service synchronized void usingService(Object requestor, Object service, Class serviceClass, BeanContextServiceProvider bcsp, boolean isDelegated, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException, UnsupportedOperationException { // first, process mapping from serviceClass to requestor(s) BCSSCServiceClassRef serviceClassRef = null; if (serviceClasses == null) serviceClasses = new HashMap(1); else serviceClassRef = (BCSSCServiceClassRef)serviceClasses.get(serviceClass); if (serviceClassRef == null) { // new service being used ... serviceClassRef = new BCSSCServiceClassRef(serviceClass, bcsp, isDelegated); serviceClasses.put(serviceClass, serviceClassRef); } else { // existing service ... serviceClassRef.verifyAndMaybeSetProvider(bcsp, isDelegated); // throws serviceClassRef.verifyRequestor(requestor, bcsrl); // throws } serviceClassRef.addRequestor(requestor, bcsrl); serviceClassRef.addRef(isDelegated); // now handle mapping from requestor to service(s) BCSSCServiceRef serviceRef = null; Map services = null; if (serviceRequestors == null) { serviceRequestors = new HashMap(1); } else { services = (Map)serviceRequestors.get(requestor); } if (services == null) { services = new HashMap(1); serviceRequestors.put(requestor, services); } else serviceRef = (BCSSCServiceRef)services.get(service); if (serviceRef == null) { serviceRef = new BCSSCServiceRef(serviceClassRef, isDelegated); services.put(service, serviceRef); } else { serviceRef.addRef(); } } // release a service reference synchronized void releaseService(Object requestor, Object service) { if (serviceRequestors == null) return; Map services = (Map)serviceRequestors.get(requestor); if (services == null) return; // oops its not there anymore! BCSSCServiceRef serviceRef = (BCSSCServiceRef)services.get(service); if (serviceRef == null) return; // oops its not there anymore! BCSSCServiceClassRef serviceClassRef = serviceRef.getServiceClassRef(); boolean isDelegated = serviceRef.isDelegated(); BeanContextServiceProvider bcsp = isDelegated ? serviceClassRef.getDelegateProvider() : serviceClassRef.getServiceProvider(); bcsp.releaseService(BeanContextServicesSupport.this.getBeanContextServicesPeer(), requestor, service); serviceClassRef.releaseRef(isDelegated); serviceClassRef.removeRequestor(requestor); if (serviceRef.release() == 0) { services.remove(service); if (services.isEmpty()) { serviceRequestors.remove(requestor); serviceClassRef.removeRequestor(requestor); } if (serviceRequestors.isEmpty()) { serviceRequestors = null; } if (serviceClassRef.isEmpty()) { serviceClasses.remove(serviceClassRef.getServiceClass()); } if (serviceClasses.isEmpty()) serviceClasses = null; } } // revoke a service synchronized void revokeService(Class serviceClass, boolean isDelegated, boolean revokeNow) { if (serviceClasses == null) return; BCSSCServiceClassRef serviceClassRef = (BCSSCServiceClassRef)serviceClasses.get(serviceClass); if (serviceClassRef == null) return; Iterator i = serviceClassRef.cloneOfEntries(); BeanContextServiceRevokedEvent bcsre = new BeanContextServiceRevokedEvent(BeanContextServicesSupport.this.getBeanContextServicesPeer(), serviceClass, revokeNow); boolean noMoreRefs = false; while (i.hasNext() && serviceRequestors != null) { Map.Entry entry = (Map.Entry)i.next(); BeanContextServiceRevokedListener listener = (BeanContextServiceRevokedListener)entry.getValue(); if (revokeNow) { Object requestor = entry.getKey(); Map services = (Map)serviceRequestors.get(requestor); if (services != null) { Iterator i1 = services.entrySet().iterator(); while (i1.hasNext()) { Map.Entry tmp = (Map.Entry)i1.next(); BCSSCServiceRef serviceRef = (BCSSCServiceRef)tmp.getValue(); if (serviceRef.getServiceClassRef().equals(serviceClassRef) && isDelegated == serviceRef.isDelegated()) { i1.remove(); } } if (noMoreRefs = services.isEmpty()) { serviceRequestors.remove(requestor); } } if (noMoreRefs) serviceClassRef.removeRequestor(requestor); } listener.serviceRevoked(bcsre); } if (revokeNow && serviceClasses != null) { if (serviceClassRef.isEmpty()) serviceClasses.remove(serviceClass); if (serviceClasses.isEmpty()) serviceClasses = null; } if (serviceRequestors != null && serviceRequestors.isEmpty()) serviceRequestors = null; } // release all references for this child since it has been unnested. void cleanupReferences() { if (serviceRequestors == null) return; Iterator requestors = serviceRequestors.entrySet().iterator(); while(requestors.hasNext()) { Map.Entry tmp = (Map.Entry)requestors.next(); Object requestor = tmp.getKey(); Iterator services = ((Map)tmp.getValue()).entrySet().iterator(); requestors.remove(); while (services.hasNext()) { Map.Entry entry = (Map.Entry)services.next(); Object service = entry.getKey(); BCSSCServiceRef sref = (BCSSCServiceRef)entry.getValue(); BCSSCServiceClassRef scref = sref.getServiceClassRef(); BeanContextServiceProvider bcsp = sref.isDelegated() ? scref.getDelegateProvider() : scref.getServiceProvider(); scref.removeRequestor(requestor); services.remove(); while (sref.release() >= 0) { bcsp.releaseService(BeanContextServicesSupport.this.getBeanContextServicesPeer(), requestor, service); } } } serviceRequestors = null; serviceClasses = null; } void revokeAllDelegatedServicesNow() { if (serviceClasses == null) return; Iterator serviceClassRefs = new HashSet(serviceClasses.values()).iterator(); while (serviceClassRefs.hasNext()) { BCSSCServiceClassRef serviceClassRef = (BCSSCServiceClassRef)serviceClassRefs.next(); if (!serviceClassRef.isDelegated()) continue; Iterator i = serviceClassRef.cloneOfEntries(); BeanContextServiceRevokedEvent bcsre = new BeanContextServiceRevokedEvent(BeanContextServicesSupport.this.getBeanContextServicesPeer(), serviceClassRef.getServiceClass(), true); boolean noMoreRefs = false; while (i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); BeanContextServiceRevokedListener listener = (BeanContextServiceRevokedListener)entry.getValue(); Object requestor = entry.getKey(); Map services = (Map)serviceRequestors.get(requestor); if (services != null) { Iterator i1 = services.entrySet().iterator(); while (i1.hasNext()) { Map.Entry tmp = (Map.Entry)i1.next(); BCSSCServiceRef serviceRef = (BCSSCServiceRef)tmp.getValue(); if (serviceRef.getServiceClassRef().equals(serviceClassRef) && serviceRef.isDelegated()) { i1.remove(); } } if (noMoreRefs = services.isEmpty()) { serviceRequestors.remove(requestor); } } if (noMoreRefs) serviceClassRef.removeRequestor(requestor); listener.serviceRevoked(bcsre); if (serviceClassRef.isEmpty()) serviceClasses.remove(serviceClassRef.getServiceClass()); } } if (serviceClasses.isEmpty()) serviceClasses = null; if (serviceRequestors != null && serviceRequestors.isEmpty()) serviceRequestors = null; } /* * fields */ private transient HashMap serviceClasses; private transient HashMap serviceRequestors; } /** {@collect.stats} * <p> * Subclasses can override this method to insert their own subclass * of Child without having to override add() or the other Collection * methods that add children to the set. * </p> * * @param targetChild the child to create the Child on behalf of * @param peer the peer if the targetChild and peer are related by BeanContextProxy */ protected BCSChild createBCSChild(Object targetChild, Object peer) { return new BCSSChild(targetChild, peer); } /** {@collect.stats} **********************************************************************/ /** {@collect.stats} * subclasses may subclass this nested class to add behaviors for * each BeanContextServicesProvider. */ protected static class BCSSServiceProvider implements Serializable { BCSSServiceProvider(Class sc, BeanContextServiceProvider bcsp) { super(); serviceProvider = bcsp; } protected BeanContextServiceProvider getServiceProvider() { return serviceProvider; } /* * fields */ protected BeanContextServiceProvider serviceProvider; } /** {@collect.stats} * subclasses can override this method to create new subclasses of * BCSSServiceProvider without having to overrride addService() in * order to instantiate. */ protected BCSSServiceProvider createBCSSServiceProvider(Class sc, BeanContextServiceProvider bcsp) { return new BCSSServiceProvider(sc, bcsp); } /** {@collect.stats} **********************************************************************/ /** {@collect.stats} * add a BeanContextServicesListener * * @throws NullPointerException */ public void addBeanContextServicesListener(BeanContextServicesListener bcsl) { if (bcsl == null) throw new NullPointerException("bcsl"); synchronized(bcsListeners) { if (bcsListeners.contains(bcsl)) return; else bcsListeners.add(bcsl); } } /** {@collect.stats} * remove a BeanContextServicesListener */ public void removeBeanContextServicesListener(BeanContextServicesListener bcsl) { if (bcsl == null) throw new NullPointerException("bcsl"); synchronized(bcsListeners) { if (!bcsListeners.contains(bcsl)) return; else bcsListeners.remove(bcsl); } } /** {@collect.stats} * add a service */ public boolean addService(Class serviceClass, BeanContextServiceProvider bcsp) { return addService(serviceClass, bcsp, true); } /** {@collect.stats} * add a service */ protected boolean addService(Class serviceClass, BeanContextServiceProvider bcsp, boolean fireEvent) { if (serviceClass == null) throw new NullPointerException("serviceClass"); if (bcsp == null) throw new NullPointerException("bcsp"); synchronized(BeanContext.globalHierarchyLock) { if (services.containsKey(serviceClass)) return false; else { services.put(serviceClass, createBCSSServiceProvider(serviceClass, bcsp)); if (bcsp instanceof Serializable) serializable++; if (!fireEvent) return true; BeanContextServiceAvailableEvent bcssae = new BeanContextServiceAvailableEvent(getBeanContextServicesPeer(), serviceClass); fireServiceAdded(bcssae); synchronized(children) { Iterator i = children.keySet().iterator(); while (i.hasNext()) { Object c = i.next(); if (c instanceof BeanContextServices) { ((BeanContextServicesListener)c).serviceAvailable(bcssae); } } } return true; } } } /** {@collect.stats} * remove a service */ public void revokeService(Class serviceClass, BeanContextServiceProvider bcsp, boolean revokeCurrentServicesNow) { if (serviceClass == null) throw new NullPointerException("serviceClass"); if (bcsp == null) throw new NullPointerException("bcsp"); synchronized(BeanContext.globalHierarchyLock) { if (!services.containsKey(serviceClass)) return; BCSSServiceProvider bcsssp = (BCSSServiceProvider)services.get(serviceClass); if (!bcsssp.getServiceProvider().equals(bcsp)) throw new IllegalArgumentException("service provider mismatch"); services.remove(serviceClass); if (bcsp instanceof Serializable) serializable--; Iterator i = bcsChildren(); // get the BCSChild values. while (i.hasNext()) { ((BCSSChild)i.next()).revokeService(serviceClass, false, revokeCurrentServicesNow); } fireServiceRevoked(serviceClass, revokeCurrentServicesNow); } } /** {@collect.stats} * has a service, which may be delegated */ public synchronized boolean hasService(Class serviceClass) { if (serviceClass == null) throw new NullPointerException("serviceClass"); synchronized(BeanContext.globalHierarchyLock) { if (services.containsKey(serviceClass)) return true; BeanContextServices bcs = null; try { bcs = (BeanContextServices)getBeanContext(); } catch (ClassCastException cce) { return false; } return bcs == null ? false : bcs.hasService(serviceClass); } } /** {@collect.stats} **********************************************************************/ /* * a nested subclass used to represent a proxy for serviceClasses delegated * to an enclosing BeanContext. */ protected class BCSSProxyServiceProvider implements BeanContextServiceProvider, BeanContextServiceRevokedListener { BCSSProxyServiceProvider(BeanContextServices bcs) { super(); nestingCtxt = bcs; } public Object getService(BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector) { Object service = null; try { service = nestingCtxt.getService(bcs, requestor, serviceClass, serviceSelector, this); } catch (TooManyListenersException tmle) { return null; } return service; } public void releaseService(BeanContextServices bcs, Object requestor, Object service) { nestingCtxt.releaseService(bcs, requestor, service); } public Iterator getCurrentServiceSelectors(BeanContextServices bcs, Class serviceClass) { return nestingCtxt.getCurrentServiceSelectors(serviceClass); } public void serviceRevoked(BeanContextServiceRevokedEvent bcsre) { Iterator i = bcsChildren(); // get the BCSChild values. while (i.hasNext()) { ((BCSSChild)i.next()).revokeService(bcsre.getServiceClass(), true, bcsre.isCurrentServiceInvalidNow()); } } /* * fields */ private BeanContextServices nestingCtxt; } /** {@collect.stats} **********************************************************************/ /** {@collect.stats} * obtain a service which may be delegated */ public Object getService(BeanContextChild child, Object requestor, Class serviceClass, Object serviceSelector, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException { if (child == null) throw new NullPointerException("child"); if (serviceClass == null) throw new NullPointerException("serviceClass"); if (requestor == null) throw new NullPointerException("requestor"); if (bcsrl == null) throw new NullPointerException("bcsrl"); Object service = null; BCSSChild bcsc; BeanContextServices bcssp = getBeanContextServicesPeer(); synchronized(BeanContext.globalHierarchyLock) { synchronized(children) { bcsc = (BCSSChild)children.get(child); } if (bcsc == null) throw new IllegalArgumentException("not a child of this context"); // not a child ... BCSSServiceProvider bcsssp = (BCSSServiceProvider)services.get(serviceClass); if (bcsssp != null) { BeanContextServiceProvider bcsp = bcsssp.getServiceProvider(); service = bcsp.getService(bcssp, requestor, serviceClass, serviceSelector); if (service != null) { // do bookkeeping ... try { bcsc.usingService(requestor, service, serviceClass, bcsp, false, bcsrl); } catch (TooManyListenersException tmle) { bcsp.releaseService(bcssp, requestor, service); throw tmle; } catch (UnsupportedOperationException uope) { bcsp.releaseService(bcssp, requestor, service); throw uope; // unchecked rt exception } return service; } } if (proxy != null) { // try to delegate ... service = proxy.getService(bcssp, requestor, serviceClass, serviceSelector); if (service != null) { // do bookkeeping ... try { bcsc.usingService(requestor, service, serviceClass, proxy, true, bcsrl); } catch (TooManyListenersException tmle) { proxy.releaseService(bcssp, requestor, service); throw tmle; } catch (UnsupportedOperationException uope) { proxy.releaseService(bcssp, requestor, service); throw uope; // unchecked rt exception } return service; } } } return null; } /** {@collect.stats} * release a service */ public void releaseService(BeanContextChild child, Object requestor, Object service) { if (child == null) throw new NullPointerException("child"); if (requestor == null) throw new NullPointerException("requestor"); if (service == null) throw new NullPointerException("service"); BCSSChild bcsc; synchronized(BeanContext.globalHierarchyLock) { synchronized(children) { bcsc = (BCSSChild)children.get(child); } if (bcsc != null) bcsc.releaseService(requestor, service); else throw new IllegalArgumentException("child actual is not a child of this BeanContext"); } } /** {@collect.stats} * @return an iterator for all the currently registered service classes. */ public Iterator getCurrentServiceClasses() { return new BCSIterator(services.keySet().iterator()); } /** {@collect.stats} * @return an iterator for all the currently available service selectors * (if any) available for the specified service. */ public Iterator getCurrentServiceSelectors(Class serviceClass) { BCSSServiceProvider bcsssp = (BCSSServiceProvider)services.get(serviceClass); return bcsssp != null ? new BCSIterator(bcsssp.getServiceProvider().getCurrentServiceSelectors(getBeanContextServicesPeer(), serviceClass)) : null; } /** {@collect.stats} * BeanContextServicesListener callback, propagates event to all * currently registered listeners and BeanContextServices children, * if this BeanContextService does not already implement this service * itself. * * subclasses may override or envelope this method to implement their * own propagation semantics. */ public void serviceAvailable(BeanContextServiceAvailableEvent bcssae) { synchronized(BeanContext.globalHierarchyLock) { if (services.containsKey(bcssae.getServiceClass())) return; fireServiceAdded(bcssae); Iterator i; synchronized(children) { i = children.keySet().iterator(); } while (i.hasNext()) { Object c = i.next(); if (c instanceof BeanContextServices) { ((BeanContextServicesListener)c).serviceAvailable(bcssae); } } } } /** {@collect.stats} * BeanContextServicesListener callback, propagates event to all * currently registered listeners and BeanContextServices children, * if this BeanContextService does not already implement this service * itself. * * subclasses may override or envelope this method to implement their * own propagation semantics. */ public void serviceRevoked(BeanContextServiceRevokedEvent bcssre) { synchronized(BeanContext.globalHierarchyLock) { if (services.containsKey(bcssre.getServiceClass())) return; fireServiceRevoked(bcssre); Iterator i; synchronized(children) { i = children.keySet().iterator(); } while (i.hasNext()) { Object c = i.next(); if (c instanceof BeanContextServices) { ((BeanContextServicesListener)c).serviceRevoked(bcssre); } } } } /** {@collect.stats} * Gets the <tt>BeanContextServicesListener</tt> (if any) of the specified * child. * * @param child the specified child * @return the BeanContextServicesListener (if any) of the specified child */ protected static final BeanContextServicesListener getChildBeanContextServicesListener(Object child) { try { return (BeanContextServicesListener)child; } catch (ClassCastException cce) { return null; } } /** {@collect.stats} * called from superclass child removal operations after a child * has been successfully removed. called with child synchronized. * * This subclass uses this hook to immediately revoke any services * being used by this child if it is a BeanContextChild. * * subclasses may envelope this method in order to implement their * own child removal side-effects. */ protected void childJustRemovedHook(Object child, BCSChild bcsc) { BCSSChild bcssc = (BCSSChild)bcsc; bcssc.cleanupReferences(); } /** {@collect.stats} * called from setBeanContext to notify a BeanContextChild * to release resources obtained from the nesting BeanContext. * * This method revokes any services obtained from its parent. * * subclasses may envelope this method to implement their own semantics. */ protected synchronized void releaseBeanContextResources() { Object[] bcssc; super.releaseBeanContextResources(); synchronized(children) { if (children.isEmpty()) return; bcssc = children.values().toArray(); } for (int i = 0; i < bcssc.length; i++) { ((BCSSChild)bcssc[i]).revokeAllDelegatedServicesNow(); } proxy = null; } /** {@collect.stats} * called from setBeanContext to notify a BeanContextChild * to allocate resources obtained from the nesting BeanContext. * * subclasses may envelope this method to implement their own semantics. */ protected synchronized void initializeBeanContextResources() { super.initializeBeanContextResources(); BeanContext nbc = getBeanContext(); if (nbc == null) return; try { BeanContextServices bcs = (BeanContextServices)nbc; proxy = new BCSSProxyServiceProvider(bcs); } catch (ClassCastException cce) { // do nothing ... } } /** {@collect.stats} * Fires a <tt>BeanContextServiceEvent</tt> notifying of a new service. */ protected final void fireServiceAdded(Class serviceClass) { BeanContextServiceAvailableEvent bcssae = new BeanContextServiceAvailableEvent(getBeanContextServicesPeer(), serviceClass); fireServiceAdded(bcssae); } /** {@collect.stats} * Fires a <tt>BeanContextServiceAvailableEvent</tt> indicating that a new * service has become available. * * @param bcssae the <tt>BeanContextServiceAvailableEvent</tt> */ protected final void fireServiceAdded(BeanContextServiceAvailableEvent bcssae) { Object[] copy; synchronized (bcsListeners) { copy = bcsListeners.toArray(); } for (int i = 0; i < copy.length; i++) { ((BeanContextServicesListener)copy[i]).serviceAvailable(bcssae); } } /** {@collect.stats} * Fires a <tt>BeanContextServiceEvent</tt> notifying of a service being revoked. * * @param bcsre the <tt>BeanContextServiceRevokedEvent</tt> */ protected final void fireServiceRevoked(BeanContextServiceRevokedEvent bcsre) { Object[] copy; synchronized (bcsListeners) { copy = bcsListeners.toArray(); } for (int i = 0; i < copy.length; i++) { ((BeanContextServiceRevokedListener)copy[i]).serviceRevoked(bcsre); } } /** {@collect.stats} * Fires a <tt>BeanContextServiceRevokedEvent</tt> * indicating that a particular service is * no longer available. */ protected final void fireServiceRevoked(Class serviceClass, boolean revokeNow) { Object[] copy; BeanContextServiceRevokedEvent bcsre = new BeanContextServiceRevokedEvent(getBeanContextServicesPeer(), serviceClass, revokeNow); synchronized (bcsListeners) { copy = bcsListeners.toArray(); } for (int i = 0; i < copy.length; i++) { ((BeanContextServicesListener)copy[i]).serviceRevoked(bcsre); } } /** {@collect.stats} * called from BeanContextSupport writeObject before it serializes the * children ... * * This class will serialize any Serializable BeanContextServiceProviders * herein. * * subclasses may envelope this method to insert their own serialization * processing that has to occur prior to serialization of the children */ protected synchronized void bcsPreSerializationHook(ObjectOutputStream oos) throws IOException { oos.writeInt(serializable); if (serializable <= 0) return; int count = 0; Iterator i = services.entrySet().iterator(); while (i.hasNext() && count < serializable) { Map.Entry entry = (Map.Entry)i.next(); BCSSServiceProvider bcsp = null; try { bcsp = (BCSSServiceProvider)entry.getValue(); } catch (ClassCastException cce) { continue; } if (bcsp.getServiceProvider() instanceof Serializable) { oos.writeObject(entry.getKey()); oos.writeObject(bcsp); count++; } } if (count != serializable) throw new IOException("wrote different number of service providers than expected"); } /** {@collect.stats} * called from BeanContextSupport readObject before it deserializes the * children ... * * This class will deserialize any Serializable BeanContextServiceProviders * serialized earlier thus making them available to the children when they * deserialized. * * subclasses may envelope this method to insert their own serialization * processing that has to occur prior to serialization of the children */ protected synchronized void bcsPreDeserializationHook(ObjectInputStream ois) throws IOException, ClassNotFoundException { serializable = ois.readInt(); int count = serializable; while (count > 0) { services.put(ois.readObject(), ois.readObject()); count--; } } /** {@collect.stats} * serialize the instance */ private synchronized void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject(); serialize(oos, (Collection)bcsListeners); } /** {@collect.stats} * deserialize the instance */ private synchronized void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); deserialize(ois, (Collection)bcsListeners); } /* * fields */ /** {@collect.stats} * all accesses to the <code> protected transient HashMap services </code> * field should be synchronized on that object */ protected transient HashMap services; /** {@collect.stats} * The number of instances of a serializable <tt>BeanContextServceProvider</tt>. */ protected transient int serializable = 0; /** {@collect.stats} * Delegate for the <tt>BeanContextServiceProvider</tt>. */ protected transient BCSSProxyServiceProvider proxy; /** {@collect.stats} * List of <tt>BeanContextServicesListener</tt> objects. */ protected transient ArrayList bcsListeners; }
Java
/* * Copyright (c) 1998, 2002, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; /** {@collect.stats} * <p> * This interface is implemented by a JavaBean that does * not directly have a BeanContext(Child) associated with * it (via implementing that interface or a subinterface thereof), * but has a public BeanContext(Child) delegated from it. * For example, a subclass of java.awt.Container may have a BeanContext * associated with it that all Component children of that Container shall * be contained within. * </p> * <p> * An Object may not implement this interface and the * BeanContextChild interface * (or any subinterfaces thereof) they are mutually exclusive. * </p> * <p> * Callers of this interface shall examine the return type in order to * obtain a particular subinterface of BeanContextChild as follows: * <code> * BeanContextChild bcc = o.getBeanContextProxy(); * * if (bcc instanceof BeanContext) { * // ... * } * </code> * or * <code> * BeanContextChild bcc = o.getBeanContextProxy(); * BeanContext bc = null; * * try { * bc = (BeanContext)bcc; * } catch (ClassCastException cce) { * // cast failed, bcc is not an instanceof BeanContext * } * </code> * </p> * <p> * The return value is a constant for the lifetime of the implementing * instance * </p> * @author Laurence P. G. Cable * @since 1.2 * * @see java.beans.beancontext.BeanContextChild * @see java.beans.beancontext.BeanContextChildSupport */ public interface BeanContextProxy { /** {@collect.stats} * Gets the <code>BeanContextChild</code> (or subinterface) * associated with this object. * @return the <code>BeanContextChild</code> (or subinterface) * associated with this object */ BeanContextChild getBeanContextProxy(); }
Java
/* * Copyright (c) 1998, 2002, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.awt.Container; /** {@collect.stats} * <p> * This interface is implemented by BeanContexts' that have an AWT Container * associated with them. * </p> * * @author Laurence P. G. Cable * @since 1.2 * * @see java.beans.beancontext.BeanContext * @see java.beans.beancontext.BeanContextSupport */ public interface BeanContextContainerProxy { /** {@collect.stats} * Gets the <code>java.awt.Container</code> associated * with this <code>BeanContext</code>. * @return the <code>java.awt.Container</code> associated * with this <code>BeanContext</code>. */ Container getContainer(); }
Java
/* * Copyright (c) 1998, 2002, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans.beancontext; import java.awt.Component; /** {@collect.stats} * <p> * This interface is implemented by * <code>BeanContextChildren</code> that have an AWT <code>Component</code> * associated with them. * </p> * * @author Laurence P. G. Cable * @since 1.2 * * @see java.beans.beancontext.BeanContext * @see java.beans.beancontext.BeanContextSupport */ public interface BeanContextChildComponentProxy { /** {@collect.stats} * Gets the <code>java.awt.Component</code> associated with * this <code>BeanContextChild</code>. * @return the AWT <code>Component</code> associated with * this <code>BeanContextChild</code> */ Component getComponent(); }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import sun.beans.editors.*; /** {@collect.stats} * The PropertyEditorManager can be used to locate a property editor for * any given type name. This property editor must support the * java.beans.PropertyEditor interface for editing a given object. * <P> * The PropertyEditorManager uses three techniques for locating an editor * for a given type. First, it provides a registerEditor method to allow * an editor to be specifically registered for a given type. Second it * tries to locate a suitable class by adding "Editor" to the full * qualified classname of the given type (e.g. "foo.bah.FozEditor"). * Finally it takes the simple classname (without the package name) adds * "Editor" to it and looks in a search-path of packages for a matching * class. * <P> * So for an input class foo.bah.Fred, the PropertyEditorManager would * first look in its tables to see if an editor had been registered for * foo.bah.Fred and if so use that. Then it will look for a * foo.bah.FredEditor class. Then it will look for (say) * standardEditorsPackage.FredEditor class. * <p> * Default PropertyEditors will be provided for the Java primitive types * "boolean", "byte", "short", "int", "long", "float", and "double"; and * for the classes java.lang.String. java.awt.Color, and java.awt.Font. */ public class PropertyEditorManager { /** {@collect.stats} * Register an editor class to be used to edit values of * a given target class. * * <p>First, if there is a security manager, its <code>checkPropertiesAccess</code> * method is called. This could result in a SecurityException. * * @param targetType the Class object of the type to be edited * @param editorClass the Class object of the editor class. If * this is null, then any existing definition will be removed. * @exception SecurityException if a security manager exists and its * <code>checkPropertiesAccess</code> method doesn't allow setting * of system properties. * @see SecurityManager#checkPropertiesAccess */ public static void registerEditor(Class<?> targetType, Class<?> editorClass) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } initialize(); if (editorClass == null) { registry.remove(targetType); } else { registry.put(targetType, editorClass); } } /** {@collect.stats} * Locate a value editor for a given target type. * * @param targetType The Class object for the type to be edited * @return An editor object for the given target class. * The result is null if no suitable editor can be found. */ public static synchronized PropertyEditor findEditor(Class<?> targetType) { initialize(); Class editorClass = (Class)registry.get(targetType); if (editorClass != null) { try { Object o = editorClass.newInstance(); return (PropertyEditor)o; } catch (Exception ex) { System.err.println("Couldn't instantiate type editor \"" + editorClass.getName() + "\" : " + ex); } } // Now try adding "Editor" to the class name. String editorName = targetType.getName() + "Editor"; try { return (PropertyEditor) Introspector.instantiate(targetType, editorName); } catch (Exception ex) { // Silently ignore any errors. } // Now try looking for <searchPath>.fooEditor int index = editorName.lastIndexOf('.') + 1; if (index > 0) { editorName = editorName.substring(index); } for (String path : searchPath) { String name = path + '.' + editorName; try { return (PropertyEditor) Introspector.instantiate(targetType, name); } catch (Exception ex) { // Silently ignore any errors. } } if (null != targetType.getEnumConstants()) { return new EnumEditor(targetType); } // We couldn't find a suitable Editor. return null; } /** {@collect.stats} * Gets the package names that will be searched for property editors. * * @return The array of package names that will be searched in * order to find property editors. * <p> The default value for this array is implementation-dependent, * e.g. Sun implementation initially sets to {"sun.beans.editors"}. */ public static synchronized String[] getEditorSearchPath() { // Return a copy of the searchPath. String result[] = new String[searchPath.length]; System.arraycopy(searchPath, 0, result, 0, searchPath.length); return result; } /** {@collect.stats} * Change the list of package names that will be used for * finding property editors. * * <p>First, if there is a security manager, its <code>checkPropertiesAccess</code> * method is called. This could result in a SecurityException. * * @param path Array of package names. * @exception SecurityException if a security manager exists and its * <code>checkPropertiesAccess</code> method doesn't allow setting * of system properties. * @see SecurityManager#checkPropertiesAccess */ public static synchronized void setEditorSearchPath(String path[]) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } if (path == null) { path = new String[0]; } searchPath = path; } private static synchronized void initialize() { if (registry != null) { return; } registry = new java.util.Hashtable(); registry.put(Byte.TYPE, ByteEditor.class); registry.put(Short.TYPE, ShortEditor.class); registry.put(Integer.TYPE, IntegerEditor.class); registry.put(Long.TYPE, LongEditor.class); registry.put(Boolean.TYPE, BooleanEditor.class); registry.put(Float.TYPE, FloatEditor.class); registry.put(Double.TYPE, DoubleEditor.class); } private static String[] searchPath = { "sun.beans.editors" }; private static java.util.Hashtable registry; }
Java
/* * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import com.sun.beans.ObjectHandler; import java.io.InputStream; import java.io.IOException; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import org.xml.sax.SAXException; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; /** {@collect.stats} * The <code>XMLDecoder</code> class is used to read XML documents * created using the <code>XMLEncoder</code> and is used just like * the <code>ObjectInputStream</code>. For example, one can use * the following fragment to read the first object defined * in an XML document written by the <code>XMLEncoder</code> * class: * <pre> * XMLDecoder d = new XMLDecoder( * new BufferedInputStream( * new FileInputStream("Test.xml"))); * Object result = d.readObject(); * d.close(); * </pre> * *<p> * For more information you might also want to check out * <a href="http://java.sun.com/products/jfc/tsc/articles/persistence3">Long Term Persistence of JavaBeans Components: XML Schema</a>, * an article in <em>The Swing Connection.</em> * @see XMLEncoder * @see java.io.ObjectInputStream * * @since 1.4 * * @author Philip Milne */ public class XMLDecoder { private InputStream in; private Object owner; private ExceptionListener exceptionListener; private ObjectHandler handler; private Reference clref; /** {@collect.stats} * Creates a new input stream for reading archives * created by the <code>XMLEncoder</code> class. * * @param in The underlying stream. * * @see XMLEncoder#XMLEncoder(java.io.OutputStream) */ public XMLDecoder(InputStream in) { this(in, null); } /** {@collect.stats} * Creates a new input stream for reading archives * created by the <code>XMLEncoder</code> class. * * @param in The underlying stream. * @param owner The owner of this stream. * */ public XMLDecoder(InputStream in, Object owner) { this(in, owner, null); } /** {@collect.stats} * Creates a new input stream for reading archives * created by the <code>XMLEncoder</code> class. * * @param in the underlying stream. * @param owner the owner of this stream. * @param exceptionListener the exception handler for the stream; * if <code>null</code> the default exception listener will be used. */ public XMLDecoder(InputStream in, Object owner, ExceptionListener exceptionListener) { this(in, owner, exceptionListener, null); } /** {@collect.stats} * Creates a new input stream for reading archives * created by the <code>XMLEncoder</code> class. * * @param in the underlying stream. <code>null</code> may be passed without * error, though the resulting XMLDecoder will be useless * @param owner the owner of this stream. <code>null</code> is a legal * value * @param exceptionListener the exception handler for the stream, or * <code>null</code> to use the default * @param cl the class loader used for instantiating objects. * <code>null</code> indicates that the default class loader should * be used * @since 1.5 */ public XMLDecoder(InputStream in, Object owner, ExceptionListener exceptionListener, ClassLoader cl) { this.in = in; setOwner(owner); setExceptionListener(exceptionListener); setClassLoader(cl); } /** {@collect.stats} * Set the class loader used to instantiate objects for this stream. * * @param cl a classloader to use; if null then the default class loader * will be used */ private void setClassLoader(ClassLoader cl) { if (cl != null) { this.clref = new WeakReference(cl); } } /** {@collect.stats} * Return the class loader used to instantiate objects. If the class loader * has not been explicitly set then null is returned. * * @return the class loader used to instantiate objects */ private ClassLoader getClassLoader() { if (clref != null) { return (ClassLoader)clref.get(); } return null; } /** {@collect.stats} * This method closes the input stream associated * with this stream. */ public void close() { if (in != null) { getHandler(); try { in.close(); } catch (IOException e) { getExceptionListener().exceptionThrown(e); } } } /** {@collect.stats} * Sets the exception handler for this stream to <code>exceptionListener</code>. * The exception handler is notified when this stream catches recoverable * exceptions. * * @param exceptionListener The exception handler for this stream; * if <code>null</code> the default exception listener will be used. * * @see #getExceptionListener */ public void setExceptionListener(ExceptionListener exceptionListener) { this.exceptionListener = exceptionListener; } /** {@collect.stats} * Gets the exception handler for this stream. * * @return The exception handler for this stream. * Will return the default exception listener if this has not explicitly been set. * * @see #setExceptionListener */ public ExceptionListener getExceptionListener() { return (exceptionListener != null) ? exceptionListener : Statement.defaultExceptionListener; } /** {@collect.stats} * Reads the next object from the underlying input stream. * * @return the next object read * * @throws ArrayIndexOutOfBoundsException if the stream contains no objects * (or no more objects) * * @see XMLEncoder#writeObject */ public Object readObject() { if (in == null) { return null; } return getHandler().dequeueResult(); } /** {@collect.stats} * Sets the owner of this decoder to <code>owner</code>. * * @param owner The owner of this decoder. * * @see #getOwner */ public void setOwner(Object owner) { this.owner = owner; } /** {@collect.stats} * Gets the owner of this decoder. * * @return The owner of this decoder. * * @see #setOwner */ public Object getOwner() { return owner; } /** {@collect.stats} * Returns the object handler for input stream. * The object handler is created if necessary. * * @return the object handler */ private ObjectHandler getHandler() { if ( handler == null ) { SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); handler = new ObjectHandler( this, getClassLoader() ); parser.parse( in, handler ); } catch ( ParserConfigurationException e ) { getExceptionListener().exceptionThrown( e ); } catch ( SAXException se ) { Exception e = se.getException(); if ( e == null ) { e = se; } getExceptionListener().exceptionThrown( e ); } catch ( IOException ioe ) { getExceptionListener().exceptionThrown( ioe ); } } return handler; } }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * Under some circumstances a bean may be run on servers where a GUI * is not available. This interface can be used to query a bean to * determine whether it absolutely needs a gui, and to advise the * bean whether a GUI is available. * <p> * This interface is for expert developers, and is not needed * for normal simple beans. To avoid confusing end-users we * avoid using getXXX setXXX design patterns for these methods. */ public interface Visibility { /** {@collect.stats} * Determines whether this bean needs a GUI. * * @return True if the bean absolutely needs a GUI available in * order to get its work done. */ boolean needsGui(); /** {@collect.stats} * This method instructs the bean that it should not use the Gui. */ void dontUseGui(); /** {@collect.stats} * This method instructs the bean that it is OK to use the Gui. */ void okToUseGui(); /** {@collect.stats} * Determines whether this bean is avoiding using a GUI. * * @return true if the bean is currently avoiding use of the Gui. * e.g. due to a call on dontUseGui(). */ boolean avoidingGui(); }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * An <code>Expression</code> object represents a primitive expression * in which a single method is applied to a target and a set of * arguments to return a result - as in <code>"a.getFoo()"</code>. * <p> * In addition to the properties of the super class, the * <code>Expression</code> object provides a <em>value</em> which * is the object returned when this expression is evaluated. * The return value is typically not provided by the caller and * is instead computed by dynamically finding the method and invoking * it when the first call to <code>getValue</code> is made. * * @see #getValue * @see #setValue * * @since 1.4 * * @author Philip Milne */ public class Expression extends Statement { private static Object unbound = new Object(); private Object value = unbound; /** {@collect.stats} * Creates a new <code>Statement</code> object with a <code>target</code>, * <code>methodName</code> and <code>arguments</code> as per the parameters. * * @param target The target of this expression. * @param methodName The methodName of this expression. * @param arguments The arguments of this expression. If <code>null</code> then an empty array will be used. * * @see #getValue */ public Expression(Object target, String methodName, Object[] arguments) { super(target, methodName, arguments); } /** {@collect.stats} * Creates a new <code>Expression</code> object for a method * that returns a result. The result will never be calculated * however, since this constructor uses the <code>value</code> * parameter to set the value property by calling the * <code>setValue</code> method. * * @param value The value of this expression. * @param target The target of this expression. * @param methodName The methodName of this expression. * @param arguments The arguments of this expression. If <code>null</code> then an empty array will be used. * * @see #setValue */ public Expression(Object value, Object target, String methodName, Object[] arguments) { this(target, methodName, arguments); setValue(value); } /** {@collect.stats} * If the value property of this instance is not already set, * this method dynamically finds the method with the specified * methodName on this target with these arguments and calls it. * The result of the method invocation is first copied * into the value property of this expression and then returned * as the result of <code>getValue</code>. If the value property * was already set, either by a call to <code>setValue</code> * or a previous call to <code>getValue</code> then the value * property is returned without either looking up or calling the method. * <p> * The value property of an <code>Expression</code> is set to * a unique private (non-<code>null</code>) value by default and * this value is used as an internal indication that the method * has not yet been called. A return value of <code>null</code> * replaces this default value in the same way that any other value * would, ensuring that expressions are never evaluated more than once. * <p> * See the <code>excecute</code> method for details on how * methods are chosen using the dynamic types of the target * and arguments. * * @see Statement#execute * @see #setValue * * @return The result of applying this method to these arguments. */ public Object getValue() throws Exception { if (value == unbound) { setValue(invoke()); } return value; } /** {@collect.stats} * Sets the value of this expression to <code>value</code>. * This value will be returned by the getValue method * without calling the method associated with this * expression. * * @param value The value of this expression. * * @see #getValue */ public void setValue(Object value) { this.value = value; } /*pp*/ String instanceName(Object instance) { return instance == unbound ? "<unbound>" : super.instanceName(instance); } /** {@collect.stats} * Prints the value of this expression using a Java-style syntax. */ public String toString() { return instanceName(value) + "=" + super.toString(); } }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * A "PropertyChange" event gets delivered whenever a bean changes a "bound" * or "constrained" property. A PropertyChangeEvent object is sent as an * argument to the PropertyChangeListener and VetoableChangeListener methods. * <P> * Normally PropertyChangeEvents are accompanied by the name and the old * and new value of the changed property. If the new value is a primitive * type (such as int or boolean) it must be wrapped as the * corresponding java.lang.* Object type (such as Integer or Boolean). * <P> * Null values may be provided for the old and the new values if their * true values are not known. * <P> * An event source may send a null object as the name to indicate that an * arbitrary set of if its properties have changed. In this case the * old and new values should also be null. */ public class PropertyChangeEvent extends java.util.EventObject { /** {@collect.stats} * Constructs a new <code>PropertyChangeEvent</code>. * * @param source The bean that fired the event. * @param propertyName The programmatic name of the property * that was changed. * @param oldValue The old value of the property. * @param newValue The new value of the property. */ public PropertyChangeEvent(Object source, String propertyName, Object oldValue, Object newValue) { super(source); this.propertyName = propertyName; this.newValue = newValue; this.oldValue = oldValue; } /** {@collect.stats} * Gets the programmatic name of the property that was changed. * * @return The programmatic name of the property that was changed. * May be null if multiple properties have changed. */ public String getPropertyName() { return propertyName; } /** {@collect.stats} * Gets the new value for the property, expressed as an Object. * * @return The new value for the property, expressed as an Object. * May be null if multiple properties have changed. */ public Object getNewValue() { return newValue; } /** {@collect.stats} * Gets the old value for the property, expressed as an Object. * * @return The old value for the property, expressed as an Object. * May be null if multiple properties have changed. */ public Object getOldValue() { return oldValue; } /** {@collect.stats} * Sets the propagationId object for the event. * * @param propagationId The propagationId object for the event. */ public void setPropagationId(Object propagationId) { this.propagationId = propagationId; } /** {@collect.stats} * The "propagationId" field is reserved for future use. In Beans 1.0 * the sole requirement is that if a listener catches a PropertyChangeEvent * and then fires a PropertyChangeEvent of its own, then it should * make sure that it propagates the propagationId field from its * incoming event to its outgoing event. * * @return the propagationId object associated with a bound/constrained * property update. */ public Object getPropagationId() { return propagationId; } /** {@collect.stats} * name of the property that changed. May be null, if not known. * @serial */ private String propertyName; /** {@collect.stats} * New value for property. May be null if not known. * @serial */ private Object newValue; /** {@collect.stats} * Previous value for property. May be null if not known. * @serial */ private Object oldValue; /** {@collect.stats} * Propagation ID. May be null. * @serial * @see #getPropagationId */ private Object propagationId; }
Java
/* * Copyright (c) 1996, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * A bean implementor who wishes to provide explicit information about * their bean may provide a BeanInfo class that implements this BeanInfo * interface and provides explicit information about the methods, * properties, events, etc, of their bean. * <p> * A bean implementor doesn't need to provide a complete set of * explicit information. You can pick and choose which information * you want to provide and the rest will be obtained by automatic * analysis using low-level reflection of the bean classes' methods * and applying standard design patterns. * <p> * You get the opportunity to provide lots and lots of different * information as part of the various XyZDescriptor classes. But * don't panic, you only really need to provide the minimal core * information required by the various constructors. * <P> * See also the SimpleBeanInfo class which provides a convenient * "noop" base class for BeanInfo classes, which you can override * for those specific places where you want to return explicit info. * <P> * To learn about all the behaviour of a bean see the Introspector class. */ public interface BeanInfo { /** {@collect.stats} * Gets the beans <code>BeanDescriptor</code>. * * @return A BeanDescriptor providing overall information about * the bean, such as its displayName, its customizer, etc. May * return null if the information should be obtained by automatic * analysis. */ BeanDescriptor getBeanDescriptor(); /** {@collect.stats} * Gets the beans <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ EventSetDescriptor[] getEventSetDescriptors(); /** {@collect.stats} * A bean may have a "default" event that is the event that will * mostly commonly be used by humans when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ int getDefaultEventIndex(); /** {@collect.stats} * Gets the beans <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ PropertyDescriptor[] getPropertyDescriptors(); /** {@collect.stats} * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ int getDefaultPropertyIndex(); /** {@collect.stats} * Gets the beans <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the externally * visible methods supported by this bean. May return null if * the information should be obtained by automatic analysis. */ MethodDescriptor[] getMethodDescriptors(); /** {@collect.stats} * This method allows a BeanInfo object to return an arbitrary collection * of other BeanInfo objects that provide additional information on the * current bean. * <P> * If there are conflicts or overlaps between the information provided * by different BeanInfo objects, then the current BeanInfo takes precedence * over the getAdditionalBeanInfo objects, and later elements in the array * take precedence over earlier ones. * * @return an array of BeanInfo objects. May return null. */ BeanInfo[] getAdditionalBeanInfo(); /** {@collect.stats} * This method returns an image object that can be used to * represent the bean in toolboxes, toolbars, etc. Icon images * will typically be GIFs, but may in future include other formats. * <p> * Beans aren't required to provide icons and may return null from * this method. * <p> * There are four possible flavors of icons (16x16 color, * 32x32 color, 16x16 mono, 32x32 mono). If a bean choses to only * support a single icon we recommend supporting 16x16 color. * <p> * We recommend that icons have a "transparent" background * so they can be rendered onto an existing background. * * @param iconKind The kind of icon requested. This should be * one of the constant values ICON_COLOR_16x16, ICON_COLOR_32x32, * ICON_MONO_16x16, or ICON_MONO_32x32. * @return An image object representing the requested icon. May * return null if no suitable icon is available. */ java.awt.Image getIcon(int iconKind); /** {@collect.stats} * Constant to indicate a 16 x 16 color icon. */ final static int ICON_COLOR_16x16 = 1; /** {@collect.stats} * Constant to indicate a 32 x 32 color icon. */ final static int ICON_COLOR_32x32 = 2; /** {@collect.stats} * Constant to indicate a 16 x 16 monochrome icon. */ final static int ICON_MONO_16x16 = 3; /** {@collect.stats} * Constant to indicate a 32 x 32 monochrome icon. */ final static int ICON_MONO_32x32 = 4; }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * A PropertyVetoException is thrown when a proposed change to a * property represents an unacceptable value. */ public class PropertyVetoException extends Exception { /** {@collect.stats} * Constructs a <code>PropertyVetoException</code> with a * detailed message. * * @param mess Descriptive message * @param evt A PropertyChangeEvent describing the vetoed change. */ public PropertyVetoException(String mess, PropertyChangeEvent evt) { super(mess); this.evt = evt; } /** {@collect.stats} * Gets the vetoed <code>PropertyChangeEvent</code>. * * @return A PropertyChangeEvent describing the vetoed change. */ public PropertyChangeEvent getPropertyChangeEvent() { return evt; } /** {@collect.stats} * A PropertyChangeEvent describing the vetoed change. * @serial */ private PropertyChangeEvent evt; }
Java
/* * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; import static java.util.Locale.ENGLISH; /** {@collect.stats} * A utility class which generates unique names for object instances. * The name will be a concatenation of the unqualified class name * and an instance number. * <p> * For example, if the first object instance javax.swing.JButton * is passed into <code>instanceName</code> then the returned * string identifier will be &quot;JButton0&quot;. * * @author Philip Milne */ class NameGenerator { private Map valueToName; private Map nameToCount; public NameGenerator() { valueToName = new IdentityHashMap(); nameToCount = new HashMap(); } /** {@collect.stats} * Clears the name cache. Should be called to near the end of * the encoding cycle. */ public void clear() { valueToName.clear(); nameToCount.clear(); } /** {@collect.stats} * Returns the root name of the class. */ public static String unqualifiedClassName(Class type) { if (type.isArray()) { return unqualifiedClassName(type.getComponentType())+"Array"; } String name = type.getName(); return name.substring(name.lastIndexOf('.')+1); } /** {@collect.stats} * Returns a String which capitalizes the first letter of the string. */ public static String capitalize(String name) { if (name == null || name.length() == 0) { return name; } return name.substring(0, 1).toUpperCase(ENGLISH) + name.substring(1); } /** {@collect.stats} * Returns a unique string which identifies the object instance. * Invocations are cached so that if an object has been previously * passed into this method then the same identifier is returned. * * @param instance object used to generate string * @return a unique string representing the object */ public String instanceName(Object instance) { if (instance == null) { return "null"; } if (instance instanceof Class) { return unqualifiedClassName((Class)instance); } else { String result = (String)valueToName.get(instance); if (result != null) { return result; } Class type = instance.getClass(); String className = unqualifiedClassName(type); Object size = nameToCount.get(className); int instanceNumber = (size == null) ? 0 : ((Integer)size).intValue() + 1; nameToCount.put(className, new Integer(instanceNumber)); result = className + instanceNumber; valueToName.put(instance, result); return result; } } }
Java
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import com.sun.beans.TypeResolver; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.ref.SoftReference; import java.lang.reflect.Method; import java.lang.reflect.Type; /** {@collect.stats} * The FeatureDescriptor class is the common baseclass for PropertyDescriptor, * EventSetDescriptor, and MethodDescriptor, etc. * <p> * It supports some common information that can be set and retrieved for * any of the introspection descriptors. * <p> * In addition it provides an extension mechanism so that arbitrary * attribute/value pairs can be associated with a design feature. */ public class FeatureDescriptor { private Reference<Class> classRef; /** {@collect.stats} * Constructs a <code>FeatureDescriptor</code>. */ public FeatureDescriptor() { } /** {@collect.stats} * Gets the programmatic name of this feature. * * @return The programmatic name of the property/method/event */ public String getName() { return name; } /** {@collect.stats} * Sets the programmatic name of this feature. * * @param name The programmatic name of the property/method/event */ public void setName(String name) { this.name = name; } /** {@collect.stats} * Gets the localized display name of this feature. * * @return The localized display name for the property/method/event. * This defaults to the same as its programmatic name from getName. */ public String getDisplayName() { if (displayName == null) { return getName(); } return displayName; } /** {@collect.stats} * Sets the localized display name of this feature. * * @param displayName The localized display name for the * property/method/event. */ public void setDisplayName(String displayName) { this.displayName = displayName; } /** {@collect.stats} * The "expert" flag is used to distinguish between those features that are * intended for expert users from those that are intended for normal users. * * @return True if this feature is intended for use by experts only. */ public boolean isExpert() { return expert; } /** {@collect.stats} * The "expert" flag is used to distinguish between features that are * intended for expert users from those that are intended for normal users. * * @param expert True if this feature is intended for use by experts only. */ public void setExpert(boolean expert) { this.expert = expert; } /** {@collect.stats} * The "hidden" flag is used to identify features that are intended only * for tool use, and which should not be exposed to humans. * * @return True if this feature should be hidden from human users. */ public boolean isHidden() { return hidden; } /** {@collect.stats} * The "hidden" flag is used to identify features that are intended only * for tool use, and which should not be exposed to humans. * * @param hidden True if this feature should be hidden from human users. */ public void setHidden(boolean hidden) { this.hidden = hidden; } /** {@collect.stats} * The "preferred" flag is used to identify features that are particularly * important for presenting to humans. * * @return True if this feature should be preferentially shown to human users. */ public boolean isPreferred() { return preferred; } /** {@collect.stats} * The "preferred" flag is used to identify features that are particularly * important for presenting to humans. * * @param preferred True if this feature should be preferentially shown * to human users. */ public void setPreferred(boolean preferred) { this.preferred = preferred; } /** {@collect.stats} * Gets the short description of this feature. * * @return A localized short description associated with this * property/method/event. This defaults to be the display name. */ public String getShortDescription() { if (shortDescription == null) { return getDisplayName(); } return shortDescription; } /** {@collect.stats} * You can associate a short descriptive string with a feature. Normally * these descriptive strings should be less than about 40 characters. * @param text A (localized) short description to be associated with * this property/method/event. */ public void setShortDescription(String text) { shortDescription = text; } /** {@collect.stats} * Associate a named attribute with this feature. * * @param attributeName The locale-independent name of the attribute * @param value The value. */ public void setValue(String attributeName, Object value) { if (table == null) { table = new java.util.Hashtable(); } table.put(attributeName, value); } /** {@collect.stats} * Retrieve a named attribute with this feature. * * @param attributeName The locale-independent name of the attribute * @return The value of the attribute. May be null if * the attribute is unknown. */ public Object getValue(String attributeName) { if (table == null) { return null; } return table.get(attributeName); } /** {@collect.stats} * Gets an enumeration of the locale-independent names of this * feature. * * @return An enumeration of the locale-independent names of any * attributes that have been registered with setValue. */ public java.util.Enumeration<String> attributeNames() { if (table == null) { table = new java.util.Hashtable(); } return table.keys(); } /** {@collect.stats} * Package-private constructor, * Merge information from two FeatureDescriptors. * The merged hidden and expert flags are formed by or-ing the values. * In the event of other conflicts, the second argument (y) is * given priority over the first argument (x). * * @param x The first (lower priority) MethodDescriptor * @param y The second (higher priority) MethodDescriptor */ FeatureDescriptor(FeatureDescriptor x, FeatureDescriptor y) { expert = x.expert | y.expert; hidden = x.hidden | y.hidden; preferred = x.preferred | y.preferred; name = y.name; shortDescription = x.shortDescription; if (y.shortDescription != null) { shortDescription = y.shortDescription; } displayName = x.displayName; if (y.displayName != null) { displayName = y.displayName; } classRef = x.classRef; if (y.classRef != null) { classRef = y.classRef; } addTable(x.table); addTable(y.table); } /* * Package-private dup constructor * This must isolate the new object from any changes to the old object. */ FeatureDescriptor(FeatureDescriptor old) { expert = old.expert; hidden = old.hidden; preferred = old.preferred; name = old.name; shortDescription = old.shortDescription; displayName = old.displayName; classRef = old.classRef; addTable(old.table); } private void addTable(java.util.Hashtable t) { if (t == null) { return; } java.util.Enumeration keys = t.keys(); while (keys.hasMoreElements()) { String key = (String)keys.nextElement(); Object value = t.get(key); setValue(key, value); } } // Package private methods for recreating the weak/soft referent void setClass0(Class cls) { this.classRef = getWeakReference(cls); } Class getClass0() { return (this.classRef != null) ? this.classRef.get() : null; } /** {@collect.stats} * Create a Reference wrapper for the object. * * @param obj object that will be wrapped * @param soft true if a SoftReference should be created; otherwise Soft * @return a Reference or null if obj is null. */ static Reference createReference(Object obj, boolean soft) { Reference ref = null; if (obj != null) { if (soft) { ref = new SoftReference(obj); } else { ref = new WeakReference(obj); } } return ref; } // Convenience method which creates a WeakReference. static Reference createReference(Object obj) { return createReference(obj, false); } /** {@collect.stats} * Returns an object from a Reference wrapper. * * @return the Object in a wrapper or null. */ static Object getObject(Reference ref) { return (ref == null) ? null : (Object)ref.get(); } /** {@collect.stats} * Creates a new soft reference that refers to the given object. * * @return a new soft reference or <code>null</code> if object is <code>null</code> * * @see SoftReference */ static <T> Reference<T> getSoftReference(T object) { return (object != null) ? new SoftReference<T>(object) : null; } /** {@collect.stats} * Creates a new weak reference that refers to the given object. * * @return a new weak reference or <code>null</code> if object is <code>null</code> * * @see WeakReference */ static <T> Reference<T> getWeakReference(T object) { return (object != null) ? new WeakReference<T>(object) : null; } /** {@collect.stats} * Resolves the return type of the method. * * @param base the class that contains the method in the hierarchy * @param method the object that represents the method * @return a class identifying the return type of the method * * @see Method#getGenericReturnType * @see Method#getReturnType */ static Class getReturnType(Class base, Method method) { if (base == null) { base = method.getDeclaringClass(); } return TypeResolver.erase(TypeResolver.resolveInClass(base, method.getGenericReturnType())); } /** {@collect.stats} * Resolves the parameter types of the method. * * @param base the class that contains the method in the hierarchy * @param method the object that represents the method * @return an array of classes identifying the parameter types of the method * * @see Method#getGenericParameterTypes * @see Method#getParameterTypes */ static Class[] getParameterTypes(Class base, Method method) { if (base == null) { base = method.getDeclaringClass(); } return TypeResolver.erase(TypeResolver.resolveInClass(base, method.getGenericParameterTypes())); } private boolean expert; private boolean hidden; private boolean preferred; private String shortDescription; private String name; private String displayName; private java.util.Hashtable table; }
Java
/* * Copyright (c) 2000, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.awt.AWTKeyStroke; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Color; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.font.TextAttribute; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.sql.Timestamp; import java.util.*; import javax.swing.Box; import javax.swing.JLayeredPane; import javax.swing.border.MatteBorder; import javax.swing.plaf.ColorUIResource; import sun.swing.PrintColorUIResource; /* * Like the <code>Intropector</code>, the <code>MetaData</code> class * contains <em>meta</em> objects that describe the way * classes should express their state in terms of their * own public APIs. * * @see java.beans.Intropector * * @author Philip Milne * @author Steve Langley */ class NullPersistenceDelegate extends PersistenceDelegate { // Note this will be called by all classes when they reach the // top of their superclass chain. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { } protected Expression instantiate(Object oldInstance, Encoder out) { return null; } public void writeObject(Object oldInstance, Encoder out) { // System.out.println("NullPersistenceDelegate:writeObject " + oldInstance); } } /** {@collect.stats} * The persistence delegate for <CODE>enum</CODE> classes. * * @author Sergey A. Malenkov */ class EnumPersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return oldInstance == newInstance; } protected Expression instantiate(Object oldInstance, Encoder out) { Enum e = (Enum) oldInstance; return new Expression(e, Enum.class, "valueOf", new Object[]{e.getClass(), e.name()}); } } class PrimitivePersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return oldInstance.equals(newInstance); } protected Expression instantiate(Object oldInstance, Encoder out) { return new Expression(oldInstance, oldInstance.getClass(), "new", new Object[]{oldInstance.toString()}); } } class ArrayPersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return (newInstance != null && oldInstance.getClass() == newInstance.getClass() && // Also ensures the subtype is correct. Array.getLength(oldInstance) == Array.getLength(newInstance)); } protected Expression instantiate(Object oldInstance, Encoder out) { // System.out.println("instantiate: " + type + " " + oldInstance); Class oldClass = oldInstance.getClass(); return new Expression(oldInstance, Array.class, "newInstance", new Object[]{oldClass.getComponentType(), new Integer(Array.getLength(oldInstance))}); } protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { int n = Array.getLength(oldInstance); for (int i = 0; i < n; i++) { Object index = new Integer(i); // Expression oldGetExp = new Expression(Array.class, "get", new Object[]{oldInstance, index}); // Expression newGetExp = new Expression(Array.class, "get", new Object[]{newInstance, index}); Expression oldGetExp = new Expression(oldInstance, "get", new Object[]{index}); Expression newGetExp = new Expression(newInstance, "get", new Object[]{index}); try { Object oldValue = oldGetExp.getValue(); Object newValue = newGetExp.getValue(); out.writeExpression(oldGetExp); if (!MetaData.equals(newValue, out.get(oldValue))) { // System.out.println("Not equal: " + newGetExp + " != " + actualGetExp); // invokeStatement(Array.class, "set", new Object[]{oldInstance, index, oldValue}, out); DefaultPersistenceDelegate.invokeStatement(oldInstance, "set", new Object[]{index, oldValue}, out); } } catch (Exception e) { // System.err.println("Warning:: failed to write: " + oldGetExp); out.getExceptionListener().exceptionThrown(e); } } } } class ProxyPersistenceDelegate extends PersistenceDelegate { protected Expression instantiate(Object oldInstance, Encoder out) { Class type = oldInstance.getClass(); java.lang.reflect.Proxy p = (java.lang.reflect.Proxy)oldInstance; // This unappealing hack is not required but makes the // representation of EventHandlers much more concise. java.lang.reflect.InvocationHandler ih = java.lang.reflect.Proxy.getInvocationHandler(p); if (ih instanceof EventHandler) { EventHandler eh = (EventHandler)ih; Vector args = new Vector(); args.add(type.getInterfaces()[0]); args.add(eh.getTarget()); args.add(eh.getAction()); if (eh.getEventPropertyName() != null) { args.add(eh.getEventPropertyName()); } if (eh.getListenerMethodName() != null) { args.setSize(4); args.add(eh.getListenerMethodName()); } return new Expression(oldInstance, EventHandler.class, "create", args.toArray()); } return new Expression(oldInstance, java.lang.reflect.Proxy.class, "newProxyInstance", new Object[]{type.getClassLoader(), type.getInterfaces(), ih}); } } // Strings class java_lang_String_PersistenceDelegate extends PersistenceDelegate { protected Expression instantiate(Object oldInstance, Encoder out) { return null; } public void writeObject(Object oldInstance, Encoder out) { // System.out.println("NullPersistenceDelegate:writeObject " + oldInstance); } } // Classes class java_lang_Class_PersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return oldInstance.equals(newInstance); } protected Expression instantiate(Object oldInstance, Encoder out) { Class c = (Class)oldInstance; // As of 1.3 it is not possible to call Class.forName("int"), // so we have to generate different code for primitive types. // This is needed for arrays whose subtype may be primitive. if (c.isPrimitive()) { Field field = null; try { field = ReflectionUtils.typeToClass(c).getDeclaredField("TYPE"); } catch (NoSuchFieldException ex) { System.err.println("Unknown primitive type: " + c); } return new Expression(oldInstance, field, "get", new Object[]{null}); } else if (oldInstance == String.class) { return new Expression(oldInstance, "", "getClass", new Object[]{}); } else if (oldInstance == Class.class) { return new Expression(oldInstance, String.class, "getClass", new Object[]{}); } else { return new Expression(oldInstance, Class.class, "forName", new Object[]{c.getName()}); } } } // Fields class java_lang_reflect_Field_PersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return oldInstance.equals(newInstance); } protected Expression instantiate(Object oldInstance, Encoder out) { Field f = (Field)oldInstance; return new Expression(oldInstance, f.getDeclaringClass(), "getField", new Object[]{f.getName()}); } } // Methods class java_lang_reflect_Method_PersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return oldInstance.equals(newInstance); } protected Expression instantiate(Object oldInstance, Encoder out) { Method m = (Method)oldInstance; return new Expression(oldInstance, m.getDeclaringClass(), "getMethod", new Object[]{m.getName(), m.getParameterTypes()}); } } // Dates /** {@collect.stats} * The persistence delegate for <CODE>java.util.Date</CODE> classes. * Do not extend DefaultPersistenceDelegate to improve performance and * to avoid problems with <CODE>java.sql.Date</CODE>, * <CODE>java.sql.Time</CODE> and <CODE>java.sql.Timestamp</CODE>. * * @author Sergey A. Malenkov */ class java_util_Date_PersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { if (!super.mutatesTo(oldInstance, newInstance)) { return false; } Date oldDate = (Date)oldInstance; Date newDate = (Date)newInstance; return oldDate.getTime() == newDate.getTime(); } protected Expression instantiate(Object oldInstance, Encoder out) { Date date = (Date)oldInstance; return new Expression(date, date.getClass(), "new", new Object[] {date.getTime()}); } } /** {@collect.stats} * The persistence delegate for <CODE>java.sql.Timestamp</CODE> classes. * It supports nanoseconds. * * @author Sergey A. Malenkov */ final class java_sql_Timestamp_PersistenceDelegate extends java_util_Date_PersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { Timestamp oldTime = (Timestamp)oldInstance; Timestamp newTime = (Timestamp)newInstance; int nanos = oldTime.getNanos(); if (nanos != newTime.getNanos()) { out.writeStatement(new Statement(oldTime, "setNanos", new Object[] {nanos})); } } } // Collections /* The Hashtable and AbstractMap classes have no common ancestor yet may be handled with a single persistence delegate: one which uses the methods of the Map insterface exclusively. Attatching the persistence delegates to the interfaces themselves is fraught however since, in the case of the Map, both the AbstractMap and HashMap classes are declared to implement the Map interface, leaving the obvious implementation prone to repeating their initialization. These issues and questions around the ordering of delegates attached to interfaces have lead us to ignore any delegates attached to interfaces and force all persistence delegates to be registered with concrete classes. */ /** {@collect.stats} * The base class for persistence delegates for inner classes * that can be created using {@link Collections}. * * @author Sergey A. Malenkov */ abstract class java_util_Collections extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { if (!super.mutatesTo(oldInstance, newInstance)) { return false; } if ((oldInstance instanceof List) || (oldInstance instanceof Set) || (oldInstance instanceof Map)) { return oldInstance.equals(newInstance); } Collection oldC = (Collection) oldInstance; Collection newC = (Collection) newInstance; return (oldC.size() == newC.size()) && oldC.containsAll(newC); } static final class EmptyList_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { return new Expression(oldInstance, Collections.class, "emptyList", null); } } static final class EmptySet_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { return new Expression(oldInstance, Collections.class, "emptySet", null); } } static final class EmptyMap_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { return new Expression(oldInstance, Collections.class, "emptyMap", null); } } static final class SingletonList_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { List list = (List) oldInstance; return new Expression(oldInstance, Collections.class, "singletonList", new Object[]{list.get(0)}); } } static final class SingletonSet_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { Set set = (Set) oldInstance; return new Expression(oldInstance, Collections.class, "singleton", new Object[]{set.iterator().next()}); } } static final class SingletonMap_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { Map map = (Map) oldInstance; Object key = map.keySet().iterator().next(); return new Expression(oldInstance, Collections.class, "singletonMap", new Object[]{key, map.get(key)}); } } static final class UnmodifiableCollection_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { List list = new ArrayList((Collection) oldInstance); return new Expression(oldInstance, Collections.class, "unmodifiableCollection", new Object[]{list}); } } static final class UnmodifiableList_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { List list = new LinkedList((Collection) oldInstance); return new Expression(oldInstance, Collections.class, "unmodifiableList", new Object[]{list}); } } static final class UnmodifiableRandomAccessList_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { List list = new ArrayList((Collection) oldInstance); return new Expression(oldInstance, Collections.class, "unmodifiableList", new Object[]{list}); } } static final class UnmodifiableSet_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { Set set = new HashSet((Set) oldInstance); return new Expression(oldInstance, Collections.class, "unmodifiableSet", new Object[]{set}); } } static final class UnmodifiableSortedSet_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { SortedSet set = new TreeSet((SortedSet) oldInstance); return new Expression(oldInstance, Collections.class, "unmodifiableSortedSet", new Object[]{set}); } } static final class UnmodifiableMap_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { Map map = new HashMap((Map) oldInstance); return new Expression(oldInstance, Collections.class, "unmodifiableMap", new Object[]{map}); } } static final class UnmodifiableSortedMap_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { SortedMap map = new TreeMap((SortedMap) oldInstance); return new Expression(oldInstance, Collections.class, "unmodifiableSortedMap", new Object[]{map}); } } static final class SynchronizedCollection_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { List list = new ArrayList((Collection) oldInstance); return new Expression(oldInstance, Collections.class, "synchronizedCollection", new Object[]{list}); } } static final class SynchronizedList_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { List list = new LinkedList((Collection) oldInstance); return new Expression(oldInstance, Collections.class, "synchronizedList", new Object[]{list}); } } static final class SynchronizedRandomAccessList_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { List list = new ArrayList((Collection) oldInstance); return new Expression(oldInstance, Collections.class, "synchronizedList", new Object[]{list}); } } static final class SynchronizedSet_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { Set set = new HashSet((Set) oldInstance); return new Expression(oldInstance, Collections.class, "synchronizedSet", new Object[]{set}); } } static final class SynchronizedSortedSet_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { SortedSet set = new TreeSet((SortedSet) oldInstance); return new Expression(oldInstance, Collections.class, "synchronizedSortedSet", new Object[]{set}); } } static final class SynchronizedMap_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { Map map = new HashMap((Map) oldInstance); return new Expression(oldInstance, Collections.class, "synchronizedMap", new Object[]{map}); } } static final class SynchronizedSortedMap_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { SortedMap map = new TreeMap((SortedMap) oldInstance); return new Expression(oldInstance, Collections.class, "synchronizedSortedMap", new Object[]{map}); } } static final class CheckedCollection_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { Object type = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedCollection.type"); List list = new ArrayList((Collection) oldInstance); return new Expression(oldInstance, Collections.class, "checkedCollection", new Object[]{list, type}); } } static final class CheckedList_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { Object type = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedCollection.type"); List list = new LinkedList((Collection) oldInstance); return new Expression(oldInstance, Collections.class, "checkedList", new Object[]{list, type}); } } static final class CheckedRandomAccessList_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { Object type = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedCollection.type"); List list = new ArrayList((Collection) oldInstance); return new Expression(oldInstance, Collections.class, "checkedList", new Object[]{list, type}); } } static final class CheckedSet_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { Object type = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedCollection.type"); Set set = new HashSet((Set) oldInstance); return new Expression(oldInstance, Collections.class, "checkedSet", new Object[]{set, type}); } } static final class CheckedSortedSet_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { Object type = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedCollection.type"); SortedSet set = new TreeSet((SortedSet) oldInstance); return new Expression(oldInstance, Collections.class, "checkedSortedSet", new Object[]{set, type}); } } static final class CheckedMap_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { Object keyType = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedMap.keyType"); Object valueType = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedMap.valueType"); Map map = new HashMap((Map) oldInstance); return new Expression(oldInstance, Collections.class, "checkedMap", new Object[]{map, keyType, valueType}); } } static final class CheckedSortedMap_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { Object keyType = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedMap.keyType"); Object valueType = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedMap.valueType"); SortedMap map = new TreeMap((SortedMap) oldInstance); return new Expression(oldInstance, Collections.class, "checkedSortedMap", new Object[]{map, keyType, valueType}); } } } /** {@collect.stats} * The persistence delegate for <CODE>java.util.EnumMap</CODE> classes. * * @author Sergey A. Malenkov */ class java_util_EnumMap_PersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return super.mutatesTo(oldInstance, newInstance) && (getType(oldInstance) == getType(newInstance)); } protected Expression instantiate(Object oldInstance, Encoder out) { return new Expression(oldInstance, EnumMap.class, "new", new Object[] {getType(oldInstance)}); } private static Object getType(Object instance) { return MetaData.getPrivateFieldValue(instance, "java.util.EnumMap.keyType"); } } /** {@collect.stats} * The persistence delegate for <CODE>java.util.EnumSet</CODE> classes. * * @author Sergey A. Malenkov */ class java_util_EnumSet_PersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return super.mutatesTo(oldInstance, newInstance) && (getType(oldInstance) == getType(newInstance)); } protected Expression instantiate(Object oldInstance, Encoder out) { return new Expression(oldInstance, EnumSet.class, "noneOf", new Object[] {getType(oldInstance)}); } private static Object getType(Object instance) { return MetaData.getPrivateFieldValue(instance, "java.util.EnumSet.elementType"); } } // Collection class java_util_Collection_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { java.util.Collection oldO = (java.util.Collection)oldInstance; java.util.Collection newO = (java.util.Collection)newInstance; if (newO.size() != 0) { invokeStatement(oldInstance, "clear", new Object[]{}, out); } for (Iterator i = oldO.iterator(); i.hasNext();) { invokeStatement(oldInstance, "add", new Object[]{i.next()}, out); } } } // List class java_util_List_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { java.util.List oldO = (java.util.List)oldInstance; java.util.List newO = (java.util.List)newInstance; int oldSize = oldO.size(); int newSize = (newO == null) ? 0 : newO.size(); if (oldSize < newSize) { invokeStatement(oldInstance, "clear", new Object[]{}, out); newSize = 0; } for (int i = 0; i < newSize; i++) { Object index = new Integer(i); Expression oldGetExp = new Expression(oldInstance, "get", new Object[]{index}); Expression newGetExp = new Expression(newInstance, "get", new Object[]{index}); try { Object oldValue = oldGetExp.getValue(); Object newValue = newGetExp.getValue(); out.writeExpression(oldGetExp); if (!MetaData.equals(newValue, out.get(oldValue))) { invokeStatement(oldInstance, "set", new Object[]{index, oldValue}, out); } } catch (Exception e) { out.getExceptionListener().exceptionThrown(e); } } for (int i = newSize; i < oldSize; i++) { invokeStatement(oldInstance, "add", new Object[]{oldO.get(i)}, out); } } } // Map class java_util_Map_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { // System.out.println("Initializing: " + newInstance); java.util.Map oldMap = (java.util.Map)oldInstance; java.util.Map newMap = (java.util.Map)newInstance; // Remove the new elements. // Do this first otherwise we undo the adding work. if (newMap != null) { for ( Object newKey : newMap.keySet() ) { // PENDING: This "key" is not in the right environment. if (!oldMap.containsKey(newKey)) { invokeStatement(oldInstance, "remove", new Object[]{newKey}, out); } } } // Add the new elements. for ( Object oldKey : oldMap.keySet() ) { Expression oldGetExp = new Expression(oldInstance, "get", new Object[]{oldKey}); // Pending: should use newKey. Expression newGetExp = new Expression(newInstance, "get", new Object[]{oldKey}); try { Object oldValue = oldGetExp.getValue(); Object newValue = newGetExp.getValue(); out.writeExpression(oldGetExp); if (!MetaData.equals(newValue, out.get(oldValue))) { invokeStatement(oldInstance, "put", new Object[]{oldKey, oldValue}, out); } else if ((newValue == null) && !newMap.containsKey(oldKey)) { // put oldValue(=null?) if oldKey is absent in newMap invokeStatement(oldInstance, "put", new Object[]{oldKey, oldValue}, out); } } catch (Exception e) { out.getExceptionListener().exceptionThrown(e); } } } } class java_util_AbstractCollection_PersistenceDelegate extends java_util_Collection_PersistenceDelegate {} class java_util_AbstractList_PersistenceDelegate extends java_util_List_PersistenceDelegate {} class java_util_AbstractMap_PersistenceDelegate extends java_util_Map_PersistenceDelegate {} class java_util_Hashtable_PersistenceDelegate extends java_util_Map_PersistenceDelegate {} // Beans class java_beans_beancontext_BeanContextSupport_PersistenceDelegate extends java_util_Collection_PersistenceDelegate {} // AWT /** {@collect.stats} * The persistence delegate for {@link Dimension}. * It is impossible to use {@link DefaultPersistenceDelegate} * because all getters have return types that differ from parameter types * of the constructor {@link Dimension#Dimension(int, int)}. * * @author Sergey A. Malenkov */ final class java_awt_Dimension_PersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return oldInstance.equals(newInstance); } protected Expression instantiate(Object oldInstance, Encoder out) { Dimension dimension = (Dimension) oldInstance; Object[] args = new Object[] { dimension.width, dimension.height, }; return new Expression(dimension, dimension.getClass(), "new", args); } } /** {@collect.stats} * The persistence delegate for {@link GridBagConstraints}. * It is impossible to use {@link DefaultPersistenceDelegate} * because this class does not have any properties. * * @author Sergey A. Malenkov */ final class java_awt_GridBagConstraints_PersistenceDelegate extends PersistenceDelegate { protected Expression instantiate(Object oldInstance, Encoder out) { GridBagConstraints gbc = (GridBagConstraints) oldInstance; Object[] args = new Object[] { gbc.gridx, gbc.gridy, gbc.gridwidth, gbc.gridheight, gbc.weightx, gbc.weighty, gbc.anchor, gbc.fill, gbc.insets, gbc.ipadx, gbc.ipady, }; return new Expression(gbc, gbc.getClass(), "new", args); } } /** {@collect.stats} * The persistence delegate for {@link Insets}. * It is impossible to use {@link DefaultPersistenceDelegate} * because this class does not have any properties. * * @author Sergey A. Malenkov */ final class java_awt_Insets_PersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return oldInstance.equals(newInstance); } protected Expression instantiate(Object oldInstance, Encoder out) { Insets insets = (Insets) oldInstance; Object[] args = new Object[] { insets.top, insets.left, insets.bottom, insets.right, }; return new Expression(insets, insets.getClass(), "new", args); } } /** {@collect.stats} * The persistence delegate for {@link Point}. * It is impossible to use {@link DefaultPersistenceDelegate} * because all getters have return types that differ from parameter types * of the constructor {@link Point#Point(int, int)}. * * @author Sergey A. Malenkov */ final class java_awt_Point_PersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return oldInstance.equals(newInstance); } protected Expression instantiate(Object oldInstance, Encoder out) { Point point = (Point) oldInstance; Object[] args = new Object[] { point.x, point.y, }; return new Expression(point, point.getClass(), "new", args); } } /** {@collect.stats} * The persistence delegate for {@link Rectangle}. * It is impossible to use {@link DefaultPersistenceDelegate} * because all getters have return types that differ from parameter types * of the constructor {@link Rectangle#Rectangle(int, int, int, int)}. * * @author Sergey A. Malenkov */ final class java_awt_Rectangle_PersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return oldInstance.equals(newInstance); } protected Expression instantiate(Object oldInstance, Encoder out) { Rectangle rectangle = (Rectangle) oldInstance; Object[] args = new Object[] { rectangle.x, rectangle.y, rectangle.width, rectangle.height, }; return new Expression(rectangle, rectangle.getClass(), "new", args); } } /** {@collect.stats} * The persistence delegate for {@link Font}. * It is impossible to use {@link DefaultPersistenceDelegate} * because size of the font can be float value. * * @author Sergey A. Malenkov */ final class java_awt_Font_PersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return oldInstance.equals(newInstance); } protected Expression instantiate(Object oldInstance, Encoder out) { Font font = (Font) oldInstance; int count = 0; String family = null; int style = Font.PLAIN; int size = 12; Map basic = font.getAttributes(); Map clone = new HashMap(basic.size()); for (Object key : basic.keySet()) { Object value = basic.get(key); if (value != null) { clone.put(key, value); } if (key == TextAttribute.FAMILY) { if (value instanceof String) { count++; family = (String) value; } } else if (key == TextAttribute.WEIGHT) { if (TextAttribute.WEIGHT_REGULAR.equals(value)) { count++; } else if (TextAttribute.WEIGHT_BOLD.equals(value)) { count++; style |= Font.BOLD; } } else if (key == TextAttribute.POSTURE) { if (TextAttribute.POSTURE_REGULAR.equals(value)) { count++; } else if (TextAttribute.POSTURE_OBLIQUE.equals(value)) { count++; style |= Font.ITALIC; } } else if (key == TextAttribute.SIZE) { if (value instanceof Number) { Number number = (Number) value; size = number.intValue(); if (size == number.floatValue()) { count++; } } } } Class type = font.getClass(); if (count == clone.size()) { return new Expression(font, type, "new", new Object[]{family, style, size}); } if (type == Font.class) { return new Expression(font, type, "getFont", new Object[]{clone}); } return new Expression(font, type, "new", new Object[]{Font.getFont(clone)}); } } /** {@collect.stats} * The persistence delegate for {@link AWTKeyStroke}. * It is impossible to use {@link DefaultPersistenceDelegate} * because this class have no public constructor. * * @author Sergey A. Malenkov */ final class java_awt_AWTKeyStroke_PersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return oldInstance.equals(newInstance); } protected Expression instantiate(Object oldInstance, Encoder out) { AWTKeyStroke key = (AWTKeyStroke) oldInstance; char ch = key.getKeyChar(); int code = key.getKeyCode(); int mask = key.getModifiers(); boolean onKeyRelease = key.isOnKeyRelease(); Object[] args = null; if (ch == KeyEvent.CHAR_UNDEFINED) { args = !onKeyRelease ? new Object[]{code, mask} : new Object[]{code, mask, onKeyRelease}; } else if (code == KeyEvent.VK_UNDEFINED) { if (!onKeyRelease) { args = (mask == 0) ? new Object[]{ch} : new Object[]{ch, mask}; } else if (mask == 0) { args = new Object[]{ch, onKeyRelease}; } } if (args == null) { throw new IllegalStateException("Unsupported KeyStroke: " + key); } Class type = key.getClass(); String name = type.getName(); // get short name of the class int index = name.lastIndexOf('.') + 1; if (index > 0) { name = name.substring(index); } return new Expression( key, type, "get" + name, args ); } } class StaticFieldsPersistenceDelegate extends PersistenceDelegate { protected void installFields(Encoder out, Class<?> cls) { Field fields[] = cls.getFields(); for(int i = 0; i < fields.length; i++) { Field field = fields[i]; // Don't install primitives, their identity will not be preserved // by wrapping. if (Object.class.isAssignableFrom(field.getType())) { out.writeExpression(new Expression(field, "get", new Object[]{null})); } } } protected Expression instantiate(Object oldInstance, Encoder out) { throw new RuntimeException("Unrecognized instance: " + oldInstance); } public void writeObject(Object oldInstance, Encoder out) { if (out.getAttribute(this) == null) { out.setAttribute(this, Boolean.TRUE); installFields(out, oldInstance.getClass()); } super.writeObject(oldInstance, out); } } // SystemColor class java_awt_SystemColor_PersistenceDelegate extends StaticFieldsPersistenceDelegate {} // TextAttribute class java_awt_font_TextAttribute_PersistenceDelegate extends StaticFieldsPersistenceDelegate {} // MenuShortcut class java_awt_MenuShortcut_PersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return oldInstance.equals(newInstance); } protected Expression instantiate(Object oldInstance, Encoder out) { java.awt.MenuShortcut m = (java.awt.MenuShortcut)oldInstance; return new Expression(oldInstance, m.getClass(), "new", new Object[]{new Integer(m.getKey()), Boolean.valueOf(m.usesShiftModifier())}); } } // Component class java_awt_Component_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); java.awt.Component c = (java.awt.Component)oldInstance; java.awt.Component c2 = (java.awt.Component)newInstance; // The "background", "foreground" and "font" properties. // The foreground and font properties of Windows change from // null to defined values after the Windows are made visible - // special case them for now. if (!(oldInstance instanceof java.awt.Window)) { String[] fieldNames = new String[]{"background", "foreground", "font"}; for(int i = 0; i < fieldNames.length; i++) { String name = fieldNames[i]; Object oldValue = ReflectionUtils.getPrivateField(oldInstance, java.awt.Component.class, name, out.getExceptionListener()); Object newValue = (newInstance == null) ? null : ReflectionUtils.getPrivateField(newInstance, java.awt.Component.class, name, out.getExceptionListener()); if (oldValue != null && !oldValue.equals(newValue)) { invokeStatement(oldInstance, "set" + NameGenerator.capitalize(name), new Object[]{oldValue}, out); } } } // Bounds java.awt.Container p = c.getParent(); if (p == null || p.getLayout() == null) { // Use the most concise construct. boolean locationCorrect = c.getLocation().equals(c2.getLocation()); boolean sizeCorrect = c.getSize().equals(c2.getSize()); if (!locationCorrect && !sizeCorrect) { invokeStatement(oldInstance, "setBounds", new Object[]{c.getBounds()}, out); } else if (!locationCorrect) { invokeStatement(oldInstance, "setLocation", new Object[]{c.getLocation()}, out); } else if (!sizeCorrect) { invokeStatement(oldInstance, "setSize", new Object[]{c.getSize()}, out); } } } } // Container class java_awt_Container_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); // Ignore the children of a JScrollPane. // Pending(milne) find a better way to do this. if (oldInstance instanceof javax.swing.JScrollPane) { return; } java.awt.Container oldC = (java.awt.Container)oldInstance; java.awt.Component[] oldChildren = oldC.getComponents(); java.awt.Container newC = (java.awt.Container)newInstance; java.awt.Component[] newChildren = (newC == null) ? new java.awt.Component[0] : newC.getComponents(); BorderLayout layout = ( oldC.getLayout() instanceof BorderLayout ) ? ( BorderLayout )oldC.getLayout() : null; JLayeredPane oldLayeredPane = (oldInstance instanceof JLayeredPane) ? (JLayeredPane) oldInstance : null; // Pending. Assume all the new children are unaltered. for(int i = newChildren.length; i < oldChildren.length; i++) { Object[] args = ( layout != null ) ? new Object[] {oldChildren[i], layout.getConstraints( oldChildren[i] )} : (oldLayeredPane != null) ? new Object[] {oldChildren[i], oldLayeredPane.getLayer(oldChildren[i]), Integer.valueOf(-1)} : new Object[] {oldChildren[i]}; invokeStatement(oldInstance, "add", args, out); } } } // Choice class java_awt_Choice_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); java.awt.Choice m = (java.awt.Choice)oldInstance; java.awt.Choice n = (java.awt.Choice)newInstance; for (int i = n.getItemCount(); i < m.getItemCount(); i++) { invokeStatement(oldInstance, "add", new Object[]{m.getItem(i)}, out); } } } // Menu class java_awt_Menu_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); java.awt.Menu m = (java.awt.Menu)oldInstance; java.awt.Menu n = (java.awt.Menu)newInstance; for (int i = n.getItemCount(); i < m.getItemCount(); i++) { invokeStatement(oldInstance, "add", new Object[]{m.getItem(i)}, out); } } } // MenuBar class java_awt_MenuBar_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); java.awt.MenuBar m = (java.awt.MenuBar)oldInstance; java.awt.MenuBar n = (java.awt.MenuBar)newInstance; for (int i = n.getMenuCount(); i < m.getMenuCount(); i++) { invokeStatement(oldInstance, "add", new Object[]{m.getMenu(i)}, out); } } } // List class java_awt_List_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); java.awt.List m = (java.awt.List)oldInstance; java.awt.List n = (java.awt.List)newInstance; for (int i = n.getItemCount(); i < m.getItemCount(); i++) { invokeStatement(oldInstance, "add", new Object[]{m.getItem(i)}, out); } } } // LayoutManagers // BorderLayout class java_awt_BorderLayout_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); String[] locations = {"north", "south", "east", "west", "center"}; String[] names = {java.awt.BorderLayout.NORTH, java.awt.BorderLayout.SOUTH, java.awt.BorderLayout.EAST, java.awt.BorderLayout.WEST, java.awt.BorderLayout.CENTER}; for(int i = 0; i < locations.length; i++) { Object oldC = ReflectionUtils.getPrivateField(oldInstance, java.awt.BorderLayout.class, locations[i], out.getExceptionListener()); Object newC = ReflectionUtils.getPrivateField(newInstance, java.awt.BorderLayout.class, locations[i], out.getExceptionListener()); // Pending, assume any existing elements are OK. if (oldC != null && newC == null) { invokeStatement(oldInstance, "addLayoutComponent", new Object[]{oldC, names[i]}, out); } } } } // CardLayout class java_awt_CardLayout_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); Hashtable tab = (Hashtable)ReflectionUtils.getPrivateField(oldInstance, java.awt.CardLayout.class, "tab", out.getExceptionListener()); if (tab != null) { for(Enumeration e = tab.keys(); e.hasMoreElements();) { Object child = e.nextElement(); invokeStatement(oldInstance, "addLayoutComponent", new Object[]{child, (String)tab.get(child)}, out); } } } } // GridBagLayout class java_awt_GridBagLayout_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); Hashtable comptable = (Hashtable)ReflectionUtils.getPrivateField(oldInstance, java.awt.GridBagLayout.class, "comptable", out.getExceptionListener()); if (comptable != null) { for(Enumeration e = comptable.keys(); e.hasMoreElements();) { Object child = e.nextElement(); invokeStatement(oldInstance, "addLayoutComponent", new Object[]{child, comptable.get(child)}, out); } } } } // Swing // JFrame (If we do this for Window instead of JFrame, the setVisible call // will be issued before we have added all the children to the JFrame and // will appear blank). class javax_swing_JFrame_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); java.awt.Window oldC = (java.awt.Window)oldInstance; java.awt.Window newC = (java.awt.Window)newInstance; boolean oldV = oldC.isVisible(); boolean newV = newC.isVisible(); if (newV != oldV) { // false means: don't execute this statement at write time. boolean executeStatements = out.executeStatements; out.executeStatements = false; invokeStatement(oldInstance, "setVisible", new Object[]{Boolean.valueOf(oldV)}, out); out.executeStatements = executeStatements; } } } // Models // DefaultListModel class javax_swing_DefaultListModel_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { // Note, the "size" property will be set here. super.initialize(type, oldInstance, newInstance, out); javax.swing.DefaultListModel m = (javax.swing.DefaultListModel)oldInstance; javax.swing.DefaultListModel n = (javax.swing.DefaultListModel)newInstance; for (int i = n.getSize(); i < m.getSize(); i++) { invokeStatement(oldInstance, "add", // Can also use "addElement". new Object[]{m.getElementAt(i)}, out); } } } // DefaultComboBoxModel class javax_swing_DefaultComboBoxModel_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); javax.swing.DefaultComboBoxModel m = (javax.swing.DefaultComboBoxModel)oldInstance; for (int i = 0; i < m.getSize(); i++) { invokeStatement(oldInstance, "addElement", new Object[]{m.getElementAt(i)}, out); } } } // DefaultMutableTreeNode class javax_swing_tree_DefaultMutableTreeNode_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); javax.swing.tree.DefaultMutableTreeNode m = (javax.swing.tree.DefaultMutableTreeNode)oldInstance; javax.swing.tree.DefaultMutableTreeNode n = (javax.swing.tree.DefaultMutableTreeNode)newInstance; for (int i = n.getChildCount(); i < m.getChildCount(); i++) { invokeStatement(oldInstance, "add", new Object[]{m.getChildAt(i)}, out); } } } // ToolTipManager class javax_swing_ToolTipManager_PersistenceDelegate extends PersistenceDelegate { protected Expression instantiate(Object oldInstance, Encoder out) { return new Expression(oldInstance, javax.swing.ToolTipManager.class, "sharedInstance", new Object[]{}); } } // JTabbedPane class javax_swing_JTabbedPane_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); javax.swing.JTabbedPane p = (javax.swing.JTabbedPane)oldInstance; for (int i = 0; i < p.getTabCount(); i++) { invokeStatement(oldInstance, "addTab", new Object[]{ p.getTitleAt(i), p.getIconAt(i), p.getComponentAt(i)}, out); } } } // Box class javax_swing_Box_PersistenceDelegate extends DefaultPersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return super.mutatesTo(oldInstance, newInstance) && getAxis(oldInstance).equals(getAxis(newInstance)); } protected Expression instantiate(Object oldInstance, Encoder out) { return new Expression(oldInstance, oldInstance.getClass(), "new", new Object[] {getAxis(oldInstance)}); } private Integer getAxis(Object object) { Box box = (Box) object; return (Integer) MetaData.getPrivateFieldValue(box.getLayout(), "javax.swing.BoxLayout.axis"); } } // JMenu // Note that we do not need to state the initialiser for // JMenuItems since the getComponents() method defined in // Container will return all of the sub menu items that // need to be added to the menu item. // Not so for JMenu apparently. class javax_swing_JMenu_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); javax.swing.JMenu m = (javax.swing.JMenu)oldInstance; java.awt.Component[] c = m.getMenuComponents(); for (int i = 0; i < c.length; i++) { invokeStatement(oldInstance, "add", new Object[]{c[i]}, out); } } } /** {@collect.stats} * The persistence delegate for {@link MatteBorder}. * It is impossible to use {@link DefaultPersistenceDelegate} * because this class does not have writable properties. * * @author Sergey A. Malenkov */ final class javax_swing_border_MatteBorder_PersistenceDelegate extends PersistenceDelegate { protected Expression instantiate(Object oldInstance, Encoder out) { MatteBorder border = (MatteBorder) oldInstance; Insets insets = border.getBorderInsets(); Object object = border.getTileIcon(); if (object == null) { object = border.getMatteColor(); } Object[] args = new Object[] { insets.top, insets.left, insets.bottom, insets.right, object, }; return new Expression(border, border.getClass(), "new", args); } } /* XXX - doens't seem to work. Debug later. class javax_swing_JMenu_PersistenceDelegate extends DefaultPersistenceDelegate { protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); javax.swing.JMenu m = (javax.swing.JMenu)oldInstance; javax.swing.JMenu n = (javax.swing.JMenu)newInstance; for (int i = n.getItemCount(); i < m.getItemCount(); i++) { invokeStatement(oldInstance, "add", new Object[]{m.getItem(i)}, out); } } } */ /** {@collect.stats} * The persistence delegate for {@link PrintColorUIResource}. * It is impossible to use {@link DefaultPersistenceDelegate} * because this class has special rule for serialization: * it should be converted to {@link ColorUIResource}. * * @see PrintColorUIResource#writeReplace * * @author Sergey A. Malenkov */ final class sun_swing_PrintColorUIResource_PersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo(Object oldInstance, Object newInstance) { return oldInstance.equals(newInstance); } protected Expression instantiate(Object oldInstance, Encoder out) { Color color = (Color) oldInstance; Object[] args = new Object[] {color.getRGB()}; return new Expression(color, ColorUIResource.class, "new", args); } } class MetaData { private static final Map<String,Field> fields = Collections.synchronizedMap(new WeakHashMap<String, Field>()); private static Hashtable internalPersistenceDelegates = new Hashtable(); private static Hashtable transientProperties = new Hashtable(); private static PersistenceDelegate nullPersistenceDelegate = new NullPersistenceDelegate(); private static PersistenceDelegate enumPersistenceDelegate = new EnumPersistenceDelegate(); private static PersistenceDelegate primitivePersistenceDelegate = new PrimitivePersistenceDelegate(); private static PersistenceDelegate defaultPersistenceDelegate = new DefaultPersistenceDelegate(); private static PersistenceDelegate arrayPersistenceDelegate; private static PersistenceDelegate proxyPersistenceDelegate; static { // Constructors. // beans registerConstructor("java.beans.Statement", new String[]{"target", "methodName", "arguments"}); registerConstructor("java.beans.Expression", new String[]{"target", "methodName", "arguments"}); registerConstructor("java.beans.EventHandler", new String[]{"target", "action", "eventPropertyName", "listenerMethodName"}); // awt registerConstructor("java.awt.Color", new String[]{"red", "green", "blue", "alpha"}); registerConstructor("java.awt.Cursor", new String[]{"type"}); registerConstructor("java.awt.ScrollPane", new String[]{"scrollbarDisplayPolicy"}); // swing registerConstructor("javax.swing.plaf.ColorUIResource", new String[]{"red", "green", "blue"}); registerConstructor("javax.swing.tree.DefaultTreeModel", new String[]{"root"}); registerConstructor("javax.swing.JTree", new String[]{"model"}); registerConstructor("javax.swing.tree.TreePath", new String[]{"path"}); registerConstructor("javax.swing.OverlayLayout", new String[]{"target"}); registerConstructor("javax.swing.BoxLayout", new String[]{"target", "axis"}); registerConstructor("javax.swing.Box$Filler", new String[]{"minimumSize", "preferredSize", "maximumSize"}); registerConstructor("javax.swing.DefaultCellEditor", new String[]{"component"}); /* This is required because the JSplitPane reveals a private layout class called BasicSplitPaneUI$BasicVerticalLayoutManager which changes with the orientation. To avoid the necessity for instantiating it we cause the orientation attribute to get set before the layout manager - that way the layout manager will be changed as a side effect. Unfortunately, the layout property belongs to the superclass and therefore precedes the orientation property. PENDING - we need to allow this kind of modification. For now, put the property in the constructor. */ registerConstructor("javax.swing.JSplitPane", new String[]{"orientation"}); // Try to synthesize the ImageIcon from its description. registerConstructor("javax.swing.ImageIcon", new String[]{"description"}); // JButton's "text" and "actionCommand" properties are related, // use the text as a constructor argument to ensure that it is set first. // This remove the benign, but unnecessary, manipulation of actionCommand // property in the common case. registerConstructor("javax.swing.JButton", new String[]{"text"}); // borders registerConstructor("javax.swing.border.BevelBorder", new String[]{"bevelType", "highlightOuterColor", "highlightInnerColor", "shadowOuterColor", "shadowInnerColor"}); registerConstructor("javax.swing.plaf.BorderUIResource$BevelBorderUIResource", new String[]{"bevelType", "highlightOuterColor", "highlightInnerColor", "shadowOuterColor", "shadowInnerColor"}); registerConstructor("javax.swing.border.CompoundBorder", new String[]{"outsideBorder", "insideBorder"}); registerConstructor("javax.swing.plaf.BorderUIResource$CompoundBorderUIResource", new String[]{"outsideBorder", "insideBorder"}); registerConstructor("javax.swing.border.EmptyBorder", new String[]{"borderInsets"}); registerConstructor("javax.swing.plaf.BorderUIResource$EmptyBorderUIResource", new String[]{"borderInsets"}); registerConstructor("javax.swing.border.EtchedBorder", new String[]{"etchType", "highlightColor", "shadowColor"}); registerConstructor("javax.swing.plaf.BorderUIResource$EtchedBorderUIResource", new String[]{"etchType", "highlightColor", "shadowColor"}); registerConstructor("javax.swing.border.LineBorder", new String[]{"lineColor", "thickness", "roundedCorners"}); registerConstructor("javax.swing.plaf.BorderUIResource$LineBorderUIResource", new String[]{"lineColor", "thickness"}); registerConstructor("javax.swing.border.SoftBevelBorder", new String[]{"bevelType", "highlightOuterColor", "highlightInnerColor", "shadowOuterColor", "shadowInnerColor"}); // registerConstructorWithBadEqual("javax.swing.plaf.BorderUIResource$SoftBevelBorderUIResource", new String[]{"bevelType", "highlightOuter", "highlightInner", "shadowOuter", "shadowInner"}); registerConstructor("javax.swing.border.TitledBorder", new String[]{"border", "title", "titleJustification", "titlePosition", "titleFont", "titleColor"}); registerConstructor("javax.swing.plaf.BorderUIResource$TitledBorderUIResource", new String[]{"border", "title", "titleJustification", "titlePosition", "titleFont", "titleColor"}); internalPersistenceDelegates.put("java.net.URI", new PrimitivePersistenceDelegate()); // it is possible because MatteBorder is assignable from MatteBorderUIResource internalPersistenceDelegates.put("javax.swing.plaf.BorderUIResource$MatteBorderUIResource", new javax_swing_border_MatteBorder_PersistenceDelegate()); // it is possible because FontUIResource is supported by java_awt_Font_PersistenceDelegate internalPersistenceDelegates.put("javax.swing.plaf.FontUIResource", new java_awt_Font_PersistenceDelegate()); // it is possible because KeyStroke is supported by java_awt_AWTKeyStroke_PersistenceDelegate internalPersistenceDelegates.put("javax.swing.KeyStroke", new java_awt_AWTKeyStroke_PersistenceDelegate()); internalPersistenceDelegates.put("java.sql.Date", new java_util_Date_PersistenceDelegate()); internalPersistenceDelegates.put("java.sql.Time", new java_util_Date_PersistenceDelegate()); internalPersistenceDelegates.put("java.util.JumboEnumSet", new java_util_EnumSet_PersistenceDelegate()); internalPersistenceDelegates.put("java.util.RegularEnumSet", new java_util_EnumSet_PersistenceDelegate()); // Transient properties // awt // Infinite graphs. removeProperty("java.awt.geom.RectangularShape", "frame"); // removeProperty("java.awt.Rectangle2D", "frame"); // removeProperty("java.awt.Rectangle", "frame"); removeProperty("java.awt.Rectangle", "bounds"); removeProperty("java.awt.Dimension", "size"); removeProperty("java.awt.Point", "location"); // The color and font properties in Component need special treatment, see above. removeProperty("java.awt.Component", "foreground"); removeProperty("java.awt.Component", "background"); removeProperty("java.awt.Component", "font"); // The visible property of Component needs special treatment because of Windows. removeProperty("java.awt.Component", "visible"); // This property throws an exception if accessed when there is no child. removeProperty("java.awt.ScrollPane", "scrollPosition"); // 4917458 this should be removed for XAWT since it may throw // an unsupported exception if there isn't any input methods. // This shouldn't be a problem since these are added behind // the scenes automatically. removeProperty("java.awt.im.InputContext", "compositionEnabled"); // swing // The size properties in JComponent need special treatment, see above. removeProperty("javax.swing.JComponent", "minimumSize"); removeProperty("javax.swing.JComponent", "preferredSize"); removeProperty("javax.swing.JComponent", "maximumSize"); // These properties have platform specific implementations // and should not appear in archives. removeProperty("javax.swing.ImageIcon", "image"); removeProperty("javax.swing.ImageIcon", "imageObserver"); // This property unconditionally throws a "not implemented" exception. removeProperty("javax.swing.JMenuBar", "helpMenu"); // The scrollBars in a JScrollPane are dynamic and should not // be archived. The row and columns headers are changed by // components like JTable on "addNotify". removeProperty("javax.swing.JScrollPane", "verticalScrollBar"); removeProperty("javax.swing.JScrollPane", "horizontalScrollBar"); removeProperty("javax.swing.JScrollPane", "rowHeader"); removeProperty("javax.swing.JScrollPane", "columnHeader"); removeProperty("javax.swing.JViewport", "extentSize"); // Renderers need special treatment, since their properties // change during rendering. removeProperty("javax.swing.table.JTableHeader", "defaultRenderer"); removeProperty("javax.swing.JList", "cellRenderer"); removeProperty("javax.swing.JList", "selectedIndices"); // The lead and anchor selection indexes are best ignored. // Selection is rarely something that should persist from // development to deployment. removeProperty("javax.swing.DefaultListSelectionModel", "leadSelectionIndex"); removeProperty("javax.swing.DefaultListSelectionModel", "anchorSelectionIndex"); // The selection must come after the text itself. removeProperty("javax.swing.JComboBox", "selectedIndex"); // All selection information should come after the JTabbedPane is built removeProperty("javax.swing.JTabbedPane", "selectedIndex"); removeProperty("javax.swing.JTabbedPane", "selectedComponent"); // PENDING: The "disabledIcon" property is often computed from the icon property. removeProperty("javax.swing.AbstractButton", "disabledIcon"); removeProperty("javax.swing.JLabel", "disabledIcon"); // The caret property throws errors when it it set beyond // the extent of the text. We could just set it after the // text, but this is probably not something we want to archive anyway. removeProperty("javax.swing.text.JTextComponent", "caret"); removeProperty("javax.swing.text.JTextComponent", "caretPosition"); // The selectionStart must come after the text itself. removeProperty("javax.swing.text.JTextComponent", "selectionStart"); removeProperty("javax.swing.text.JTextComponent", "selectionEnd"); } /*pp*/ static boolean equals(Object o1, Object o2) { return (o1 == null) ? (o2 == null) : o1.equals(o2); } public synchronized static PersistenceDelegate getPersistenceDelegate(Class type) { if (type == null) { return nullPersistenceDelegate; } if (Enum.class.isAssignableFrom(type)) { return enumPersistenceDelegate; } if (ReflectionUtils.isPrimitive(type)) { return primitivePersistenceDelegate; } // The persistence delegate for arrays is non-trivial; instantiate it lazily. if (type.isArray()) { if (arrayPersistenceDelegate == null) { arrayPersistenceDelegate = new ArrayPersistenceDelegate(); } return arrayPersistenceDelegate; } // Handle proxies lazily for backward compatibility with 1.2. try { if (java.lang.reflect.Proxy.isProxyClass(type)) { if (proxyPersistenceDelegate == null) { proxyPersistenceDelegate = new ProxyPersistenceDelegate(); } return proxyPersistenceDelegate; } } catch(Exception e) {} // else if (type.getDeclaringClass() != null) { // return new DefaultPersistenceDelegate(new String[]{"this$0"}); // } String typeName = type.getName(); // Check to see if there are properties that have been lazily registered for removal. if (getBeanAttribute(type, "transient_init") == null) { Vector tp = (Vector)transientProperties.get(typeName); if (tp != null) { for(int i = 0; i < tp.size(); i++) { setPropertyAttribute(type, (String)tp.get(i), "transient", Boolean.TRUE); } } setBeanAttribute(type, "transient_init", Boolean.TRUE); } PersistenceDelegate pd = (PersistenceDelegate)getBeanAttribute(type, "persistenceDelegate"); if (pd == null) { pd = (PersistenceDelegate)internalPersistenceDelegates.get(typeName); if (pd != null) { return pd; } internalPersistenceDelegates.put(typeName, defaultPersistenceDelegate); try { String name = type.getName(); Class c = Class.forName("java.beans." + name.replace('.', '_') + "_PersistenceDelegate"); pd = (PersistenceDelegate)c.newInstance(); internalPersistenceDelegates.put(typeName, pd); } catch (ClassNotFoundException e) { String[] properties = getConstructorProperties(type); if (properties != null) { pd = new DefaultPersistenceDelegate(properties); internalPersistenceDelegates.put(typeName, pd); } } catch (Exception e) { System.err.println("Internal error: " + e); } } return (pd != null) ? pd : defaultPersistenceDelegate; } private static String[] getConstructorProperties(Class type) { String[] names = null; int length = 0; for (Constructor<?> constructor : type.getConstructors()) { String[] value = getAnnotationValue(constructor); if ((value != null) && (length < value.length) && isValid(constructor, value)) { names = value; length = value.length; } } return names; } private static String[] getAnnotationValue(Constructor<?> constructor) { ConstructorProperties annotation = constructor.getAnnotation(ConstructorProperties.class); return (annotation != null) ? annotation.value() : null; } private static boolean isValid(Constructor<?> constructor, String[] names) { Class[] parameters = constructor.getParameterTypes(); if (names.length != parameters.length) { return false; } for (String name : names) { if (name == null) { return false; } } return true; } // Wrapper for Introspector.getBeanInfo to handle exception handling. // Note: this relys on new 1.4 Introspector semantics which cache the BeanInfos public static BeanInfo getBeanInfo(Class type) { BeanInfo info = null; try { info = Introspector.getBeanInfo(type); } catch (Throwable e) { e.printStackTrace(); } return info; } private static PropertyDescriptor getPropertyDescriptor(Class type, String propertyName) { BeanInfo info = getBeanInfo(type); PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors(); // System.out.println("Searching for: " + propertyName + " in " + type); for(int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor pd = propertyDescriptors[i]; if (propertyName.equals(pd.getName())) { return pd; } } return null; } private static void setPropertyAttribute(Class type, String property, String attribute, Object value) { PropertyDescriptor pd = getPropertyDescriptor(type, property); if (pd == null) { System.err.println("Warning: property " + property + " is not defined on " + type); return; } pd.setValue(attribute, value); } private static void setBeanAttribute(Class type, String attribute, Object value) { getBeanInfo(type).getBeanDescriptor().setValue(attribute, value); } private static Object getBeanAttribute(Class type, String attribute) { return getBeanInfo(type).getBeanDescriptor().getValue(attribute); } // MetaData registration private synchronized static void registerConstructor(String typeName, String[] constructor) { internalPersistenceDelegates.put(typeName, new DefaultPersistenceDelegate(constructor)); } private static void removeProperty(String typeName, String property) { Vector tp = (Vector)transientProperties.get(typeName); if (tp == null) { tp = new Vector(); transientProperties.put(typeName, tp); } tp.add(property); } static Object getPrivateFieldValue(Object instance, String name) { Field field = fields.get(name); if (field == null) { int index = name.lastIndexOf('.'); final String className = name.substring(0, index); final String fieldName = name.substring(1 + index); field = AccessController.doPrivileged(new PrivilegedAction<Field>() { public Field run() { try { Field field = Class.forName(className).getDeclaredField(fieldName); field.setAccessible(true); return field; } catch (ClassNotFoundException exception) { throw new IllegalStateException("Could not find class", exception); } catch (NoSuchFieldException exception) { throw new IllegalStateException("Could not find field", exception); } } }); fields.put(name, field); } try { return field.get(instance); } catch (IllegalAccessException exception) { throw new IllegalStateException("Could not get value of the field", exception); } } }
Java
/* * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.List; import java.util.ArrayList; /** {@collect.stats} * A MethodDescriptor describes a particular method that a Java Bean * supports for external access from other components. */ public class MethodDescriptor extends FeatureDescriptor { private Reference<Method> methodRef; private String[] paramNames; private List params; private ParameterDescriptor parameterDescriptors[]; /** {@collect.stats} * Constructs a <code>MethodDescriptor</code> from a * <code>Method</code>. * * @param method The low-level method information. */ public MethodDescriptor(Method method) { this(method, null); } /** {@collect.stats} * Constructs a <code>MethodDescriptor</code> from a * <code>Method</code> providing descriptive information for each * of the method's parameters. * * @param method The low-level method information. * @param parameterDescriptors Descriptive information for each of the * method's parameters. */ public MethodDescriptor(Method method, ParameterDescriptor parameterDescriptors[]) { setName(method.getName()); setMethod(method); this.parameterDescriptors = parameterDescriptors; } /** {@collect.stats} * Gets the method that this MethodDescriptor encapsualtes. * * @return The low-level description of the method */ public synchronized Method getMethod() { Method method = getMethod0(); if (method == null) { Class cls = getClass0(); if (cls != null) { Class[] params = getParams(); if (params == null) { for (int i = 0; i < 3; i++) { // Find methods for up to 2 params. We are guessing here. // This block should never execute unless the classloader // that loaded the argument classes disappears. method = Introspector.findMethod(cls, getName(), i, null); if (method != null) { break; } } } else { method = Introspector.findMethod(cls, getName(), params.length, params); } setMethod(method); } } return method; } private synchronized void setMethod(Method method) { if (method == null) { return; } if (getClass0() == null) { setClass0(method.getDeclaringClass()); } setParams(getParameterTypes(getClass0(), method)); this.methodRef = getSoftReference(method); } private Method getMethod0() { return (this.methodRef != null) ? this.methodRef.get() : null; } private synchronized void setParams(Class[] param) { if (param == null) { return; } paramNames = new String[param.length]; params = new ArrayList(param.length); for (int i = 0; i < param.length; i++) { paramNames[i] = param[i].getName(); params.add(new WeakReference(param[i])); } } // pp getParamNames used as an optimization to avoid method.getParameterTypes. String[] getParamNames() { return paramNames; } private synchronized Class[] getParams() { Class[] clss = new Class[params.size()]; for (int i = 0; i < params.size(); i++) { Reference ref = (Reference)params.get(i); Class cls = (Class)ref.get(); if (cls == null) { return null; } else { clss[i] = cls; } } return clss; } /** {@collect.stats} * Gets the ParameterDescriptor for each of this MethodDescriptor's * method's parameters. * * @return The locale-independent names of the parameters. May return * a null array if the parameter names aren't known. */ public ParameterDescriptor[] getParameterDescriptors() { return parameterDescriptors; } /* public String toString() { String message = "name=" + getName(); Class cls = getClass0(); if (cls != null) { message += ", class="; message += cls.getName(); } String[] names = getParamNames(); if (names != null) { for (int i = 0; i < names.length; i++) { message += ", param=" + names[i]; } } return message; } */ /* * Package-private constructor * Merge two method descriptors. Where they conflict, give the * second argument (y) priority over the first argument (x). * @param x The first (lower priority) MethodDescriptor * @param y The second (higher priority) MethodDescriptor */ MethodDescriptor(MethodDescriptor x, MethodDescriptor y) { super(x,y); methodRef = x.methodRef; if (y.methodRef != null) { methodRef = y.methodRef; } params = x.params; if (y.params != null) { params = y.params; } paramNames = x.paramNames; if (y.paramNames != null) { paramNames = y.paramNames; } parameterDescriptors = x.parameterDescriptors; if (y.parameterDescriptors != null) { parameterDescriptors = y.parameterDescriptors; } } /* * Package-private dup constructor * This must isolate the new object from any changes to the old object. */ MethodDescriptor(MethodDescriptor old) { super(old); methodRef = old.methodRef; params = old.params; paramNames = old.paramNames; if (old.parameterDescriptors != null) { int len = old.parameterDescriptors.length; parameterDescriptors = new ParameterDescriptor[len]; for (int i = 0; i < len ; i++) { parameterDescriptors[i] = new ParameterDescriptor(old.parameterDescriptors[i]); } } } }
Java
/* * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * <p> * This interface is intended to be implemented by, or delegated from, instances * of java.beans.beancontext.BeanContext, in order to propagate to its nested hierarchy * of java.beans.beancontext.BeanContextChild instances, the current "designTime" property. * <p> * The JavaBeans specification defines the notion of design time as is a * mode in which JavaBeans instances should function during their composition * and customization in a interactive design, composition or construction tool, * as opposed to runtime when the JavaBean is part of an applet, application, * or other live Java executable abstraction. * * @author Laurence P. G. Cable * @since 1.2 * * @see java.beans.beancontext.BeanContext * @see java.beans.beancontext.BeanContextChild * @see java.beans.beancontext.BeanContextMembershipListener * @see java.beans.PropertyChangeEvent */ public interface DesignMode { /** {@collect.stats} * The standard value of the propertyName as fired from a BeanContext or * other source of PropertyChangeEvents. */ static String PROPERTYNAME = "designTime"; /** {@collect.stats} * Sets the "value" of the "designTime" property. * <p> * If the implementing object is an instance of java.beans.beancontext.BeanContext, * or a subinterface thereof, then that BeanContext should fire a * PropertyChangeEvent, to its registered BeanContextMembershipListeners, with * parameters: * <ul> * <li><code>propertyName</code> - <code>java.beans.DesignMode.PROPERTYNAME</code> * <li><code>oldValue</code> - previous value of "designTime" * <li><code>newValue</code> - current value of "designTime" * </ul> * Note it is illegal for a BeanContextChild to invoke this method * associated with a BeanContext that it is nested within. * * @param designTime the current "value" of the "designTime" property * @see java.beans.beancontext.BeanContext * @see java.beans.beancontext.BeanContextMembershipListener * @see java.beans.PropertyChangeEvent */ void setDesignTime(boolean designTime); /** {@collect.stats} * A value of true denotes that JavaBeans should behave in design time * mode, a value of false denotes runtime behavior. * * @return the current "value" of the "designTime" property. */ boolean isDesignTime(); }
Java
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.lang.ref.Reference; import java.lang.reflect.Method; /** {@collect.stats} * An IndexedPropertyDescriptor describes a property that acts like an * array and has an indexed read and/or indexed write method to access * specific elements of the array. * <p> * An indexed property may also provide simple non-indexed read and write * methods. If these are present, they read and write arrays of the type * returned by the indexed read method. */ public class IndexedPropertyDescriptor extends PropertyDescriptor { private Reference<Class> indexedPropertyTypeRef; private Reference<Method> indexedReadMethodRef; private Reference<Method> indexedWriteMethodRef; private String indexedReadMethodName; private String indexedWriteMethodName; /** {@collect.stats} * This constructor constructs an IndexedPropertyDescriptor for a property * that follows the standard Java conventions by having getFoo and setFoo * accessor methods, for both indexed access and array access. * <p> * Thus if the argument name is "fred", it will assume that there * is an indexed reader method "getFred", a non-indexed (array) reader * method also called "getFred", an indexed writer method "setFred", * and finally a non-indexed writer method "setFred". * * @param propertyName The programmatic name of the property. * @param beanClass The Class object for the target bean. * @exception IntrospectionException if an exception occurs during * introspection. */ public IndexedPropertyDescriptor(String propertyName, Class<?> beanClass) throws IntrospectionException { this(propertyName, beanClass, Introspector.GET_PREFIX + NameGenerator.capitalize(propertyName), Introspector.SET_PREFIX + NameGenerator.capitalize(propertyName), Introspector.GET_PREFIX + NameGenerator.capitalize(propertyName), Introspector.SET_PREFIX + NameGenerator.capitalize(propertyName)); } /** {@collect.stats} * This constructor takes the name of a simple property, and method * names for reading and writing the property, both indexed * and non-indexed. * * @param propertyName The programmatic name of the property. * @param beanClass The Class object for the target bean. * @param readMethodName The name of the method used for reading the property * values as an array. May be null if the property is write-only * or must be indexed. * @param writeMethodName The name of the method used for writing the property * values as an array. May be null if the property is read-only * or must be indexed. * @param indexedReadMethodName The name of the method used for reading * an indexed property value. * May be null if the property is write-only. * @param indexedWriteMethodName The name of the method used for writing * an indexed property value. * May be null if the property is read-only. * @exception IntrospectionException if an exception occurs during * introspection. */ public IndexedPropertyDescriptor(String propertyName, Class<?> beanClass, String readMethodName, String writeMethodName, String indexedReadMethodName, String indexedWriteMethodName) throws IntrospectionException { super(propertyName, beanClass, readMethodName, writeMethodName); this.indexedReadMethodName = indexedReadMethodName; if (indexedReadMethodName != null && getIndexedReadMethod() == null) { throw new IntrospectionException("Method not found: " + indexedReadMethodName); } this.indexedWriteMethodName = indexedWriteMethodName; if (indexedWriteMethodName != null && getIndexedWriteMethod() == null) { throw new IntrospectionException("Method not found: " + indexedWriteMethodName); } // Implemented only for type checking. findIndexedPropertyType(getIndexedReadMethod(), getIndexedWriteMethod()); } /** {@collect.stats} * This constructor takes the name of a simple property, and Method * objects for reading and writing the property. * * @param propertyName The programmatic name of the pro perty. * @param readMethod The method used for reading the property values as an array. * May be null if the property is write-only or must be indexed. * @param writeMethod The method used for writing the property values as an array. * May be null if the property is read-only or must be indexed. * @param indexedReadMethod The method used for reading an indexed property value. * May be null if the property is write-only. * @param indexedWriteMethod The method used for writing an indexed property value. * May be null if the property is read-only. * @exception IntrospectionException if an exception occurs during * introspection. */ public IndexedPropertyDescriptor(String propertyName, Method readMethod, Method writeMethod, Method indexedReadMethod, Method indexedWriteMethod) throws IntrospectionException { super(propertyName, readMethod, writeMethod); setIndexedReadMethod0(indexedReadMethod); setIndexedWriteMethod0(indexedWriteMethod); // Type checking setIndexedPropertyType(findIndexedPropertyType(indexedReadMethod, indexedWriteMethod)); } /** {@collect.stats} * Creates <code>PropertyDescriptor</code> for the specified bean * with the specified name and methods to read/write the property value. * * @param bean the type of the target bean * @param base the base name of the property (the rest of the method name) * @param read the method used for reading the property value * @param write the method used for writing the property value * @param readIndexed the method used for reading an indexed property value * @param writeIndexed the method used for writing an indexed property value * @exception IntrospectionException if an exception occurs during introspection * * @since 1.7 */ IndexedPropertyDescriptor(Class<?> bean, String base, Method read, Method write, Method readIndexed, Method writeIndexed) throws IntrospectionException { super(bean, base, read, write); setIndexedReadMethod0(readIndexed); setIndexedWriteMethod0(writeIndexed); // Type checking setIndexedPropertyType(findIndexedPropertyType(readIndexed, writeIndexed)); } /** {@collect.stats} * Gets the method that should be used to read an indexed * property value. * * @return The method that should be used to read an indexed * property value. * May return null if the property isn't indexed or is write-only. */ public synchronized Method getIndexedReadMethod() { Method indexedReadMethod = getIndexedReadMethod0(); if (indexedReadMethod == null) { Class cls = getClass0(); if (cls == null || (indexedReadMethodName == null && indexedReadMethodRef == null)) { // the Indexed readMethod was explicitly set to null. return null; } if (indexedReadMethodName == null) { Class type = getIndexedPropertyType0(); if (type == boolean.class || type == null) { indexedReadMethodName = Introspector.IS_PREFIX + getBaseName(); } else { indexedReadMethodName = Introspector.GET_PREFIX + getBaseName(); } } Class[] args = { int.class }; indexedReadMethod = Introspector.findMethod(cls, indexedReadMethodName, 1, args); if (indexedReadMethod == null) { // no "is" method, so look for a "get" method. indexedReadMethodName = Introspector.GET_PREFIX + getBaseName(); indexedReadMethod = Introspector.findMethod(cls, indexedReadMethodName, 1, args); } setIndexedReadMethod0(indexedReadMethod); } return indexedReadMethod; } /** {@collect.stats} * Sets the method that should be used to read an indexed property value. * * @param readMethod The new indexed read method. */ public synchronized void setIndexedReadMethod(Method readMethod) throws IntrospectionException { // the indexed property type is set by the reader. setIndexedPropertyType(findIndexedPropertyType(readMethod, getIndexedWriteMethod0())); setIndexedReadMethod0(readMethod); } private void setIndexedReadMethod0(Method readMethod) { if (readMethod == null) { indexedReadMethodName = null; indexedReadMethodRef = null; return; } setClass0(readMethod.getDeclaringClass()); indexedReadMethodName = readMethod.getName(); this.indexedReadMethodRef = getSoftReference(readMethod); } /** {@collect.stats} * Gets the method that should be used to write an indexed property value. * * @return The method that should be used to write an indexed * property value. * May return null if the property isn't indexed or is read-only. */ public synchronized Method getIndexedWriteMethod() { Method indexedWriteMethod = getIndexedWriteMethod0(); if (indexedWriteMethod == null) { Class cls = getClass0(); if (cls == null || (indexedWriteMethodName == null && indexedWriteMethodRef == null)) { // the Indexed writeMethod was explicitly set to null. return null; } // We need the indexed type to ensure that we get the correct method. // Cannot use the getIndexedPropertyType method since that could // result in an infinite loop. Class type = getIndexedPropertyType0(); if (type == null) { try { type = findIndexedPropertyType(getIndexedReadMethod(), null); setIndexedPropertyType(type); } catch (IntrospectionException ex) { // Set iprop type to be the classic type Class propType = getPropertyType(); if (propType.isArray()) { type = propType.getComponentType(); } } } if (indexedWriteMethodName == null) { indexedWriteMethodName = Introspector.SET_PREFIX + getBaseName(); } indexedWriteMethod = Introspector.findMethod(cls, indexedWriteMethodName, 2, (type == null) ? null : new Class[] { int.class, type }); setIndexedWriteMethod0(indexedWriteMethod); } return indexedWriteMethod; } /** {@collect.stats} * Sets the method that should be used to write an indexed property value. * * @param writeMethod The new indexed write method. */ public synchronized void setIndexedWriteMethod(Method writeMethod) throws IntrospectionException { // If the indexed property type has not been set, then set it. Class type = findIndexedPropertyType(getIndexedReadMethod(), writeMethod); setIndexedPropertyType(type); setIndexedWriteMethod0(writeMethod); } private void setIndexedWriteMethod0(Method writeMethod) { if (writeMethod == null) { indexedWriteMethodName = null; indexedWriteMethodRef = null; return; } setClass0(writeMethod.getDeclaringClass()); indexedWriteMethodName = writeMethod.getName(); this.indexedWriteMethodRef = getSoftReference(writeMethod); } /** {@collect.stats} * Gets the <code>Class</code> object of the indexed properties' type. * The returned <code>Class</code> may describe a primitive type such as <code>int</code>. * * @return The <code>Class</code> for the indexed properties' type; may return <code>null</code> * if the type cannot be determined. */ public synchronized Class<?> getIndexedPropertyType() { Class type = getIndexedPropertyType0(); if (type == null) { try { type = findIndexedPropertyType(getIndexedReadMethod(), getIndexedWriteMethod()); setIndexedPropertyType(type); } catch (IntrospectionException ex) { // fall } } return type; } // Private methods which set get/set the Reference objects private void setIndexedPropertyType(Class type) { this.indexedPropertyTypeRef = getWeakReference(type); } private Class getIndexedPropertyType0() { return (this.indexedPropertyTypeRef != null) ? this.indexedPropertyTypeRef.get() : null; } private Method getIndexedReadMethod0() { return (this.indexedReadMethodRef != null) ? this.indexedReadMethodRef.get() : null; } private Method getIndexedWriteMethod0() { return (this.indexedWriteMethodRef != null) ? this.indexedWriteMethodRef.get() : null; } private Class findIndexedPropertyType(Method indexedReadMethod, Method indexedWriteMethod) throws IntrospectionException { Class indexedPropertyType = null; if (indexedReadMethod != null) { Class params[] = getParameterTypes(getClass0(), indexedReadMethod); if (params.length != 1) { throw new IntrospectionException("bad indexed read method arg count"); } if (params[0] != Integer.TYPE) { throw new IntrospectionException("non int index to indexed read method"); } indexedPropertyType = getReturnType(getClass0(), indexedReadMethod); if (indexedPropertyType == Void.TYPE) { throw new IntrospectionException("indexed read method returns void"); } } if (indexedWriteMethod != null) { Class params[] = getParameterTypes(getClass0(), indexedWriteMethod); if (params.length != 2) { throw new IntrospectionException("bad indexed write method arg count"); } if (params[0] != Integer.TYPE) { throw new IntrospectionException("non int index to indexed write method"); } if (indexedPropertyType != null && indexedPropertyType != params[1]) { throw new IntrospectionException( "type mismatch between indexed read and indexed write methods: " + getName()); } indexedPropertyType = params[1]; } Class propertyType = getPropertyType(); if (propertyType != null && (!propertyType.isArray() || propertyType.getComponentType() != indexedPropertyType)) { throw new IntrospectionException("type mismatch between indexed and non-indexed methods: " + getName()); } return indexedPropertyType; } /** {@collect.stats} * Compares this <code>PropertyDescriptor</code> against the specified object. * Returns true if the objects are the same. Two <code>PropertyDescriptor</code>s * are the same if the read, write, property types, property editor and * flags are equivalent. * * @since 1.4 */ public boolean equals(Object obj) { // Note: This would be identical to PropertyDescriptor but they don't // share the same fields. if (this == obj) { return true; } if (obj != null && obj instanceof IndexedPropertyDescriptor) { IndexedPropertyDescriptor other = (IndexedPropertyDescriptor)obj; Method otherIndexedReadMethod = other.getIndexedReadMethod(); Method otherIndexedWriteMethod = other.getIndexedWriteMethod(); if (!compareMethods(getIndexedReadMethod(), otherIndexedReadMethod)) { return false; } if (!compareMethods(getIndexedWriteMethod(), otherIndexedWriteMethod)) { return false; } if (getIndexedPropertyType() != other.getIndexedPropertyType()) { return false; } return super.equals(obj); } return false; } /** {@collect.stats} * Package-private constructor. * Merge two property descriptors. Where they conflict, give the * second argument (y) priority over the first argumnnt (x). * * @param x The first (lower priority) PropertyDescriptor * @param y The second (higher priority) PropertyDescriptor */ IndexedPropertyDescriptor(PropertyDescriptor x, PropertyDescriptor y) { super(x,y); if (x instanceof IndexedPropertyDescriptor) { IndexedPropertyDescriptor ix = (IndexedPropertyDescriptor)x; try { Method xr = ix.getIndexedReadMethod(); if (xr != null) { setIndexedReadMethod(xr); } Method xw = ix.getIndexedWriteMethod(); if (xw != null) { setIndexedWriteMethod(xw); } } catch (IntrospectionException ex) { // Should not happen throw new AssertionError(ex); } } if (y instanceof IndexedPropertyDescriptor) { IndexedPropertyDescriptor iy = (IndexedPropertyDescriptor)y; try { Method yr = iy.getIndexedReadMethod(); if (yr != null && yr.getDeclaringClass() == getClass0()) { setIndexedReadMethod(yr); } Method yw = iy.getIndexedWriteMethod(); if (yw != null && yw.getDeclaringClass() == getClass0()) { setIndexedWriteMethod(yw); } } catch (IntrospectionException ex) { // Should not happen throw new AssertionError(ex); } } } /* * Package-private dup constructor * This must isolate the new object from any changes to the old object. */ IndexedPropertyDescriptor(IndexedPropertyDescriptor old) { super(old); indexedReadMethodRef = old.indexedReadMethodRef; indexedWriteMethodRef = old.indexedWriteMethodRef; indexedPropertyTypeRef = old.indexedPropertyTypeRef; indexedWriteMethodName = old.indexedWriteMethodName; indexedReadMethodName = old.indexedReadMethodName; } /** {@collect.stats} * Returns a hash code value for the object. * See {@link java.lang.Object#hashCode} for a complete description. * * @return a hash code value for this object. * @since 1.5 */ public int hashCode() { int result = super.hashCode(); result = 37 * result + ((indexedWriteMethodName == null) ? 0 : indexedWriteMethodName.hashCode()); result = 37 * result + ((indexedReadMethodName == null) ? 0 : indexedReadMethodName.hashCode()); result = 37 * result + ((getIndexedPropertyType() == null) ? 0 : getIndexedPropertyType().hashCode()); return result; } /* public String toString() { String message = super.toString(); message += ", indexedType="; message += getIndexedPropertyType(); message += ", indexedWriteMethod="; message += indexedWriteMethodName; message += ", indexedReadMethod="; message += indexedReadMethodName; return message; } */ }
Java
/* * Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; /** {@collect.stats} * A class which extends the <code>EventListenerProxy</code> specifically * for adding a named <code>PropertyChangeListener</code>. Instances of * this class can be added as <code>PropertyChangeListener</code> to * an object. * <p> * If the object has a <code>getPropertyChangeListeners()</code> * method then the array returned could be a mixture of * <code>PropertyChangeListener</code> and * <code>PropertyChangeListenerProxy</code> objects. * * @see java.util.EventListenerProxy * @since 1.4 */ public class PropertyChangeListenerProxy extends java.util.EventListenerProxy implements PropertyChangeListener { private String propertyName; /** {@collect.stats} * Constructor which binds the PropertyChangeListener to a specific * property. * * @param listener The listener object * @param propertyName The name of the property to listen on. */ public PropertyChangeListenerProxy(String propertyName, PropertyChangeListener listener) { // XXX - msd NOTE: I changed the order of the arguments so that it's // similar to PropertyChangeSupport.addPropertyChangeListener(String, // PropertyChangeListener); super(listener); this.propertyName = propertyName; } /** {@collect.stats} * Forwards the property change event to the listener delegate. * * @param evt the property change event */ public void propertyChange(PropertyChangeEvent evt) { ((PropertyChangeListener)getListener()).propertyChange(evt); } /** {@collect.stats} * Returns the name of the named property associated with the * listener. */ public String getPropertyName() { return propertyName; } }
Java
/* * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.util.*; import com.sun.beans.ObjectHandler; import sun.reflect.misc.MethodUtil; import sun.reflect.misc.ConstructorUtil; import sun.reflect.misc.ReflectUtil; /** {@collect.stats} * A utility class for reflectively finding methods, constuctors and fields * using reflection. */ class ReflectionUtils { private static Reference methodCacheRef; public static Class typeToClass(Class type) { return type.isPrimitive() ? ObjectHandler.typeNameToClass(type.getName()) : type; } public static boolean isPrimitive(Class type) { return primitiveTypeFor(type) != null; } public static Class primitiveTypeFor(Class wrapper) { if (wrapper == Boolean.class) return Boolean.TYPE; if (wrapper == Byte.class) return Byte.TYPE; if (wrapper == Character.class) return Character.TYPE; if (wrapper == Short.class) return Short.TYPE; if (wrapper == Integer.class) return Integer.TYPE; if (wrapper == Long.class) return Long.TYPE; if (wrapper == Float.class) return Float.TYPE; if (wrapper == Double.class) return Double.TYPE; if (wrapper == Void.class) return Void.TYPE; return null; } /** {@collect.stats} * Tests each element on the class arrays for assignability. * * @param argClasses arguments to be tested * @param argTypes arguments from Method * @return true if each class in argTypes is assignable from the * corresponding class in argClasses. */ private static boolean matchArguments(Class[] argClasses, Class[] argTypes) { return matchArguments(argClasses, argTypes, false); } /** {@collect.stats} * Tests each element on the class arrays for equality. * * @param argClasses arguments to be tested * @param argTypes arguments from Method * @return true if each class in argTypes is equal to the * corresponding class in argClasses. */ private static boolean matchExplicitArguments(Class[] argClasses, Class[] argTypes) { return matchArguments(argClasses, argTypes, true); } private static boolean matchArguments(Class[] argClasses, Class[] argTypes, boolean explicit) { boolean match = (argClasses.length == argTypes.length); for(int j = 0; j < argClasses.length && match; j++) { Class argType = argTypes[j]; if (argType.isPrimitive()) { argType = typeToClass(argType); } if (explicit) { // Test each element for equality if (argClasses[j] != argType) { match = false; } } else { // Consider null an instance of all classes. if (argClasses[j] != null && !(argType.isAssignableFrom(argClasses[j]))) { match = false; } } } return match; } /** {@collect.stats} * @return the method which best matches the signature or throw an exception * if it can't be found or the method is ambiguous. */ static Method getPublicMethod(Class declaringClass, String methodName, Class[] argClasses) throws NoSuchMethodException { Method m; m = findPublicMethod(declaringClass, methodName, argClasses); if (m == null) throw new NoSuchMethodException(declaringClass.getName() + "." + methodName); return m; } /** {@collect.stats} * @return the method which best matches the signature or null if it cant be found or * the method is ambiguous. */ public static Method findPublicMethod(Class declaringClass, String methodName, Class[] argClasses) { // Many methods are "getters" which take no arguments. // This permits the following optimisation which // avoids the expensive call to getMethods(). if (argClasses.length == 0) { try { return MethodUtil.getMethod(declaringClass, methodName, argClasses); } catch (NoSuchMethodException e) { return null; } catch (SecurityException se) { // fall through } } Method[] methods = MethodUtil.getPublicMethods(declaringClass); List list = new ArrayList(); for(int i = 0; i < methods.length; i++) { // Collect all the methods which match the signature. Method method = methods[i]; if (method.getName().equals(methodName)) { if (matchArguments(argClasses, method.getParameterTypes())) { list.add(method); } } } if (list.size() > 0) { if (list.size() == 1) { return (Method)list.get(0); } else { ListIterator iterator = list.listIterator(); Method method; while (iterator.hasNext()) { method = (Method)iterator.next(); if (matchExplicitArguments(argClasses, method.getParameterTypes())) { return method; } } // There are more than one method which matches this signature. // try to return the most specific method. return getMostSpecificMethod(list, argClasses); } } return null; } /** {@collect.stats} * Return the most specific method from the list of methods which * matches the args. The most specific method will have the most * number of equal parameters or will be closest in the inheritance * heirarchy to the runtime execution arguments. * <p> * See the JLS section 15.12 * http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#20448 * * @param methods List of methods which already have the same param length * and arg types are assignable to param types * @param args an array of param types to match * @return method or null if a specific method cannot be determined */ private static Method getMostSpecificMethod(List methods, Class[] args) { Method method = null; int matches = 0; int lastMatch = matches; ListIterator iterator = methods.listIterator(); while (iterator.hasNext()) { Method m = (Method)iterator.next(); Class[] mArgs = m.getParameterTypes(); matches = 0; for (int i = 0; i < args.length; i++) { Class mArg = mArgs[i]; if (mArg.isPrimitive()) { mArg = typeToClass(mArg); } if (args[i] == mArg) { matches++; } } if (matches == 0 && lastMatch == 0) { if (method == null) { method = m; } else { // Test existing method. We already know that the args can // be assigned to all the method params. However, if the // current method parameters is higher in the inheritance // hierarchy then replace it. if (!matchArguments(method.getParameterTypes(), m.getParameterTypes())) { method = m; } } } else if (matches > lastMatch) { lastMatch = matches; method = m; } else if (matches == lastMatch) { // ambiguous method selection. method = null; } } return method; } /** {@collect.stats} * @return the method or null if it can't be found or is ambiguous. */ public static Method findMethod(Class targetClass, String methodName, Class[] argClasses) { Method m = findPublicMethod(targetClass, methodName, argClasses); if (m != null && Modifier.isPublic(m.getDeclaringClass().getModifiers())) { return m; } /* Search the interfaces for a public version of this method. Example: the getKeymap() method of a JTextField returns a package private implementation of the of the public Keymap interface. In the Keymap interface there are a number of "properties" one being the "resolveParent" property implied by the getResolveParent() method. This getResolveParent() cannot be called reflectively because the class itself is not public. Instead we search the class's interfaces and find the getResolveParent() method of the Keymap interface - on which invoke may be applied without error. So in :- JTextField o = new JTextField("Hello, world"); Keymap km = o.getKeymap(); Method m1 = km.getClass().getMethod("getResolveParent", new Class[0]); Method m2 = Keymap.class.getMethod("getResolveParent", new Class[0]); Methods m1 and m2 are different. The invocation of method m1 unconditionally throws an IllegalAccessException where the invocation of m2 will invoke the implementation of the method. Note that (ignoring the overloading of arguments) there is only one implementation of the named method which may be applied to this target. */ for(Class type = targetClass; type != null; type = type.getSuperclass()) { Class[] interfaces = type.getInterfaces(); for(int i = 0; i < interfaces.length; i++) { m = findPublicMethod(interfaces[i], methodName, argClasses); if (m != null) { return m; } } } return null; } /** {@collect.stats} * A class that represents the unique elements of a method that will be a * key in the method cache. */ private static class Signature { private Class targetClass; private String methodName; private Class[] argClasses; private volatile int hashCode = 0; public Signature(Class targetClass, String methodName, Class[] argClasses) { this.targetClass = targetClass; this.methodName = methodName; this.argClasses = argClasses; } public boolean equals(Object o2) { if (this == o2) { return true; } Signature that = (Signature)o2; if (!(targetClass == that.targetClass)) { return false; } if (!(methodName.equals(that.methodName))) { return false; } if (argClasses.length != that.argClasses.length) { return false; } for (int i = 0; i < argClasses.length; i++) { if (!(argClasses[i] == that.argClasses[i])) { return false; } } return true; } /** {@collect.stats} * Hash code computed using algorithm suggested in * Effective Java, Item 8. */ public int hashCode() { if (hashCode == 0) { int result = 17; result = 37 * result + targetClass.hashCode(); result = 37 * result + methodName.hashCode(); if (argClasses != null) { for (int i = 0; i < argClasses.length; i++) { result = 37 * result + ((argClasses[i] == null) ? 0 : argClasses[i].hashCode()); } } hashCode = result; } return hashCode; } } /** {@collect.stats} * A wrapper to findMethod(), which will search or populate the method * in a cache. * @throws exception if the method is ambiguios. */ public static synchronized Method getMethod(Class targetClass, String methodName, Class[] argClasses) { Object signature = new Signature(targetClass, methodName, argClasses); Method method = null; Map methodCache = null; boolean cache = false; if (ReflectUtil.isPackageAccessible(targetClass)) { cache = true; } if (cache && methodCacheRef != null && (methodCache = (Map)methodCacheRef.get()) != null) { method = (Method)methodCache.get(signature); if (method != null) { return method; } } method = findMethod(targetClass, methodName, argClasses); if (cache && method != null) { if (methodCache == null) { methodCache = new HashMap(); methodCacheRef = new SoftReference(methodCache); } methodCache.put(signature, method); } return method; } /** {@collect.stats} * Return a constructor on the class with the arguments. * * @throws exception if the method is ambiguios. */ public static Constructor getConstructor(Class cls, Class[] args) { Constructor constructor = null; // PENDING: Implement the resolutuion of ambiguities properly. Constructor[] ctors = ConstructorUtil.getConstructors(cls); for(int i = 0; i < ctors.length; i++) { if (matchArguments(args, ctors[i].getParameterTypes())) { constructor = ctors[i]; } } return constructor; } public static Object getPrivateField(Object instance, Class cls, String name) { return getPrivateField(instance, cls, name, null); } /** {@collect.stats} * Returns the value of a private field. * * @param instance object instance * @param cls class * @param name name of the field * @param el an exception listener to handle exceptions; or null * @return value of the field; null if not found or an error is encountered */ public static Object getPrivateField(Object instance, Class cls, String name, ExceptionListener el) { try { Field f = cls.getDeclaredField(name); f.setAccessible(true); return f.get(instance); } catch (Exception e) { if (el != null) { el.exceptionThrown(e); } } return null; } }
Java
/* * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.lang.annotation.*; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; /** {@collect.stats} <p>An annotation on a constructor that shows how the parameters of that constructor correspond to the constructed object's getter methods. For example: <blockquote> <pre> public class Point { &#64;ConstructorProperties({"x", "y"}) public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } private final int x, y; } </pre> </blockquote> The annotation shows that the first parameter of the constructor can be retrieved with the {@code getX()} method and the second with the {@code getY()} method. Since parameter names are not in general available at runtime, without the annotation there would be no way to know whether the parameters correspond to {@code getX()} and {@code getY()} or the other way around.</p> @since 1.6 */ @Documented @Target(CONSTRUCTOR) @Retention(RUNTIME) public @interface ConstructorProperties { /** {@collect.stats} <p>The getter names.</p> @return the getter names corresponding to the parameters in the annotated constructor. */ String[] value(); }
Java
/* * Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.beans.*; /** {@collect.stats} * This is a support class to help build property editors. * <p> * It can be used either as a base class or as a delagatee. */ public class PropertyEditorSupport implements PropertyEditor { /** {@collect.stats} * Constructs a <code>PropertyEditorSupport</code> object. * * @since 1.5 */ public PropertyEditorSupport() { setSource(this); } /** {@collect.stats} * Constructs a <code>PropertyEditorSupport</code> object. * * @param source the source used for event firing * @since 1.5 */ public PropertyEditorSupport(Object source) { if (source == null) { throw new NullPointerException(); } setSource(source); } /** {@collect.stats} * Returns the bean that is used as the * source of events. If the source has not * been explicitly set then this instance of * <code>PropertyEditorSupport</code> is returned. * * @return the source object or this instance * @since 1.5 */ public Object getSource() { return source; } /** {@collect.stats} * Sets the source bean. * <p> * The source bean is used as the source of events * for the property changes. This source should be used for information * purposes only and should not be modified by the PropertyEditor. * * @param source source object to be used for events * @since 1.5 */ public void setSource(Object source) { this.source = source; } /** {@collect.stats} * Set (or change) the object that is to be edited. * * @param value The new target object to be edited. Note that this * object should not be modified by the PropertyEditor, rather * the PropertyEditor should create a new object to hold any * modified value. */ public void setValue(Object value) { this.value = value; firePropertyChange(); } /** {@collect.stats} * Gets the value of the property. * * @return The value of the property. */ public Object getValue() { return value; } //---------------------------------------------------------------------- /** {@collect.stats} * Determines whether the class will honor the paintValue method. * * @return True if the class will honor the paintValue method. */ public boolean isPaintable() { return false; } /** {@collect.stats} * Paint a representation of the value into a given area of screen * real estate. Note that the propertyEditor is responsible for doing * its own clipping so that it fits into the given rectangle. * <p> * If the PropertyEditor doesn't honor paint requests (see isPaintable) * this method should be a silent noop. * * @param gfx Graphics object to paint into. * @param box Rectangle within graphics object into which we should paint. */ public void paintValue(java.awt.Graphics gfx, java.awt.Rectangle box) { } //---------------------------------------------------------------------- /** {@collect.stats} * This method is intended for use when generating Java code to set * the value of the property. It should return a fragment of Java code * that can be used to initialize a variable with the current property * value. * <p> * Example results are "2", "new Color(127,127,34)", "Color.orange", etc. * * @return A fragment of Java code representing an initializer for the * current value. */ public String getJavaInitializationString() { return "???"; } //---------------------------------------------------------------------- /** {@collect.stats} * Gets the property value as a string suitable for presentation * to a human to edit. * * @return The property value as a string suitable for presentation * to a human to edit. * <p> Returns "null" is the value can't be expressed as a string. * <p> If a non-null value is returned, then the PropertyEditor should * be prepared to parse that string back in setAsText(). */ public String getAsText() { return (this.value != null) ? this.value.toString() : "null"; } /** {@collect.stats} * Sets the property value by parsing a given String. May raise * java.lang.IllegalArgumentException if either the String is * badly formatted or if this kind of property can't be expressed * as text. * * @param text The string to be parsed. */ public void setAsText(String text) throws java.lang.IllegalArgumentException { if (value instanceof String) { setValue(text); return; } throw new java.lang.IllegalArgumentException(text); } //---------------------------------------------------------------------- /** {@collect.stats} * If the property value must be one of a set of known tagged values, * then this method should return an array of the tag values. This can * be used to represent (for example) enum values. If a PropertyEditor * supports tags, then it should support the use of setAsText with * a tag value as a way of setting the value. * * @return The tag values for this property. May be null if this * property cannot be represented as a tagged value. * */ public String[] getTags() { return null; } //---------------------------------------------------------------------- /** {@collect.stats} * A PropertyEditor may chose to make available a full custom Component * that edits its property value. It is the responsibility of the * PropertyEditor to hook itself up to its editor Component itself and * to report property value changes by firing a PropertyChange event. * <P> * The higher-level code that calls getCustomEditor may either embed * the Component in some larger property sheet, or it may put it in * its own individual dialog, or ... * * @return A java.awt.Component that will allow a human to directly * edit the current property value. May be null if this is * not supported. */ public java.awt.Component getCustomEditor() { return null; } /** {@collect.stats} * Determines whether the propertyEditor can provide a custom editor. * * @return True if the propertyEditor can provide a custom editor. */ public boolean supportsCustomEditor() { return false; } //---------------------------------------------------------------------- /** {@collect.stats} * Register a listener for the PropertyChange event. The class will * fire a PropertyChange value whenever the value is updated. * * @param listener An object to be invoked when a PropertyChange * event is fired. */ public synchronized void addPropertyChangeListener( PropertyChangeListener listener) { if (listeners == null) { listeners = new java.util.Vector(); } listeners.addElement(listener); } /** {@collect.stats} * Remove a listener for the PropertyChange event. * * @param listener The PropertyChange listener to be removed. */ public synchronized void removePropertyChangeListener( PropertyChangeListener listener) { if (listeners == null) { return; } listeners.removeElement(listener); } /** {@collect.stats} * Report that we have been modified to any interested listeners. */ public void firePropertyChange() { java.util.Vector targets; synchronized (this) { if (listeners == null) { return; } targets = (java.util.Vector) listeners.clone(); } // Tell our listeners that "everything" has changed. PropertyChangeEvent evt = new PropertyChangeEvent(source, null, null, null); for (int i = 0; i < targets.size(); i++) { PropertyChangeListener target = (PropertyChangeListener)targets.elementAt(i); target.propertyChange(evt); } } //---------------------------------------------------------------------- private Object value; private Object source; private java.util.Vector listeners; }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamConstants; import java.io.OutputStream; import java.io.Serializable; import sun.rmi.server.MarshalInputStream; import sun.rmi.server.MarshalOutputStream; /** {@collect.stats} * A <code>MarshalledObject</code> contains a byte stream with the serialized * representation of an object given to its constructor. The <code>get</code> * method returns a new copy of the original object, as deserialized from * the contained byte stream. The contained object is serialized and * deserialized with the same serialization semantics used for marshaling * and unmarshaling parameters and return values of RMI calls: When the * serialized form is created: * * <ul> * <li> classes are annotated with a codebase URL from where the class * can be loaded (if available), and * <li> any remote object in the <code>MarshalledObject</code> is * represented by a serialized instance of its stub. * </ul> * * <p>When copy of the object is retrieved (via the <code>get</code> method), * if the class is not available locally, it will be loaded from the * appropriate location (specified the URL annotated with the class descriptor * when the class was serialized. * * <p><code>MarshalledObject</code> facilitates passing objects in RMI calls * that are not automatically deserialized immediately by the remote peer. * * @param <T> the type of the object contained in this * <code>MarshalledObject</code> * * @author Ann Wollrath * @author Peter Jones * @since 1.2 */ public final class MarshalledObject<T> implements Serializable { /** {@collect.stats} * @serial Bytes of serialized representation. If <code>objBytes</code> is * <code>null</code> then the object marshalled was a <code>null</code> * reference. */ private byte[] objBytes = null; /** {@collect.stats} * @serial Bytes of location annotations, which are ignored by * <code>equals</code>. If <code>locBytes</code> is null, there were no * non-<code>null</code> annotations during marshalling. */ private byte[] locBytes = null; /** {@collect.stats} * @serial Stored hash code of contained object. * * @see #hashCode */ private int hash; /** {@collect.stats} Indicate compatibility with 1.2 version of class. */ private static final long serialVersionUID = 8988374069173025854L; /** {@collect.stats} * Creates a new <code>MarshalledObject</code> that contains the * serialized representation of the current state of the supplied object. * The object is serialized with the semantics used for marshaling * parameters for RMI calls. * * @param obj the object to be serialized (must be serializable) * @exception IOException if an <code>IOException</code> occurs; an * <code>IOException</code> may occur if <code>obj</code> is not * serializable. * @since 1.2 */ public MarshalledObject(T obj) throws IOException { if (obj == null) { hash = 13; return; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); ByteArrayOutputStream lout = new ByteArrayOutputStream(); MarshalledObjectOutputStream out = new MarshalledObjectOutputStream(bout, lout); out.writeObject(obj); out.flush(); objBytes = bout.toByteArray(); // locBytes is null if no annotations locBytes = (out.hadAnnotations() ? lout.toByteArray() : null); /* * Calculate hash from the marshalled representation of object * so the hashcode will be comparable when sent between VMs. */ int h = 0; for (int i = 0; i < objBytes.length; i++) { h = 31 * h + objBytes[i]; } hash = h; } /** {@collect.stats} * Returns a new copy of the contained marshalledobject. The internal * representation is deserialized with the semantics used for * unmarshaling paramters for RMI calls. * * @return a copy of the contained object * @exception IOException if an <code>IOException</code> occurs while * deserializing the object from its internal representation. * @exception ClassNotFoundException if a * <code>ClassNotFoundException</code> occurs while deserializing the * object from its internal representation. * could not be found * @since 1.2 */ public T get() throws IOException, ClassNotFoundException { if (objBytes == null) // must have been a null object return null; ByteArrayInputStream bin = new ByteArrayInputStream(objBytes); // locBytes is null if no annotations ByteArrayInputStream lin = (locBytes == null ? null : new ByteArrayInputStream(locBytes)); MarshalledObjectInputStream in = new MarshalledObjectInputStream(bin, lin); T obj = (T) in.readObject(); in.close(); return obj; } /** {@collect.stats} * Return a hash code for this <code>MarshalledObject</code>. * * @return a hash code */ public int hashCode() { return hash; } /** {@collect.stats} * Compares this <code>MarshalledObject</code> to another object. * Returns true if and only if the argument refers to a * <code>MarshalledObject</code> that contains exactly the same * serialized representation of an object as this one does. The * comparison ignores any class codebase annotation, meaning that * two objects are equivalent if they have the same serialized * representation <i>except</i> for the codebase of each class * in the serialized representation. * * @param obj the object to compare with this <code>MarshalledObject</code> * @return <code>true</code> if the argument contains an equaivalent * serialized object; <code>false</code> otherwise * @since 1.2 */ public boolean equals(Object obj) { if (obj == this) return true; if (obj != null && obj instanceof MarshalledObject) { MarshalledObject other = (MarshalledObject) obj; // if either is a ref to null, both must be if (objBytes == null || other.objBytes == null) return objBytes == other.objBytes; // quick, easy test if (objBytes.length != other.objBytes.length) return false; //!! There is talk about adding an array comparision method //!! at 1.2 -- if so, this should be rewritten. -arnold for (int i = 0; i < objBytes.length; ++i) { if (objBytes[i] != other.objBytes[i]) return false; } return true; } else { return false; } } /** {@collect.stats} * This class is used to marshal objects for * <code>MarshalledObject</code>. It places the location annotations * to one side so that two <code>MarshalledObject</code>s can be * compared for equality if they differ only in location * annotations. Objects written using this stream should be read back * from a <code>MarshalledObjectInputStream</code>. * * @see java.rmi.MarshalledObject * @see MarshalledObjectInputStream */ private static class MarshalledObjectOutputStream extends MarshalOutputStream { /** {@collect.stats} The stream on which location objects are written. */ private ObjectOutputStream locOut; /** {@collect.stats} <code>true</code> if non-<code>null</code> annotations are * written. */ private boolean hadAnnotations; /** {@collect.stats} * Creates a new <code>MarshalledObjectOutputStream</code> whose * non-location bytes will be written to <code>objOut</code> and whose * location annotations (if any) will be written to * <code>locOut</code>. */ MarshalledObjectOutputStream(OutputStream objOut, OutputStream locOut) throws IOException { super(objOut); this.useProtocolVersion(ObjectStreamConstants.PROTOCOL_VERSION_2); this.locOut = new ObjectOutputStream(locOut); hadAnnotations = false; } /** {@collect.stats} * Returns <code>true</code> if any non-<code>null</code> location * annotations have been written to this stream. */ boolean hadAnnotations() { return hadAnnotations; } /** {@collect.stats} * Overrides MarshalOutputStream.writeLocation implementation to write * annotations to the location stream. */ protected void writeLocation(String loc) throws IOException { hadAnnotations |= (loc != null); locOut.writeObject(loc); } public void flush() throws IOException { super.flush(); locOut.flush(); } } /** {@collect.stats} * The counterpart to <code>MarshalledObjectOutputStream</code>. * * @see MarshalledObjectOutputStream */ private static class MarshalledObjectInputStream extends MarshalInputStream { /** {@collect.stats} * The stream from which annotations will be read. If this is * <code>null</code>, then all annotations were <code>null</code>. */ private ObjectInputStream locIn; /** {@collect.stats} * Creates a new <code>MarshalledObjectInputStream</code> that * reads its objects from <code>objIn</code> and annotations * from <code>locIn</code>. If <code>locIn</code> is * <code>null</code>, then all annotations will be * <code>null</code>. */ MarshalledObjectInputStream(InputStream objIn, InputStream locIn) throws IOException { super(objIn); this.locIn = (locIn == null ? null : new ObjectInputStream(locIn)); } /** {@collect.stats} * Overrides MarshalInputStream.readLocation to return locations from * the stream we were given, or <code>null</code> if we were given a * <code>null</code> location stream. */ protected Object readLocation() throws IOException, ClassNotFoundException { return (locIn == null ? null : locIn.readObject()); } } }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * An <code>UnmarshalException</code> can be thrown while unmarshalling the * parameters or results of a remote method call if any of the following * conditions occur: * <ul> * <li> if an exception occurs while unmarshalling the call header * <li> if the protocol for the return value is invalid * <li> if a <code>java.io.IOException</code> occurs unmarshalling * parameters (on the server side) or the return value (on the client side). * <li> if a <code>java.lang.ClassNotFoundException</code> occurs during * unmarshalling parameters or return values * <li> if no skeleton can be loaded on the server-side; note that skeletons * are required in the 1.1 stub protocol, but not in the 1.2 stub protocol. * <li> if the method hash is invalid (i.e., missing method). * <li> if there is a failure to create a remote reference object for * a remote object's stub when it is unmarshalled. * </ul> * * @author Ann Wollrath * @since JDK1.1 */ public class UnmarshalException extends RemoteException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = 594380845140740218L; /** {@collect.stats} * Constructs an <code>UnmarshalException</code> with the specified * detail message. * * @param s the detail message * @since JDK1.1 */ public UnmarshalException(String s) { super(s); } /** {@collect.stats} * Constructs an <code>UnmarshalException</code> with the specified * detail message and nested exception. * * @param s the detail message * @param ex the nested exception * @since JDK1.1 */ public UnmarshalException(String s, Exception ex) { super(s, ex); } }
Java
/* * Copyright (c) 1996, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * A <code>ServerError</code> is thrown as a result of a remote method * invocation when an <code>Error</code> is thrown while processing * the invocation on the server, either while unmarshalling the arguments, * executing the remote method itself, or marshalling the return value. * * A <code>ServerError</code> instance contains the original * <code>Error</code> that occurred as its cause. * * @author Ann Wollrath * @since JDK1.1 */ public class ServerError extends RemoteException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = 8455284893909696482L; /** {@collect.stats} * Constructs a <code>ServerError</code> with the specified * detail message and nested error. * * @param s the detail message * @param err the nested error * @since JDK1.1 */ public ServerError(String s, Error err) { super(s, err); } }
Java
/* * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; import java.rmi.registry.*; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; /** {@collect.stats} * The <code>Naming</code> class provides methods for storing and obtaining * references to remote objects in a remote object registry. Each method of * the <code>Naming</code> class takes as one of its arguments a name that * is a <code>java.lang.String</code> in URL format (without the * scheme component) of the form: * * <PRE> * //host:port/name * </PRE> * * <P>where <code>host</code> is the host (remote or local) where the registry * is located, <code>port</code> is the port number on which the registry * accepts calls, and where <code>name</code> is a simple string uninterpreted * by the registry. Both <code>host</code> and <code>port</code> are optional. * If <code>host</code> is omitted, the host defaults to the local host. If * <code>port</code> is omitted, then the port defaults to 1099, the * "well-known" port that RMI's registry, <code>rmiregistry</code>, uses. * * <P><em>Binding</em> a name for a remote object is associating or * registering a name for a remote object that can be used at a later time to * look up that remote object. A remote object can be associated with a name * using the <code>Naming</code> class's <code>bind</code> or * <code>rebind</code> methods. * * <P>Once a remote object is registered (bound) with the RMI registry on the * local host, callers on a remote (or local) host can lookup the remote * object by name, obtain its reference, and then invoke remote methods on the * object. A registry may be shared by all servers running on a host or an * individual server process may create and use its own registry if desired * (see <code>java.rmi.registry.LocateRegistry.createRegistry</code> method * for details). * * @author Ann Wollrath * @author Roger Riggs * @since JDK1.1 * @see java.rmi.registry.Registry * @see java.rmi.registry.LocateRegistry * @see java.rmi.registry.LocateRegistry#createRegistry(int) */ public final class Naming { /** {@collect.stats} * Disallow anyone from creating one of these */ private Naming() {} /** {@collect.stats} * Returns a reference, a stub, for the remote object associated * with the specified <code>name</code>. * * @param name a name in URL format (without the scheme component) * @return a reference for a remote object * @exception NotBoundException if name is not currently bound * @exception RemoteException if registry could not be contacted * @exception AccessException if this operation is not permitted * @exception MalformedURLException if the name is not an appropriately * formatted URL * @since JDK1.1 */ public static Remote lookup(String name) throws NotBoundException, java.net.MalformedURLException, RemoteException { ParsedNamingURL parsed = parseURL(name); Registry registry = getRegistry(parsed); if (parsed.name == null) return registry; return registry.lookup(parsed.name); } /** {@collect.stats} * Binds the specified <code>name</code> to a remote object. * * @param name a name in URL format (without the scheme component) * @param obj a reference for the remote object (usually a stub) * @exception AlreadyBoundException if name is already bound * @exception MalformedURLException if the name is not an appropriately * formatted URL * @exception RemoteException if registry could not be contacted * @exception AccessException if this operation is not permitted (if * originating from a non-local host, for example) * @since JDK1.1 */ public static void bind(String name, Remote obj) throws AlreadyBoundException, java.net.MalformedURLException, RemoteException { ParsedNamingURL parsed = parseURL(name); Registry registry = getRegistry(parsed); if (obj == null) throw new NullPointerException("cannot bind to null"); registry.bind(parsed.name, obj); } /** {@collect.stats} * Destroys the binding for the specified name that is associated * with a remote object. * * @param name a name in URL format (without the scheme component) * @exception NotBoundException if name is not currently bound * @exception MalformedURLException if the name is not an appropriately * formatted URL * @exception RemoteException if registry could not be contacted * @exception AccessException if this operation is not permitted (if * originating from a non-local host, for example) * @since JDK1.1 */ public static void unbind(String name) throws RemoteException, NotBoundException, java.net.MalformedURLException { ParsedNamingURL parsed = parseURL(name); Registry registry = getRegistry(parsed); registry.unbind(parsed.name); } /** {@collect.stats} * Rebinds the specified name to a new remote object. Any existing * binding for the name is replaced. * * @param name a name in URL format (without the scheme component) * @param obj new remote object to associate with the name * @exception MalformedURLException if the name is not an appropriately * formatted URL * @exception RemoteException if registry could not be contacted * @exception AccessException if this operation is not permitted (if * originating from a non-local host, for example) * @since JDK1.1 */ public static void rebind(String name, Remote obj) throws RemoteException, java.net.MalformedURLException { ParsedNamingURL parsed = parseURL(name); Registry registry = getRegistry(parsed); if (obj == null) throw new NullPointerException("cannot bind to null"); registry.rebind(parsed.name, obj); } /** {@collect.stats} * Returns an array of the names bound in the registry. The names are * URL-formatted (without the scheme component) strings. The array contains * a snapshot of the names present in the registry at the time of the * call. * * @param name a registry name in URL format (without the scheme * component) * @return an array of names (in the appropriate format) bound * in the registry * @exception MalformedURLException if the name is not an appropriately * formatted URL * @exception RemoteException if registry could not be contacted. * @since JDK1.1 */ public static String[] list(String name) throws RemoteException, java.net.MalformedURLException { ParsedNamingURL parsed = parseURL(name); Registry registry = getRegistry(parsed); String prefix = ""; if (parsed.port > 0 || !parsed.host.equals("")) prefix += "//" + parsed.host; if (parsed.port > 0) prefix += ":" + parsed.port; prefix += "/"; String[] names = registry.list(); for (int i = 0; i < names.length; i++) { names[i] = prefix + names[i]; } return names; } /** {@collect.stats} * Returns a registry reference obtained from information in the URL. */ private static Registry getRegistry(ParsedNamingURL parsed) throws RemoteException { return LocateRegistry.getRegistry(parsed.host, parsed.port); } /** {@collect.stats} * Dissect Naming URL strings to obtain referenced host, port and * object name. * * @return an object which contains each of the above * components. * * @exception MalformedURLException if given url string is malformed */ private static ParsedNamingURL parseURL(String str) throws MalformedURLException { try { return intParseURL(str); } catch (URISyntaxException ex) { /* With RFC 3986 URI handling, 'rmi://:<port>' and * '//:<port>' forms will result in a URI syntax exception * Convert the authority to a localhost:<port> form */ MalformedURLException mue = new MalformedURLException( "invalid URL String: " + str); mue.initCause(ex); int indexSchemeEnd = str.indexOf(':'); int indexAuthorityBegin = str.indexOf("//:"); if (indexAuthorityBegin < 0) { throw mue; } if ((indexAuthorityBegin == 0) || ((indexSchemeEnd > 0) && (indexAuthorityBegin == indexSchemeEnd + 1))) { int indexHostBegin = indexAuthorityBegin + 2; String newStr = str.substring(0, indexHostBegin) + "localhost" + str.substring(indexHostBegin); try { return intParseURL(newStr); } catch (URISyntaxException inte) { throw mue; } catch (MalformedURLException inte) { throw inte; } } throw mue; } } private static ParsedNamingURL intParseURL(String str) throws MalformedURLException, URISyntaxException { URI uri = new URI(str); if (uri.isOpaque()) { throw new MalformedURLException( "not a hierarchical URL: " + str); } if (uri.getFragment() != null) { throw new MalformedURLException( "invalid character, '#', in URL name: " + str); } else if (uri.getQuery() != null) { throw new MalformedURLException( "invalid character, '?', in URL name: " + str); } else if (uri.getUserInfo() != null) { throw new MalformedURLException( "invalid character, '@', in URL host: " + str); } String scheme = uri.getScheme(); if (scheme != null && !scheme.equals("rmi")) { throw new MalformedURLException("invalid URL scheme: " + str); } String name = uri.getPath(); if (name != null) { if (name.startsWith("/")) { name = name.substring(1); } if (name.length() == 0) { name = null; } } String host = uri.getHost(); if (host == null) { host = ""; try { /* * With 2396 URI handling, forms such as 'rmi://host:bar' * or 'rmi://:<port>' are parsed into a registry based * authority. We only want to allow server based naming * authorities. */ uri.parseServerAuthority(); } catch (URISyntaxException use) { // Check if the authority is of form ':<port>' String authority = uri.getAuthority(); if (authority != null && authority.startsWith(":")) { // Convert the authority to 'localhost:<port>' form authority = "localhost" + authority; try { uri = new URI(null, authority, null, null, null); // Make sure it now parses to a valid server based // naming authority uri.parseServerAuthority(); } catch (URISyntaxException use2) { throw new MalformedURLException("invalid authority: " + str); } } else { throw new MalformedURLException("invalid authority: " + str); } } } int port = uri.getPort(); if (port == -1) { port = Registry.REGISTRY_PORT; } return new ParsedNamingURL(host, port, name); } /** {@collect.stats} * Simple class to enable multiple URL return values. */ private static class ParsedNamingURL { String host; int port; String name; ParsedNamingURL(String host, int port, String name) { this.host = host; this.port = port; this.name = name; } } }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * A <code>MarshalException</code> is thrown if a * <code>java.io.IOException</code> occurs while marshalling the remote call * header, arguments or return value for a remote method call. A * <code>MarshalException</code> is also thrown if the receiver does not * support the protocol version of the sender. * * <p>If a <code>MarshalException</code> occurs during a remote method call, * the call may or may not have reached the server. If the call did reach the * server, parameters may have been deserialized. A call may not be * retransmitted after a <code>MarshalException</code> and reliably preserve * "at most once" call semantics. * * @author Ann Wollrath * @since JDK1.1 */ public class MarshalException extends RemoteException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = 6223554758134037936L; /** {@collect.stats} * Constructs a <code>MarshalException</code> with the specified * detail message. * * @param s the detail message * @since JDK1.1 */ public MarshalException(String s) { super(s); } /** {@collect.stats} * Constructs a <code>MarshalException</code> with the specified * detail message and nested exception. * * @param s the detail message * @param ex the nested exception * @since JDK1.1 */ public MarshalException(String s, Exception ex) { super(s, ex); } }
Java
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * From a server executing on JDK&nbsp;1.1, a * <code>ServerRuntimeException</code> is thrown as a result of a * remote method invocation when a <code>RuntimeException</code> is * thrown while processing the invocation on the server, either while * unmarshalling the arguments, executing the remote method itself, or * marshalling the return value. * * A <code>ServerRuntimeException</code> instance contains the original * <code>RuntimeException</code> that occurred as its cause. * * <p>A <code>ServerRuntimeException</code> is not thrown from servers * executing on the Java 2 platform v1.2 or later versions. * * @author Ann Wollrath * @since JDK1.1 * @deprecated no replacement */ @Deprecated public class ServerRuntimeException extends RemoteException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = 7054464920481467219L; /** {@collect.stats} * Constructs a <code>ServerRuntimeException</code> with the specified * detail message and nested exception. * * @param s the detail message * @param ex the nested exception * @deprecated no replacement * @since JDK1.1 */ @Deprecated public ServerRuntimeException(String s, Exception ex) { super(s, ex); } }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * The <code>Remote</code> interface serves to identify interfaces whose * methods may be invoked from a non-local virtual machine. Any object that * is a remote object must directly or indirectly implement this interface. * Only those methods specified in a "remote interface", an interface that * extends <code>java.rmi.Remote</code> are available remotely. * * <p>Implementation classes can implement any number of remote interfaces and * can extend other remote implementation classes. RMI provides some * convenience classes that remote object implementations can extend which * facilitate remote object creation. These classes are * <code>java.rmi.server.UnicastRemoteObject</code> and * <code>java.rmi.activation.Activatable</code>. * * <p>For complete details on RMI, see the <a href=../../../platform/rmi/spec/rmiTOC.html>RMI Specification</a> which describes the RMI API and system. * * @since JDK1.1 * @author Ann Wollrath * @see java.rmi.server.UnicastRemoteObject * @see java.rmi.activation.Activatable */ public interface Remote {}
Java
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.rmi.Remote; /** {@collect.stats} * The <code>Skeleton</code> interface is used solely by the RMI * implementation. * * <p> Every version 1.1 (and version 1.1 compatible skeletons generated in * 1.2 using <code>rmic -vcompat</code>) skeleton class generated by the rmic * stub compiler implements this interface. A skeleton for a remote object is * a server-side entity that dispatches calls to the actual remote object * implementation. * * @author Ann Wollrath * @since JDK1.1 * @deprecated no replacement. Skeletons are no longer required for remote * method calls in the Java 2 platform v1.2 and greater. */ @Deprecated public interface Skeleton { /** {@collect.stats} * Unmarshals arguments, calls the actual remote object implementation, * and marshals the return value or any exception. * * @param obj remote implementation to dispatch call to * @param theCall object representing remote call * @param opnum operation number * @param hash stub/skeleton interface hash * @exception java.lang.Exception if a general exception occurs. * @since JDK1.1 * @deprecated no replacement */ @Deprecated void dispatch(Remote obj, RemoteCall theCall, int opnum, long hash) throws Exception; /** {@collect.stats} * Returns the operations supported by the skeleton. * @return operations supported by skeleton * @since JDK1.1 * @deprecated no replacement */ @Deprecated Operation[] getOperations(); }
Java
/* * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; /** {@collect.stats} * An obsolete subclass of {@link ExportException}. * * @author Ann Wollrath * @since JDK1.1 **/ public class SocketSecurityException extends ExportException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -7622072999407781979L; /** {@collect.stats} * Constructs an <code>SocketSecurityException</code> with the specified * detail message. * * @param s the detail message. * @since JDK1.1 */ public SocketSecurityException(String s) { super(s); } /** {@collect.stats} * Constructs an <code>SocketSecurityException</code> with the specified * detail message and nested exception. * * @param s the detail message. * @param ex the nested exception * @since JDK1.1 */ public SocketSecurityException(String s, Exception ex) { super(s, ex); } }
Java
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.rmi.*; /** {@collect.stats} * <code>RemoteRef</code> represents the handle for a remote object. A * <code>RemoteStub</code> uses a remote reference to carry out a * remote method invocation to a remote object. * * @author Ann Wollrath * @since JDK1.1 * @see java.rmi.server.RemoteStub */ public interface RemoteRef extends java.io.Externalizable { /** {@collect.stats} indicate compatibility with JDK 1.1.x version of class. */ static final long serialVersionUID = 3632638527362204081L; /** {@collect.stats} * Initialize the server package prefix: assumes that the * implementation of server ref classes (e.g., UnicastRef, * UnicastServerRef) are located in the package defined by the * prefix. */ final static String packagePrefix = "sun.rmi.server"; /** {@collect.stats} * Invoke a method. This form of delegating method invocation * to the reference allows the reference to take care of * setting up the connection to the remote host, marshaling * some representation for the method and parameters, then * communicating the method invocation to the remote host. * This method either returns the result of a method invocation * on the remote object which resides on the remote host or * throws a RemoteException if the call failed or an * application-level exception if the remote invocation throws * an exception. * * @param obj the object that contains the RemoteRef (e.g., the * RemoteStub for the object. * @param method the method to be invoked * @param params the parameter list * @param opnum a hash that may be used to represent the method * @return result of remote method invocation * @exception Exception if any exception occurs during remote method * invocation * @since 1.2 */ Object invoke(Remote obj, java.lang.reflect.Method method, Object[] params, long opnum) throws Exception; /** {@collect.stats} * Creates an appropriate call object for a new remote method * invocation on this object. Passing operation array and index, * allows the stubs generator to assign the operation indexes and * interpret them. The remote reference may need the operation to * encode in the call. * * @since JDK1.1 * @deprecated 1.2 style stubs no longer use this method. Instead of * using a sequence of method calls on the stub's the remote reference * (<code>newCall</code>, <code>invoke</code>, and <code>done</code>), a * stub uses a single method, <code>invoke(Remote, Method, Object[], * int)</code>, on the remote reference to carry out parameter * marshalling, remote method executing and unmarshalling of the return * value. * * @param obj remote stub through which to make call * @param op array of stub operations * @param opnum operation number * @param hash stub/skeleton interface hash * @return call object representing remote call * @throws RemoteException if failed to initiate new remote call * @see #invoke(Remote,java.lang.reflect.Method,Object[],long) */ @Deprecated RemoteCall newCall(RemoteObject obj, Operation[] op, int opnum, long hash) throws RemoteException; /** {@collect.stats} * Executes the remote call. * * Invoke will raise any "user" exceptions which * should pass through and not be caught by the stub. If any * exception is raised during the remote invocation, invoke should * take care of cleaning up the connection before raising the * "user" or remote exception. * * @since JDK1.1 * @deprecated 1.2 style stubs no longer use this method. Instead of * using a sequence of method calls to the remote reference * (<code>newCall</code>, <code>invoke</code>, and <code>done</code>), a * stub uses a single method, <code>invoke(Remote, Method, Object[], * int)</code>, on the remote reference to carry out parameter * marshalling, remote method executing and unmarshalling of the return * value. * * @param call object representing remote call * @throws Exception if any exception occurs during remote method * @see #invoke(Remote,java.lang.reflect.Method,Object[],long) */ @Deprecated void invoke(RemoteCall call) throws Exception; /** {@collect.stats} * Allows the remote reference to clean up (or reuse) the connection. * Done should only be called if the invoke returns successfully * (non-exceptionally) to the stub. * * @since JDK1.1 * @deprecated 1.2 style stubs no longer use this method. Instead of * using a sequence of method calls to the remote reference * (<code>newCall</code>, <code>invoke</code>, and <code>done</code>), a * stub uses a single method, <code>invoke(Remote, Method, Object[], * int)</code>, on the remote reference to carry out parameter * marshalling, remote method executing and unmarshalling of the return * value. * * @param call object representing remote call * @throws RemoteException if remote error occurs during call cleanup * @see #invoke(Remote,java.lang.reflect.Method,Object[],long) */ @Deprecated void done(RemoteCall call) throws RemoteException; /** {@collect.stats} * Returns the class name of the ref type to be serialized onto * the stream 'out'. * @param out the output stream to which the reference will be serialized * @return the class name (without package qualification) of the reference * type * @since JDK1.1 */ String getRefClass(java.io.ObjectOutput out); /** {@collect.stats} * Returns a hashcode for a remote object. Two remote object stubs * that refer to the same remote object will have the same hash code * (in order to support remote objects as keys in hash tables). * * @return remote object hashcode * @see java.util.Hashtable * @since JDK1.1 */ int remoteHashCode(); /** {@collect.stats} * Compares two remote objects for equality. * Returns a boolean that indicates whether this remote object is * equivalent to the specified Object. This method is used when a * remote object is stored in a hashtable. * @param obj the Object to compare with * @return true if these Objects are equal; false otherwise. * @see java.util.Hashtable * @since JDK1.1 */ boolean remoteEquals(RemoteRef obj); /** {@collect.stats} * Returns a String that represents the reference of this remote * object. * @return string representing remote object reference * @since JDK1.1 */ String remoteToString(); }
Java
/* * Copyright (c) 1996, 2002, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.io.*; import java.net.*; /** {@collect.stats} * An <code>RMISocketFactory</code> instance is used by the RMI runtime * in order to obtain client and server sockets for RMI calls. An * application may use the <code>setSocketFactory</code> method to * request that the RMI runtime use its socket factory instance * instead of the default implementation.<p> * * The default socket factory implementation used goes through a * three-tiered approach to creating client sockets. First, a direct * socket connection to the remote VM is attempted. If that fails * (due to a firewall), the runtime uses HTTP with the explicit port * number of the server. If the firewall does not allow this type of * communication, then HTTP to a cgi-bin script on the server is used * to POST the RMI call.<p> * * @author Ann Wollrath * @author Peter Jones * @since JDK1.1 */ public abstract class RMISocketFactory implements RMIClientSocketFactory, RMIServerSocketFactory { /** {@collect.stats} Client/server socket factory to be used by RMI runtime */ private static RMISocketFactory factory = null; /** {@collect.stats} default socket factory used by this RMI implementation */ private static RMISocketFactory defaultSocketFactory; /** {@collect.stats} Handler for socket creation failure */ private static RMIFailureHandler handler = null; /** {@collect.stats} * Constructs an <code>RMISocketFactory</code>. * @since JDK1.1 */ public RMISocketFactory() { super(); } /** {@collect.stats} * Creates a client socket connected to the specified host and port. * @param host the host name * @param port the port number * @return a socket connected to the specified host and port. * @exception IOException if an I/O error occurs during socket creation * @since JDK1.1 */ public abstract Socket createSocket(String host, int port) throws IOException; /** {@collect.stats} * Create a server socket on the specified port (port 0 indicates * an anonymous port). * @param port the port number * @return the server socket on the specified port * @exception IOException if an I/O error occurs during server socket * creation * @since JDK1.1 */ public abstract ServerSocket createServerSocket(int port) throws IOException; /** {@collect.stats} * Set the global socket factory from which RMI gets sockets (if the * remote object is not associated with a specific client and/or server * socket factory). The RMI socket factory can only be set once. Note: The * RMISocketFactory may only be set if the current security manager allows * setting a socket factory; if disallowed, a SecurityException will be * thrown. * @param fac the socket factory * @exception IOException if the RMI socket factory is already set * @exception SecurityException if a security manager exists and its * <code>checkSetFactory</code> method doesn't allow the operation. * @see #getSocketFactory * @see java.lang.SecurityManager#checkSetFactory() * @since JDK1.1 */ public synchronized static void setSocketFactory(RMISocketFactory fac) throws IOException { if (factory != null) { throw new SocketException("factory already defined"); } SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkSetFactory(); } factory = fac; } /** {@collect.stats} * Returns the socket factory set by the <code>setSocketFactory</code> * method. Returns <code>null</code> if no socket factory has been * set. * @return the socket factory * @see #setSocketFactory(RMISocketFactory) * @since JDK1.1 */ public synchronized static RMISocketFactory getSocketFactory() { return factory; } /** {@collect.stats} * Returns a reference to the default socket factory used * by this RMI implementation. This will be the factory used * by the RMI runtime when <code>getSocketFactory</code> * returns <code>null</code>. * @return the default RMI socket factory * @since JDK1.1 */ public synchronized static RMISocketFactory getDefaultSocketFactory() { if (defaultSocketFactory == null) { defaultSocketFactory = new sun.rmi.transport.proxy.RMIMasterSocketFactory(); } return defaultSocketFactory; } /** {@collect.stats} * Sets the failure handler to be called by the RMI runtime if server * socket creation fails. By default, if no failure handler is installed * and server socket creation fails, the RMI runtime does attempt to * recreate the server socket. * * <p>If there is a security manager, this method first calls * the security manager's <code>checkSetFactory</code> method * to ensure the operation is allowed. * This could result in a <code>SecurityException</code>. * * @param fh the failure handler * @throws SecurityException if a security manager exists and its * <code>checkSetFactory</code> method doesn't allow the * operation. * @see #getFailureHandler * @see java.rmi.server.RMIFailureHandler#failure(Exception) * @since JDK1.1 */ public synchronized static void setFailureHandler(RMIFailureHandler fh) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkSetFactory(); } handler = fh; } /** {@collect.stats} * Returns the handler for socket creation failure set by the * <code>setFailureHandler</code> method. * @return the failure handler * @see #setFailureHandler(RMIFailureHandler) * @since JDK1.1 */ public synchronized static RMIFailureHandler getFailureHandler() { return handler; } }
Java
/* * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.io.*; import java.net.*; /** {@collect.stats} * An <code>RMIServerSocketFactory</code> instance is used by the RMI runtime * in order to obtain server sockets for RMI calls. A remote object can be * associated with an <code>RMIServerSocketFactory</code> when it is * created/exported via the constructors or <code>exportObject</code> methods * of <code>java.rmi.server.UnicastRemoteObject</code> and * <code>java.rmi.activation.Activatable</code> . * * <p>An <code>RMIServerSocketFactory</code> instance associated with a remote * object is used to obtain the <code>ServerSocket</code> used to accept * incoming calls from clients. * * <p>An <code>RMIServerSocketFactory</code> instance can also be associated * with a remote object registry so that clients can use custom socket * communication with a remote object registry. * * <p>An implementation of this interface * should implement {@link Object#equals} to return <code>true</code> when * passed an instance that represents the same (functionally equivalent) * server socket factory, and <code>false</code> otherwise (and it should also * implement {@link Object#hashCode} consistently with its * <code>Object.equals</code> implementation). * * @author Ann Wollrath * @author Peter Jones * @since 1.2 * @see java.rmi.server.UnicastRemoteObject * @see java.rmi.activation.Activatable * @see java.rmi.registry.LocateRegistry */ public interface RMIServerSocketFactory { /** {@collect.stats} * Create a server socket on the specified port (port 0 indicates * an anonymous port). * @param port the port number * @return the server socket on the specified port * @exception IOException if an I/O error occurs during server socket * creation * @since 1.2 */ public ServerSocket createServerSocket(int port) throws IOException; }
Java
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.net.MalformedURLException; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Iterator; import java.util.ServiceLoader; /** {@collect.stats} * <code>RMIClassLoader</code> comprises static methods to support * dynamic class loading with RMI. Included are methods for loading * classes from a network location (one or more URLs) and obtaining * the location from which an existing class should be loaded by * remote parties. These methods are used by the RMI runtime when * marshalling and unmarshalling classes contained in the arguments * and return values of remote method calls, and they also may be * invoked directly by applications in order to mimic RMI's dynamic * class loading behavior. * * <p>The implementation of the following static methods * * <ul> * * <li>{@link #loadClass(URL,String)} * <li>{@link #loadClass(String,String)} * <li>{@link #loadClass(String,String,ClassLoader)} * <li>{@link #loadProxyClass(String,String[],ClassLoader)} * <li>{@link #getClassLoader(String)} * <li>{@link #getClassAnnotation(Class)} * * </ul> * * is provided by an instance of {@link RMIClassLoaderSpi}, the * service provider interface for those methods. When one of the * methods is invoked, its behavior is to delegate to a corresponding * method on the service provider instance. The details of how each * method delegates to the provider instance is described in the * documentation for each particular method. * * <p>The service provider instance is chosen as follows: * * <ul> * * <li>If the system property * <code>java.rmi.server.RMIClassLoaderSpi</code> is defined, then if * its value equals the string <code>"default"</code>, the provider * instance will be the value returned by an invocation of the {@link * #getDefaultProviderInstance()} method, and for any other value, if * a class named with the value of the property can be loaded by the * system class loader (see {@link ClassLoader#getSystemClassLoader}) * and that class is assignable to {@link RMIClassLoaderSpi} and has a * public no-argument constructor, then that constructor will be * invoked to create the provider instance. If the property is * defined but any other of those conditions are not true, then an * unspecified <code>Error</code> will be thrown to code that attempts * to use <code>RMIClassLoader</code>, indicating the failure to * obtain a provider instance. * * <li>If a resource named * <code>META-INF/services/java.rmi.server.RMIClassLoaderSpi</code> is * visible to the system class loader, then the contents of that * resource are interpreted as a provider-configuration file, and the * first class name specified in that file is used as the provider * class name. If a class with that name can be loaded by the system * class loader and that class is assignable to {@link * RMIClassLoaderSpi} and has a public no-argument constructor, then * that constructor will be invoked to create the provider instance. * If the resource is found but a provider cannot be instantiated as * described, then an unspecified <code>Error</code> will be thrown to * code that attempts to use <code>RMIClassLoader</code>, indicating * the failure to obtain a provider instance. * * <li>Otherwise, the provider instance will be the value returned by * an invocation of the {@link #getDefaultProviderInstance()} method. * * </ul> * * @author Ann Wollrath * @author Peter Jones * @author Laird Dornin * @see RMIClassLoaderSpi * @since JDK1.1 */ public class RMIClassLoader { /** {@collect.stats} "default" provider instance */ private static final RMIClassLoaderSpi defaultProvider = newDefaultProviderInstance(); /** {@collect.stats} provider instance */ private static final RMIClassLoaderSpi provider = AccessController.doPrivileged( new PrivilegedAction<RMIClassLoaderSpi>() { public RMIClassLoaderSpi run() { return initializeProvider(); } }); /* * Disallow anyone from creating one of these. */ private RMIClassLoader() {} /** {@collect.stats} * Loads the class with the specified <code>name</code>. * * <p>This method delegates to {@link #loadClass(String,String)}, * passing <code>null</code> as the first argument and * <code>name</code> as the second argument. * * @param name the name of the class to load * * @return the <code>Class</code> object representing the loaded class * * @throws MalformedURLException if a provider-specific URL used * to load classes is invalid * * @throws ClassNotFoundException if a definition for the class * could not be found at the codebase location * * @deprecated replaced by <code>loadClass(String,String)</code> method * @see #loadClass(String,String) */ @Deprecated public static Class<?> loadClass(String name) throws MalformedURLException, ClassNotFoundException { return loadClass((String) null, name); } /** {@collect.stats} * Loads a class from a codebase URL. * * If <code>codebase</code> is <code>null</code>, then this method * will behave the same as {@link #loadClass(String,String)} with a * <code>null</code> <code>codebase</code> and the given class name. * * <p>This method delegates to the * {@link RMIClassLoaderSpi#loadClass(String,String,ClassLoader)} * method of the provider instance, passing the result of invoking * {@link URL#toString} on the given URL (or <code>null</code> if * <code>codebase</code> is null) as the first argument, * <code>name</code> as the second argument, * and <code>null</code> as the third argument. * * @param codebase the URL to load the class from, or <code>null</code> * * @param name the name of the class to load * * @return the <code>Class</code> object representing the loaded class * * @throws MalformedURLException if <code>codebase</code> is * <code>null</code> and a provider-specific URL used * to load classes is invalid * * @throws ClassNotFoundException if a definition for the class * could not be found at the specified URL */ public static Class<?> loadClass(URL codebase, String name) throws MalformedURLException, ClassNotFoundException { return provider.loadClass( codebase != null ? codebase.toString() : null, name, null); } /** {@collect.stats} * Loads a class from a codebase URL path. * * <p>This method delegates to the * {@link RMIClassLoaderSpi#loadClass(String,String,ClassLoader)} * method of the provider instance, passing <code>codebase</code> * as the first argument, <code>name</code> as the second argument, * and <code>null</code> as the third argument. * * @param codebase the list of URLs (separated by spaces) to load * the class from, or <code>null</code> * * @param name the name of the class to load * * @return the <code>Class</code> object representing the loaded class * * @throws MalformedURLException if <code>codebase</code> is * non-<code>null</code> and contains an invalid URL, or if * <code>codebase</code> is <code>null</code> and a provider-specific * URL used to load classes is invalid * * @throws ClassNotFoundException if a definition for the class * could not be found at the specified location * * @since 1.2 */ public static Class<?> loadClass(String codebase, String name) throws MalformedURLException, ClassNotFoundException { return provider.loadClass(codebase, name, null); } /** {@collect.stats} * Loads a class from a codebase URL path, optionally using the * supplied loader. * * This method should be used when the caller would like to make * available to the provider implementation an additional contextual * class loader to consider, such as the loader of a caller on the * stack. Typically, a provider implementation will attempt to * resolve the named class using the given <code>defaultLoader</code>, * if specified, before attempting to resolve the class from the * codebase URL path. * * <p>This method delegates to the * {@link RMIClassLoaderSpi#loadClass(String,String,ClassLoader)} * method of the provider instance, passing <code>codebase</code> * as the first argument, <code>name</code> as the second argument, * and <code>defaultLoader</code> as the third argument. * * @param codebase the list of URLs (separated by spaces) to load * the class from, or <code>null</code> * * @param name the name of the class to load * * @param defaultLoader additional contextual class loader * to use, or <code>null</code> * * @return the <code>Class</code> object representing the loaded class * * @throws MalformedURLException if <code>codebase</code> is * non-<code>null</code> and contains an invalid URL, or if * <code>codebase</code> is <code>null</code> and a provider-specific * URL used to load classes is invalid * * @throws ClassNotFoundException if a definition for the class * could not be found at the specified location * * @since 1.4 */ public static Class<?> loadClass(String codebase, String name, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException { return provider.loadClass(codebase, name, defaultLoader); } /** {@collect.stats} * Loads a dynamic proxy class (see {@link java.lang.reflect.Proxy}) * that implements a set of interfaces with the given names * from a codebase URL path. * * <p>The interfaces will be resolved similar to classes loaded via * the {@link #loadClass(String,String)} method using the given * <code>codebase</code>. * * <p>This method delegates to the * {@link RMIClassLoaderSpi#loadProxyClass(String,String[],ClassLoader)} * method of the provider instance, passing <code>codebase</code> * as the first argument, <code>interfaces</code> as the second argument, * and <code>defaultLoader</code> as the third argument. * * @param codebase the list of URLs (space-separated) to load * classes from, or <code>null</code> * * @param interfaces the names of the interfaces for the proxy class * to implement * * @param defaultLoader additional contextual class loader * to use, or <code>null</code> * * @return a dynamic proxy class that implements the named interfaces * * @throws MalformedURLException if <code>codebase</code> is * non-<code>null</code> and contains an invalid URL, or * if <code>codebase</code> is <code>null</code> and a provider-specific * URL used to load classes is invalid * * @throws ClassNotFoundException if a definition for one of * the named interfaces could not be found at the specified location, * or if creation of the dynamic proxy class failed (such as if * {@link java.lang.reflect.Proxy#getProxyClass(ClassLoader,Class[])} * would throw an <code>IllegalArgumentException</code> for the given * interface list) * * @since 1.4 */ public static Class<?> loadProxyClass(String codebase, String[] interfaces, ClassLoader defaultLoader) throws ClassNotFoundException, MalformedURLException { return provider.loadProxyClass(codebase, interfaces, defaultLoader); } /** {@collect.stats} * Returns a class loader that loads classes from the given codebase * URL path. * * <p>The class loader returned is the class loader that the * {@link #loadClass(String,String)} method would use to load classes * for the same <code>codebase</code> argument. * * <p>This method delegates to the * {@link RMIClassLoaderSpi#getClassLoader(String)} method * of the provider instance, passing <code>codebase</code> as the argument. * * <p>If there is a security manger, its <code>checkPermission</code> * method will be invoked with a * <code>RuntimePermission("getClassLoader")</code> permission; * this could result in a <code>SecurityException</code>. * The provider implementation of this method may also perform further * security checks to verify that the calling context has permission to * connect to all of the URLs in the codebase URL path. * * @param codebase the list of URLs (space-separated) from which * the returned class loader will load classes from, or <code>null</code> * * @return a class loader that loads classes from the given codebase URL * path * * @throws MalformedURLException if <code>codebase</code> is * non-<code>null</code> and contains an invalid URL, or * if <code>codebase</code> is <code>null</code> and a provider-specific * URL used to identify the class loader is invalid * * @throws SecurityException if there is a security manager and the * invocation of its <code>checkPermission</code> method fails, or * if the caller does not have permission to connect to all of the * URLs in the codebase URL path * * @since 1.3 */ public static ClassLoader getClassLoader(String codebase) throws MalformedURLException, SecurityException { return provider.getClassLoader(codebase); } /** {@collect.stats} * Returns the annotation string (representing a location for * the class definition) that RMI will use to annotate the class * descriptor when marshalling objects of the given class. * * <p>This method delegates to the * {@link RMIClassLoaderSpi#getClassAnnotation(Class)} method * of the provider instance, passing <code>cl</code> as the argument. * * @param cl the class to obtain the annotation for * * @return a string to be used to annotate the given class when * it gets marshalled, or <code>null</code> * * @throws NullPointerException if <code>cl</code> is <code>null</code> * * @since 1.2 */ /* * REMIND: Should we say that the returned class annotation will or * should be a (space-separated) list of URLs? */ public static String getClassAnnotation(Class<?> cl) { return provider.getClassAnnotation(cl); } /** {@collect.stats} * Returns the canonical instance of the default provider * for the service provider interface {@link RMIClassLoaderSpi}. * If the system property <code>java.rmi.server.RMIClassLoaderSpi</code> * is not defined, then the <code>RMIClassLoader</code> static * methods * * <ul> * * <li>{@link #loadClass(URL,String)} * <li>{@link #loadClass(String,String)} * <li>{@link #loadClass(String,String,ClassLoader)} * <li>{@link #loadProxyClass(String,String[],ClassLoader)} * <li>{@link #getClassLoader(String)} * <li>{@link #getClassAnnotation(Class)} * * </ul> * * will use the canonical instance of the default provider * as the service provider instance. * * <p>If there is a security manager, its * <code>checkPermission</code> method will be invoked with a * <code>RuntimePermission("setFactory")</code> permission; this * could result in a <code>SecurityException</code>. * * <p>The default service provider instance implements * {@link RMIClassLoaderSpi} as follows: * * <blockquote> * * <p>The <b>{@link RMIClassLoaderSpi#getClassAnnotation(Class) * getClassAnnotation}</b> method returns a <code>String</code> * representing the codebase URL path that a remote party should * use to download the definition for the specified class. The * format of the returned string is a path of URLs separated by * spaces. * * The codebase string returned depends on the defining class * loader of the specified class: * * <ul> * * <p><li>If the class loader is the system class loader (see * {@link ClassLoader#getSystemClassLoader}), a parent of the * system class loader such as the loader used for installed * extensions, or the bootstrap class loader (which may be * represented by <code>null</code>), then the value of the * <code>java.rmi.server.codebase</code> property (or possibly an * earlier cached value) is returned, or * <code>null</code> is returned if that property is not set. * * <p><li>Otherwise, if the class loader is an instance of * <code>URLClassLoader</code>, then the returned string is a * space-separated list of the external forms of the URLs returned * by invoking the <code>getURLs</code> methods of the loader. If * the <code>URLClassLoader</code> was created by this provider to * service an invocation of its <code>loadClass</code> or * <code>loadProxyClass</code> methods, then no permissions are * required to get the associated codebase string. If it is an * arbitrary other <code>URLClassLoader</code> instance, then if * there is a security manager, its <code>checkPermission</code> * method will be invoked once for each URL returned by the * <code>getURLs</code> method, with the permission returned by * invoking <code>openConnection().getPermission()</code> on each * URL; if any of those invocations throws a * <code>SecurityException</code> or an <code>IOException</code>, * then the value of the <code>java.rmi.server.codebase</code> * property (or possibly an earlier cached value) is returned, or * <code>null</code> is returned if that property is not set. * * <p><li>Finally, if the class loader is not an instance of * <code>URLClassLoader</code>, then the value of the * <code>java.rmi.server.codebase</code> property (or possibly an * earlier cached value) is returned, or * <code>null</code> is returned if that property is not set. * * </ul> * * <p>For the implementations of the methods described below, * which all take a <code>String</code> parameter named * <code>codebase</code> that is a space-separated list of URLs, * each invocation has an associated <i>codebase loader</i> that * is identified using the <code>codebase</code> argument in * conjunction with the current thread's context class loader (see * {@link Thread#getContextClassLoader()}). When there is a * security manager, this provider maintains an internal table of * class loader instances (which are at least instances of {@link * java.net.URLClassLoader}) keyed by the pair of their parent * class loader and their codebase URL path (an ordered list of * URLs). If the <code>codebase</code> argument is <code>null</code>, * the codebase URL path is the value of the system property * <code>java.rmi.server.codebase</code> or possibly an * earlier cached value. For a given codebase URL path passed as the * <code>codebase</code> argument to an invocation of one of the * below methods in a given context, the codebase loader is the * loader in the table with the specified codebase URL path and * the current thread's context class loader as its parent. If no * such loader exists, then one is created and added to the table. * The table does not maintain strong references to its contained * loaders, in order to allow them and their defined classes to be * garbage collected when not otherwise reachable. In order to * prevent arbitrary untrusted code from being implicitly loaded * into a virtual machine with no security manager, if there is no * security manager set, the codebase loader is just the current * thread's context class loader (the supplied codebase URL path * is ignored, so remote class loading is disabled). * * <p>The <b>{@link RMIClassLoaderSpi#getClassLoader(String) * getClassLoader}</b> method returns the codebase loader for the * specified codebase URL path. If there is a security manager, * then if the calling context does not have permission to connect * to all of the URLs in the codebase URL path, a * <code>SecurityException</code> will be thrown. * * <p>The <b>{@link * RMIClassLoaderSpi#loadClass(String,String,ClassLoader) * loadClass}</b> method attempts to load the class with the * specified name as follows: * * <blockquote> * * If the <code>defaultLoader</code> argument is * non-<code>null</code>, it first attempts to load the class with the * specified <code>name</code> using the * <code>defaultLoader</code>, such as by evaluating * * <pre> * Class.forName(name, false, defaultLoader) * </pre> * * If the class is successfully loaded from the * <code>defaultLoader</code>, that class is returned. If an * exception other than <code>ClassNotFoundException</code> is * thrown, that exception is thrown to the caller. * * <p>Next, the <code>loadClass</code> method attempts to load the * class with the specified <code>name</code> using the codebase * loader for the specified codebase URL path. * If there is a security manager, then the calling context * must have permission to connect to all of the URLs in the * codebase URL path; otherwise, the current thread's context * class loader will be used instead of the codebase loader. * * </blockquote> * * <p>The <b>{@link * RMIClassLoaderSpi#loadProxyClass(String,String[],ClassLoader) * loadProxyClass}</b> method attempts to return a dynamic proxy * class with the named interface as follows: * * <blockquote> * * <p>If the <code>defaultLoader</code> argument is * non-<code>null</code> and all of the named interfaces can be * resolved through that loader, then, * * <ul> * * <li>if all of the resolved interfaces are <code>public</code>, * then it first attempts to obtain a dynamic proxy class (using * {@link * java.lang.reflect.Proxy#getProxyClass(ClassLoader,Class[]) * Proxy.getProxyClass}) for the resolved interfaces defined in * the codebase loader; if that attempt throws an * <code>IllegalArgumentException</code>, it then attempts to * obtain a dynamic proxy class for the resolved interfaces * defined in the <code>defaultLoader</code>. If both attempts * throw <code>IllegalArgumentException</code>, then this method * throws a <code>ClassNotFoundException</code>. If any other * exception is thrown, that exception is thrown to the caller. * * <li>if all of the non-<code>public</code> resolved interfaces * are defined in the same class loader, then it attempts to * obtain a dynamic proxy class for the resolved interfaces * defined in that loader. * * <li>otherwise, a <code>LinkageError</code> is thrown (because a * class that implements all of the specified interfaces cannot be * defined in any loader). * * </ul> * * <p>Otherwise, if all of the named interfaces can be resolved * through the codebase loader, then, * * <ul> * * <li>if all of the resolved interfaces are <code>public</code>, * then it attempts to obtain a dynamic proxy class for the * resolved interfaces in the codebase loader. If the attempt * throws an <code>IllegalArgumentException</code>, then this * method throws a <code>ClassNotFoundException</code>. * * <li>if all of the non-<code>public</code> resolved interfaces * are defined in the same class loader, then it attempts to * obtain a dynamic proxy class for the resolved interfaces * defined in that loader. * * <li>otherwise, a <code>LinkageError</code> is thrown (because a * class that implements all of the specified interfaces cannot be * defined in any loader). * * </ul> * * <p>Otherwise, a <code>ClassNotFoundException</code> is thrown * for one of the named interfaces that could not be resolved. * * </blockquote> * * </blockquote> * * @return the canonical instance of the default service provider * * @throws SecurityException if there is a security manager and the * invocation of its <code>checkPermission</code> method fails * * @since 1.4 */ public static RMIClassLoaderSpi getDefaultProviderInstance() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new RuntimePermission("setFactory")); } return defaultProvider; } /** {@collect.stats} * Returns the security context of the given class loader. * * @param loader a class loader from which to get the security context * * @return the security context * * @deprecated no replacement. As of the Java 2 platform v1.2, RMI no * longer uses this method to obtain a class loader's security context. * @see java.lang.SecurityManager#getSecurityContext() */ @Deprecated public static Object getSecurityContext(ClassLoader loader) { return sun.rmi.server.LoaderHandler.getSecurityContext(loader); } /** {@collect.stats} * Creates an instance of the default provider class. */ private static RMIClassLoaderSpi newDefaultProviderInstance() { return new RMIClassLoaderSpi() { public Class<?> loadClass(String codebase, String name, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException { return sun.rmi.server.LoaderHandler.loadClass( codebase, name, defaultLoader); } public Class<?> loadProxyClass(String codebase, String[] interfaces, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException { return sun.rmi.server.LoaderHandler.loadProxyClass( codebase, interfaces, defaultLoader); } public ClassLoader getClassLoader(String codebase) throws MalformedURLException { return sun.rmi.server.LoaderHandler.getClassLoader(codebase); } public String getClassAnnotation(Class<?> cl) { return sun.rmi.server.LoaderHandler.getClassAnnotation(cl); } }; } /** {@collect.stats} * Chooses provider instance, following above documentation. * * This method assumes that it has been invoked in a privileged block. */ private static RMIClassLoaderSpi initializeProvider() { /* * First check for the system property being set: */ String providerClassName = System.getProperty("java.rmi.server.RMIClassLoaderSpi"); if (providerClassName != null) { if (providerClassName.equals("default")) { return defaultProvider; } try { Class<? extends RMIClassLoaderSpi> providerClass = Class.forName(providerClassName, false, ClassLoader.getSystemClassLoader()) .asSubclass(RMIClassLoaderSpi.class); return providerClass.newInstance(); } catch (ClassNotFoundException e) { throw new NoClassDefFoundError(e.getMessage()); } catch (IllegalAccessException e) { throw new IllegalAccessError(e.getMessage()); } catch (InstantiationException e) { throw new InstantiationError(e.getMessage()); } catch (ClassCastException e) { Error error = new LinkageError( "provider class not assignable to RMIClassLoaderSpi"); error.initCause(e); throw error; } } /* * Next look for a provider configuration file installed: */ Iterator<RMIClassLoaderSpi> iter = ServiceLoader.load(RMIClassLoaderSpi.class, ClassLoader.getSystemClassLoader()).iterator(); if (iter.hasNext()) { try { return iter.next(); } catch (ClassCastException e) { Error error = new LinkageError( "provider class not assignable to RMIClassLoaderSpi"); error.initCause(e); throw error; } } /* * Finally, return the canonical instance of the default provider. */ return defaultProvider; } }
Java
/* * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.rmi.*; import sun.rmi.server.UnicastServerRef; import sun.rmi.server.UnicastServerRef2; /** {@collect.stats} * Used for exporting a remote object with JRMP and obtaining a stub * that communicates to the remote object. * * <p>For the constructors and static <code>exportObject</code> methods * below, the stub for a remote object being exported is obtained as * follows: * * <p><ul> * * <li>If the remote object is exported using the {@link * #exportObject(Remote) UnicastRemoteObject.exportObject(Remote)} method, * a stub class (typically pregenerated from the remote object's class * using the <code>rmic</code> tool) is loaded and an instance of that stub * class is constructed as follows. * <ul> * * <li>A "root class" is determined as follows: if the remote object's * class directly implements an interface that extends {@link Remote}, then * the remote object's class is the root class; otherwise, the root class is * the most derived superclass of the remote object's class that directly * implements an interface that extends <code>Remote</code>. * * <li>The name of the stub class to load is determined by concatenating * the binary name of the root class with the suffix <code>"_Stub"</code>. * * <li>The stub class is loaded by name using the class loader of the root * class. The stub class must extend {@link RemoteStub} and must have a * public constructor that has one parameter, of type {@link RemoteRef}. * * <li>Finally, an instance of the stub class is constructed with a * {@link RemoteRef}. * </ul> * * <li>If the appropriate stub class could not be found, or the stub class * could not be loaded, or a problem occurs creating the stub instance, a * {@link StubNotFoundException} is thrown. * * <p> * <li>For all other means of exporting: * <p><ul> * * <li>If the remote object's stub class (as defined above) could not be * loaded or the system property * <code>java.rmi.server.ignoreStubClasses</code> is set to * <code>"true"</code> (case insensitive), a {@link * java.lang.reflect.Proxy} instance is constructed with the following * properties: * * <ul> * * <li>The proxy's class is defined by the class loader of the remote * object's class. * * <li>The proxy implements all the remote interfaces implemented by the * remote object's class. * * <li>The proxy's invocation handler is a {@link * RemoteObjectInvocationHandler} instance constructed with a * {@link RemoteRef}. * * <li>If the proxy could not be created, a {@link StubNotFoundException} * will be thrown. * </ul> * * <p> * <li>Otherwise, an instance of the remote object's stub class (as * described above) is used as the stub. * * </ul> * </ul> * * @author Ann Wollrath * @author Peter Jones * @since JDK1.1 **/ public class UnicastRemoteObject extends RemoteServer { /** {@collect.stats} * @serial port number on which to export object */ private int port = 0; /** {@collect.stats} * @serial client-side socket factory (if any) */ private RMIClientSocketFactory csf = null; /** {@collect.stats} * @serial server-side socket factory (if any) to use when * exporting object */ private RMIServerSocketFactory ssf = null; /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = 4974527148936298033L; /** {@collect.stats} * Creates and exports a new UnicastRemoteObject object using an * anonymous port. * @throws RemoteException if failed to export object * @since JDK1.1 */ protected UnicastRemoteObject() throws RemoteException { this(0); } /** {@collect.stats} * Creates and exports a new UnicastRemoteObject object using the * particular supplied port. * @param port the port number on which the remote object receives calls * (if <code>port</code> is zero, an anonymous port is chosen) * @throws RemoteException if failed to export object * @since 1.2 */ protected UnicastRemoteObject(int port) throws RemoteException { this.port = port; exportObject((Remote) this, port); } /** {@collect.stats} * Creates and exports a new UnicastRemoteObject object using the * particular supplied port and socket factories. * @param port the port number on which the remote object receives calls * (if <code>port</code> is zero, an anonymous port is chosen) * @param csf the client-side socket factory for making calls to the * remote object * @param ssf the server-side socket factory for receiving remote calls * @throws RemoteException if failed to export object * @since 1.2 */ protected UnicastRemoteObject(int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf) throws RemoteException { this.port = port; this.csf = csf; this.ssf = ssf; exportObject((Remote) this, port, csf, ssf); } /** {@collect.stats} * Re-export the remote object when it is deserialized. */ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { in.defaultReadObject(); reexport(); } /** {@collect.stats} * Returns a clone of the remote object that is distinct from * the original. * * @exception CloneNotSupportedException if clone failed due to * a RemoteException. * @return the new remote object * @since JDK1.1 */ public Object clone() throws CloneNotSupportedException { try { UnicastRemoteObject cloned = (UnicastRemoteObject) super.clone(); cloned.reexport(); return cloned; } catch (RemoteException e) { throw new ServerCloneException("Clone failed", e); } } /* * Exports this UnicastRemoteObject using its initialized fields because * its creation bypassed running its constructors (via deserialization * or cloning, for example). */ private void reexport() throws RemoteException { if (csf == null && ssf == null) { exportObject((Remote) this, port); } else { exportObject((Remote) this, port, csf, ssf); } } /** {@collect.stats} * Exports the remote object to make it available to receive incoming * calls using an anonymous port. * @param obj the remote object to be exported * @return remote object stub * @exception RemoteException if export fails * @since JDK1.1 */ public static RemoteStub exportObject(Remote obj) throws RemoteException { /* * Use UnicastServerRef constructor passing the boolean value true * to indicate that only a generated stub class should be used. A * generated stub class must be used instead of a dynamic proxy * because the return value of this method is RemoteStub which a * dynamic proxy class cannot extend. */ return (RemoteStub) exportObject(obj, new UnicastServerRef(true)); } /** {@collect.stats} * Exports the remote object to make it available to receive incoming * calls, using the particular supplied port. * @param obj the remote object to be exported * @param port the port to export the object on * @return remote object stub * @exception RemoteException if export fails * @since 1.2 */ public static Remote exportObject(Remote obj, int port) throws RemoteException { return exportObject(obj, new UnicastServerRef(port)); } /** {@collect.stats} * Exports the remote object to make it available to receive incoming * calls, using a transport specified by the given socket factory. * @param obj the remote object to be exported * @param port the port to export the object on * @param csf the client-side socket factory for making calls to the * remote object * @param ssf the server-side socket factory for receiving remote calls * @return remote object stub * @exception RemoteException if export fails * @since 1.2 */ public static Remote exportObject(Remote obj, int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf) throws RemoteException { return exportObject(obj, new UnicastServerRef2(port, csf, ssf)); } /** {@collect.stats} * Removes the remote object, obj, from the RMI runtime. If * successful, the object can no longer accept incoming RMI calls. * If the force parameter is true, the object is forcibly unexported * even if there are pending calls to the remote object or the * remote object still has calls in progress. If the force * parameter is false, the object is only unexported if there are * no pending or in progress calls to the object. * * @param obj the remote object to be unexported * @param force if true, unexports the object even if there are * pending or in-progress calls; if false, only unexports the object * if there are no pending or in-progress calls * @return true if operation is successful, false otherwise * @exception NoSuchObjectException if the remote object is not * currently exported * @since 1.2 */ public static boolean unexportObject(Remote obj, boolean force) throws java.rmi.NoSuchObjectException { return sun.rmi.transport.ObjectTable.unexportObject(obj, force); } /** {@collect.stats} * Exports the specified object using the specified server ref. */ private static Remote exportObject(Remote obj, UnicastServerRef sref) throws RemoteException { // if obj extends UnicastRemoteObject, set its ref. if (obj instanceof UnicastRemoteObject) { ((UnicastRemoteObject) obj).ref = sref; } return sref.exportObject(obj, null, false); } }
Java
/* * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.io.InvalidObjectException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.rmi.Remote; import java.rmi.UnexpectedException; import java.rmi.activation.Activatable; import java.util.Map; import java.util.WeakHashMap; import sun.rmi.server.Util; import sun.rmi.server.WeakClassHashMap; /** {@collect.stats} * An implementation of the <code>InvocationHandler</code> interface for * use with Java Remote Method Invocation (Java RMI). This invocation * handler can be used in conjunction with a dynamic proxy instance as a * replacement for a pregenerated stub class. * * <p>Applications are not expected to use this class directly. A remote * object exported to use a dynamic proxy with {@link UnicastRemoteObject} * or {@link Activatable} has an instance of this class as that proxy's * invocation handler. * * @author Ann Wollrath * @since 1.5 **/ public class RemoteObjectInvocationHandler extends RemoteObject implements InvocationHandler { private static final long serialVersionUID = 2L; /** {@collect.stats} * A weak hash map, mapping classes to weak hash maps that map * method objects to method hashes. **/ private static final MethodToHash_Maps methodToHash_Maps = new MethodToHash_Maps(); /** {@collect.stats} * Creates a new <code>RemoteObjectInvocationHandler</code> constructed * with the specified <code>RemoteRef</code>. * * @param ref the remote ref * * @throws NullPointerException if <code>ref</code> is <code>null</code> **/ public RemoteObjectInvocationHandler(RemoteRef ref) { super(ref); if (ref == null) { throw new NullPointerException(); } } /** {@collect.stats} * Processes a method invocation made on the encapsulating * proxy instance, <code>proxy</code>, and returns the result. * * <p><code>RemoteObjectInvocationHandler</code> implements this method * as follows: * * <p>If <code>method</code> is one of the following methods, it * is processed as described below: * * <ul> * * <li>{@link Object#hashCode Object.hashCode}: Returns the hash * code value for the proxy. * * <li>{@link Object#equals Object.equals}: Returns <code>true</code> * if the argument (<code>args[0]</code>) is an instance of a dynamic * proxy class and this invocation handler is equal to the invocation * handler of that argument, and returns <code>false</code> otherwise. * * <li>{@link Object#toString Object.toString}: Returns a string * representation of the proxy. * </ul> * * <p>Otherwise, a remote call is made as follows: * * <ul> * <li>If <code>proxy</code> is not an instance of the interface * {@link Remote}, then an {@link IllegalArgumentException} is thrown. * * <li>Otherwise, the {@link RemoteRef#invoke invoke} method is invoked * on this invocation handler's <code>RemoteRef</code>, passing * <code>proxy</code>, <code>method</code>, <code>args</code>, and the * method hash (defined in section 8.3 of the "Java Remote Method * Invocation (RMI) Specification") for <code>method</code>, and the * result is returned. * * <li>If an exception is thrown by <code>RemoteRef.invoke</code> and * that exception is a checked exception that is not assignable to any * exception in the <code>throws</code> clause of the method * implemented by the <code>proxy</code>'s class, then that exception * is wrapped in an {@link UnexpectedException} and the wrapped * exception is thrown. Otherwise, the exception thrown by * <code>invoke</code> is thrown by this method. * </ul> * * <p>The semantics of this method are unspecified if the * arguments could not have been produced by an instance of some * valid dynamic proxy class containing this invocation handler. * * @param proxy the proxy instance that the method was invoked on * @param method the <code>Method</code> instance corresponding to the * interface method invoked on the proxy instance * @param args an array of objects containing the values of the * arguments passed in the method invocation on the proxy instance, or * <code>null</code> if the method takes no arguments * @return the value to return from the method invocation on the proxy * instance * @throws Throwable the exception to throw from the method invocation * on the proxy instance **/ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass() == Object.class) { return invokeObjectMethod(proxy, method, args); } else { return invokeRemoteMethod(proxy, method, args); } } /** {@collect.stats} * Handles java.lang.Object methods. **/ private Object invokeObjectMethod(Object proxy, Method method, Object[] args) { String name = method.getName(); if (name.equals("hashCode")) { return hashCode(); } else if (name.equals("equals")) { Object obj = args[0]; return proxy == obj || (obj != null && Proxy.isProxyClass(obj.getClass()) && equals(Proxy.getInvocationHandler(obj))); } else if (name.equals("toString")) { return proxyToString(proxy); } else { throw new IllegalArgumentException( "unexpected Object method: " + method); } } /** {@collect.stats} * Handles remote methods. **/ private Object invokeRemoteMethod(Object proxy, Method method, Object[] args) throws Exception { try { if (!(proxy instanceof Remote)) { throw new IllegalArgumentException( "proxy not Remote instance"); } return ref.invoke((Remote) proxy, method, args, getMethodHash(method)); } catch (Exception e) { if (!(e instanceof RuntimeException)) { Class<?> cl = proxy.getClass(); try { method = cl.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException nsme) { throw (IllegalArgumentException) new IllegalArgumentException().initCause(nsme); } Class<?> thrownType = e.getClass(); for (Class<?> declaredType : method.getExceptionTypes()) { if (declaredType.isAssignableFrom(thrownType)) { throw e; } } e = new UnexpectedException("unexpected exception", e); } throw e; } } /** {@collect.stats} * Returns a string representation for a proxy that uses this invocation * handler. **/ private String proxyToString(Object proxy) { Class<?>[] interfaces = proxy.getClass().getInterfaces(); if (interfaces.length == 0) { return "Proxy[" + this + "]"; } String iface = interfaces[0].getName(); if (iface.equals("java.rmi.Remote") && interfaces.length > 1) { iface = interfaces[1].getName(); } int dot = iface.lastIndexOf('.'); if (dot >= 0) { iface = iface.substring(dot + 1); } return "Proxy[" + iface + "," + this + "]"; } /** {@collect.stats} * @throws InvalidObjectException unconditionally **/ private void readObjectNoData() throws InvalidObjectException { throw new InvalidObjectException("no data in stream; class: " + this.getClass().getName()); } /** {@collect.stats} * Returns the method hash for the specified method. Subsequent calls * to "getMethodHash" passing the same method argument should be faster * since this method caches internally the result of the method to * method hash mapping. The method hash is calculated using the * "computeMethodHash" method. * * @param method the remote method * @return the method hash for the specified method */ private static long getMethodHash(Method method) { return methodToHash_Maps.get(method.getDeclaringClass()).get(method); } /** {@collect.stats} * A weak hash map, mapping classes to weak hash maps that map * method objects to method hashes. **/ private static class MethodToHash_Maps extends WeakClassHashMap<Map<Method,Long>> { MethodToHash_Maps() {} protected Map<Method,Long> computeValue(Class<?> remoteClass) { return new WeakHashMap<Method,Long>() { public synchronized Long get(Object key) { Long hash = super.get(key); if (hash == null) { Method method = (Method) key; hash = Util.computeMethodHash(method); put(method, hash); } return hash; } }; } } }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.rmi.RemoteException; /** {@collect.stats} * A <code>SkeletonNotFoundException</code> is thrown if the * <code>Skeleton</code> corresponding to the remote object being * exported is not found. Skeletons are no longer required, so this * exception is never thrown. * * @since JDK1.1 * @deprecated no replacement. Skeletons are no longer required for remote * method calls in the Java 2 platform v1.2 and greater. */ @Deprecated public class SkeletonNotFoundException extends RemoteException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -7860299673822761231L; /** {@collect.stats} * Constructs a <code>SkeletonNotFoundException</code> with the specified * detail message. * * @param s the detail message. * @since JDK1.1 */ public SkeletonNotFoundException(String s) { super(s); } /** {@collect.stats} * Constructs a <code>SkeletonNotFoundException</code> with the specified * detail message and nested exception. * * @param s the detail message. * @param ex the nested exception * @since JDK1.1 */ public SkeletonNotFoundException(String s, Exception ex) { super(s, ex); } }
Java
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.net.MalformedURLException; import java.net.URL; /** {@collect.stats} * <code>LoaderHandler</code> is an interface used internally by the RMI * runtime in previous implementation versions. It should never be accessed * by application code. * * @author Ann Wollrath * @since JDK1.1 * * @deprecated no replacement */ @Deprecated public interface LoaderHandler { /** {@collect.stats} package of system <code>LoaderHandler</code> implementation. */ final static String packagePrefix = "sun.rmi.server"; /** {@collect.stats} * Loads a class from the location specified by the * <code>java.rmi.server.codebase</code> property. * * @param name the name of the class to load * @return the <code>Class</code> object representing the loaded class * @exception MalformedURLException * if the system property <b>java.rmi.server.codebase</b> * contains an invalid URL * @exception ClassNotFoundException * if a definition for the class could not * be found at the codebase location. * @since JDK1.1 * @deprecated no replacement */ @Deprecated Class<?> loadClass(String name) throws MalformedURLException, ClassNotFoundException; /** {@collect.stats} * Loads a class from a URL. * * @param codebase the URL from which to load the class * @param name the name of the class to load * @return the <code>Class</code> object representing the loaded class * @exception MalformedURLException * if the <code>codebase</code> paramater * contains an invalid URL * @exception ClassNotFoundException * if a definition for the class could not * be found at the specified URL * @since JDK1.1 * @deprecated no replacement */ @Deprecated Class<?> loadClass(URL codebase, String name) throws MalformedURLException, ClassNotFoundException; /** {@collect.stats} * Returns the security context of the given class loader. * * @param loader a class loader from which to get the security context * @return the security context * @since JDK1.1 * @deprecated no replacement */ @Deprecated Object getSecurityContext(ClassLoader loader); }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; /** {@collect.stats} * An <code>RMIFailureHandler</code> can be registered via the * <code>RMISocketFactory.setFailureHandler</code> call. The * <code>failure</code> method of the handler is invoked when the RMI * runtime is unable to create a <code>ServerSocket</code> to listen * for incoming calls. The <code>failure</code> method returns a boolean * indicating whether the runtime should attempt to re-create the * <code>ServerSocket</code>. * * @author Ann Wollrath * @since JDK1.1 */ public interface RMIFailureHandler { /** {@collect.stats} * The <code>failure</code> callback is invoked when the RMI * runtime is unable to create a <code>ServerSocket</code> via the * <code>RMISocketFactory</code>. An <code>RMIFailureHandler</code> * is registered via a call to * <code>RMISocketFacotry.setFailureHandler</code>. If no failure * handler is installed, the default behavior is to attempt to * re-create the ServerSocket. * * @param ex the exception that occurred during <code>ServerSocket</code> * creation * @return if true, the RMI runtime attempts to retry * <code>ServerSocket</code> creation * @see java.rmi.server.RMISocketFactory#setFailureHandler(RMIFailureHandler) * @since JDK1.1 */ public boolean failure(Exception ex); }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.Serializable; import java.security.SecureRandom; /** {@collect.stats} * A <code>UID</code> represents an identifier that is unique over time * with respect to the host it is generated on, or one of 2<sup>16</sup> * "well-known" identifiers. * * <p>The {@link #UID()} constructor can be used to generate an * identifier that is unique over time with respect to the host it is * generated on. The {@link #UID(short)} constructor can be used to * create one of 2<sup>16</sup> well-known identifiers. * * <p>A <code>UID</code> instance contains three primitive values: * <ul> * <li><code>unique</code>, an <code>int</code> that uniquely identifies * the VM that this <code>UID</code> was generated in, with respect to its * host and at the time represented by the <code>time</code> value (an * example implementation of the <code>unique</code> value would be a * process identifier), * or zero for a well-known <code>UID</code> * <li><code>time</code>, a <code>long</code> equal to a time (as returned * by {@link System#currentTimeMillis()}) at which the VM that this * <code>UID</code> was generated in was alive, * or zero for a well-known <code>UID</code> * <li><code>count</code>, a <code>short</code> to distinguish * <code>UID</code>s generated in the same VM with the same * <code>time</code> value * </ul> * * <p>An independently generated <code>UID</code> instance is unique * over time with respect to the host it is generated on as long as * the host requires more than one millisecond to reboot and its system * clock is never set backward. A globally unique identifier can be * constructed by pairing a <code>UID</code> instance with a unique host * identifier, such as an IP address. * * @author Ann Wollrath * @author Peter Jones * @since JDK1.1 */ public final class UID implements Serializable { private static int hostUnique; private static boolean hostUniqueSet = false; private static final Object lock = new Object(); private static long lastTime = System.currentTimeMillis(); private static short lastCount = Short.MIN_VALUE; /** {@collect.stats} indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = 1086053664494604050L; /** {@collect.stats} * number that uniquely identifies the VM that this <code>UID</code> * was generated in with respect to its host and at the given time * @serial */ private final int unique; /** {@collect.stats} * a time (as returned by {@link System#currentTimeMillis()}) at which * the VM that this <code>UID</code> was generated in was alive * @serial */ private final long time; /** {@collect.stats} * 16-bit number to distinguish <code>UID</code> instances created * in the same VM with the same time value * @serial */ private final short count; /** {@collect.stats} * Generates a <code>UID</code> that is unique over time with * respect to the host that it was generated on. */ public UID() { synchronized (lock) { if (!hostUniqueSet) { hostUnique = (new SecureRandom()).nextInt(); hostUniqueSet = true; } unique = hostUnique; if (lastCount == Short.MAX_VALUE) { boolean interrupted = Thread.interrupted(); boolean done = false; while (!done) { long now = System.currentTimeMillis(); if (now <= lastTime) { // wait for time to change try { Thread.currentThread().sleep(1); } catch (InterruptedException e) { interrupted = true; } } else { lastTime = now; lastCount = Short.MIN_VALUE; done = true; } } if (interrupted) { Thread.currentThread().interrupt(); } } time = lastTime; count = lastCount++; } } /** {@collect.stats} * Creates a "well-known" <code>UID</code>. * * There are 2<sup>16</sup> possible such well-known ids. * * <p>A <code>UID</code> created via this constructor will not * clash with any <code>UID</code>s generated via the no-arg * constructor. * * @param num number for well-known <code>UID</code> */ public UID(short num) { unique = 0; time = 0; count = num; } /** {@collect.stats} * Constructs a <code>UID</code> given data read from a stream. */ private UID(int unique, long time, short count) { this.unique = unique; this.time = time; this.count = count; } /** {@collect.stats} * Returns the hash code value for this <code>UID</code>. * * @return the hash code value for this <code>UID</code> */ public int hashCode() { return (int) time + (int) count; } /** {@collect.stats} * Compares the specified object with this <code>UID</code> for * equality. * * This method returns <code>true</code> if and only if the * specified object is a <code>UID</code> instance with the same * <code>unique</code>, <code>time</code>, and <code>count</code> * values as this one. * * @param obj the object to compare this <code>UID</code> to * * @return <code>true</code> if the given object is equivalent to * this one, and <code>false</code> otherwise */ public boolean equals(Object obj) { if (obj instanceof UID) { UID uid = (UID) obj; return (unique == uid.unique && count == uid.count && time == uid.time); } else { return false; } } /** {@collect.stats} * Returns a string representation of this <code>UID</code>. * * @return a string representation of this <code>UID</code> */ public String toString() { return Integer.toString(unique,16) + ":" + Long.toString(time,16) + ":" + Integer.toString(count,16); } /** {@collect.stats} * Marshals a binary representation of this <code>UID</code> to * a <code>DataOutput</code> instance. * * <p>Specifically, this method first invokes the given stream's * {@link DataOutput#writeInt(int)} method with this <code>UID</code>'s * <code>unique</code> value, then it invokes the stream's * {@link DataOutput#writeLong(long)} method with this <code>UID</code>'s * <code>time</code> value, and then it invokes the stream's * {@link DataOutput#writeShort(int)} method with this <code>UID</code>'s * <code>count</code> value. * * @param out the <code>DataOutput</code> instance to write * this <code>UID</code> to * * @throws IOException if an I/O error occurs while performing * this operation */ public void write(DataOutput out) throws IOException { out.writeInt(unique); out.writeLong(time); out.writeShort(count); } /** {@collect.stats} * Constructs and returns a new <code>UID</code> instance by * unmarshalling a binary representation from an * <code>DataInput</code> instance. * * <p>Specifically, this method first invokes the given stream's * {@link DataInput#readInt()} method to read a <code>unique</code> value, * then it invoke's the stream's * {@link DataInput#readLong()} method to read a <code>time</code> value, * then it invoke's the stream's * {@link DataInput#readShort()} method to read a <code>count</code> value, * and then it creates and returns a new <code>UID</code> instance * that contains the <code>unique</code>, <code>time</code>, and * <code>count</code> values that were read from the stream. * * @param in the <code>DataInput</code> instance to read * <code>UID</code> from * * @return unmarshalled <code>UID</code> instance * * @throws IOException if an I/O error occurs while performing * this operation */ public static UID read(DataInput in) throws IOException { int unique = in.readInt(); long time = in.readLong(); short count = in.readShort(); return new UID(unique, time, count); } }
Java
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; /** {@collect.stats} * The <code>RemoteStub</code> class is the common superclass to client * stubs and provides the framework to support a wide range of remote * reference semantics. Stub objects are surrogates that support * exactly the same set of remote interfaces defined by the actual * implementation of the remote object. * * @author Ann Wollrath * @since JDK1.1 */ abstract public class RemoteStub extends RemoteObject { /** {@collect.stats} indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -1585587260594494182L; /** {@collect.stats} * Constructs a <code>RemoteStub</code>. */ protected RemoteStub() { super(); } /** {@collect.stats} * Constructs a <code>RemoteStub</code>, with the specified remote * reference. * * @param ref the remote reference * @since JDK1.1 */ protected RemoteStub(RemoteRef ref) { super(ref); } /** {@collect.stats} * Sets the remote reference inside the remote stub. * * @param stub the remote stub * @param ref the remote reference * @since JDK1.1 * @deprecated no replacement. The <code>setRef</code> method * is not needed since <code>RemoteStub</code>s can be created with * the <code>RemoteStub(RemoteRef)</code> constructor. */ @Deprecated protected static void setRef(RemoteStub stub, RemoteRef ref) { throw new UnsupportedOperationException(); } }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Serializable; import java.security.AccessController; import java.security.SecureRandom; import java.util.concurrent.atomic.AtomicLong; import sun.security.action.GetPropertyAction; /** {@collect.stats} * An <code>ObjID</code> is used to identify a remote object exported * to an RMI runtime. When a remote object is exported, it is assigned * an object identifier either implicitly or explicitly, depending on * the API used to export. * * <p>The {@link #ObjID()} constructor can be used to generate a unique * object identifier. Such an <code>ObjID</code> is unique over time * with respect to the host it is generated on. * * The {@link #ObjID(int)} constructor can be used to create a * "well-known" object identifier. The scope of a well-known * <code>ObjID</code> depends on the RMI runtime it is exported to. * * <p>An <code>ObjID</code> instance contains an object number (of type * <code>long</code>) and an address space identifier (of type * {@link UID}). In a unique <code>ObjID</code>, the address space * identifier is unique with respect to a given host over time. In a * well-known <code>ObjID</code>, the address space identifier is * equivalent to one returned by invoking the {@link UID#UID(short)} * constructor with the value zero. * * <p>If the system property <code>java.rmi.server.randomIDs</code> * is defined to equal the string <code>"true"</code> (case insensitive), * then the {@link #ObjID()} constructor will use a cryptographically * strong random number generator to choose the object number of the * returned <code>ObjID</code>. * * @author Ann Wollrath * @author Peter Jones * @since JDK1.1 */ public final class ObjID implements Serializable { /** {@collect.stats} Object number for well-known <code>ObjID</code> of the registry. */ public static final int REGISTRY_ID = 0; /** {@collect.stats} Object number for well-known <code>ObjID</code> of the activator. */ public static final int ACTIVATOR_ID = 1; /** {@collect.stats} * Object number for well-known <code>ObjID</code> of * the distributed garbage collector. */ public static final int DGC_ID = 2; /** {@collect.stats} indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -6386392263968365220L; private static final AtomicLong nextObjNum = new AtomicLong(0); private static final UID mySpace = new UID(); private static final SecureRandom secureRandom = new SecureRandom(); /** {@collect.stats} * @serial object number * @see #hashCode */ private final long objNum; /** {@collect.stats} * @serial address space identifier (unique to host over time) */ private final UID space; /** {@collect.stats} * Generates a unique object identifier. * * <p>If the system property <code>java.rmi.server.randomIDs</code> * is defined to equal the string <code>"true"</code> (case insensitive), * then this constructor will use a cryptographically * strong random number generator to choose the object number of the * returned <code>ObjID</code>. */ public ObjID() { /* * If generating random object numbers, create a new UID to * ensure uniqueness; otherwise, use a shared UID because * sequential object numbers already ensure uniqueness. */ if (useRandomIDs()) { space = new UID(); objNum = secureRandom.nextLong(); } else { space = mySpace; objNum = nextObjNum.getAndIncrement(); } } /** {@collect.stats} * Creates a "well-known" object identifier. * * <p>An <code>ObjID</code> created via this constructor will not * clash with any <code>ObjID</code>s generated via the no-arg * constructor. * * @param objNum object number for well-known object identifier */ public ObjID(int objNum) { space = new UID((short) 0); this.objNum = objNum; } /** {@collect.stats} * Constructs an object identifier given data read from a stream. */ private ObjID(long objNum, UID space) { this.objNum = objNum; this.space = space; } /** {@collect.stats} * Marshals a binary representation of this <code>ObjID</code> to * an <code>ObjectOutput</code> instance. * * <p>Specifically, this method first invokes the given stream's * {@link ObjectOutput#writeLong(long)} method with this object * identifier's object number, and then it writes its address * space identifier by invoking its {@link UID#write(DataOutput)} * method with the stream. * * @param out the <code>ObjectOutput</code> instance to write * this <code>ObjID</code> to * * @throws IOException if an I/O error occurs while performing * this operation */ public void write(ObjectOutput out) throws IOException { out.writeLong(objNum); space.write(out); } /** {@collect.stats} * Constructs and returns a new <code>ObjID</code> instance by * unmarshalling a binary representation from an * <code>ObjectInput</code> instance. * * <p>Specifically, this method first invokes the given stream's * {@link ObjectInput#readLong()} method to read an object number, * then it invokes {@link UID#read(DataInput)} with the * stream to read an address space identifier, and then it * creates and returns a new <code>ObjID</code> instance that * contains the object number and address space identifier that * were read from the stream. * * @param in the <code>ObjectInput</code> instance to read * <code>ObjID</code> from * * @return unmarshalled <code>ObjID</code> instance * * @throws IOException if an I/O error occurs while performing * this operation */ public static ObjID read(ObjectInput in) throws IOException { long num = in.readLong(); UID space = UID.read(in); return new ObjID(num, space); } /** {@collect.stats} * Returns the hash code value for this object identifier, the * object number. * * @return the hash code value for this object identifier */ public int hashCode() { return (int) objNum; } /** {@collect.stats} * Compares the specified object with this <code>ObjID</code> for * equality. * * This method returns <code>true</code> if and only if the * specified object is an <code>ObjID</code> instance with the same * object number and address space identifier as this one. * * @param obj the object to compare this <code>ObjID</code> to * * @return <code>true</code> if the given object is equivalent to * this one, and <code>false</code> otherwise */ public boolean equals(Object obj) { if (obj instanceof ObjID) { ObjID id = (ObjID) obj; return objNum == id.objNum && space.equals(id.space); } else { return false; } } /** {@collect.stats} * Returns a string representation of this object identifier. * * @return a string representation of this object identifier */ /* * The address space identifier is only included in the string * representation if it does not denote the local address space * (or if the randomIDs property was set). */ public String toString() { return "[" + (space.equals(mySpace) ? "" : space + ", ") + objNum + "]"; } private static boolean useRandomIDs() { String value = AccessController.doPrivileged( new GetPropertyAction("java.rmi.server.randomIDs")); return value == null ? true : Boolean.parseBoolean(value); } }
Java
/* * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.io.*; import java.net.*; /** {@collect.stats} * An <code>RMIClientSocketFactory</code> instance is used by the RMI runtime * in order to obtain client sockets for RMI calls. A remote object can be * associated with an <code>RMIClientSocketFactory</code> when it is * created/exported via the constructors or <code>exportObject</code> methods * of <code>java.rmi.server.UnicastRemoteObject</code> and * <code>java.rmi.activation.Activatable</code> . * * <p>An <code>RMIClientSocketFactory</code> instance associated with a remote * object will be downloaded to clients when the remote object's reference is * transmitted in an RMI call. This <code>RMIClientSocketFactory</code> will * be used to create connections to the remote object for remote method calls. * * <p>An <code>RMIClientSocketFactory</code> instance can also be associated * with a remote object registry so that clients can use custom socket * communication with a remote object registry. * * <p>An implementation of this interface should be serializable and * should implement {@link Object#equals} to return <code>true</code> when * passed an instance that represents the same (functionally equivalent) * client socket factory, and <code>false</code> otherwise (and it should also * implement {@link Object#hashCode} consistently with its * <code>Object.equals</code> implementation). * * @author Ann Wollrath * @author Peter Jones * @since 1.2 * @see java.rmi.server.UnicastRemoteObject * @see java.rmi.activation.Activatable * @see java.rmi.registry.LocateRegistry */ public interface RMIClientSocketFactory { /** {@collect.stats} * Create a client socket connected to the specified host and port. * @param host the host name * @param port the port number * @return a socket connected to the specified host and port. * @exception IOException if an I/O error occurs during socket creation * @since 1.2 */ public Socket createSocket(String host, int port) throws IOException; }
Java