code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright (c) 2003, 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 javax.sql.rowset.serial;
import java.sql.*;
import java.io.*;
import java.util.*;
/** {@collect.stats}
* A serialized mapping of a <code>Ref</code> object, which is the mapping in the
* Java programming language of an SQL <code>REF</code> value.
* <p>
* The <code>SerialRef</code> class provides a constructor for
* creating a <code>SerialRef</code> instance from a <code>Ref</code>
* object and provides methods for getting and setting the <code>Ref</code> object.
*/
public class SerialRef implements Ref, Serializable, Cloneable {
/** {@collect.stats}
* String containing the base type name.
* @serial
*/
private String baseTypeName;
/** {@collect.stats}
* This will store the type <code>Ref</code> as an <code>Object</code>.
*/
private Object object;
/** {@collect.stats}
* Private copy of the Ref reference.
*/
private Ref reference;
/** {@collect.stats}
* Constructs a <code>SerialRef</code> object from the given <code>Ref</code>
* object.
*
* @param ref a Ref object; cannot be <code>null</code>
* @throws SQLException if a database access occurs; if <code>ref</code>
* is <code>null</code>; or if the <code>Ref</code> object returns a
* <code>null</code> value base type name.
* @throws SerialException if an error occurs serializing the <code>Ref</code>
* object
*/
public SerialRef(Ref ref) throws SerialException, SQLException {
if (ref == null) {
throw new SQLException("Cannot instantiate a SerialRef object " +
"with a null Ref object");
}
reference = ref;
object = ref;
if (ref.getBaseTypeName() == null) {
throw new SQLException("Cannot instantiate a SerialRef object " +
"that returns a null base type name");
} else {
baseTypeName = new String(ref.getBaseTypeName());
}
}
/** {@collect.stats}
* Returns a string describing the base type name of the <code>Ref</code>.
*
* @return a string of the base type name of the Ref
* @throws SerialException in no Ref object has been set
*/
public String getBaseTypeName() throws SerialException {
return baseTypeName;
}
/** {@collect.stats}
* Returns an <code>Object</code> representing the SQL structured type
* to which this <code>SerialRef</code> object refers. The attributes
* of the structured type are mapped according to the given type map.
*
* @param map a <code>java.util.Map</code> object containing zero or
* more entries, with each entry consisting of 1) a <code>String</code>
* giving the fully qualified name of a UDT and 2) the
* <code>Class</code> object for the <code>SQLData</code> implementation
* that defines how the UDT is to be mapped
* @return an object instance resolved from the Ref reference and mapped
* according to the supplied type map
* @throws SerialException if an error is encountered in the reference
* resolution
*/
public Object getObject(java.util.Map<String,Class<?>> map)
throws SerialException
{
map = new Hashtable(map);
if (!object.equals(null)) {
return map.get(object);
} else {
throw new SerialException("The object is not set");
}
}
/** {@collect.stats}
* Returns an <code>Object</code> representing the SQL structured type
* to which this <code>SerialRef</code> object refers.
*
* @return an object instance resolved from the Ref reference
* @throws SerialException if an error is encountered in the reference
* resolution
*/
public Object getObject() throws SerialException {
if (reference != null) {
try {
return reference.getObject();
} catch (SQLException e) {
throw new SerialException("SQLException: " + e.getMessage());
}
}
if (object != null) {
return object;
}
throw new SerialException("The object is not set");
}
/** {@collect.stats}
* Sets the SQL structured type that this <code>SerialRef</code> object
* references to the given <code>Object</code> object.
*
* @param obj an <code>Object</code> representing the SQL structured type
* to be referenced
* @throws SerialException if an error is encountered generating the
* the structured type referenced by this <code>SerialRef</code> object
*/
public void setObject(Object obj) throws SerialException {
try {
reference.setObject(obj);
} catch (SQLException e) {
throw new SerialException("SQLException: " + e.getMessage());
}
object = obj;
}
/** {@collect.stats}
* The identifier that assists in the serialization of this <code>SerialRef</code>
* object.
*/
static final long serialVersionUID = -4727123500609662274L;
}
| 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 javax.sql.rowset.serial;
import java.sql.*;
import java.io.*;
import java.lang.reflect.*;
/** {@collect.stats}
* A serialized mapping in the Java programming language of an SQL
* <code>BLOB</code> value.
* <P>
* The <code>SerialBlob</code> class provides a constructor for creating
* an instance from a <code>Blob</code> object. Note that the
* <code>Blob</code>
* object should have brought the SQL <code>BLOB</code> value's data over
* to the client before a <code>SerialBlob</code> object
* is constructed from it. The data of an SQL <code>BLOB</code> value can
* be materialized on the client as an array of bytes (using the method
* <code>Blob.getBytes</code>) or as a stream of uninterpreted bytes
* (using the method <code>Blob.getBinaryStream</code>).
* <P>
* <code>SerialBlob</code> methods make it possible to make a copy of a
* <code>SerialBlob</code> object as an array of bytes or as a stream.
* They also make it possible to locate a given pattern of bytes or a
* <code>Blob</code> object within a <code>SerialBlob</code> object
* and to update or truncate a <code>Blob</code> object.
*
* @author Jonathan Bruce
*/
public class SerialBlob implements Blob, Serializable, Cloneable {
/** {@collect.stats}
* A serialized array of uninterpreted bytes representing the
* value of this <code>SerialBlob</code> object.
* @serial
*/
private byte buf[];
/** {@collect.stats}
* The internal representation of the <code>Blob</code> object on which this
* <code>SerialBlob</code> object is based.
*/
private Blob blob;
/** {@collect.stats}
* The number of bytes in this <code>SerialBlob</code> object's
* array of bytes.
* @serial
*/
private long len;
/** {@collect.stats}
* The orginal number of bytes in this <code>SerialBlob</code> object's
* array of bytes when it was first established.
* @serial
*/
private long origLen;
/** {@collect.stats}
* Constructs a <code>SerialBlob</code> object that is a serialized version of
* the given <code>byte</code> array.
* <p>
* The new <code>SerialBlob</code> object is initialized with the data from the
* <code>byte</code> array, thus allowing disconnected <code>RowSet</code>
* objects to establish serialized <code>Blob</code> objects without
* touching the data source.
*
* @param b the <code>byte</code> array containing the data for the
* <code>Blob</code> object to be serialized
* @throws SerialException if an error occurs during serialization
* @throws SQLException if a SQL errors occurs
*/
public SerialBlob(byte[] b) throws SerialException, SQLException {
len = b.length;
buf = new byte[(int)len];
for(int i = 0; i < len; i++) {
buf[i] = b[i];
}
origLen = len;
}
/** {@collect.stats}
* Constructs a <code>SerialBlob</code> object that is a serialized
* version of the given <code>Blob</code> object.
* <P>
* The new <code>SerialBlob</code> object is initialized with the
* data from the <code>Blob</code> object; therefore, the
* <code>Blob</code> object should have previously brought the
* SQL <code>BLOB</code> value's data over to the client from
* the database. Otherwise, the new <code>SerialBlob</code> object
* will contain no data.
*
* @param blob the <code>Blob</code> object from which this
* <code>SerialBlob</code> object is to be constructed;
* cannot be null.
* @throws SerialException if an error occurs during serialization
* @throws SQLException if the <code>Blob</code> passed to this
* to this constructor is a <code>null</code>.
* @see java.sql.Blob
*/
public SerialBlob (Blob blob) throws SerialException, SQLException {
if (blob == null) {
throw new SQLException("Cannot instantiate a SerialBlob " +
"object with a null Blob object");
}
len = blob.length();
buf = blob.getBytes(1, (int)len );
this.blob = blob;
//if ( len < 10240000)
// len = 10240000;
origLen = len;
}
/** {@collect.stats}
* Copies the specified number of bytes, starting at the given
* position, from this <code>SerialBlob</code> object to
* another array of bytes.
* <P>
* Note that if the given number of bytes to be copied is larger than
* the length of this <code>SerialBlob</code> object's array of
* bytes, the given number will be shortened to the array's length.
*
* @param pos the ordinal position of the first byte in this
* <code>SerialBlob</code> object to be copied;
* numbering starts at <code>1</code>; must not be less
* than <code>1</code> and must be less than or equal
* to the length of this <code>SerialBlob</code> object
* @param length the number of bytes to be copied
* @return an array of bytes that is a copy of a region of this
* <code>SerialBlob</code> object, starting at the given
* position and containing the given number of consecutive bytes
* @throws SerialException if the given starting position is out of bounds
*/
public byte[] getBytes(long pos, int length) throws SerialException {
if (length > len) {
length = (int)len;
}
if (pos < 1 || length - pos < 0 ) {
throw new SerialException("Invalid arguments: position cannot be less that 1");
}
pos--; // correct pos to array index
byte[] b = new byte[length];
for (int i = 0; i < length; i++) {
b[i] = this.buf[(int)pos];
pos++;
}
return b;
}
/** {@collect.stats}
* Retrieves the number of bytes in this <code>SerialBlob</code>
* object's array of bytes.
*
* @return a <code>long</code> indicating the length in bytes of this
* <code>SerialBlob</code> object's array of bytes
* @throws SerialException if an error occurs
*/
public long length() throws SerialException {
return len;
}
/** {@collect.stats}
* Returns this <code>SerialBlob</code> object as an input stream.
* Unlike the related method, <code>setBinaryStream</code>,
* a stream is produced regardless of whether the <code>SerialBlob</code>
* was created with a <code>Blob</code> object or a <code>byte</code> array.
*
* @return a <code>java.io.InputStream</code> object that contains
* this <code>SerialBlob</code> object's array of bytes
* @throws SerialException if an error occurs
* @see #setBinaryStream
*/
public java.io.InputStream getBinaryStream() throws SerialException {
InputStream stream = new ByteArrayInputStream(buf);
return (java.io.InputStream)stream;
}
/** {@collect.stats}
* Returns the position in this <code>SerialBlob</code> object where
* the given pattern of bytes begins, starting the search at the
* specified position.
*
* @param pattern the pattern of bytes for which to search
* @param start the position of the byte in this
* <code>SerialBlob</code> object from which to begin
* the search; the first position is <code>1</code>;
* must not be less than <code>1</code> nor greater than
* the length of this <code>SerialBlob</code> object
* @return the position in this <code>SerialBlob</code> object
* where the given pattern begins, starting at the specified
* position; <code>-1</code> if the pattern is not found
* or the given starting position is out of bounds; position
* numbering for the return value starts at <code>1</code>
* @throws SerialException if an error occurs when serializing the blob
* @throws SQLException if there is an error accessing the <code>BLOB</code>
* value from the database
*/
public long position(byte[] pattern, long start)
throws SerialException, SQLException {
if (start < 1 || start > len) {
return -1;
}
int pos = (int)start-1; // internally Blobs are stored as arrays.
int i = 0;
long patlen = pattern.length;
while (pos < len) {
if (pattern[i] == buf[pos]) {
if (i + 1 == patlen) {
return (pos + 1) - (patlen - 1);
}
i++; pos++; // increment pos, and i
} else if (pattern[i] != buf[pos]) {
pos++; // increment pos only
}
}
return -1; // not found
}
/** {@collect.stats}
* Returns the position in this <code>SerialBlob</code> object where
* the given <code>Blob</code> object begins, starting the search at the
* specified position.
*
* @param pattern the <code>Blob</code> object for which to search;
* @param start the position of the byte in this
* <code>SerialBlob</code> object from which to begin
* the search; the first position is <code>1</code>;
* must not be less than <code>1</code> nor greater than
* the length of this <code>SerialBlob</code> object
* @return the position in this <code>SerialBlob</code> object
* where the given <code>Blob</code> object begins, starting
* at the specified position; <code>-1</code> if the pattern is
* not found or the given starting position is out of bounds;
* position numbering for the return value starts at <code>1</code>
* @throws SerialException if an error occurs when serializing the blob
* @throws SQLException if there is an error accessing the <code>BLOB</code>
* value from the database
*/
public long position(Blob pattern, long start)
throws SerialException, SQLException {
return position(pattern.getBytes(1, (int)(pattern.length())), start);
}
/** {@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.
*
* @param pos the position in the SQL <code>BLOB</code> value at which
* to start writing. The first position is <code>1</code>;
* must not be less than <code>1</code> nor greater than
* the length of this <code>SerialBlob</code> object.
* @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
* @throws SerialException if there is an error accessing the
* <code>BLOB</code> value; or if an invalid position is set; if an
* invalid offset value is set
* @throws SQLException if there is an error accessing the <code>BLOB</code>
* value from the database
* @see #getBytes
*/
public int setBytes(long pos, byte[] bytes)
throws SerialException, SQLException {
return (setBytes(pos, bytes, 0, bytes.length));
}
/** {@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; <i>len</i> bytes from the given byte array are written.
*
* @param pos the position in the <code>BLOB</code> object at which
* to start writing. The first position is <code>1</code>;
* must not be less than <code>1</code> nor greater than
* the length of this <code>SerialBlob</code> object.
* @param bytes the array of bytes to be written to the <code>BLOB</code>
* value
* @param offset the offset in the <code>byte</code> array at which
* to start reading the bytes. The first offset position is
* <code>0</code>; must not be less than <code>0</code> nor greater
* than the length of the <code>byte</code> array
* @param length the number of bytes to be written to the
* <code>BLOB</code> value from the array of bytes <i>bytes</i>.
*
* @return the number of bytes written
* @throws SerialException if there is an error accessing the
* <code>BLOB</code> value; if an invalid position is set; if an
* invalid offset value is set; if number of bytes to be written
* is greater than the <code>SerialBlob</code> length; or the combined
* values of the length and offset is greater than the Blob buffer
* @throws SQLException if there is an error accessing the <code>BLOB</code>
* value from the database.
* @see #getBytes
*/
public int setBytes(long pos, byte[] bytes, int offset, int length)
throws SerialException, SQLException {
if (offset < 0 || offset > bytes.length) {
throw new SerialException("Invalid offset in byte array set");
}
if (pos < 1 || pos > this.length()) {
throw new SerialException("Invalid position in BLOB object set");
}
if ((long)(length) > origLen) {
throw new SerialException("Buffer is not sufficient to hold the value");
}
if ((length + offset) > bytes.length) {
throw new SerialException("Invalid OffSet. Cannot have combined offset " +
"and length that is greater that the Blob buffer");
}
int i = 0;
pos--; // correct to array indexing
while ( i < length || (offset + i +1) < (bytes.length-offset) ) {
this.buf[(int)pos + i] = bytes[offset + i ];
i++;
}
return i;
}
/** {@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>. This method forwards the
* <code>setBinaryStream()</code> call to the underlying <code>Blob</code> in
* the event that this <code>SerialBlob</code> object is instantiated with a
* <code>Blob</code>. If this <code>SerialBlob</code> is instantiated with
* a <code>byte</code> array, a <code>SerialException</code> is thrown.
*
* @param pos the position in the <code>BLOB</code> value at which
* to start writing
* @return a <code>java.io.OutputStream</code> object to which data can
* be written
* @throws SQLException if there is an error accessing the
* <code>BLOB</code> value
* @throws SerialException if the SerialBlob in not instantiated with a
* <code>Blob</code> object that supports <code>setBinaryStream()</code>
* @see #getBinaryStream
*/
public java.io.OutputStream setBinaryStream(long pos)
throws SerialException, SQLException {
if (this.blob.setBinaryStream(pos) != null) {
return this.blob.setBinaryStream(pos);
} else {
throw new SerialException("Unsupported operation. SerialBlob cannot " +
"return a writable binary stream, unless instantiated with a Blob object " +
"that provides a setBinaryStream() implementation");
}
}
/** {@collect.stats}
* Truncates the <code>BLOB</code> value that this <code>Blob</code>
* object represents to be <code>len</code> bytes in length.
*
* @param length the length, in bytes, to which the <code>BLOB</code>
* value that this <code>Blob</code> object represents should be
* truncated
* @throws SerialException if there is an error accessing the Blob value;
* or the length to truncate is greater that the SerialBlob length
*/
public void truncate(long length) throws SerialException {
if (length > len) {
throw new SerialException
("Length more than what can be truncated");
} else if((int)length == 0) {
buf = new byte[0];
len = length;
} else {
len = length;
buf = this.getBytes(1, (int)len);
}
}
/** {@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>
*
* @since 1.6
*/
public InputStream getBinaryStream(long pos,long length) throws SQLException {
throw new java.lang.UnsupportedOperationException("Not supported");
}
/** {@collect.stats}
* This method frees the <code>Blob</code> object and releases the resources that it holds.
* <code>Blob</code> object. The object is invalid once the <code>free</code>
* method is called. If <code>free</code> is called multiple times, the subsequent
* calls to <code>free</code> are treated as a no-op.
*
* @throws SQLException if an error occurs releasing
* the Blob's resources
* @since 1.6
*/
public void free() throws SQLException {
throw new java.lang.UnsupportedOperationException("Not supported");
}
/** {@collect.stats}
* The identifier that assists in the serialization of this <code>SerialBlob</code>
* object.
*/
static final long serialVersionUID = -8144641928112860441L;
}
| Java |
/*
* Copyright (c) 2003, 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 javax.sql.rowset.serial;
import java.sql.SQLException;
/** {@collect.stats}
* Indicates and an error with the serialization or de-serialization of
* SQL types such as <code>BLOB, CLOB, STRUCT or ARRAY</code> in
* addition to SQL types such as <code>DATALINK and JAVAOBJECT</code>
*
*/
public class SerialException extends java.sql.SQLException {
/** {@collect.stats}
* Creates a new <code>SerialException</code> without a
* message.
*/
public SerialException() {
}
/** {@collect.stats}
* Creates a new <code>SerialException</code> with the
* specified message.
*
* @param msg the detail message
*/
public SerialException(String msg) {
super(msg);
}
static final long serialVersionUID = -489794565168592690L;
}
| Java |
/*
* Copyright (c) 2003, 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 javax.sql.rowset.serial;
import java.sql.*;
import java.io.*;
import java.net.URL;
/** {@collect.stats}
* A serialized mapping in the Java programming language of an SQL
* <code>DATALINK</code> value. A <code>DATALINK</code> value
* references a file outside of the underlying data source that the
* data source manages.
* <P>
* <code>RowSet</code> implementations can use the method <code>RowSet.getURL</code>
* to retrieve a <code>java.net.URL</code> object, which can be used
* to manipulate the external data.
* <pre>
* java.net.URL url = rowset.getURL(1);
* </pre>
*/
public class SerialDatalink implements Serializable, Cloneable {
/** {@collect.stats}
* The extracted URL field retrieved from the DATALINK field.
* @serial
*/
private URL url;
/** {@collect.stats}
* The SQL type of the elements in this <code>SerialDatalink</code>
* object. The type is expressed as one of the contants from the
* class <code>java.sql.Types</code>.
* @serial
*/
private int baseType;
/** {@collect.stats}
* The type name used by the DBMS for the elements in the SQL
* <code>DATALINK</code> value that this SerialDatalink object
* represents.
* @serial
*/
private String baseTypeName;
/** {@collect.stats}
* Constructs a new <code>SerialDatalink</code> object from the given
* <code>java.net.URL</code> object.
* <P>
* @throws SerialException if url parameter is a null
*/
public SerialDatalink(URL url) throws SerialException {
if (url == null) {
throw new SerialException("Cannot serialize empty URL instance");
}
this.url = url;
}
/** {@collect.stats}
* Returns a new URL that is a copy of this <code>SerialDatalink</code>
* object.
*
* @return a copy of this <code>SerialDatalink</code> object as a
* <code>URL</code> object in the Java programming language.
* @throws SerialException if the <code>URL</code> object cannot be de-serialized
*/
public URL getDatalink() throws SerialException {
URL aURL = null;
try {
aURL = new URL((this.url).toString());
} catch (java.net.MalformedURLException e) {
throw new SerialException("MalformedURLException: " + e.getMessage());
}
return aURL;
}
/** {@collect.stats}
* The identifier that assists in the serialization of this <code>SerialDatalink</code>
* object.
*/
static final long serialVersionUID = 2826907821828733626L;
}
| 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 javax.sql.rowset.serial;
import java.sql.*;
import java.io.*;
import java.util.Map;
import java.lang.reflect.*;
import javax.sql.rowset.RowSetWarning;
/** {@collect.stats}
* A serializable mapping in the Java programming language of an SQL
* <code>JAVA_OBJECT</code> value. Assuming the Java object
* implements the <code>Serializable</code> interface, this class simply wraps the
* serialization process.
* <P>
* If however, the serialization is not possible because
* the Java object is not immediately serializable, this class will
* attempt to serialize all non-static members to permit the object
* state to be serialized.
* Static or transient fields cannot be serialized; an attempt to serialize
* them will result in a <code>SerialException</code> object being thrown.
*
* @author Jonathan Bruce
*/
public class SerialJavaObject implements Serializable, Cloneable {
/** {@collect.stats}
* Placeholder for object to be serialized.
*/
private Object obj;
/** {@collect.stats}
* Placeholder for all fields in the <code>JavaObject</code> being serialized.
*/
private transient Field[] fields;
/** {@collect.stats}
* Constructor for <code>SerialJavaObject</code> helper class.
* <p>
*
* @param obj the Java <code>Object</code> to be serialized
* @throws SerialException if the object is found
* to be unserializable
*/
public SerialJavaObject(Object obj) throws SerialException {
// if any static fields are found, an exception
// should be thrown
// get Class. Object instance should always be available
Class c = obj.getClass();
// determine if object implements Serializable i/f
boolean serializableImpl = false;
Class[] theIf = c.getInterfaces();
for (int i = 0; i < theIf.length; i++) {
String ifName = theIf[i].getName();
if (ifName == "java.io.Serializable") {
serializableImpl = true;
}
}
// can only determine public fields (obviously). If
// any of these are static, this should invalidate
// the action of attempting to persist these fields
// in a serialized form
boolean anyStaticFields = false;
fields = c.getFields();
//fields = new Object[field.length];
for (int i = 0; i < fields.length; i++ ) {
if ( fields[i].getModifiers() == Modifier.STATIC ) {
anyStaticFields = true;
}
//fields[i] = field[i].get(obj);
}
try {
if (!(serializableImpl)) {
throw new RowSetWarning("Test");
}
} catch (RowSetWarning w) {
setWarning(w);
}
if (anyStaticFields) {
throw new SerialException("Located static fields in " +
"object instance. Cannot serialize");
}
this.obj = obj;
}
/** {@collect.stats}
* Returns an <code>Object</code> that is a copy of this <code>SerialJavaObject</code>
* object.
*
* @return a copy of this <code>SerialJavaObject</code> object as an
* <code>Object</code> in the Java programming language
* @throws SerialException if the instance is corrupt
*/
public Object getObject() throws SerialException {
return this.obj;
}
/** {@collect.stats}
* Returns an array of <code>Field</code> objects that contains each
* field of the object that this helper class is serializing.
*
* @return an array of <code>Field</code> objects
* @throws SerialException if an error is encountered accessing
* the serialized object
*/
public Field[] getFields() throws SerialException {
if (fields != null) {
Class c = this.obj.getClass();
//the following has to be commented before mustang integration
//return c.getFields();
//the following has to be uncommented before mustang integration
return sun.reflect.misc.FieldUtil.getFields(c);
} else {
throw new SerialException("SerialJavaObject does not contain" +
" a serialized object instance");
}
}
/** {@collect.stats}
* The identifier that assists in the serialization of this
* <code>SerialJavaObject</code> object.
*/
static final long serialVersionUID = -1465795139032831023L;
/** {@collect.stats}
* A container for the warnings issued on this <code>SerialJavaObject</code>
* object. When there are multiple warnings, each warning is chained to the
* previous warning.
*/
java.util.Vector chain;
/** {@collect.stats}
* Registers the given warning.
*/
private void setWarning(RowSetWarning e) {
if (chain == null) {
chain = new java.util.Vector();
}
chain.add(e);
}
}
| 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 javax.sql.rowset.serial;
import java.sql.*;
import javax.sql.*;
import java.io.*;
import java.math.*;
import java.util.Map;
/** {@collect.stats}
* An input stream used for custom mapping user-defined types (UDTs).
* An <code>SQLInputImpl</code> object is an input stream that contains a
* stream of values that are the attributes of a UDT.
* <p>
* This class is used by the driver behind the scenes when the method
* <code>getObject</code> is called on an SQL structured or distinct type
* that has a custom mapping; a programmer never invokes
* <code>SQLInputImpl</code> methods directly. They are provided here as a
* convenience for those who write <code>RowSet</code> implementations.
* <P>
* The <code>SQLInputImpl</code> class provides a set of
* reader methods analogous to the <code>ResultSet</code> getter
* methods. These methods make it possible to read the values in an
* <code>SQLInputImpl</code> object.
* <P>
* The method <code>wasNull</code> is used to determine whether the
* 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 UDT being custom mapped. The driver
* creates an instance of <code>SQLInputImpl</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>SQLInputImpl</code> reader methods
* to read the attributes from the input stream.
* @see java.sql.SQLData
*/
public class SQLInputImpl implements SQLInput {
/** {@collect.stats}
* <code>true</code> if the last value returned was <code>SQL NULL</code>;
* <code>false</code> otherwise.
*/
private boolean lastValueWasNull;
/** {@collect.stats}
* The current index into the array of SQL structured type attributes
* that will be read from this <code>SQLInputImpl</code> object and
* mapped to the fields of a class in the Java programming language.
*/
private int idx;
/** {@collect.stats}
* The array of attributes to be read from this stream. The order
* of the attributes is the same as the order in which they were
* listed in the SQL definition of the UDT.
*/
private Object attrib[];
/** {@collect.stats}
* The type map to use when the method <code>readObject</code>
* is invoked. This is a <code>java.util.Map</code> object in which
* there may be zero or more entries. Each entry consists of the
* fully qualified name of a UDT (the value to be mapped) and the
* <code>Class</code> object for a class that implements
* <code>SQLData</code> (the Java class that defines how the UDT
* will be mapped).
*/
private Map map;
/** {@collect.stats}
* Creates an <code>SQLInputImpl</code> object initialized with the
* given array of attributes and the given type map. If any of the
* attributes is a UDT whose name is in an entry in the type map,
* the attribute will be mapped according to the corresponding
* <code>SQLData</code> implementation.
*
* @param attributes an array of <code>Object</code> instances in which
* each element is an attribute of a UDT. The order of the
* attributes in the array is the same order in which
* the attributes were defined in the UDT definition.
* @param map a <code>java.util.Map</code> object containing zero or more
* entries, with each entry consisting of 1) a <code>String</code>
* giving the fully
* qualified name of the UDT and 2) the <code>Class</code> object
* for the <code>SQLData</code> implementation that defines how
* the UDT is to be mapped
* @throws SQLException if the <code>attributes</code> or the <code>map</code>
* is a <code>null</code> value
*/
public SQLInputImpl(Object[] attributes, Map<String,Class<?>> map)
throws SQLException
{
if ((attributes == null) || (map == null)) {
throw new SQLException("Cannot instantiate a SQLInputImpl " +
"object with null parameters");
}
// assign our local reference to the attribute stream
attrib = attributes;
// init the index point before the head of the stream
idx = -1;
// set the map
this.map = map;
}
/** {@collect.stats}
* Retrieves the next attribute in this <code>SQLInputImpl</code> object
* as an <code>Object</code> in the Java programming language.
*
* @return the next value in the input stream
* as an <code>Object</code> in the Java programming language
* @throws SQLException if the read position is located at an invalid
* position or if there are no further values in the stream
*/
private Object getNextAttribute() throws SQLException {
if (++idx >= attrib.length) {
throw new SQLException("SQLInputImpl exception: Invalid read " +
"position");
} else {
return attrib[idx];
}
}
//================================================================
// Methods for reading attributes from the stream of SQL data.
// These methods correspond to the column-accessor methods of
// java.sql.ResultSet.
//================================================================
/** {@collect.stats}
* Retrieves the next attribute in this <code>SQLInputImpl</code> object as
* a <code>String</code> in the Java programming language.
* <p>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type; this responsibility is delegated
* to the UDT mapping as defined by a <code>SQLData</code>
* implementation.
* <p>
* @return the next attribute in this <code>SQLInputImpl</code> object;
* if the value is <code>SQL NULL</code>, return <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position or if there are no further values in the stream.
*/
public String readString() throws SQLException {
String attrib = (String)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return null;
} else {
lastValueWasNull = false;
return attrib;
}
}
/** {@collect.stats}
* Retrieves the next attribute in this <code>SQLInputImpl</code> object as
* a <code>boolean</code> in the Java programming language.
* <p>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type; this responsibility is delegated
* to the UDT mapping as defined by a <code>SQLData</code>
* implementation.
* <p>
* @return the next attribute in this <code>SQLInputImpl</code> object;
* if the value is <code>SQL NULL</code>, return <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position or if there are no further values in the stream.
*/
public boolean readBoolean() throws SQLException {
Boolean attrib = (Boolean)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return false;
} else {
lastValueWasNull = false;
return attrib.booleanValue();
}
}
/** {@collect.stats}
* Retrieves the next attribute in this <code>SQLInputImpl</code> object as
* a <code>byte</code> in the Java programming language.
* <p>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type; this responsibility is delegated
* to the UDT mapping as defined by a <code>SQLData</code>
* implementation.
* <p>
* @return the next attribute in this <code>SQLInputImpl</code> object;
* if the value is <code>SQL NULL</code>, return <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position or if there are no further values in the stream
*/
public byte readByte() throws SQLException {
Byte attrib = (Byte)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return (byte)0;
} else {
lastValueWasNull = false;
return attrib.byteValue();
}
}
/** {@collect.stats}
* Retrieves the next attribute in this <code>SQLInputImpl</code> object
* as a <code>short</code> in the Java programming language.
* <P>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type; this responsibility is delegated
* to the UDT mapping as defined by a <code>SQLData</code> implementation.
* <P>
* @return the next attribute in this <code>SQLInputImpl</code> object;
* if the value is <code>SQL NULL</code>, return <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position or if there are no more values in the stream
*/
public short readShort() throws SQLException {
Short attrib = (Short)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return (short)0;
} else {
lastValueWasNull = false;
return attrib.shortValue();
}
}
/** {@collect.stats}
* Retrieves the next attribute in this <code>SQLInputImpl</code> object
* as an <code>int</code> in the Java programming language.
* <P>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type; this responsibility is delegated
* to the UDT mapping as defined by a <code>SQLData</code> implementation.
* <P>
* @return the next attribute in this <code>SQLInputImpl</code> object;
* if the value is <code>SQL NULL</code>, return <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position or if there are no more values in the stream
*/
public int readInt() throws SQLException {
Integer attrib = (Integer)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return (int)0;
} else {
lastValueWasNull = false;
return attrib.intValue();
}
}
/** {@collect.stats}
* Retrieves the next attribute in this <code>SQLInputImpl</code> object
* as a <code>long</code> in the Java programming language.
* <P>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type; this responsibility is delegated
* to the UDT mapping as defined by a <code>SQLData</code> implementation.
* <P>
* @return the next attribute in this <code>SQLInputImpl</code> object;
* if the value is <code>SQL NULL</code>, return <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position or if there are no more values in the stream
*/
public long readLong() throws SQLException {
Long attrib = (Long)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return (long)0;
} else {
lastValueWasNull = false;
return attrib.longValue();
}
}
/** {@collect.stats}
* Retrieves the next attribute in this <code>SQLInputImpl</code> object
* as a <code>float</code> in the Java programming language.
* <P>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type; this responsibility is delegated
* to the UDT mapping as defined by a <code>SQLData</code> implementation.
* <P>
* @return the next attribute in this <code>SQLInputImpl</code> object;
* if the value is <code>SQL NULL</code>, return <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position or if there are no more values in the stream
*/
public float readFloat() throws SQLException {
Float attrib = (Float)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return (float)0;
} else {
lastValueWasNull = false;
return attrib.floatValue();
}
}
/** {@collect.stats}
* Retrieves the next attribute in this <code>SQLInputImpl</code> object
* as a <code>double</code> in the Java programming language.
* <P>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type; this responsibility is delegated
* to the UDT mapping as defined by a <code>SQLData</code> implementation.
* <P>
* @return the next attribute in this <code>SQLInputImpl</code> object;
* if the value is <code>SQL NULL</code>, return <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position or if there are no more values in the stream
*/
public double readDouble() throws SQLException {
Double attrib = (Double)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return (double)0;
} else {
lastValueWasNull = false;
return attrib.doubleValue();
}
}
/** {@collect.stats}
* Retrieves the next attribute in this <code>SQLInputImpl</code> object
* as a <code>java.math.BigDecimal</code>.
* <P>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type; this responsibility is delegated
* to the UDT mapping as defined by a <code>SQLData</code> implementation.
* <P>
* @return the next attribute in this <code>SQLInputImpl</code> object;
* if the value is <code>SQL NULL</code>, return <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position or if there are no more values in the stream
*/
public java.math.BigDecimal readBigDecimal() throws SQLException {
java.math.BigDecimal attrib = (java.math.BigDecimal)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return null;
} else {
lastValueWasNull = false;
return attrib;
}
}
/** {@collect.stats}
* Retrieves the next attribute in this <code>SQLInputImpl</code> object
* as an array of bytes.
* <p>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type; this responsibility is delegated
* to the UDT mapping as defined by a <code>SQLData</code> implementation.
* <P>
* @return the next attribute in this <code>SQLInputImpl</code> object;
* if the value is <code>SQL NULL</code>, return <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position or if there are no more values in the stream
*/
public byte[] readBytes() throws SQLException {
byte[] attrib = (byte[])getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return null;
} else {
lastValueWasNull = false;
return attrib;
}
}
/** {@collect.stats}
* Retrieves the next attribute in this <code>SQLInputImpl</code> as
* a <code>java.sql.Date</code> object.
* <P>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type; this responsibility is delegated
* to the UDT mapping as defined by a <code>SQLData</code> implementation.
* <P>
* @return the next attribute in this <code>SQLInputImpl</code> object;
* if the value is <code>SQL NULL</code>, return <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position or if there are no more values in the stream
*/
public java.sql.Date readDate() throws SQLException {
java.sql.Date attrib = (java.sql.Date)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return null;
} else {
lastValueWasNull = false;
return attrib;
}
}
/** {@collect.stats}
* Retrieves the next attribute in this <code>SQLInputImpl</code> object as
* a <code>java.sql.Time</code> object.
* <P>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type as this responsibility is delegated
* to the UDT mapping as implemented by a <code>SQLData</code>
* implementation.
*
* @return the attribute; if the value is <code>SQL NULL</code>, return
* <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position; or if there are no further values in the stream.
*/
public java.sql.Time readTime() throws SQLException {
java.sql.Time attrib = (java.sql.Time)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return null;
} else {
lastValueWasNull = false;
return attrib;
}
}
/** {@collect.stats}
* Retrieves the next attribute in this <code>SQLInputImpl</code> object as
* a <code>java.sql.Timestamp</code> object.
*
* @return the attribute; if the value is <code>SQL NULL</code>, return
* <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position; or if there are no further values in the stream.
*/
public java.sql.Timestamp readTimestamp() throws SQLException {
java.sql.Timestamp attrib = (java.sql.Timestamp)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return null;
} else {
lastValueWasNull = false;
return attrib;
}
}
/** {@collect.stats}
* Retrieves the next attribute in this <code>SQLInputImpl</code> object
* as a stream of Unicode characters.
* <P>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type as this responsibility is delegated
* to the UDT mapping as implemented by a <code>SQLData</code>
* implementation.
*
* @return the attribute; if the value is <code>SQL NULL</code>, return <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position; or if there are no further values in the stream.
*/
public java.io.Reader readCharacterStream() throws SQLException {
java.io.Reader attrib = (java.io.Reader)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return null;
} else {
lastValueWasNull = false;
return attrib;
}
}
/** {@collect.stats}
* Returns the next attribute in this <code>SQLInputImpl</code> object
* as a stream of ASCII characters.
* <P>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type as this responsibility is delegated
* to the UDT mapping as implemented by a <code>SQLData</code>
* implementation.
*
* @return the attribute; if the value is <code>SQL NULL</code>,
* return <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position; or if there are no further values in the stream.
*/
public java.io.InputStream readAsciiStream() throws SQLException {
java.io.InputStream attrib = (java.io.InputStream)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return null;
} else {
lastValueWasNull = false;
return attrib;
}
}
/** {@collect.stats}
* Returns the next attribute in this <code>SQLInputImpl</code> object
* as a stream of uninterpreted bytes.
* <P>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type as this responsibility is delegated
* to the UDT mapping as implemented by a <code>SQLData</code>
* implementation.
*
* @return the attribute; if the value is <code>SQL NULL</code>, return
* <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position; or if there are no further values in the stream.
*/
public java.io.InputStream readBinaryStream() throws SQLException {
java.io.InputStream attrib = (java.io.InputStream)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return null;
} else {
lastValueWasNull = false;
return attrib;
}
}
//================================================================
// Methods for reading items of SQL user-defined types from the stream.
//================================================================
/** {@collect.stats}
* Retrieves the value at the head of this <code>SQLInputImpl</code>
* object as an <code>Object</code> in the Java programming language. The
* actual type of the object returned is determined by the default
* mapping of SQL types to types in the Java programming language unless
* there is a custom mapping, in which case the type of the object
* returned is determined by this stream's type map.
* <P>
* The JDBC technology-enabled driver registers a type map with the stream
* before passing the stream to the application.
* <P>
* When the datum at the head of the stream is an SQL <code>NULL</code>,
* this method returns <code>null</code>. If the datum is an SQL
* structured or distinct type with a custom mapping, this method
* determines the SQL type of the datum at the head of the stream,
* constructs an object of the appropriate class, and calls the method
* <code>SQLData.readSQL</code> on that object. The <code>readSQL</code>
* method then calls the appropriate <code>SQLInputImpl.readXXX</code>
* methods to retrieve the attribute values from the stream.
*
* @return the value at the head of the stream as an <code>Object</code>
* in the Java programming language; <code>null</code> if
* the value is SQL <code>NULL</code>
* @throws SQLException if the read position is located at an invalid
* position; or if there are no further values in the stream.
*/
public Object readObject() throws SQLException {
Object attrib = (Object)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return null;
} else {
lastValueWasNull = false;
if (attrib instanceof Struct) {
Struct s = (Struct)attrib;
// look up the class in the map
Class c = (Class)map.get(s.getSQLTypeName());
if (c != null) {
// create new instance of the class
SQLData obj = null;
try {
obj = (SQLData)c.newInstance();
} catch (java.lang.InstantiationException ex) {
throw new SQLException("Unable to instantiate: " +
ex.getMessage());
} catch (java.lang.IllegalAccessException ex) {
throw new SQLException("Unable to instantiate: " +
ex.getMessage());
}
// get the attributes from the struct
Object attribs[] = s.getAttributes(map);
// create the SQLInput "stream"
SQLInputImpl sqlInput = new SQLInputImpl(attribs, map);
// read the values...
obj.readSQL(sqlInput, s.getSQLTypeName());
return (Object)obj;
}
}
return (Object)attrib;
}
}
/** {@collect.stats}
* Retrieves the value at the head of this <code>SQLInputImpl</code> object
* 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; if the value
* is <code>SQL NULL</code> return <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position; or if there are no further values in the stream.
*/
public Ref readRef() throws SQLException {
Ref attrib = (Ref)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return null;
} else {
lastValueWasNull = false;
return attrib;
}
}
/** {@collect.stats}
* Retrieves the <code>BLOB</code> value at the head of this
* <code>SQLInputImpl</code> object as a <code>Blob</code> object
* in the Java programming language.
* <P>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type as this responsibility is delegated
* to the UDT mapping as implemented by a <code>SQLData</code>
* implementation.
*
* @return a <code>Blob</code> object representing the SQL
* <code>BLOB</code> value at the head of this stream;
* if the value is <code>SQL NULL</code>, return
* <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position; or if there are no further values in the stream.
*/
public Blob readBlob() throws SQLException {
Blob attrib = (Blob)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return null;
} else {
lastValueWasNull = false;
return attrib;
}
}
/** {@collect.stats}
* Retrieves the <code>CLOB</code> value at the head of this
* <code>SQLInputImpl</code> object as a <code>Clob</code> object
* in the Java programming language.
* <P>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type as this responsibility is delegated
* to the UDT mapping as implemented by a <code>SQLData</code>
* implementation.
*
* @return a <code>Clob</code> object representing the SQL
* <code>CLOB</code> value at the head of the stream;
* if the value is <code>SQL NULL</code>, return
* <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position; or if there are no further values in the stream.
*/
public Clob readClob() throws SQLException {
Clob attrib = (Clob)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return null;
} else {
lastValueWasNull = false;
return attrib;
}
}
/** {@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.
* <P>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type as this responsibility is delegated
* to the UDT mapping as implemented by a <code>SQLData</code>
* implementation.
*
* @return an <code>Array</code> object representing the SQL
* <code>ARRAY</code> value at the head of the stream; *
* if the value is <code>SQL NULL</code>, return
* <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position; or if there are no further values in the stream.
*/
public Array readArray() throws SQLException {
Array attrib = (Array)getNextAttribute();
if (attrib == null) {
lastValueWasNull = true;
return null;
} else {
lastValueWasNull = false;
return attrib;
}
}
/** {@collect.stats}
* Ascertains whether the last value read from this
* <code>SQLInputImpl</code> object was <code>null</code>.
*
* @return <code>true</code> if the SQL value read most recently was
* <code>null</code>; otherwise, <code>false</code>; by default it
* will return false
* @throws SQLException if an error occurs determining the last value
* read was a <code>null</code> value or not;
*/
public boolean wasNull() throws SQLException {
return lastValueWasNull;
}
/** {@collect.stats}
* Reads an SQL <code>DATALINK</code> value from the stream and
* returns it as an <code>URL</code> object in the Java programming
* language.
* <P>
* This method does not perform type-safe checking to determine if the
* returned type is the expected type as this responsibility is delegated
* to the UDT mapping as implemented by a <code>SQLData</code>
* implementation.
*
* @return an <code>URL</code> object representing the SQL
* <code>DATALINK</code> value at the head of the stream; *
* if the value is <code>SQL NULL</code>, return
* <code>null</code>
* @throws SQLException if the read position is located at an invalid
* position; or if there are no further values in the stream.
*/
public java.net.URL readURL() throws SQLException {
throw new SQLException("Operation not supported");
}
//---------------------------- JDBC 4.0 -------------------------
/** {@collect.stats}
* Reads an SQL <code>NCLOB</code> value from the stream and returns it as a
* <code>Clob</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
*/
public NClob readNClob() throws SQLException {
throw new UnsupportedOperationException("Operation not supported");
}
/** {@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
*/
public String readNString() throws SQLException {
throw new UnsupportedOperationException("Operation not supported");
}
/** {@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
*/
public SQLXML readSQLXML() throws SQLException {
throw new UnsupportedOperationException("Operation not supported");
}
/** {@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
*/
public RowId readRowId() throws SQLException {
throw new UnsupportedOperationException("Operation not supported");
}
}
| 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 javax.sql.rowset.serial;
import java.sql.*;
import javax.sql.*;
import java.io.*;
import java.lang.String;
import java.math.*;
import java.util.Map;
import java.util.Vector;
/** {@collect.stats}
* The output stream for writing the attributes of a
* custom-mapped user-defined type (UDT) back to the database.
* The driver uses this interface internally, and its
* methods are never directly invoked by an application programmer.
* <p>
* When an application calls the
* method <code>PreparedStatement.setObject</code>, the driver
* checks to see whether the value to be written is a UDT with
* a custom mapping. If it is, there will be an entry in a
* type map containing the <code>Class</code> object for the
* class that implements <code>SQLData</code> for this UDT.
* If the value to be written is an instance of <code>SQLData</code>,
* the driver will create an instance of <code>SQLOutputImpl</code>
* and pass it to the method <code>SQLData.writeSQL</code>.
* The method <code>writeSQL</code> in turn calls the
* appropriate <code>SQLOutputImpl.writeXXX</code> methods
* to write data from the <code>SQLData</code> object to
* the <code>SQLOutputImpl</code> output stream as the
* representation of an SQL user-defined type.
*/
public class SQLOutputImpl implements SQLOutput {
/** {@collect.stats}
* A reference to an existing vector that
* contains the attributes of a <code>Struct</code> object.
*/
private Vector attribs;
/** {@collect.stats}
* The type map the driver supplies to a newly created
* <code>SQLOutputImpl</code> object. This type map
* indicates the <code>SQLData</code> class whose
* <code>writeSQL</code> method will be called. This
* method will in turn call the appropriate
* <code>SQLOutputImpl</code> writer methods.
*/
private Map map;
/** {@collect.stats}
* Creates a new <code>SQLOutputImpl</code> object
* initialized with the given vector of attributes and
* type map. The driver will use the type map to determine
* which <code>SQLData.writeSQL</code> method to invoke.
* This method will then call the appropriate
* <code>SQLOutputImpl</code> writer methods in order and
* thereby write the attributes to the new output stream.
*
* @param attributes a <code>Vector</code> object containing the attributes of
* the UDT to be mapped to one or more objects in the Java
* programming language
*
* @param map a <code>java.util.Map</code> object containing zero or
* more entries, with each entry consisting of 1) a <code>String</code>
* giving the fully qualified name of a UDT and 2) the
* <code>Class</code> object for the <code>SQLData</code> implementation
* that defines how the UDT is to be mapped
* @throws SQLException if the <code>attributes</code> or the <code>map</code>
* is a <code>null</code> value
*/
public SQLOutputImpl(Vector<?> attributes, Map<String,?> map)
throws SQLException
{
if ((attributes == null) || (map == null)) {
throw new SQLException("Cannot instantiate a SQLOutputImpl " +
"instance with null parameters");
}
this.attribs = attributes;
this.map = map;
}
//================================================================
// 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 a <code>String</code> in the Java programming language
* to this <code>SQLOutputImpl</code> object. The driver converts
* it to an SQL <code>CHAR</code>, <code>VARCHAR</code>, or
* <code>LONGVARCHAR</code> before returning it to the database.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeString(String x) throws SQLException {
//System.out.println("Adding :"+x);
attribs.add(x);
}
/** {@collect.stats}
* Writes a <code>boolean</code> in the Java programming language
* to this <code>SQLOutputImpl</code> object. The driver converts
* it to an SQL <code>BIT</code> before returning it to the database.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeBoolean(boolean x) throws SQLException {
attribs.add(new Boolean(x));
}
/** {@collect.stats}
* Writes a <code>byte</code> in the Java programming language
* to this <code>SQLOutputImpl</code> object. The driver converts
* it to an SQL <code>BIT</code> before returning it to the database.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeByte(byte x) throws SQLException {
attribs.add(new Byte(x));
}
/** {@collect.stats}
* Writes a <code>short</code> in the Java programming language
* to this <code>SQLOutputImpl</code> object. The driver converts
* it to an SQL <code>SMALLINT</code> before returning it to the database.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeShort(short x) throws SQLException {
attribs.add(new Short(x));
}
/** {@collect.stats}
* Writes an <code>int</code> in the Java programming language
* to this <code>SQLOutputImpl</code> object. The driver converts
* it to an SQL <code>INTEGER</code> before returning it to the database.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeInt(int x) throws SQLException {
attribs.add(new Integer(x));
}
/** {@collect.stats}
* Writes a <code>long</code> in the Java programming language
* to this <code>SQLOutputImpl</code> object. The driver converts
* it to an SQL <code>BIGINT</code> before returning it to the database.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeLong(long x) throws SQLException {
attribs.add(new Long(x));
}
/** {@collect.stats}
* Writes a <code>float</code> in the Java programming language
* to this <code>SQLOutputImpl</code> object. The driver converts
* it to an SQL <code>REAL</code> before returning it to the database.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeFloat(float x) throws SQLException {
attribs.add(new Float(x));
}
/** {@collect.stats}
* Writes a <code>double</code> in the Java programming language
* to this <code>SQLOutputImpl</code> object. The driver converts
* it to an SQL <code>DOUBLE</code> before returning it to the database.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeDouble(double x) throws SQLException{
attribs.add(new Double(x));
}
/** {@collect.stats}
* Writes a <code>java.math.BigDecimal</code> object in the Java programming
* language to this <code>SQLOutputImpl</code> object. The driver converts
* it to an SQL <code>NUMERIC</code> before returning it to the database.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeBigDecimal(java.math.BigDecimal x) throws SQLException{
attribs.add(x);
}
/** {@collect.stats}
* Writes an array of <code>bytes</code> in the Java programming language
* to this <code>SQLOutputImpl</code> object. The driver converts
* it to an SQL <code>VARBINARY</code> or <code>LONGVARBINARY</code>
* before returning it to the database.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeBytes(byte[] x) throws SQLException {
attribs.add(x);
}
/** {@collect.stats}
* Writes a <code>java.sql.Date</code> object in the Java programming
* language to this <code>SQLOutputImpl</code> object. The driver converts
* it to an SQL <code>DATE</code> before returning it to the database.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeDate(java.sql.Date x) throws SQLException {
attribs.add(x);
}
/** {@collect.stats}
* Writes a <code>java.sql.Time</code> object in the Java programming
* language to this <code>SQLOutputImpl</code> object. The driver converts
* it to an SQL <code>TIME</code> before returning it to the database.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeTime(java.sql.Time x) throws SQLException {
attribs.add(x);
}
/** {@collect.stats}
* Writes a <code>java.sql.Timestamp</code> object in the Java programming
* language to this <code>SQLOutputImpl</code> object. The driver converts
* it to an SQL <code>TIMESTAMP</code> before returning it to the database.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeTimestamp(java.sql.Timestamp x) throws SQLException {
attribs.add(x);
}
/** {@collect.stats}
* Writes a stream of Unicode characters to this
* <code>SQLOutputImpl</code> object. The driver will do any necessary
* conversion from Unicode to the database <code>CHAR</code> format.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeCharacterStream(java.io.Reader x) throws SQLException {
BufferedReader bufReader = new BufferedReader(x);
try {
int i;
while( (i = bufReader.read()) != -1 ) {
char ch = (char)i;
StringBuffer strBuf = new StringBuffer();
strBuf.append(ch);
String str = new String(strBuf);
String strLine = bufReader.readLine();
writeString(str.concat(strLine));
}
} catch(IOException ioe) {
}
}
/** {@collect.stats}
* Writes a stream of ASCII characters to this
* <code>SQLOutputImpl</code> object. The driver will do any necessary
* conversion from ASCII to the database <code>CHAR</code> format.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeAsciiStream(java.io.InputStream x) throws SQLException {
BufferedReader bufReader = new BufferedReader(new InputStreamReader(x));
try {
int i;
while( (i=bufReader.read()) != -1 ) {
char ch = (char)i;
StringBuffer strBuf = new StringBuffer();
strBuf.append(ch);
String str = new String(strBuf);
String strLine = bufReader.readLine();
writeString(str.concat(strLine));
}
}catch(IOException ioe) {
throw new SQLException(ioe.getMessage());
}
}
/** {@collect.stats}
* Writes a stream of uninterpreted bytes to this <code>SQLOutputImpl</code>
* object.
*
* @param x the value to pass to the database
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeBinaryStream(java.io.InputStream x) throws SQLException {
BufferedReader bufReader = new BufferedReader(new InputStreamReader(x));
try {
int i;
while( (i=bufReader.read()) != -1 ) {
char ch = (char)i;
StringBuffer strBuf = new StringBuffer();
strBuf.append(ch);
String str = new String(strBuf);
String strLine = bufReader.readLine();
writeString(str.concat(strLine));
}
} catch(IOException ioe) {
throw new SQLException(ioe.getMessage());
}
}
//================================================================
// 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.
* <P>
* The implementation of the method <code>SQLData.writeSQ</code>
* calls the appropriate <code>SQLOutputImpl.writeXXX</code> 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>SQLOutputImpl</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
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeObject(SQLData x) throws SQLException {
/*
* Except for the types that are passed as objects
* this seems to be the only way for an object to
* get a null value for a field in a structure.
*
* Note: this means that the class defining SQLData
* will need to track if a field is SQL null for itself
*/
if (x == null) {
attribs.add(x);
return;
}
/*
* We have to write out a SerialStruct that contains
* the name of this class otherwise we don't know
* what to re-instantiate during readSQL()
*/
attribs.add(new SerialStruct((SQLData)x, map));
}
/** {@collect.stats}
* Writes a <code>Ref</code> object in the Java programming language
* to this <code>SQLOutputImpl</code> object. The driver converts
* it to a serializable <code>SerialRef</code> SQL <code>REF</code> value
* before returning it to the database.
*
* @param x an object representing an SQL <code>REF</code> value
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeRef(Ref x) throws SQLException {
if (x == null) {
attribs.add(x);
return;
}
attribs.add(new SerialRef(x));
}
/** {@collect.stats}
* Writes a <code>Blob</code> object in the Java programming language
* to this <code>SQLOutputImpl</code> object. The driver converts
* it to a serializable <code>SerialBlob</code> SQL <code>BLOB</code> value
* before returning it to the database.
*
* @param x an object representing an SQL <code>BLOB</code> value
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeBlob(Blob x) throws SQLException {
if (x == null) {
attribs.add(x);
return;
}
attribs.add(new SerialBlob(x));
}
/** {@collect.stats}
* Writes a <code>Clob</code> object in the Java programming language
* to this <code>SQLOutputImpl</code> object. The driver converts
* it to a serializable <code>SerialClob</code> SQL <code>CLOB</code> value
* before returning it to the database.
*
* @param x an object representing an SQL <code>CLOB</code> value
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeClob(Clob x) throws SQLException {
if (x == null) {
attribs.add(x);
return;
}
attribs.add(new SerialClob(x));
}
/** {@collect.stats}
* Writes a <code>Struct</code> object in the Java
* programming language to this <code>SQLOutputImpl</code>
* object. The driver converts this value to an SQL structured type
* before returning it to the database.
* <P>
* This method should be used when an SQL structured type has been
* mapped to a <code>Struct</code> object in the Java programming
* language (the standard mapping). The method
* <code>writeObject</code> should be used if an SQL structured type
* has been custom mapped to a class in the Java programming language.
*
* @param x an object representing the attributes of an SQL structured type
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeStruct(Struct x) throws SQLException {
SerialStruct s = new SerialStruct(x,map);;
attribs.add(s);
}
/** {@collect.stats}
* Writes an <code>Array</code> object in the Java
* programming language to this <code>SQLOutputImpl</code>
* object. The driver converts this value to a serializable
* <code>SerialArray</code> SQL <code>ARRAY</code>
* value before returning it to the database.
*
* @param x an object representing an SQL <code>ARRAY</code> value
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeArray(Array x) throws SQLException {
if (x == null) {
attribs.add(x);
return;
}
attribs.add(new SerialArray(x, map));
}
/** {@collect.stats}
* Writes an <code>java.sql.Type.DATALINK</code> object in the Java
* programming language to this <code>SQLOutputImpl</code> object. The
* driver converts this value to a serializable <code>SerialDatalink</code>
* SQL <code>DATALINK</code> value before return it to the database.
*
* @param url an object representing a SQL <code>DATALINK</code> value
* @throws SQLException if the <code>SQLOutputImpl</code> object is in
* use by a <code>SQLData</code> object attempting to write the attribute
* values of a UDT to the database.
*/
public void writeURL(java.net.URL url) throws SQLException {
if (url == null) {
attribs.add(url);
return;
}
attribs.add(new SerialDatalink(url));
}
/** {@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
* @since 1.6
*/
public void writeNString(String x) throws SQLException {
throw new UnsupportedOperationException("Operation not supported");
}
/** {@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
* @since 1.6
*/
public void writeNClob(NClob x) throws SQLException {
throw new UnsupportedOperationException("Operation not supported");
}
/** {@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
* @since 1.6
*/
public void writeRowId(RowId x) throws SQLException {
throw new UnsupportedOperationException("Operation not supported");
}
/** {@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
*
* @exception SQLException if a database access error occurs
* @since 1.6
*/
public void writeSQLXML(SQLXML x) throws SQLException {
throw new UnsupportedOperationException("Operation not supported");
}
}
| Java |
/*
* Copyright (c) 2003, 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 javax.sql.rowset.serial;
import java.sql.*;
import javax.sql.*;
import java.io.*;
import java.math.*;
import java.util.Map;
import java.util.Vector;
import javax.sql.rowset.*;
/** {@collect.stats}
* A serialized mapping in the Java programming language of an SQL
* structured type. Each attribute that is not already serialized
* is mapped to a serialized form, and if an attribute is itself
* a structured type, each of its attributes that is not already
* serialized is mapped to a serialized form.
* <P>
* In addition, the structured type is custom mapped to a class in the
* Java programming language if there is such a mapping, as are
* its attributes, if appropriate.
* <P>
* The <code>SerialStruct</code> class provides a constructor for creating
* an instance from a <code>Struct</code> object, a method for retrieving
* the SQL type name of the SQL structured type in the database, and methods
* for retrieving its attribute values.
*/
public class SerialStruct implements Struct, Serializable, Cloneable {
/** {@collect.stats}
* The SQL type name for the structured type that this
* <code>SerialStruct</code> object represents. This is the name
* used in the SQL definition of the SQL structured type.
*
* @serial
*/
private String SQLTypeName;
/** {@collect.stats}
* An array of <code>Object</code> instances in which each
* element is an attribute of the SQL structured type that this
* <code>SerialStruct</code> object represents. The attributes are
* ordered according to their order in the definition of the
* SQL structured type.
*
* @serial
*/
private Object attribs[];
/** {@collect.stats}
* Constructs a <code>SerialStruct</code> object from the given
* <code>Struct</code> object, using the given <code>java.util.Map</code>
* object for custom mapping the SQL structured type or any of its
* attributes that are SQL structured types.
*
* @param map a <code>java.util.Map</code> object in which
* each entry consists of 1) a <code>String</code> object
* giving the fully qualified name of a UDT and 2) the
* <code>Class</code> object for the <code>SQLData</code> implementation
* that defines how the UDT is to be mapped
* @throws SerialException if an error occurs
* @see java.sql.Struct
*/
public SerialStruct(Struct in, Map<String,Class<?>> map)
throws SerialException
{
try {
// get the type name
SQLTypeName = new String(in.getSQLTypeName());
System.out.println("SQLTypeName: " + SQLTypeName);
// get the attributes of the struct
attribs = in.getAttributes(map);
/*
* the array may contain further Structs
* and/or classes that have been mapped,
* other types that we have to serialize
*/
mapToSerial(map);
} catch (SQLException e) {
throw new SerialException(e.getMessage());
}
}
/** {@collect.stats}
* Constructs a <code>SerialStruct</code> object from the
* given <code>SQLData</code> object, using the given type
* map to custom map it to a class in the Java programming
* language. The type map gives the SQL type and the class
* to which it is mapped. The <code>SQLData</code> object
* defines the class to which the SQL type will be mapped.
*
* @param in an instance of the <code>SQLData</code> class
* that defines the mapping of the SQL structured
* type to one or more objects in the Java programming language
* @param map a <code>java.util.Map</code> object in which
* each entry consists of 1) a <code>String</code> object
* giving the fully qualified name of a UDT and 2) the
* <code>Class</code> object for the <code>SQLData</code> implementation
* that defines how the UDT is to be mapped
* @throws SerialException if an error occurs
*/
public SerialStruct(SQLData in, Map<String,Class<?>> map)
throws SerialException
{
try {
//set the type name
SQLTypeName = new String(in.getSQLTypeName());
Vector tmp = new Vector();
in.writeSQL(new SQLOutputImpl(tmp, map));
attribs = tmp.toArray();
} catch (SQLException e) {
throw new SerialException(e.getMessage());
}
}
/** {@collect.stats}
* Retrieves the SQL type name for this <code>SerialStruct</code>
* object. This is the name used in the SQL definition of the
* structured type
*
* @return a <code>String</code> object representing the SQL
* type name for the SQL structured type that this
* <code>SerialStruct</code> object represents
* @throws SerialException if an error occurs
*/
public String getSQLTypeName() throws SerialException {
return SQLTypeName;
}
/** {@collect.stats}
* Retrieves an array of <code>Object</code> values containing the
* attributes of the SQL structured type that this
* <code>SerialStruct</code> object represents.
*
* @return an array of <code>Object</code> values, with each
* element being an attribute of the SQL structured type
* that this <code>SerialStruct</code> object represents
* @throws SerialException if an error occurs
*/
public Object[] getAttributes() throws SerialException {
return attribs;
}
/** {@collect.stats}
* Retrieves the attributes for the SQL structured type that
* this <code>SerialStruct</code> represents as an array of
* <code>Object</code> values, using the given type map for
* custom mapping if appropriate.
*
* @param map a <code>java.util.Map</code> object in which
* each entry consists of 1) a <code>String</code> object
* giving the fully qualified name of a UDT and 2) the
* <code>Class</code> object for the <code>SQLData</code> implementation
* that defines how the UDT is to be mapped
* @return an array of <code>Object</code> values, with each
* element being an attribute of the SQL structured
* type that this <code>SerialStruct</code> object
* represents
* @throws SerialException if an error occurs
*/
public Object[] getAttributes(Map<String,Class<?>> map)
throws SerialException
{
return attribs;
}
/** {@collect.stats}
* Maps attributes of an SQL structured type that are not
* serialized to a serialized form, using the given type map
* for custom mapping when appropriate. The following types
* in the Java programming language are mapped to their
* serialized forms: <code>Struct</code>, <code>SQLData</code>,
* <code>Ref</code>, <code>Blob</code>, <code>Clob</code>, and
* <code>Array</code>.
* <P>
* This method is called internally and is not used by an
* application programmer.
*
* @param map a <code>java.util.Map</code> object in which
* each entry consists of 1) a <code>String</code> object
* giving the fully qualified name of a UDT and 2) the
* <code>Class</code> object for the <code>SQLData</code> implementation
* that defines how the UDT is to be mapped
* @throws SerialException if an error occurs
*/
private void mapToSerial(Map map) throws SerialException {
try {
for (int i = 0; i < attribs.length; i++) {
if (attribs[i] instanceof Struct) {
attribs[i] = new SerialStruct((Struct)attribs[i], map);
} else if (attribs[i] instanceof SQLData) {
attribs[i] = new SerialStruct((SQLData)attribs[i], map);
} else if (attribs[i] instanceof Blob) {
attribs[i] = new SerialBlob((Blob)attribs[i]);
} else if (attribs[i] instanceof Clob) {
attribs[i] = new SerialClob((Clob)attribs[i]);
} else if (attribs[i] instanceof Ref) {
attribs[i] = new SerialRef((Ref)attribs[i]);
} else if (attribs[i] instanceof java.sql.Array) {
attribs[i] = new SerialArray((java.sql.Array)attribs[i], map);
}
}
} catch (SQLException e) {
throw new SerialException(e.getMessage());
}
return;
}
/** {@collect.stats}
* The identifier that assists in the serialization of this
* <code>SerialStruct</code> object.
*/
static final long serialVersionUID = -8322445504027483372L;
}
| 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 javax.sql.rowset.serial;
import java.sql.*;
import java.io.*;
import java.util.Map;
import java.net.URL;
/** {@collect.stats}
* A serialized version of an <code>Array</code>
* object, which is the mapping in the Java programming language of an SQL
* <code>ARRAY</code> value.
* <P>
* The <code>SerialArray</code> class provides a constructor for creating
* a <code>SerialArray</code> instance from an <code>Array</code> object,
* methods for getting the base type and the SQL name for the base type, and
* methods for copying all or part of a <code>SerialArray</code> object.
* <P>
* Note: In order for this class to function correctly, a connection to the
* data source
* must be available in order for the SQL <code>Array</code> object to be
* materialized (have all of its elements brought to the client server)
* if necessary. At this time, logical pointers to the data in the data source,
* such as locators, are not currently supported.
*/
public class SerialArray implements Array, Serializable, Cloneable {
/** {@collect.stats}
* A serialized array in which each element is an <code>Object</code>
* in the Java programming language that represents an element
* in the SQL <code>ARRAY</code> value.
* @serial
*/
private Object[] elements;
/** {@collect.stats}
* The SQL type of the elements in this <code>SerialArray</code> object. The
* type is expressed as one of the constants from the class
* <code>java.sql.Types</code>.
* @serial
*/
private int baseType;
/** {@collect.stats}
* The type name used by the DBMS for the elements in the SQL <code>ARRAY</code>
* value that this <code>SerialArray</code> object represents.
* @serial
*/
private String baseTypeName;
/** {@collect.stats}
* The number of elements in this <code>SerialArray</code> object, which
* is also the number of elements in the SQL <code>ARRAY</code> value
* that this <code>SerialArray</code> object represents.
* @serial
*/
private int len;
/** {@collect.stats}
* Constructs a new <code>SerialArray</code> object from the given
* <code>Array</code> object, using the given type map for the custom
* mapping of each element when the elements are SQL UDTs.
* <P>
* This method does custom mapping if the array elements are a UDT
* and the given type map has an entry for that UDT.
* Custom mapping is recursive,
* meaning that if, for instance, an element of an SQL structured type
* is an SQL structured type that itself has an element that is an SQL
* structured type, each structured type that has a custom mapping will be
* mapped according to the given type map.
* <P>
* The new <code>SerialArray</code>
* object contains the same elements as the <code>Array</code> object
* from which it is built, except when the base type is the SQL type
* <code>STRUCT</code>, <code>ARRAY</code>, <code>BLOB</code>,
* <code>CLOB</code>, <code>DATALINK</code> or <code>JAVA_OBJECT</code>.
* In this case, each element in the new
* <code>SerialArray</code> object is the appropriate serialized form,
* that is, a <code>SerialStruct</code>, <code>SerialArray</code>,
* <code>SerialBlob</code>, <code>SerialClob</code>,
* <code>SerialDatalink</code>, or <code>SerialJavaObject</code> object.
* <P>
* Note: (1) The <code>Array</code> object from which a <code>SerialArray</code>
* object is created must have materialized the SQL <code>ARRAY</code> value's
* data on the client before it is passed to the constructor. Otherwise,
* the new <code>SerialArray</code> object will contain no data.
* <p>
* Note: (2) If the <code>Array</code> contains <code>java.sql.Types.JAVA_OBJECT</code>
* types, the <code>SerialJavaObject</code> constructor is called where checks
* are made to ensure this object is serializable.
* <p>
* Note: (3) The <code>Array</code> object supplied to this constructor cannot
* return <code>null</code> for any <code>Array.getArray()</code> methods.
* <code>SerialArray</code> cannot serialize null array values.
*
*
* @param array the <code>Array</code> object to be serialized
* @param map a <code>java.util.Map</code> object in which
* each entry consists of 1) a <code>String</code> object
* giving the fully qualified name of a UDT (an SQL structured type or
* distinct type) and 2) the
* <code>Class</code> object for the <code>SQLData</code> implementation
* that defines how the UDT is to be mapped. The <i>map</i>
* parameter does not have any effect for <code>Blob</code>,
* <code>Clob</code>, <code>DATALINK</code>, or
* <code>JAVA_OBJECT</code> types.
* @throws SerialException if an error occurs serializing the
* <code>Array</code> object
* @throws SQLException if a database access error occurs or if the
* <i>array</i> or the <i>map</i> values are <code>null</code>
*/
public SerialArray(Array array, Map<String,Class<?>> map)
throws SerialException, SQLException
{
if ((array == null) || (map == null)) {
throw new SQLException("Cannot instantiate a SerialArray " +
"object with null parameters");
}
if ((elements = (Object[])array.getArray()) == null) {
throw new SQLException("Invalid Array object. Calls to Array.getArray() " +
"return null value which cannot be serialized");
}
elements = (Object[])array.getArray(map);
baseType = array.getBaseType();
baseTypeName = array.getBaseTypeName();
len = elements.length;
switch (baseType) {
case java.sql.Types.STRUCT:
for (int i = 0; i < len; i++) {
elements[i] = new SerialStruct((Struct)elements[i], map);
}
break;
case java.sql.Types.ARRAY:
for (int i = 0; i < len; i++) {
elements[i] = new SerialArray((Array)elements[i], map);
}
break;
case java.sql.Types.BLOB:
for (int i = 0; i < len; i++) {
elements[i] = new SerialBlob((Blob)elements[i]);
}
break;
case java.sql.Types.CLOB:
for (int i = 0; i < len; i++) {
elements[i] = new SerialClob((Clob)elements[i]);
}
break;
case java.sql.Types.DATALINK:
for (int i = 0; i < len; i++) {
elements[i] = new SerialDatalink((URL)elements[i]);
}
break;
case java.sql.Types.JAVA_OBJECT:
for (int i = 0; i < len; i++) {
elements[i] = new SerialJavaObject((Object)elements[i]);
}
default:
;
}
}
/** {@collect.stats}
* This method frees the <code>Array</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 Array's resources
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since 1.6
*/
public void free() throws SQLException {
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Constructs a new <code>SerialArray</code> object from the given
* <code>Array</code> object.
* <P>
* This constructor does not do custom mapping. If the base type of the array
* is an SQL structured type and custom mapping is desired, the constructor
* <code>SerialArray(Array array, Map map)</code> should be used.
* <P>
* The new <code>SerialArray</code>
* object contains the same elements as the <code>Array</code> object
* from which it is built, except when the base type is the SQL type
* <code>BLOB</code>,
* <code>CLOB</code>, <code>DATALINK</code> or <code>JAVA_OBJECT</code>.
* In this case, each element in the new
* <code>SerialArray</code> object is the appropriate serialized form,
* that is, a <code>SerialBlob</code>, <code>SerialClob</code>,
* <code>SerialDatalink</code>, or <code>SerialJavaObject</code> object.
* <P>
* Note: (1) The <code>Array</code> object from which a <code>SerialArray</code>
* object is created must have materialized the SQL <code>ARRAY</code> value's
* data on the client before it is passed to the constructor. Otherwise,
* the new <code>SerialArray</code> object will contain no data.
* <p>
* Note: (2) The <code>Array</code> object supplied to this constructor cannot
* return <code>null</code> for any <code>Array.getArray()</code> methods.
* <code>SerialArray</code> cannot serialize <code>null</code> array values.
*
* @param array the <code>Array</code> object to be serialized
* @throws SerialException if an error occurs serializing the
* <code>Array</code> object
* @throws SQLException if a database access error occurs or the
* <i>array</i> parameter is <code>null</code>.
*/
public SerialArray(Array array) throws SerialException, SQLException {
if (array == null) {
throw new SQLException("Cannot instantiate a SerialArray " +
"object with a null Array object");
}
if ((elements = (Object[])array.getArray()) == null) {
throw new SQLException("Invalid Array object. Calls to Array.getArray() " +
"return null value which cannot be serialized");
}
//elements = (Object[])array.getArray();
baseType = array.getBaseType();
baseTypeName = array.getBaseTypeName();
len = elements.length;
switch (baseType) {
case java.sql.Types.BLOB:
for (int i = 0; i < len; i++) {
elements[i] = new SerialBlob((Blob)elements[i]);
}
break;
case java.sql.Types.CLOB:
for (int i = 0; i < len; i++) {
elements[i] = new SerialClob((Clob)elements[i]);
}
break;
case java.sql.Types.DATALINK:
for (int i = 0; i < len; i++) {
elements[i] = new SerialDatalink((URL)elements[i]);
}
break;
case java.sql.Types.JAVA_OBJECT:
for (int i = 0; i < len; i++) {
elements[i] = new SerialJavaObject((Object)elements[i]);
}
default:
;
}
}
/** {@collect.stats}
* Returns a new array that is a copy of this <code>SerialArray</code>
* object.
*
* @return a copy of this <code>SerialArray</code> object as an
* <code>Object</code> in the Java programming language
* @throws SerialException if an error occurs retrieving a copy of
* this <code>SerialArray</code> object
*/
public Object getArray() throws SerialException {
Object dst = new Object[len];
System.arraycopy((Object)elements, 0, dst, 0, len);
return dst;
}
//[if an error occurstype map used??]
/** {@collect.stats}
* Returns a new array that is a copy of this <code>SerialArray</code>
* object, using the given type map for the custom
* mapping of each element when the elements are SQL UDTs.
* <P>
* This method does custom mapping if the array elements are a UDT
* and the given type map has an entry for that UDT.
* Custom mapping is recursive,
* meaning that if, for instance, an element of an SQL structured type
* is an SQL structured type that itself has an element that is an SQL
* structured type, each structured type that has a custom mapping will be
* mapped according to the given type map.
*
* @param map a <code>java.util.Map</code> object in which
* each entry consists of 1) a <code>String</code> object
* giving the fully qualified name of a UDT and 2) the
* <code>Class</code> object for the <code>SQLData</code> implementation
* that defines how the UDT is to be mapped
* @return a copy of this <code>SerialArray</code> object as an
* <code>Object</code> in the Java programming language
* @throws SerialException if an error occurs
*/
public Object getArray(Map<String, Class<?>> map) throws SerialException {
Object dst[] = new Object[len];
System.arraycopy((Object)elements, 0, dst, 0, len);
return dst;
}
/** {@collect.stats}
* Returns a new array that is a copy of a slice
* of this <code>SerialArray</code> object, starting with the
* element at the given index and containing the given number
* of consecutive elements.
*
* @param index the index into this <code>SerialArray</code> object
* of the first element to be copied;
* the index of the first element is <code>0</code>
* @param count the number of consecutive elements to be copied, starting
* at the given index
* @return a copy of the designated elements in this <code>SerialArray</code>
* object as an <code>Object</code> in the Java programming language
* @throws SerialException if an error occurs
*/
public Object getArray(long index, int count) throws SerialException {
Object dst = new Object[count];
System.arraycopy((Object)elements, (int)index, dst, 0, count);
return dst;
}
/** {@collect.stats}
* Returns a new array that is a copy of a slice
* of this <code>SerialArray</code> object, starting with the
* element at the given index and containing the given number
* of consecutive elements.
* <P>
* This method does custom mapping if the array elements are a UDT
* and the given type map has an entry for that UDT.
* Custom mapping is recursive,
* meaning that if, for instance, an element of an SQL structured type
* is an SQL structured type that itself has an element that is an SQL
* structured type, each structured type that has a custom mapping will be
* mapped according to the given type map.
*
* @param index the index into this <code>SerialArray</code> object
* of the first element to be copied; the index of the
* first element in the array is <code>0</code>
* @param count the number of consecutive elements to be copied, starting
* at the given index
* @param map a <code>java.util.Map</code> object in which
* each entry consists of 1) a <code>String</code> object
* giving the fully qualified name of a UDT and 2) the
* <code>Class</code> object for the <code>SQLData</code> implementation
* that defines how the UDT is to be mapped
* @return a copy of the designated elements in this <code>SerialArray</code>
* object as an <code>Object</code> in the Java programming language
* @throws SerialException if an error occurs
*/
public Object getArray(long index, int count, Map<String,Class<?>> map)
throws SerialException
{
Object dst = new Object[count];
System.arraycopy((Object)elements, (int)index, dst, 0, count);
return dst;
}
/** {@collect.stats}
* Retrieves the SQL type of the elements in this <code>SerialArray</code>
* object. The <code>int</code> returned is one of the constants in the class
* <code>java.sql.Types</code>.
*
* @return one of the constants in <code>java.sql.Types</code>, indicating
* the SQL type of the elements in this <code>SerialArray</code> object
* @throws SerialException if an error occurs
*/
public int getBaseType() throws SerialException {
return baseType;
}
/** {@collect.stats}
* Retrieves the DBMS-specific type name for the elements in this
* <code>SerialArray</code> object.
*
* @return the SQL type name used by the DBMS for the base type of this
* <code>SerialArray</code> object
* @throws SerialException if an error occurs
*/
public String getBaseTypeName() throws SerialException {
return baseTypeName;
}
/** {@collect.stats}
* Retrieves a <code>ResultSet</code> object holding the elements of
* the subarray that starts at
* index <i>index</i> and contains up to <i>count</i> successive elements.
* This method uses the connection's type map to map the elements of
* the array if the map contains
* an entry for the base type. Otherwise, the standard mapping is used.
*
* @param index the index into this <code>SerialArray</code> object
* of the first element to be copied; the index of the
* first element in the array is <code>0</code>
* @param count the number of consecutive elements to be copied, starting
* at the given index
* @return a <code>ResultSet</code> object containing the designated
* elements in this <code>SerialArray</code> object, with a
* separate row for each element
* @throws SerialException, which in turn throws an
* <code>UnsupportedOperationException</code>, if this method is called
*/
public ResultSet getResultSet(long index, int count) throws SerialException {
throw new UnsupportedOperationException();
}
/** {@collect.stats}
*
* Retrieves a <code>ResultSet</code> object that contains all of
* the elements of the SQL <code>ARRAY</code>
* value represented by this <code>SerialArray</code> object. This method uses
* the specified map for type map customizations unless the base type of the
* array does not match a user-defined type (UDT) in <i>map</i>, in
* which case it uses the
* standard mapping. This version of the method <code>getResultSet</code>
* uses either the given type map or the standard mapping; it never uses the
* type map associated with the connection.
*
* @param map a <code>java.util.Map</code> object in which
* each entry consists of 1) a <code>String</code> object
* giving the fully qualified name of a UDT and 2) the
* <code>Class</code> object for the <code>SQLData</code> implementation
* that defines how the UDT is to be mapped
* @return a <code>ResultSet</code> object containing all of the
* elements in this <code>SerialArray</code> object, with a
* separate row for each element
* @throws SerialException, which in turn throws an
* <code>UnsupportedOperationException</code>, if this method is called
*/
public ResultSet getResultSet(Map<String, Class<?>> map)
throws SerialException
{
throw new UnsupportedOperationException();
}
/** {@collect.stats}
* Retrieves a <code>ResultSet</code> object that contains all of
* the elements in the <code>ARRAY</code> value that this
* <code>SerialArray</code> object represents.
* If appropriate, the elements of the array are mapped using the connection's
* type map; otherwise, the standard mapping is used.
*
* @return a <code>ResultSet</code> object containing all of the
* elements in this <code>SerialArray</code> object, with a
* separate row for each element
* @throws SerialException if called, which in turn throws an
* <code>UnsupportedOperationException</code>, if this method is called
*/
public ResultSet getResultSet() throws SerialException {
throw new UnsupportedOperationException();
}
/** {@collect.stats}
* Retrieves a result set holding the elements of the subarray that starts at
* Retrieves a <code>ResultSet</code> object that contains a subarray of the
* elements in this <code>SerialArray</code> object, starting at
* index <i>index</i> and containing up to <i>count</i> successive
* elements. This method uses
* the specified map for type map customizations unless the base type of the
* array does not match a user-defined type (UDT) in <i>map</i>, in
* which case it uses the
* standard mapping. This version of the method <code>getResultSet</code> uses
* either the given type map or the standard mapping; it never uses the type
* map associated with the connection.
*
* @param index the index into this <code>SerialArray</code> object
* of the first element to be copied; the index of the
* first element in the array is <code>0</code>
* @param count the number of consecutive elements to be copied, starting
* at the given index
* @param map a <code>java.util.Map</code> object in which
* each entry consists of 1) a <code>String</code> object
* giving the fully qualified name of a UDT and 2) the
* <code>Class</code> object for the <code>SQLData</code> implementation
* that defines how the UDT is to be mapped
* @return a <code>ResultSet</code> object containing the designated
* elements in this <code>SerialArray</code> object, with a
* separate row for each element
* @throws SerialException if called, which in turn throws an
* <code>UnsupportedOperationException</code>
*/
public ResultSet getResultSet(long index, int count,
Map<String,Class<?>> map)
throws SerialException
{
throw new UnsupportedOperationException();
}
/** {@collect.stats}
* The identifier that assists in the serialization of this <code>SerialArray</code>
* object.
*/
static final long serialVersionUID = -8466174297270688520L;
}
| 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 javax.sql.rowset.serial;
import java.sql.*;
import java.io.*;
/** {@collect.stats}
* A serialized mapping in the Java programming language of an SQL
* <code>CLOB</code> value.
* <P>
* The <code>SerialClob</code> class provides a constructor for creating
* an instance from a <code>Clob</code> object. Note that the <code>Clob</code>
* object should have brought the SQL <code>CLOB</code> value's data over
* to the client before a <code>SerialClob</code> object
* is constructed from it. The data of an SQL <code>CLOB</code> value can
* be materialized on the client as a stream of Unicode characters.
* <P>
* <code>SerialClob</code> methods make it possible to get a substring
* from a <code>SerialClob</code> object or to locate the start of
* a pattern of characters.
*
* @author Jonathan Bruce
*/
public class SerialClob implements Clob, Serializable, Cloneable {
/** {@collect.stats}
* A serialized array of characters containing the data of the SQL
* <code>CLOB</code> value that this <code>SerialClob</code> object
* represents.
*
* @serial
*/
private char buf[];
/** {@collect.stats}
* Internal Clob representation if SerialClob is intialized with a
* Clob
*/
private Clob clob;
/** {@collect.stats}
* The length in characters of this <code>SerialClob</code> object's
* internal array of characters.
*
* @serial
*/
private long len;
/** {@collect.stats}
* The original length in characters of tgus <code>SerialClob</code>
* objects internal array of characters.
*
* @serial
*/
private long origLen;
/** {@collect.stats}
* Constructs a <code>SerialClob</code> object that is a serialized version of
* the given <code>char</code> array.
* <p>
* The new <code>SerialClob</code> object is initialized with the data from the
* <code>char</code> array, thus allowing disconnected <code>RowSet</code>
* objects to establish a serialized <code>Clob</code> object without touching
* the data source.
*
* @param ch the char array representing the <code>Clob</code> object to be
* serialized
* @throws SerialException if an error occurs during serialization
* @throws SQLException if a SQL error occurs
*/
public SerialClob(char ch[]) throws SerialException, SQLException {
// %%% JMB. Agreed. Add code here to throw a SQLException if no
// support is available for locatorsUpdateCopy=false
// Serializing locators is not supported.
len = ch.length;
buf = new char[(int)len];
for (int i = 0; i < len ; i++){
buf[i] = ch[i];
}
origLen = len;
}
/** {@collect.stats}
* Constructs a <code>SerialClob</code> object that is a serialized
* version of the given <code>Clob</code> object.
* <P>
* The new <code>SerialClob</code> object is initialized with the
* data from the <code>Clob</code> object; therefore, the
* <code>Clob</code> object should have previously brought the
* SQL <code>CLOB</code> value's data over to the client from
* the database. Otherwise, the new <code>SerialClob</code> object
* object will contain no data.
* <p>
* Note: The <code>Clob</code> object supplied to this constructor cannot
* return <code>null</code> for the <code>Clob.getCharacterStream()</code>
* and <code>Clob.getAsciiStream</code> methods. This <code>SerialClob</code>
* constructor cannot serialize a <code>Clob</code> object in this instance
* and will throw an <code>SQLException</code> object.
*
* @param clob the <code>Clob</code> object from which this
* <code>SerialClob</code> object is to be constructed; cannot be null
* @throws SerialException if an error occurs during serialization
* @throws SQLException if a SQL error occurs in capturing the CLOB;
* if the <code>Clob</code> object is a null; or if both the
* <code>Clob.getCharacterStream()</code> and <code>Clob.getAsciiStream()</code>
* methods on the <code>Clob</code> return a null
* @see java.sql.Clob
*/
public SerialClob(Clob clob) throws SerialException, SQLException {
if (clob == null) {
throw new SQLException("Cannot instantiate a SerialClob " +
"object with a null Clob object");
}
len = clob.length();
this.clob = clob;
buf = new char[(int)len];
int read = 0;
int offset = 0;
BufferedReader reader;
if ( (((reader = new BufferedReader(clob.getCharacterStream())) == null)) &&
(clob.getAsciiStream() == null)) {
throw new SQLException("Invalid Clob object. Calls to getCharacterStream " +
"and getAsciiStream return null which cannot be serialized.");
}
try {
do {
read = reader.read(buf, offset, (int)(len - offset));
offset += read;
} while (read > 0);
} catch (java.io.IOException ex) {
throw new SerialException("SerialClob: " + ex.getMessage());
}
origLen = len;
}
/** {@collect.stats}
* Retrieves the number of characters in this <code>SerialClob</code>
* object's array of characters.
*
* @return a <code>long</code> indicating the length in characters of this
* <code>SerialClob</code> object's array of character
* @throws SerialException if an error occurs
*/
public long length() throws SerialException {
return len;
}
/** {@collect.stats}
* Returns this <code>SerialClob</code> object's data as a stream
* of Unicode characters. Unlike the related method, <code>getAsciiStream</code>,
* a stream is produced regardless of whether the <code>SerialClob</code> object
* was created with a <code>Clob</code> object or a <code>char</code> array.
*
* @return a <code>java.io.Reader</code> object containing this
* <code>SerialClob</code> object's data
* @throws SerialException if an error occurs
*/
public java.io.Reader getCharacterStream() throws SerialException {
return (java.io.Reader) new CharArrayReader(buf);
}
/** {@collect.stats}
* Retrieves the <code>CLOB</code> value designated by this <code>SerialClob</code>
* object as an ascii stream. This method forwards the <code>getAsciiStream</code>
* call to the underlying <code>Clob</code> object in the event that this
* <code>SerialClob</code> object is instantiated with a <code>Clob</code>
* object. If this <code>SerialClob</code> object is instantiated with
* a <code>char</code> array, a <code>SerialException</code> object is thrown.
*
* @return a <code>java.io.InputStream</code> object containing
* this <code>SerialClob</code> object's data
* @throws SerialException if this <code>SerialClob</code> object was not instantiated
* with a <code>Clob</code> object
* @throws SQLException if there is an error accessing the
* <code>CLOB</code> value represented by the <code>Clob</code> object that was
* used to create this <code>SerialClob</code> object
*/
public java.io.InputStream getAsciiStream() throws SerialException, SQLException {
if (this.clob != null) {
return this.clob.getAsciiStream();
} else {
throw new SerialException("Unsupported operation. SerialClob cannot " +
"return a the CLOB value as an ascii stream, unless instantiated " +
"with a fully implemented Clob object.");
}
}
/** {@collect.stats}
* Returns a copy of the substring contained in this
* <code>SerialClob</code> object, starting at the given position
* and continuing for the specified number or characters.
*
* @param pos the position of the first character in the substring
* to be copied; the first character of the
* <code>SerialClob</code> object is at position
* <code>1</code>; must not be less than <code>1</code>,
* and the sum of the starting position and the length
* of the substring must be less than the length of this
* <code>SerialClob</code> object
* @param length the number of characters in the substring to be
* returned; must not be greater than the length of
* this <code>SerialClob</code> object, and the
* sum of the starting position and the length
* of the substring must be less than the length of this
* <code>SerialClob</code> object
* @return a <code>String</code> object containing a substring of
* this <code>SerialClob</code> object beginning at the
* given position and containing the specified number of
* consecutive characters
* @throws SerialException if either of the arguments is out of bounds
*/
public String getSubString(long pos, int length) throws SerialException {
if (pos < 1 || pos > this.length()) {
throw new SerialException("Invalid position in BLOB object set");
}
if ((pos-1) + length > this.length()) {
throw new SerialException("Invalid position and substring length");
}
try {
return new String(buf, (int)pos - 1, length);
} catch (StringIndexOutOfBoundsException e) {
throw new SerialException("StringIndexOutOfBoundsException: " +
e.getMessage());
}
}
/** {@collect.stats}
* Returns the position in this <code>SerialClob</code> object
* where the given <code>String</code> object begins, starting
* the search at the specified position. This method returns
* <code>-1</code> if the pattern is not found.
*
* @param searchStr the <code>String</code> object for which to
* search
* @param start the position in this <code>SerialClob</code> object
* at which to start the search; the first position is
* <code>1</code>; must not be less than <code>1</code> nor
* greater than the length of this <code>SerialClob</code> object
* @return the position at which the given <code>String</code> object
* begins, starting the search at the specified position;
* <code>-1</code> if the given <code>String</code> object is
* not found or the starting position is out of bounds; position
* numbering for the return value starts at <code>1</code>
* @throws SerialException if an error occurs locating the String signature
* @throws SQLException if there is an error accessing the Blob value
* from the database.
*/
public long position(String searchStr, long start)
throws SerialException, SQLException {
if (start < 1 || start > len) {
return -1;
}
char pattern[] = searchStr.toCharArray();
int pos = (int)start-1;
int i = 0;
long patlen = pattern.length;
while (pos < len) {
if (pattern[i] == buf[pos]) {
if (i + 1 == patlen) {
return (pos + 1) - (patlen - 1);
}
i++; pos++; // increment pos, and i
} else if (pattern[i] != buf[pos]) {
pos++; // increment pos only
}
}
return -1; // not found
}
/** {@collect.stats}
* Returns the position in this <code>SerialClob</code> object
* where the given <code>Clob</code> signature begins, starting
* the search at the specified position. This method returns
* <code>-1</code> if the pattern is not found.
*
* @param searchStr the <code>Clob</code> object for which to search
* @param start the position in this <code>SerialClob</code> object
* at which to begin the search; the first position is
* <code>1</code>; must not be less than <code>1</code> nor
* greater than the length of this <code>SerialClob</code> object
* @return the position at which the given <code>Clob</code>
* object begins in this <code>SerialClob</code> object,
* at or after the specified starting position
* @throws SerialException if an error occurs locating the Clob signature
* @throws SQLException if there is an error accessing the Blob value
* from the database
*/
public long position(Clob searchStr, long start)
throws SerialException, SQLException {
return position(searchStr.getSubString(1,(int)searchStr.length()), start);
}
/** {@collect.stats}
* Writes the given Java <code>String</code> to the <code>CLOB</code>
* value that this <code>SerialClob</code> object represents, at the position
* <code>pos</code>.
*
* @param pos the position at which to start writing to the <code>CLOB</code>
* value that this <code>SerialClob</code> object represents; the first
* position is <code>1</code>; must not be less than <code>1</code> nor
* greater than the length of this <code>SerialClob</code> object
* @param str the string to be written to the <code>CLOB</code>
* value that this <code>SerialClob</code> object represents
* @return the number of characters written
* @throws SerialException if there is an error accessing the
* <code>CLOB</code> value; if an invalid position is set; if an
* invalid offset value is set; if number of bytes to be written
* is greater than the <code>SerialClob</code> length; or the combined
* values of the length and offset is greater than the Clob buffer
*/
public int setString(long pos, String str) throws SerialException {
return (setString(pos, str, 0, str.length()));
}
/** {@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.
*
* @param pos the position at which to start writing to the <code>CLOB</code>
* value that this <code>SerialClob</code> object represents; the first
* position is <code>1</code>; must not be less than <code>1</code> nor
* greater than the length of this <code>SerialClob</code> object
* @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 length the number of characters to be written
* @return the number of characters written
* @throws SerialException if there is an error accessing the
* <code>CLOB</code> value; if an invalid position is set; if an
* invalid offset value is set; if number of bytes to be written
* is greater than the <code>SerialClob</code> length; or the combined
* values of the length and offset is greater than the Clob buffer
*/
public int setString(long pos, String str, int offset, int length)
throws SerialException {
String temp = str.substring(offset);
char cPattern[] = temp.toCharArray();
if (offset < 0 || offset > str.length()) {
throw new SerialException("Invalid offset in byte array set");
}
if (pos < 1 || pos > this.length()) {
throw new SerialException("Invalid position in BLOB object set");
}
if ((long)(length) > origLen) {
throw new SerialException("Buffer is not sufficient to hold the value");
}
if ((length + offset) > str.length()) {
// need check to ensure length + offset !> bytes.length
throw new SerialException("Invalid OffSet. Cannot have combined offset " +
" and length that is greater that the Blob buffer");
}
int i = 0;
pos--; //values in the array are at position one less
while ( i < length || (offset + i +1) < (str.length() - offset ) ) {
this.buf[(int)pos + i ] = cPattern[offset + i ];
i++;
}
return i;
}
/** {@collect.stats}
* Retrieves a stream to be used to write Ascii characters to the
* <code>CLOB</code> value that this <code>SerialClob</code> object represents,
* starting at position <code>pos</code>. This method forwards the
* <code>setAsciiStream()</code> call to the underlying <code>Clob</code> object in
* the event that this <code>SerialClob</code> object is instantiated with a
* <code>Clob</code> object. If this <code>SerialClob</code> object is instantiated
* with a <code>char</code> array, a <code>SerialException</code> object is thrown.
*
* @param pos the position at which to start writing to the
* <code>CLOB</code> object
* @return the stream to which ASCII encoded characters can be written
* @throws SerialException if SerialClob is not instantiated with a
* Clob object that supports <code>setAsciiStream</code>
* @throws SQLException if there is an error accessing the
* <code>CLOB</code> value
* @see #getAsciiStream
*/
public java.io.OutputStream setAsciiStream(long pos)
throws SerialException, SQLException {
if (this.clob.setAsciiStream(pos) != null) {
return this.clob.setAsciiStream(pos);
} else {
throw new SerialException("Unsupported operation. SerialClob cannot " +
"return a writable ascii stream\n unless instantiated with a Clob object " +
"that has a setAsciiStream() implementation");
}
}
/** {@collect.stats}
* Retrieves a stream to be used to write a stream of Unicode characters
* to the <code>CLOB</code> value that this <code>SerialClob</code> object
* represents, at position <code>pos</code>. This method forwards the
* <code>setCharacterStream()</code> call to the underlying <code>Clob</code>
* object in the event that this <code>SerialClob</code> object is instantiated with a
* <code>Clob</code> object. If this <code>SerialClob</code> object is instantiated with
* a <code>char</code> array, a <code>SerialException</code> is thrown.
*
* @param pos the position at which to start writing to the
* <code>CLOB</code> value
*
* @return a stream to which Unicode encoded characters can be written
* @throws SerialException if the SerialClob is not instantiated with
* a Clob object that supports <code>setCharacterStream</code>
* @throws SQLException if there is an error accessing the
* <code>CLOB</code> value
* @see #getCharacterStream
*/
public java.io.Writer setCharacterStream(long pos)
throws SerialException, SQLException {
if (this.clob.setCharacterStream(pos) != null) {
return this.clob.setCharacterStream(pos);
} else {
throw new SerialException("Unsupported operation. SerialClob cannot " +
"return a writable character stream\n unless instantiated with a Clob object " +
"that has a setCharacterStream implementation");
}
}
/** {@collect.stats}
* Truncates the <code>CLOB</code> value that this <code>SerialClob</code>
* object represents so that it has a length of <code>len</code>
* characters.
* <p>
* Truncating a <code>SerialClob</code> object to length 0 has the effect of
* clearing its contents.
*
* @param length the length, in bytes, to which the <code>CLOB</code>
* value should be truncated
* @throws SQLException if there is an error accessing the
* <code>CLOB</code> value
*/
public void truncate(long length) throws SerialException {
if (length > len) {
throw new SerialException
("Length more than what can be truncated");
} else {
len = length;
// re-size the buffer
if (len == 0) {
buf = new char[] {};
} else {
buf = (this.getSubString(1, (int)len)).toCharArray();
}
}
}
public Reader getCharacterStream(long pos, long length) throws SQLException {
throw new java.lang.UnsupportedOperationException("Not supported");
}
public void free() throws SQLException {
throw new java.lang.UnsupportedOperationException("Not supported");
}
/** {@collect.stats}
* The identifier that assists in the serialization of this <code>SerialClob</code>
* object.
*/
static final long serialVersionUID = -1662519690087375313L;
}
| Java |
/*
* Copyright (c) 2003, 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 javax.sql.rowset;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.io.*;
import java.math.*;
import java.util.*;
import javax.sql.rowset.*;
/** {@collect.stats}
* The <code>JoinRowSet</code> interface provides a mechanism for combining related
* data from different <code>RowSet</code> objects into one <code>JoinRowSet</code>
* object, which represents an SQL <code>JOIN</code>.
* In other words, a <code>JoinRowSet</code> object acts as a
* container for the data from <code>RowSet</code> objects that form an SQL
* <code>JOIN</code> relationship.
* <P>
* The <code>Joinable</code> interface provides the methods for setting,
* retrieving, and unsetting a match column, the basis for
* establishing an SQL <code>JOIN</code> relationship. The match column may
* alternatively be set by supplying it to the appropriate version of the
* <code>JointRowSet</code> method <code>addRowSet</code>.
* <P>
* <p>
* <h3>1.0 Overview</h3>
* Disconnected <code>RowSet</code> objects (<code>CachedRowSet</code> objects
* and implementations extending the <code>CachedRowSet</code> interface)
* do not have a standard way to establish an SQL <code>JOIN</code> between
* <code>RowSet</code> objects without the expensive operation of
* reconnecting to the data source. The <code>JoinRowSet</code>
* interface is specifically designed to address this need.
* <P>
* Any <code>RowSet</code> object
* can be added to a <code>JoinRowSet</code> object to become
* part of an SQL <code>JOIN</code> relationship. This means that both connected
* and disconnected <code>RowSet</code> objects can be part of a <code>JOIN</code>.
* <code>RowSet</code> objects operating in a connected environment
* (<code>JdbcRowSet</code> objects) are
* encouraged to use the database to which they are already
* connected to establish SQL <code>JOIN</code> relationships between
* tables directly. However, it is possible for a
* <code>JdbcRowSet</code> object to be added to a <code>JoinRowSet</code> object
* if necessary.
* <P>
* Any number of <code>RowSet</code> objects can be added to an
* instance of <code>JoinRowSet</code> provided that they
* can be related in an SQL <code>JOIN</code>.
* By definition, the SQL <code>JOIN</code> statement is used to
* combine the data contained in two or more relational database tables based
* upon a common attribute. The <code>Joinable</code> interface provides the methods
* for establishing a common attribute, which is done by setting a
* <i>match column</i>. The match column commonly coincides with
* the primary key, but there is
* no requirement that the match column be the same as the primary key.
* By establishing and then enforcing column matches,
* a <code>JoinRowSet</code> object establishes <code>JOIN</code> relationships
* between <code>RowSet</code> objects without the assistance of an available
* relational database.
* <P>
* The type of <code>JOIN</code> to be established is determined by setting
* one of the <code>JoinRowSet</code> constants using the method
* <code>setJoinType</code>. The following SQL <code>JOIN</code> types can be set:
* <UL>
* <LI><code>CROSS_JOIN</code>
* <LI><code>FULL_JOIN</code>
* <LI><code>INNER_JOIN</code> - the default if no <code>JOIN</code> type has been set
* <LI><code>LEFT_OUTER_JOIN</code>
* <LI><code>RIGHT_OUTER_JOIN</code>
* </UL>
* Note that if no type is set, the <code>JOIN</code> will automatically be an
* inner join. The comments for the fields in the
* <code>JoinRowSet</code> interface explain these <code>JOIN</code> types, which are
* standard SQL <code>JOIN</code> types.
* <P>
* <h3>2.0 Using a <code>JoinRowSet</code> Object for Creating a <code>JOIN</code></h3>
* When a <code>JoinRowSet</code> object is created, it is empty.
* The first <code>RowSet</code> object to be added becomes the basis for the
* <code>JOIN</code> relationship.
* Applications must determine which column in each of the
* <code>RowSet</code> objects to be added to the <code>JoinRowSet</code> object
* should be the match column. All of the
* <code>RowSet</code> objects must contain a match column, and the values in
* each match column must be ones that can be compared to values in the other match
* columns. The columns do not have to have the same name, though they often do,
* and they do not have to store the exact same data type as long as the data types
* can be compared.
* <P>
* A match column can be be set in two ways:
* <ul>
* <li>By calling the <code>Joinable</code> method <code>setMatchColumn</code><br>
* This is the only method that can set the match column before a <code>RowSet</code>
* object is added to a <code>JoinRowSet</code> object. The <code>RowSet</code> object
* must have implemented the <code>Joinable</code> interface in order to use the method
* <code>setMatchColumn</code>. Once the match column value
* has been set, this method can be used to reset the match column at any time.
* <li>By calling one of the versions of the <code>JoinRowSet</code> method
* <code>addRowSet</code> that takes a column name or number (or an array of
* column names or numbers)<BR>
* Four of the five <code>addRowSet</code> methods take a match column as a parameter.
* These four methods set or reset the match column at the time a <code>RowSet</code>
* object is being added to a <code>JoinRowSet</code> object.
* </ul>
* <h3>3.0 Sample Usage</h3>
* <p>
* The following code fragment adds two <code>CachedRowSet</code>
* objects to a <code>JoinRowSet</code> object. Note that in this example,
* no SQL <code>JOIN</code> type is set, so the default <code>JOIN</code> type,
* which is <i>INNER_JOIN</i>, is established.
* <p>
* In the following code fragment, the table <code>EMPLOYEES</code>, whose match
* column is set to the first column (<code>EMP_ID</code>), is added to the
* <code>JoinRowSet</code> object <i>jrs</i>. Then
* the table <code>ESSP_BONUS_PLAN</code>, whose match column is likewise
* the <code>EMP_ID</code> column, is added. When this second
* table is added to <i>jrs</i>, only the rows in
* <code>ESSP_BONUS_PLAN</code> whose <code>EMP_ID</code> value matches an
* <code>EMP_ID</code> value in the <code>EMPLOYEES</code> table are added.
* In this case, everyone in the bonus plan is an employee, so all of the rows
* in the table <code>ESSP_BONUS_PLAN</code> are added to the <code>JoinRowSet</code>
* object. In this example, both <code>CachedRowSet</code> objects being added
* have implemented the <code>Joinable</code> interface and can therefore call
* the <code>Joinable</code> method <code>setMatchColumn</code>.
* <PRE>
* JoinRowSet jrs = new JoinRowSetImpl();
*
* ResultSet rs1 = stmt.executeQuery("SELECT * FROM EMPLOYEES");
* CachedRowSet empl = new CachedRowSetImpl();
* empl.populate(rs1);
* empl.setMatchColumn(1);
* jrs.addRowSet(empl);
*
* ResultSet rs2 = stmt.executeQuery("SELECT * FROM ESSP_BONUS_PLAN");
* CachedRowSet bonus = new CachedRowSetImpl();
* bonus.populate(rs2);
* bonus.setMatchColumn(1); // EMP_ID is the first column
* jrs.addRowSet(bonus);
* </PRE>
* <P>
* At this point, <i>jrs</i> is an inside JOIN of the two <code>RowSet</code> objects
* based on their <code>EMP_ID</code> columns. The application can now browse the
* combined data as if it were browsing one single <code>RowSet</code> object.
* Because <i>jrs</i> is itself a <code>RowSet</code> object, an application can
* navigate or modify it using <code>RowSet</code> methods.
* <PRE>
* jrs.first();
* int employeeID = jrs.getInt(1);
* String employeeName = jrs.getString(2);
* </PRE>
* <P>
* Note that because the SQL <code>JOIN</code> must be enforced when an application
* adds a second or subsequent <code>RowSet</code> object, there
* may be an initial degradation in performance while the <code>JOIN</code> is
* being performed.
* <P>
* The following code fragment adds an additional <code>CachedRowSet</code> object.
* In this case, the match column (<code>EMP_ID</code>) is set when the
* <code>CachedRowSet</code> object is added to the <code>JoinRowSet</code> object.
* <PRE>
* ResultSet rs3 = stmt.executeQuery("SELECT * FROM 401K_CONTRIB");
* CachedRowSet fourO1k = new CachedRowSetImpl();
* four01k.populate(rs3);
* jrs.addRowSet(four01k, 1);
* </PRE>
* <P>
* The <code>JoinRowSet</code> object <i>jrs</i> now contains values from all three
* tables. The data in each row in <i>four01k</i> in which the value for the
* <code>EMP_ID</code> column matches a value for the <code>EMP_ID</code> column
* in <i>jrs</i> has been added to <i>jrs</i>.
* <P>
* <h3>4.0 <code>JoinRowSet</code> Methods</h3>
* The <code>JoinRowSet</code> interface supplies several methods for adding
* <code>RowSet</code> objects and for getting information about the
* <code>JoinRowSet</code> object.
* <UL>
* <LI>Methods for adding one or more <code>RowSet</code> objects<BR>
* These methods allow an application to add one <code>RowSet</code> object
* at a time or to add multiple <code>RowSet</code> objects at one time. In
* either case, the methods may specify the match column for each
* <code>RowSet</code> object being added.
* <LI>Methods for getting information<BR>
* One method retrieves the <code>RowSet</code> objects in the
* <code>JoinRowSet</code> object, and another method retrieves the
* <code>RowSet</code> names. A third method retrieves either the SQL
* <code>WHERE</code> clause used behind the scenes to form the
* <code>JOIN</code> or a text description of what the <code>WHERE</code>
* clause does.
* <LI>Methods related to the type of <code>JOIN</code><BR>
* One method sets the <code>JOIN</code> type, and five methods find out whether
* the <code>JoinRowSet</code> object supports a given type.
* <LI>A method to make a separate copy of the <code>JoinRowSet</code> object<BR>
* This method creates a copy that can be persisted to the data source.
* </UL>
* <P>
*/
public interface JoinRowSet extends WebRowSet {
/** {@collect.stats}
* Adds the given <code>RowSet</code> object to this <code>JoinRowSet</code>
* object. If the <code>RowSet</code> object
* is the first to be added to this <code>JoinRowSet</code>
* object, it forms the basis of the <code>JOIN</code> relationship to be
* established.
* <P>
* This method should be used only when the given <code>RowSet</code>
* object already has a match column that was set with the <code>Joinable</code>
* method <code>setMatchColumn</code>.
* <p>
* Note: A <code>Joinable</code> object is any <code>RowSet</code> object
* that has implemented the <code>Joinable</code> interface.
*
* @param rowset the <code>RowSet</code> object that is to be added to this
* <code>JoinRowSet</code> object; it must implement the
* <code>Joinable</code> interface and have a match column set
* @throws SQLException if (1) an empty rowset is added to the to this
* <code>JoinRowSet</code> object, (2) a match column has not been
* set for <i>rowset</i>, or (3) <i>rowset</i>
* violates the active <code>JOIN</code>
* @see Joinable#setMatchColumn
*/
public void addRowSet(Joinable rowset) throws SQLException;
/** {@collect.stats}
* Adds the given <code>RowSet</code> object to this <code>JoinRowSet</code>
* object and sets the designated column as the match column for
* the <code>RowSet</code> object. If the <code>RowSet</code> object
* is the first to be added to this <code>JoinRowSet</code>
* object, it forms the basis of the <code>JOIN</code> relationship to be
* established.
* <P>
* This method should be used when <i>RowSet</i> does not already have a match
* column set.
*
* @param rowset the <code>RowSet</code> object that is to be added to this
* <code>JoinRowSet</code> object; it may implement the
* <code>Joinable</code> interface
* @param columnIdx an <code>int</code> that identifies the column to become the
* match column
* @throws SQLException if (1) <i>rowset</i> is an empty rowset or
* (2) <i>rowset</i> violates the active <code>JOIN</code>
* @see Joinable#unsetMatchColumn
*/
public void addRowSet(RowSet rowset, int columnIdx) throws SQLException;
/** {@collect.stats}
* Adds <i>rowset</i> to this <code>JoinRowSet</code> object and
* sets the designated column as the match column. If <i>rowset</i>
* is the first to be added to this <code>JoinRowSet</code>
* object, it forms the basis for the <code>JOIN</code> relationship to be
* established.
* <P>
* This method should be used when the given <code>RowSet</code> object
* does not already have a match column.
*
* @param rowset the <code>RowSet</code> object that is to be added to this
* <code>JoinRowSet</code> object; it may implement the
* <code>Joinable</code> interface
* @param columnName the <code>String</code> object giving the name of the
* column to be set as the match column
* @throws SQLException if (1) <i>rowset</i> is an empty rowset or
* (2) the match column for <i>rowset</i> does not satisfy the
* conditions of the <code>JOIN</code>
*/
public void addRowSet(RowSet rowset,
String columnName) throws SQLException;
/** {@collect.stats}
* Adds one or more <code>RowSet</code> objects contained in the given
* array of <code>RowSet</code> objects to this <code>JoinRowSet</code>
* object and sets the match column for
* each of the <code>RowSet</code> objects to the match columns
* in the given array of column indexes. The first element in
* <i>columnIdx</i> is set as the match column for the first
* <code>RowSet</code> object in <i>rowset</i>, the second element of
* <i>columnIdx</i> is set as the match column for the second element
* in <i>rowset</i>, and so on.
* <P>
* The first <code>RowSet</code> object added to this <code>JoinRowSet</code>
* object forms the basis for the <code>JOIN</code> relationship.
* <P>
* This method should be used when the given <code>RowSet</code> object
* does not already have a match column.
*
* @param rowset an array of one or more <code>RowSet</code> objects
* to be added to the <code>JOIN</code>; it may implement the
* <code>Joinable</code> interface
* @param columnIdx an array of <code>int</code> values indicating the index(es)
* of the columns to be set as the match columns for the <code>RowSet</code>
* objects in <i>rowset</i>
* @throws SQLException if (1) an empty rowset is added to this
* <code>JoinRowSet</code> object, (2) a match column is not set
* for a <code>RowSet</code> object in <i>rowset</i>, or (3)
* a <code>RowSet</code> object being added violates the active
* <code>JOIN</code>
*/
public void addRowSet(RowSet[] rowset,
int[] columnIdx) throws SQLException;
/** {@collect.stats}
* Adds one or more <code>RowSet</code> objects contained in the given
* array of <code>RowSet</code> objects to this <code>JoinRowSet</code>
* object and sets the match column for
* each of the <code>RowSet</code> objects to the match columns
* in the given array of column names. The first element in
* <i>columnName</i> is set as the match column for the first
* <code>RowSet</code> object in <i>rowset</i>, the second element of
* <i>columnName</i> is set as the match column for the second element
* in <i>rowset</i>, and so on.
* <P>
* The first <code>RowSet</code> object added to this <code>JoinRowSet</code>
* object forms the basis for the <code>JOIN</code> relationship.
* <P>
* This method should be used when the given <code>RowSet</code> object(s)
* does not already have a match column.
*
* @param rowset an array of one or more <code>RowSet</code> objects
* to be added to the <code>JOIN</code>; it may implement the
* <code>Joinable</code> interface
* @param columnName an array of <code>String</code> values indicating the
* names of the columns to be set as the match columns for the
* <code>RowSet</code> objects in <i>rowset</i>
* @throws SQLException if (1) an empty rowset is added to this
* <code>JoinRowSet</code> object, (2) a match column is not set
* for a <code>RowSet</code> object in <i>rowset</i>, or (3)
* a <code>RowSet</code> object being added violates the active
* <code>JOIN</code>
*/
public void addRowSet(RowSet[] rowset,
String[] columnName) throws SQLException;
/** {@collect.stats}
* Returns a <code>Collection</code> object containing the
* <code>RowSet</code> objects that have been added to this
* <code>JoinRowSet</code> object.
* This should return the 'n' number of RowSet contained
* within the <code>JOIN</code> and maintain any updates that have occured while in
* this union.
*
* @return a <code>Collection</code> object consisting of the
* <code>RowSet</code> objects added to this <code>JoinRowSet</code>
* object
* @throws SQLException if an error occurs generating the
* <code>Collection</code> object to be returned
*/
public Collection<?> getRowSets() throws java.sql.SQLException;
/** {@collect.stats}
* Returns a <code>String</code> array containing the names of the
* <code>RowSet</code> objects added to this <code>JoinRowSet</code>
* object.
*
* @return a <code>String</code> array of the names of the
* <code>RowSet</code> objects in this <code>JoinRowSet</code>
* object
* @throws SQLException if an error occurs retrieving the names of
* the <code>RowSet</code> objects
* @see CachedRowSet#setTableName
*/
public String[] getRowSetNames() throws java.sql.SQLException;
/** {@collect.stats}
* Creates a new <code>CachedRowSet</code> object containing the
* data in this <code>JoinRowSet</code> object, which can be saved
* to a data source using the <code>SyncProvider</code> object for
* the <code>CachedRowSet</code> object.
* <P>
* If any updates or modifications have been applied to the JoinRowSet
* the CachedRowSet returned by the method will not be able to persist
* it's changes back to the originating rows and tables in the
* in the datasource. The CachedRowSet instance returned should not
* contain modification data and it should clear all properties of
* it's originating SQL statement. An application should reset the
* SQL statement using the <code>RowSet.setCommand</code> method.
* <p>
* In order to allow changes to be persisted back to the datasource
* to the originating tables, the <code>acceptChanges</code> method
* should be used and called on a JoinRowSet object instance. Implementations
* can leverage the internal data and update tracking in their
* implementations to interact with the SyncProvider to persist any
* changes.
*
* @return a CachedRowSet containing the contents of the JoinRowSet
* @throws SQLException if an error occurs assembling the CachedRowSet
* object
* @see javax.sql.RowSet
* @see javax.sql.rowset.CachedRowSet
* @see javax.sql.rowset.spi.SyncProvider
*/
public CachedRowSet toCachedRowSet() throws java.sql.SQLException;
/** {@collect.stats}
* Indicates if CROSS_JOIN is supported by a JoinRowSet
* implementation
*
* @return true if the CROSS_JOIN is supported; false otherwise
*/
public boolean supportsCrossJoin();
/** {@collect.stats}
* Indicates if INNER_JOIN is supported by a JoinRowSet
* implementation
*
* @return true is the INNER_JOIN is supported; false otherwise
*/
public boolean supportsInnerJoin();
/** {@collect.stats}
* Indicates if LEFT_OUTER_JOIN is supported by a JoinRowSet
* implementation
*
* @return true is the LEFT_OUTER_JOIN is supported; false otherwise
*/
public boolean supportsLeftOuterJoin();
/** {@collect.stats}
* Indicates if RIGHT_OUTER_JOIN is supported by a JoinRowSet
* implementation
*
* @return true is the RIGHT_OUTER_JOIN is supported; false otherwise
*/
public boolean supportsRightOuterJoin();
/** {@collect.stats}
* Indicates if FULL_JOIN is supported by a JoinRowSet
* implementation
*
* @return true is the FULL_JOIN is supported; false otherwise
*/
public boolean supportsFullJoin();
/** {@collect.stats}
* Allow the application to adjust the type of <code>JOIN</code> imposed
* on tables contained within the JoinRowSet object instance.
* Implementations should throw a SQLException if they do
* not support a given <code>JOIN</code> type.
*
* @param joinType the standard JoinRowSet.XXX static field definition
* of a SQL <code>JOIN</code> to re-configure a JoinRowSet instance on
* the fly.
* @throws SQLException if an unsupported <code>JOIN</code> type is set
* @see #getJoinType
*/
public void setJoinType(int joinType) throws SQLException;
/** {@collect.stats}
* Return a SQL-like description of the WHERE clause being used
* in a JoinRowSet object. An implementation can describe
* the WHERE clause of the SQL <code>JOIN</code> by supplying a SQL
* strings description of <code>JOIN</code> or provide a textual
* description to assist applications using a <code>JoinRowSet</code>
*
* @return whereClause a textual or SQL description of the logical
* WHERE clause used in the JoinRowSet instance
* @throws SQLException if an error occurs in generating a representation
* of the WHERE clause.
*/
public String getWhereClause() throws SQLException;
/** {@collect.stats}
* Returns a <code>int</code> describing the set SQL <code>JOIN</code> type
* governing this JoinRowSet instance. The returned type will be one of
* standard JoinRowSet types: <code>CROSS_JOIN</code>, <code>INNER_JOIN</code>,
* <code>LEFT_OUTER_JOIN</code>, <code>RIGHT_OUTER_JOIN</code> or
* <code>FULL_JOIN</code>.
*
* @return joinType one of the standard JoinRowSet static field
* definitions of a SQL <code>JOIN</code>. <code>JoinRowSet.INNER_JOIN</code>
* is returned as the default <code>JOIN</code> type is no type has been
* explicitly set.
* @throws SQLException if an error occurs determining the SQL <code>JOIN</code>
* type supported by the JoinRowSet instance.
* @see #setJoinType
*/
public int getJoinType() throws SQLException;
/** {@collect.stats}
* An ANSI-style <code>JOIN</code> providing a cross product of two tables
*/
public static int CROSS_JOIN = 0;
/** {@collect.stats}
* An ANSI-style <code>JOIN</code> providing a inner join between two tables. Any
* unmatched rows in either table of the join should be discarded.
*/
public static int INNER_JOIN = 1;
/** {@collect.stats}
* An ANSI-style <code>JOIN</code> providing a left outer join between two
* tables. In SQL, this is described where all records should be
* returned from the left side of the JOIN statement.
*/
public static int LEFT_OUTER_JOIN = 2;
/** {@collect.stats}
* An ANSI-style <code>JOIN</code> providing a right outer join between
* two tables. In SQL, this is described where all records from the
* table on the right side of the JOIN statement even if the table
* on the left has no matching record.
*/
public static int RIGHT_OUTER_JOIN = 3;
/** {@collect.stats}
* An ANSI-style <code>JOIN</code> providing a a full JOIN. Specifies that all
* rows from either table be returned regardless of matching
* records on the other table.
*/
public static int FULL_JOIN = 4;
}
| Java |
/*
* Copyright (c) 2003, 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 javax.sql.rowset;
import javax.sql.*;
import java.sql.*;
/** {@collect.stats}
* The standard interface that provides the framework for all
* <code>FilteredRowSet</code> objects to describe their filters.
* <p>
* <h3>1.0 Background</h3>
* The <code>Predicate</code> interface is a standard interface that
* applications can implement to define the filter they wish to apply to a
* a <code>FilteredRowSet</code> object. A <code>FilteredRowSet</code>
* object consumes implementations of this interface and enforces the
* constraints defined in the implementation of the method <code>evaluate</code>.
* A <code>FilteredRowSet</code> object enforces the filter constraints in a
* bi-directional manner: It outputs only rows that are within
* the constraints of the filter; and conversely, it inserts, modifies, or updates
* only rows that are within the constraints of the filter.
*
* <h3>2.0 Implementation Guidelines</h3>
* In order to supply a predicate for the <code>FilteredRowSet</code>.
* this interface must be implemented. At this time, the JDBC RowSet
* Implementations (JSR-114) does not specify any standard filters definitions.
* By specifying a standard means and mechanism for a range of filters to be
* defined and deployed with both the reference and vendor implementations
* of the <code>FilteredRowSet</code> interface, this allows for a flexible
* and application motivated implementations of <code>Predicate</code> to emerge.
* <p>
* A sample implementation would look something like this:
* <pre>
* <code>
* public class Range implements Predicate {
*
* private Object lo[];
* private Object hi[];
* private int idx[];
*
* public Range(Object[] lo, Object[] hi, int[] idx) {
* this.lo = lo;
* this.hi = hi;
* this.idx = idx;
* }
*
* public boolean evaluate(RowSet rs) {
* CachedRowSet crs = (CachedRowSet)rs;
* boolean bool1,bool2;
*
* // Check the present row determine if it lies
* // within the filtering criteria.
*
* for (int i = 0; i < idx.length; i++) {
*
* if ((rs.getObject(idx[i]) >= lo[i]) &&
* (rs.getObject(idx[i]) >= hi[i]) {
* bool1 = true; // within filter constraints
* } else {
* bool2 = true; // outside of filter constraints
* }
* }
*
* if (bool2) {
* return false;
* } else {
* return true;
* }
* }
* </code>
* </pre>
* <P>
* The example above implements a simple range predicate. Note, that
* implementations should but are not required to provider <code>String</code>
* and integer index based constructors to provide for JDBC RowSet Implementation
* applications that use both column identification conventions.
*
* @author Jonathan Bruce, Amit Handa
*
*/
// <h3>3.0 FilteredRowSet Internals</h3>
// internalNext, Frist, Last. Discuss guidelines on how to approach this
// and cite examples in reference implementations.
public interface Predicate {
/** {@collect.stats}
* This method is typically called a <code>FilteredRowSet</code> object
* internal methods (not public) that control the <code>RowSet</code> object's
* cursor moving from row to the next. In addition, if this internal method
* moves the cursor onto a row that has been deleted, the internal method will
* continue to ove the cursor until a valid row is found.
*
* @return <code>true</code> if there are more rows in the filter;
* <code>false</code> otherwise
*/
public boolean evaluate(RowSet rs);
/** {@collect.stats}
* This method is called by a <code>FilteredRowSet</code> object
* to check whether the value lies between the filtering criterion (or criteria
* if multiple constraints exist) set using the <code>setFilter()</code> method.
* <P>
* The <code>FilteredRowSet</code> object will use this method internally
* while inserting new rows to a <code>FilteredRowSet</code> instance.
*
* @param value An <code>Object</code> value which needs to be checked,
* whether it can be part of this <code>FilterRowSet</code> object.
* @param column a <code>int</code> object that must match the
* SQL index of a column in this <code>RowSet</code> object. This must
* have been passed to <code>Predicate</code> as one of the columns
* for filtering while initializing a <code>Predicate</code>
* @return <code>true</code> ifrow value lies within the filter;
* <code>false</code> otherwise
* @throws SQLException if the column is not part of filtering criteria
*/
public boolean evaluate(Object value, int column) throws SQLException;
/** {@collect.stats}
* This method is called by the <code>FilteredRowSet</code> object
* to check whether the value lies between the filtering criteria set
* using the setFilter method.
* <P>
* The <code>FilteredRowSet</code> object will use this method internally
* while inserting new rows to a <code>FilteredRowSet</code> instance.
*
* @param value An <code>Object</code> value which needs to be checked,
* whether it can be part of this <code>FilterRowSet</code>.
*
* @param columnName a <code>String</code> object that must match the
* SQL name of a column in this <code>RowSet</code>, ignoring case. This must
* have been passed to <code>Predicate</code> as one of the columns for filtering
* while initializing a <code>Predicate</code>
*
* @return <code>true</code> if value lies within the filter; <code>false</code> otherwise
*
* @throws SQLException if the column is not part of filtering criteria
*/
public boolean evaluate(Object value, String columnName) throws SQLException;
}
| Java |
/*
* Copyright (c) 2003, 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 javax.sql.rowset.spi;
import java.sql.SQLException;
import java.io.Reader;
import javax.sql.RowSetWriter;
import javax.sql.rowset.*;
import java.sql.Savepoint;
/** {@collect.stats}
* A specialized interface that facilitates an extension of the standard
* <code>SyncProvider</code> abstract class so that it has finer grained
* transaction control.
* <p>
* If one or more disconnected <code>RowSet</code> objects are particating
* in a global transaction, they may wish to coordinate their synchronization
* commits to preserve data integrity and reduce the number of
* sychronization exceptions. If this is the case, an application should set
* the <code>CachedRowSet</code> constant <code>COMMIT_ON_ACCEPT_CHANGES</code>
* to <code>false</code> and use the <code>commit</code> and <code>rollback</code>
* methods defined in this interface to manage transaction boundaries.
*/
public interface TransactionalWriter extends RowSetWriter {
/** {@collect.stats}
* Makes permanent all changes that have been performed by the
* <code>acceptChanges</code> method since the last call to either the
* <code>commit</code> or <code>rollback</code> methods.
* This method should be used only when auto-commit mode has been disabled.
*
* @throws SQLException if a database access error occurs or the
* <code>Connection</code> object within this <code>CachedRowSet</code>
* object is in auto-commit mode
*/
public void commit() throws SQLException;
/** {@collect.stats}
* Undoes all changes made in the current transaction. This method should be
* used only when auto-commit mode has been disabled.
*
* @throws SQLException if a database access error occurs or the <code>Connection</code>
* object within this <code>CachedRowSet</code> object is in auto-commit mode
*/
public void rollback() throws SQLException;
/** {@collect.stats}
* Undoes all changes made in the current transaction made prior to the given
* <code>Savepoint</code> object. This method should be used only when auto-commit
* mode has been disabled.
*
* @param s a <code>Savepoint</code> object marking a savepoint in the current
* transaction. All changes made before <i>s</i> was set will be undone.
* All changes made after <i>s</i> was set will be made permanent.
* @throws SQLException if a database access error occurs or the <code>Connection</code>
* object within this <code>CachedRowSet</code> object is in auto-commit mode
*/
public void rollback(Savepoint s) throws SQLException;
}
| Java |
/*
* Copyright (c) 2003, 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 javax.sql.rowset.spi;
import javax.sql.RowSet;
import java.sql.SQLException;
/** {@collect.stats}
* Defines a framework that allows applications to use a manual decision tree
* to decide what should be done when a synchronization conflict occurs.
* Although it is not mandatory for
* applications to resolve synchronization conflicts manually, this
* framework provides the means to delegate to the application when conflicts
* arise.
* <p>
* Note that a conflict is a situation where the <code>RowSet</code> object's original
* values for a row do not match the values in the data source, which indicates that
* the data source row has been modified since the last synchronization. Note also that
* a <code>RowSet</code> object's original values are the values it had just prior to the
* the last synchronization, which are not necessarily its initial values.
* <p>
*
* <H2>Description of a <code>SyncResolver</code> Object</H2>
*
* A <code>SyncResolver</code> object is a specialized <code>RowSet</code> object
* that implements the <code>SyncResolver</code> interface.
* It <b>may</b> operate as either a connected <code>RowSet</code> object (an
* implementation of the <code>JdbcRowSet</code> interface) or a connected
* <code>RowSet</code> object (an implementation of the
* <code>CachedRowSet</code> interface or one of its subinterfaces). For information
* on the subinterfaces, see the
* <a href="../package-summary.html"><code>javax.sql.rowset</code></a> package
* description. The reference implementation for <code>SyncResolver</code> implements
* the <code>CachedRowSet</code> interface, but other implementations
* may choose to implement the <code>JdbcRowSet</code> interface to satisfy
* particular needs.
* <P>
* After an application has attempted to synchronize a <code>RowSet</code> object with
* the data source (by calling the <code>CachedRowSet</code>
* method <code>acceptChanges</code>), and one or more conflicts have been found,
* a rowset's <code>SyncProvider</code> object creates an instance of
* <code>SyncResolver</code>. This new <code>SyncResolver</code> object has
* the same number of rows and columns as the
* <code>RowSet</code> object that was attempting the synchronization. The
* <code>SyncResolver</code> object contains the values from the data source that caused
* the conflict(s) and <code>null</code> for all other values.
* In addition, it contains information about each conflict.
* <P>
*
* <H2>Getting and Using a <code>SyncResolver</code> Object</H2>
*
* When the method <code>acceptChanges</code> encounters conflicts, the
* <code>SyncProvider</code> object creates a <code>SyncProviderException</code>
* object and sets it with the new <code>SyncResolver</code> object. The method
* <code>acceptChanges</code> will throw this exception, which
* the application can then catch and use to retrieve the
* <code>SyncResolver</code> object it contains. The following code snippet uses the
* <code>SyncProviderException</code> method <code>getSyncResolver</code> to get
* the <code>SyncResolver</code> object <i>resolver</i>.
* <PRE>
* } catch (SyncProviderException spe) {
* SyncResolver resolver = spe.getSyncResolver();
* ...
* }
* </PRE>
* <P>
* With <i>resolver</i> in hand, an application can use it to get the information
* it contains about the conflict or conflicts. A <code>SyncResolver</code> object
* such as <i>resolver</i> keeps
* track of the conflicts for each row in which there is a conflict. It also places a
* lock on the table or tables affected by the rowset's command so that no more
* conflicts can occur while the current conflicts are being resolved.
* <P>
* The following kinds of information can be obtained from a <code>SyncResolver</code>
* object:
* <P>
* <LI>What operation was being attempted when a conflict occurred<BR>
* The <code>SyncProvider</code> interface defines four constants
* describing states that may occur. Three
* constants describe the type of operation (update, delete, or insert) that a
* <code>RowSet</code> object was attempting to perform when a conflict was discovered,
* and the fourth indicates that there is no conflict.
* These constants are the possible return values when a <code>SyncResolver</code> object
* calls the method <code>getStatus</code>.
* <PRE>
* int operation = resolver.getStatus();
* </PRE>
* <P>
* <LI>The value in the data source that caused a conflict<BR>
* A conflict exists when a value that a <code>RowSet</code> object has changed
* and is attempting to write to the data source
* has also been changed in the data source since the last synchronization. An
* application can call the <code>SyncResolver</code> method
* <code>getConflictValue</code > to retrieve the
* value in the data source that is the cause of the conflict because the values in a
* <code>SyncResolver</code> object are the conflict values from the data source.
* <PRE>
* java.lang.Object conflictValue = resolver.getConflictValue(2);
* </PRE>
* Note that the column in <i>resolver</i> can be designated by the column number,
* as is done in the preceding line of code, or by the column name.
* </UL>
* <P>
* With the information retrieved from the methods <code>getStatus</code> and
* <code>getConflictValue</code>, the application may make a determination as to
* which value should be persisted in the data source. The application then calls the
* <code>SyncResolver</code> method <code>setResolvedValue</code>, which sets the value
* to be persisted in the <code>RowSet</code> object and also in the data source.
* <PRE>
* resolver.setResolvedValue("DEPT", 8390426);
* </PRE>
* In the preceding line of code,
* the column name designates the column in the <code>RowSet</code> object
* that is to be set with the given value. The column number can also be used to
* designate the column.
* <P>
* An application calls the method <code>setResolvedValue</code> after it has
* resolved all of the conflicts in the current conflict row and repeats this process
* for each conflict row in the <code>SyncResolver</code> object.
* <P>
*
* <H2>Navigating a <code>SyncResolver</code> Object</H2>
*
* Because a <code>SyncResolver</code> object is a <code>RowSet</code> object, an
* application can use all of the <code>RowSet</code> methods for moving the cursor
* to navigate a <code>SyncResolver</code> object. For example, an application can
* use the <code>RowSet</code> method <code>next</code> to get to each row and then
* call the <code>SyncResolver</code> method <code>getStatus</code> to see if the row
* contains a conflict. In a row with one or more conflicts, the application can
* iterate through the columns to find any non-null values, which will be the values
* from the data source that are in conflict.
* <P>
* To make it easier to navigate a <code>SyncResolver</code> object, especially when
* there are large numbers of rows with no conflicts, the <code>SyncResolver</code>
* interface defines the methods <code>nextConflict</code> and
* <code>previousConflict</code>, which move only to rows
* that contain at least one conflict value. Then an application can call the
* <code>SyncResolver</code> method <code>getConflictValue</code>, supplying it
* with the column number, to get the conflict value itself. The code fragment in the
* next section gives an example.
*
* <H2>Code Example</H2>
*
* The following code fragment demonstrates how a disconnected <code>RowSet</code>
* object <i>crs</i> might attempt to synchronize itself with the
* underlying data source and then resolve the conflicts. In the <code>try</code>
* block, <i>crs</i> calls the method <code>acceptChanges</code>, passing it the
* <code>Connection</code> object <i>con</i>. If there are no conflicts, the
* changes in <i>crs</i> are simply written to the data source. However, if there
* is a conflict, the method <code>acceptChanges</code> throws a
* <code>SyncProviderException</code> object, and the
* <code>catch</code> block takes effect. In this example, which
* illustrates one of the many ways a <code>SyncResolver</code> object can be used,
* the <code>SyncResolver</code> method <code>nextConflict</code> is used in a
* <code>while</code> loop. The loop will end when <code>nextConflict</code> returns
* <code>false</code>, which will occur when there are no more conflict rows in the
* <code>SyncResolver</code> object <i>resolver</i>. In This particular code fragment,
* <i>resolver</i> looks for rows that have update conflicts (rows with the status
* <code>SyncResolver.UPDATE_ROW_CONFLICT</code>), and the rest of this code fragment
* executes only for rows where conflicts occurred because <i>crs</i> was attempting an
* update.
* <P>
* After the cursor for <i>resolver</i> has moved to the next conflict row that
* has an update conflict, the method <code>getRow</code> indicates the number of the
* current row, and
* the cursor for the <code>CachedRowSet</code> object <i>crs</i> is moved to
* the comparable row in <i>crs</i>. By iterating
* through the columns of that row in both <i>resolver</i> and <i>crs</i>, the conflicting
* values can be retrieved and compared to decide which one should be persisted. In this
* code fragment, the value in <i>crs</i> is the one set as the resolved value, which means
* that it will be used to overwrite the conflict value in the data source.
*
* <PRE>
* try {
*
* crs.acceptChanges(con);
*
* } catch (SyncProviderException spe) {
*
* SyncResolver resolver = spe.getSyncResolver();
*
* Object crsValue; // value in the <code>RowSet</code> object
* Object resolverValue: // value in the <code>SyncResolver</code> object
* Object resolvedValue: // value to be persisted
*
* while(resolver.nextConflict()) {
* if(resolver.getStatus() == SyncResolver.UPDATE_ROW_CONFLICT) {
* int row = resolver.getRow();
* crs.absolute(row);
*
* int colCount = crs.getMetaData().getColumnCount();
* for(int j = 1; j <= colCount; j++) {
* if (resolver.getConflictValue(j) != null) {
* crsValue = crs.getObject(j);
* resolverValue = resolver.getConflictValue(j);
* . . .
* // compare crsValue and resolverValue to determine
* // which should be the resolved value (the value to persist)
* resolvedValue = crsValue;
*
* resolver.setResolvedValue(j, resolvedValue);
* }
* }
* }
* }
* }
* </PRE>
* @author Jonathan Bruce
*/
public interface SyncResolver extends RowSet {
/** {@collect.stats}
* Indicates that a conflict occurred while the <code>RowSet</code> object was
* attempting to update a row in the data source.
* The values in the data source row to be updated differ from the
* <code>RowSet</code> object's original values for that row, which means that
* the row in the data source has been updated or deleted since the last
* synchronization.
*/
public static int UPDATE_ROW_CONFLICT = 0;
/** {@collect.stats}
* Indicates that a conflict occurred while the <code>RowSet</code> object was
* attempting to delete a row in the data source.
* The values in the data source row to be updated differ from the
* <code>RowSet</code> object's original values for that row, which means that
* the row in the data source has been updated or deleted since the last
* synchronization.
*/
public static int DELETE_ROW_CONFLICT = 1;
/** {@collect.stats}
* Indicates that a conflict occurred while the <code>RowSet</code> object was
* attempting to insert a row into the data source. This means that a
* row with the same primary key as the row to be inserted has been inserted
* into the data source since the last synchronization.
*/
public static int INSERT_ROW_CONFLICT = 2;
/** {@collect.stats}
* Indicates that <b>no</b> conflict occured while the <code>RowSet</code> object
* was attempting to update, delete or insert a row in the data source. The values in
* the <code>SyncResolver</code> will contain <code>null</code> values only as an indication
* that no information in pertitent to the conflict resolution in this row.
*/
public static int NO_ROW_CONFLICT = 3;
/** {@collect.stats}
* Retrieves the conflict status of the current row of this <code>SyncResolver</code>,
* which indicates the operation
* the <code>RowSet</code> object was attempting when the conflict occurred.
*
* @return one of the following constants:
* <code>SyncResolver.UPDATE_ROW_CONFLICT</code>,
* <code>SyncResolver.DELETE_ROW_CONFLICT</code>,
* <code>SyncResolver.INSERT_ROW_CONFLICT</code>, or
* <code>SyncResolver.NO_ROW_CONFLICT</code>
*/
public int getStatus();
/** {@collect.stats}
* Retrieves the value in the designated column in the current row of this
* <code>SyncResolver</code> object, which is the value in the data source
* that caused a conflict.
*
* @param index an <code>int</code> designating the column in this row of this
* <code>SyncResolver</code> object from which to retrieve the value
* causing a conflict
* @return the value of the designated column in the current row of this
* <code>SyncResolver</code> object
* @throws SQLException if a database access error occurs
*/
public Object getConflictValue(int index) throws SQLException;
/** {@collect.stats}
* Retrieves the value in the designated column in the current row of this
* <code>SyncResolver</code> object, which is the value in the data source
* that caused a conflict.
*
* @param columnName a <code>String</code> object designating the column in this row of this
* <code>SyncResolver</code> object from which to retrieve the value
* causing a conflict
* @return the value of the designated column in the current row of this
* <code>SyncResolver</code> object
* @throws SQLException if a database access error occurs
*/
public Object getConflictValue(String columnName) throws SQLException;
/** {@collect.stats}
* Sets <i>obj</i> as the value in column <i>index</i> in the current row of the
* <code>RowSet</code> object that is being synchronized. <i>obj</i>
* is set as the value in the data source internally.
*
* @param index an <code>int</code> giving the number of the column into which to
* set the value to be persisted
* @param obj an <code>Object</code> that is the value to be set in the
* <code>RowSet</code> object and persisted in the data source
* @throws SQLException if a database access error occurs
*/
public void setResolvedValue(int index, Object obj) throws SQLException;
/** {@collect.stats}
* Sets <i>obj</i> as the value in column <i>columnName</i> in the current row of the
* <code>RowSet</code> object that is being synchronized. <i>obj</i>
* is set as the value in the data source internally.
*
* @param columnName a <code>String</code> object giving the name of the column
* into which to set the value to be persisted
* @param obj an <code>Object</code> that is the value to be set in the
* <code>RowSet</code> object and persisted in the data source
* @throws SQLException if a database access error occurs
*/
public void setResolvedValue(String columnName, Object obj) throws SQLException;
/** {@collect.stats}
* Moves the cursor down from its current position to the next row that contains
* a conflict value. A <code>SyncResolver</code> object's
* cursor is initially positioned before the first conflict row; the first call to the
* method <code>nextConflict</code> makes the first conflict row the current row;
* the second call makes the second conflict row the current row, and so on.
* <p>
* A call to the method <code>nextConflict</code> will implicitly close
* an input stream if one is open and will clear the <code>SyncResolver</code>
* object's warning chain.
*
* @return <code>true</code> if the new current row is valid; <code>false</code>
* if there are no more rows
* @throws SQLException if a database access error occurs or the result set type
* is <code>TYPE_FORWARD_ONLY</code>
*
*/
public boolean nextConflict() throws SQLException;
/** {@collect.stats}
* Moves the cursor up from its current position to the previous conflict
* row in this <code>SyncResolver</code> object.
* <p>
* A call to the method <code>previousConflict</code> will implicitly close
* an input stream if one is open and will clear the <code>SyncResolver</code>
* object's warning chain.
*
* @return <code>true</code> if the cursor is on a valid row; <code>false</code>
* if it is off the result set
* @throws SQLException if a database access error occurs or the result set type
* is <code>TYPE_FORWARD_ONLY</code>
*/
public boolean previousConflict() throws SQLException;
}
| 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 javax.sql.rowset.spi;
import java.util.Map;
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Properties;
import java.util.Collection;
import java.util.StringTokenizer;
import java.util.logging.*;
import java.util.*;
import java.sql.*;
import javax.sql.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import javax.naming.*;
/** {@collect.stats}
* The Service Provider Interface (SPI) mechanism that generates <code>SyncProvider</code>
* instances to be used by disconnected <code>RowSet</code> objects.
* The <code>SyncProvider</code> instances in turn provide the
* <code>javax.sql.RowSetReader</code> object the <code>RowSet</code> object
* needs to populate itself with data and the
* <code>javax.sql.RowSetWriter</code> object it needs to
* propagate changes to its
* data back to the underlying data source.
* <P>
* Because the methods in the <code>SyncFactory</code> class are all static,
* there is only one <code>SyncFactory</code> object
* per Java VM at any one time. This ensures that there is a single source from which a
* <code>RowSet</code> implementation can obtain its <code>SyncProvider</code>
* implementation.
* <p>
* <h3>1.0 Overview</h3>
* The <code>SyncFactory</code> class provides an internal registry of available
* synchronization provider implementations (<code>SyncProvider</code> objects).
* This registry may be queried to determine which
* synchronization providers are available.
* The following line of code gets an enumeration of the providers currently registered.
* <PRE>
* java.util.Enumeration e = SyncFactory.getRegisteredProviders();
* </PRE>
* All standard <code>RowSet</code> implementations must provide at least two providers:
* <UL>
* <LI>an optimistic provider for use with a <code>CachedRowSet</code> implementation
* or an implementation derived from it
* <LI>an XML provider, which is used for reading and writing XML, such as with
* <code>WebRowSet</code> objects
* </UL>
* Note that the JDBC RowSet Implementations include the <code>SyncProvider</code>
* implemtations <code>RIOptimisticProvider</code> and <code>RIXmlProvider</code>,
* which satisfy this requirement.
* <P>
* The <code>SyncFactory</code> class provides accessor methods to assist
* applications in determining which synchronization providers are currently
* registered with the <code>SyncFactory</code>.
* <p>
* Other methods let <code>RowSet</code> persistence providers be
* registered or de-registered with the factory mechanism. This
* allows additional synchronization provider implementations to be made
* available to <code>RowSet</code> objects at run time.
* <p>
* Applications can apply a degree of filtering to determine the level of
* synchronization that a <code>SyncProvider</code> implementation offers.
* The following criteria determine whether a provider is
* made available to a <code>RowSet</code> object:
* <ol>
* <li>If a particular provider is specified by a <code>RowSet</code> object, and
* the <code>SyncFactory</code> does not contain a reference to this provider,
* a <code>SyncFactoryException</code> is thrown stating that the synchronization
* provider could not be found.
* <p>
* <li>If a <code>RowSet</code> implementation is instantiated with a specified
* provider and the specified provider has been properly registered, the
* requested provider is supplied. Otherwise a <code>SyncFactoryException</code>
* is thrown.
* <p>
* <li>If a <code>RowSet</code> object does not specify a
* <code>SyncProvider</code> implementation and no additional
* <code>SyncProvider</code> implementations are available, the reference
* implementation providers are supplied.
* </ol>
* <h3>2.0 Registering <code>SyncProvider</code> Implementations</h3>
* <p>
* Both vendors and developers can register <code>SyncProvider</code>
* implementations using one of the following mechanisms.
* <ul>
* <LI><B>Using the command line</B><BR>
* The name of the provider is supplied on the command line, which will add
* the provider to the system properties.
* For example:
* <PRE>
* -Drowset.provider.classname=com.fred.providers.HighAvailabilityProvider
* </PRE>
* <li><b>Using the Standard Properties File</b><BR>
* The reference implementation is targeted
* to ship with J2SE 1.5, which will include an additional resource file
* that may be edited by hand. Here is an example of the properties file
* included in the reference implementation:
* <PRE>
* #Default JDBC RowSet sync providers listing
* #
*
* # Optimistic synchronization provider
* rowset.provider.classname.0=com.sun.rowset.providers.RIOptimisticProvider
* rowset.provider.vendor.0=Sun Microsystems Inc
* rowset.provider.version.0=1.0
*
* # XML Provider using standard XML schema
* rowset.provider.classname.1=com.sun.rowset.providers.RIXMLProvider
* rowset.provider.vendor.1=Sun Microsystems Inc.
* rowset.provider.version.1=1.0
* </PRE>
* The <code>SyncFactory</code> checks this file and registers the
* <code>SyncProvider</code> implementations that it contains. A
* developer or vendor can add other implementations to this file.
* For example, here is a possible addition:
* <PRE>
* rowset.provider.classname.2=com.fred.providers.HighAvailabilityProvider
* rowset.provider.vendor.2=Fred, Inc.
* rowset.provider.version.2=1.0
* </PRE>
* <p>
* <li><b>Using a JNDI Context</b><BR>
* Available providers can be registered on a JNDI
* context, and the <code>SyncFactory</code> will attempt to load
* <code>SyncProvider</code> implementations from that JNDI context.
* For example, the following code fragment registers a provider implementation
* on a JNDI context. This is something a deployer would normally do. In this
* example, <code>MyProvider</code> is being registered on a CosNaming
* namespace, which is the namespace used by J2EE resources.
* <PRE>
* import javax.naming.*;
*
* Hashtable svrEnv = new Hashtable();
* srvEnv.put(Context.INITIAL_CONTEXT_FACTORY, "CosNaming");
*
* Context ctx = new InitialContext(svrEnv);
* com.fred.providers.MyProvider = new MyProvider();
* ctx.rebind("providers/MyProvider", syncProvider);
* </PRE>
* </ul>
* Next, an application will register the JNDI context with the
* <code>SyncFactory</code> instance. This allows the <code>SyncFactory</code>
* to browse within the JNDI context looking for <code>SyncProvider</code>
* implementations.
* <PRE>
* Hashtable appEnv = new Hashtable();
* appEnv.put(Context.INITIAL_CONTEXT_FACTORY, "CosNaming");
* appEnv.put(Context.PROVIDER_URL, "iiop://hostname/providers");
* Context ctx = new InitialContext(appEnv);
*
* SyncFactory.registerJNDIContext(ctx);
* </PRE>
* If a <code>RowSet</code> object attempts to obtain a <code>MyProvider</code>
* object, the <code>SyncFactory</code> will try to locate it. First it searches
* for it in the system properties, then it looks in the resource files, and
* finally it checks the JNDI context that has been set. The <code>SyncFactory</code>
* instance verifies that the requested provider is a valid extension of the
* <code>SyncProvider</code> abstract class and then gives it to the
* <code>RowSet</code> object. In the following code fragment, a new
* <code>CachedRowSet</code> object is created and initialized with
* <i>env</i>, which contains the binding to <code>MyProvider</code>.
* <PRE>
* Hashtable env = new Hashtable();
* env.put(SyncFactory.ROWSET_SYNC_PROVIDER, "com.fred.providers.MyProvider");
* CachedRowSet crs = new com.sun.rowset.CachedRowSetImpl(env);
* </PRE>
* Further details on these mechanisms are available in the
* <code>javax.sql.rowset.spi</code> package specification.
*
* @author Jonathan Bruce
* @see javax.sql.rowset.spi.SyncProvider
* @see javax.sql.rowset.spi.SyncFactoryException
*/
public class SyncFactory {
/*
* The variable that represents the singleton instance
* of the <code>SyncFactory</code> class.
*/
private static SyncFactory syncFactory = null;
/** {@collect.stats}
* Creates a new <code>SyncFactory</code> object, which is the singleton
* instance.
* Having a private constructor guarantees that no more than
* one <code>SyncProvider</code> object can exist at a time.
*/
private SyncFactory() {};
/** {@collect.stats}
* The standard property-id for a synchronization provider implementation
* name.
*/
public static String ROWSET_SYNC_PROVIDER =
"rowset.provider.classname";
/** {@collect.stats}
* The standard property-id for a synchronization provider implementation
* vendor name.
*/
public static String ROWSET_SYNC_VENDOR =
"rowset.provider.vendor";
/** {@collect.stats}
* The standard property-id for a synchronization provider implementation
* version tag.
*/
public static String ROWSET_SYNC_PROVIDER_VERSION =
"rowset.provider.version";
/** {@collect.stats}
* The standard resource file name.
*/
private static String ROWSET_PROPERTIES = "rowset.properties";
/** {@collect.stats}
* The RI Optimistic Provider.
*/
private static String default_provider =
"com.sun.rowset.providers.RIOptimisticProvider";
/** {@collect.stats}
* The initial JNDI context where <code>SyncProvider</code> implementations can
* be stored and from which they can be invoked.
*/
private static Context ic;
/** {@collect.stats}
* The <code>Logger</code> object to be used by the <code>SyncFactory</code>.
*/
private static Logger rsLogger;
/** {@collect.stats}
*
*/
private static Level rsLevel;
/** {@collect.stats}
* The registry of available <code>SyncProvider</code> implementations.
* See section 2.0 of the class comment for <code>SyncFactory</code> for an
* explanation of how a provider can be added to this registry.
*/
private static Hashtable implementations;
/** {@collect.stats}
* Internal sync object used to maintain the SPI as a singleton
*/
private static Object logSync = new Object();
/** {@collect.stats}
* Internal PrintWriter field for logging facility
*/
private static java.io.PrintWriter logWriter = null;
/** {@collect.stats}
* Adds the the given synchronization provider to the factory register. Guidelines
* are provided in the <code>SyncProvider</code> specification for the
* required naming conventions for <code>SyncProvider</code>
* implementations.
* <p>
* Synchronization providers bound to a JNDI context can be
* registered by binding a SyncProvider instance to a JNDI namespace.
* <ul>
* <pre>
* SyncProvider p = new MySyncProvider();
* InitialContext ic = new InitialContext();
* ic.bind ("jdbc/rowset/MySyncProvider", p);
* </pre>
* </ul>
* Furthermore, an initial JNDI context should be set with the
* <code>SyncFactory</code> using the <code>setJNDIContext</code> method.
* The <code>SyncFactory</code> leverages this context to search for
* available <code>SyncProvider</code> objects bound to the JNDI
* context and its child nodes.
*
* @param providerID A <code>String</code> object with the unique ID of the
* synchronization provider being registered
* @throws SyncFactoryException if an attempt is made to supply an empty
* or null provider name
* @see #setJNDIContext
*/
public static synchronized void registerProvider(String providerID)
throws SyncFactoryException {
ProviderImpl impl = new ProviderImpl();
impl.setClassname(providerID);
initMapIfNecessary();
implementations.put(providerID, impl);
}
/** {@collect.stats}
* Returns the <code>SyncFactory</code> singleton.
*
* @return the <code>SyncFactory</code> instance
*/
public static SyncFactory getSyncFactory(){
// This method uses the Singleton Design Pattern
// with Double-Checked Locking Pattern for
// 1. Creating single instance of the SyncFactory
// 2. Make the class thread safe, so that at one time
// only one thread enters the synchronized block
// to instantiate.
// if syncFactory object is already there
// don't go into synchronized block and return
// that object.
// else go into synchronized block
if(syncFactory == null){
synchronized(SyncFactory.class) {
if(syncFactory == null){
syncFactory = new SyncFactory();
} //end if
} //end synchronized block
} //end if
return syncFactory;
}
/** {@collect.stats}
* Removes the designated currently registered synchronization provider from the
* Factory SPI register.
*
* @param providerID The unique-id of the synchronization provider
* @throws SyncFactoryException If an attempt is made to
* unregister a SyncProvider implementation that was not registered.
*/
public static synchronized void unregisterProvider(String providerID)
throws SyncFactoryException {
initMapIfNecessary();
if (implementations.containsKey(providerID)) {
implementations.remove(providerID);
}
}
private static String colon = ":";
private static String strFileSep = "/";
private static synchronized void initMapIfNecessary() throws SyncFactoryException {
// Local implementation class names and keys from Properties
// file, translate names into Class objects using Class.forName
// and store mappings
Properties properties = new Properties();
if (implementations == null) {
implementations = new Hashtable();
try {
// check if user is supplying his Synchronisation Provider
// Implementation if not use Sun's implementation.
// properties.load(new FileInputStream(ROWSET_PROPERTIES));
// The rowset.properties needs to be in jdk/jre/lib when
// integrated with jdk.
// else it should be picked from -D option from command line.
// -Drowset.properties will add to standard properties. Similar
// keys will over-write
/*
* Dependent on application
*/
String strRowsetProperties = System.getProperty("rowset.properties");
if ( strRowsetProperties != null) {
// Load user's implementation of SyncProvider
// here. -Drowset.properties=/abc/def/pqr.txt
ROWSET_PROPERTIES = strRowsetProperties;
properties.load(new FileInputStream(ROWSET_PROPERTIES));
parseProperties(properties);
}
/*
* Always available
*/
ROWSET_PROPERTIES = "javax" + strFileSep + "sql" +
strFileSep + "rowset" + strFileSep +
"rowset.properties";
// properties.load(
// ClassLoader.getSystemResourceAsStream(ROWSET_PROPERTIES));
ClassLoader cl = Thread.currentThread().getContextClassLoader();
properties.load(cl.getResourceAsStream(ROWSET_PROPERTIES));
parseProperties(properties);
// removed else, has properties should sum together
} catch (FileNotFoundException e) {
throw new SyncFactoryException("Cannot locate properties file: " + e);
} catch (IOException e) {
throw new SyncFactoryException("IOException: " + e);
}
/*
* Now deal with -Drowset.provider.classname
* load additional properties from -D command line
*/
properties.clear();
String providerImpls = System.getProperty(ROWSET_SYNC_PROVIDER);
if (providerImpls != null) {
int i = 0;
if (providerImpls.indexOf(colon) > 0) {
StringTokenizer tokenizer = new StringTokenizer(providerImpls, colon);
while (tokenizer.hasMoreElements()) {
properties.put(ROWSET_SYNC_PROVIDER + "." + i, tokenizer.nextToken());
i++;
}
} else {
properties.put(ROWSET_SYNC_PROVIDER, providerImpls);
}
parseProperties(properties);
}
}
}
/** {@collect.stats}
* The internal boolean switch that indicates whether a JNDI
* context has been established or not.
*/
private static boolean jndiCtxEstablished = false;
/** {@collect.stats}
* The internal debug switch.
*/
private static boolean debug = false;
/** {@collect.stats}
* Internal registry count for the number of providers contained in the
* registry.
*/
private static int providerImplIndex = 0;
/** {@collect.stats}
* Internal handler for all standard property parsing. Parses standard
* ROWSET properties and stores lazy references into the the internal registry.
*/
private static void parseProperties(Properties p) {
ProviderImpl impl = null;
String key = null;
String[] propertyNames = null;
for (Enumeration e = p.propertyNames(); e.hasMoreElements() ;) {
String str = (String)e.nextElement();
int w = str.length();
if (str.startsWith(SyncFactory.ROWSET_SYNC_PROVIDER)) {
impl = new ProviderImpl();
impl.setIndex(providerImplIndex++);
if (w == (SyncFactory.ROWSET_SYNC_PROVIDER).length()) {
// no property index has been set.
propertyNames = getPropertyNames(false);
} else {
// property index has been set.
propertyNames = getPropertyNames(true, str.substring(w-1));
}
key = p.getProperty(propertyNames[0]);
impl.setClassname(key);
impl.setVendor(p.getProperty(propertyNames[1]));
impl.setVersion(p.getProperty(propertyNames[2]));
implementations.put(key, impl);
}
}
}
/** {@collect.stats}
* Used by the parseProperties methods to disassemble each property tuple.
*/
private static String[] getPropertyNames(boolean append) {
return getPropertyNames(append, null);
}
/** {@collect.stats}
* Disassembles each property and its associated value. Also handles
* overloaded property names that contain indexes.
*/
private static String[] getPropertyNames(boolean append,
String propertyIndex) {
String dot = ".";
String[] propertyNames =
new String[] {SyncFactory.ROWSET_SYNC_PROVIDER,
SyncFactory.ROWSET_SYNC_VENDOR,
SyncFactory.ROWSET_SYNC_PROVIDER_VERSION};
if (append) {
for (int i = 0; i < propertyNames.length; i++) {
propertyNames[i] = propertyNames[i] +
dot +
propertyIndex;
}
return propertyNames;
} else {
return propertyNames;
}
}
/** {@collect.stats}
* Internal debug method that outputs the registry contents.
*/
private static void showImpl(ProviderImpl impl) {
System.out.println("Provider implementation:");
System.out.println("Classname: " + impl.getClassname());
System.out.println("Vendor: " + impl.getVendor());
System.out.println("Version: " + impl.getVersion());
System.out.println("Impl index: " + impl.getIndex());
}
/** {@collect.stats}
* Returns the <code>SyncProvider</code> instance identified by <i>providerID</i>.
*
* @param providerID the unique identifier of the provider
* @return a <code>SyncProvider</code> implementation
* @throws SyncFactoryException If the SyncProvider cannot be found or
* some error was encountered when trying to invoke this provider.
*/
public static SyncProvider getInstance(String providerID)
throws SyncFactoryException {
initMapIfNecessary(); // populate HashTable
initJNDIContext(); // check JNDI context for any additional bindings
ProviderImpl impl = (ProviderImpl)implementations.get(providerID);
if (impl == null) {
// Requested SyncProvider is unavailable. Return default provider.
return new com.sun.rowset.providers.RIOptimisticProvider();
}
// Attempt to invoke classname from registered SyncProvider list
Class c = null;
try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
/** {@collect.stats}
* The SyncProvider implementation of the user will be in
* the classpath. We need to find the ClassLoader which loads
* this SyncFactory and try to laod the SyncProvider class from
* there.
**/
c = Class.forName(providerID, true, cl);
if (c != null) {
return (SyncProvider)c.newInstance();
} else {
return new com.sun.rowset.providers.RIOptimisticProvider();
}
} catch (IllegalAccessException e) {
throw new SyncFactoryException("IllegalAccessException: " + e.getMessage());
} catch (InstantiationException e) {
throw new SyncFactoryException("InstantiationException: " + e.getMessage());
} catch (ClassNotFoundException e) {
throw new SyncFactoryException("ClassNotFoundException: " + e.getMessage());
}
}
/** {@collect.stats}
* Returns an Enumeration of currently registered synchronization
* providers. A <code>RowSet</code> implementation may use any provider in
* the enumeration as its <code>SyncProvider</code> object.
* <p>
* At a minimum, the reference synchronization provider allowing
* RowSet content data to be stored using a JDBC driver should be
* possible.
*
* @return Enumeration A enumeration of available synchronization
* providers that are registered with this Factory
*/
public static Enumeration<SyncProvider> getRegisteredProviders()
throws SyncFactoryException {
initMapIfNecessary();
// return a collection of classnames
// of type SyncProvider
return implementations.elements();
}
/** {@collect.stats}
* Sets the logging object to be used by the <code>SyncProvider</code>
* implementation provided by the <code>SyncFactory</code>. All
* <code>SyncProvider</code> implementations can log their events to
* this object and the application can retrieve a handle to this
* object using the <code>getLogger</code> method.
*
* @param logger A Logger object instance
*/
public static void setLogger(Logger logger) {
rsLogger = logger;
}
/** {@collect.stats}
* Sets the logging object that is used by <code>SyncProvider</code>
* implementations provided by the <code>SyncFactory</code> SPI. All
* <code>SyncProvider</code> implementations can log their events
* to this object and the application can retrieve a handle to this
* object using the <code>getLogger</code> method.
*
* @param logger a Logger object instance
* @param level a Level object instance indicating the degree of logging
* required
*/
public static void setLogger(Logger logger, Level level) {
// singleton
rsLogger = logger;
rsLogger.setLevel(level);
}
/** {@collect.stats}
* Returns the logging object for applications to retrieve
* synchronization events posted by SyncProvider implementations.
*
* @throws SyncFactoryException if no logging object has been set.
*/
public static Logger getLogger() throws SyncFactoryException {
// only one logger per session
if(rsLogger == null){
throw new SyncFactoryException("(SyncFactory) : No logger has been set");
}
return rsLogger;
}
/** {@collect.stats}
* Sets the initial JNDI context from which SyncProvider implementations
* can be retrieved from a JNDI namespace
*
* @param ctx a valid JNDI context
* @throws SyncFactoryException if the supplied JNDI context is null
*/
public static void setJNDIContext(javax.naming.Context ctx)
throws SyncFactoryException {
if (ctx == null) {
throw new SyncFactoryException("Invalid JNDI context supplied");
}
ic = ctx;
jndiCtxEstablished = true;
}
/** {@collect.stats}
* Controls JNDI context intialization.
*
* @throws SyncFactoryException if an error occurs parsing the JNDI context
*/
private static void initJNDIContext() throws SyncFactoryException {
if (jndiCtxEstablished && (ic != null) && (lazyJNDICtxRefresh == false)) {
try {
parseProperties(parseJNDIContext());
lazyJNDICtxRefresh = true; // touch JNDI namespace once.
} catch (NamingException e) {
e.printStackTrace();
throw new SyncFactoryException("SPI: NamingException: " + e.getExplanation());
} catch (Exception e) {
e.printStackTrace();
throw new SyncFactoryException("SPI: Exception: " + e.getMessage());
}
}
}
/** {@collect.stats}
* Internal switch indicating whether the JNDI namespace should be re-read.
*/
private static boolean lazyJNDICtxRefresh = false;
/** {@collect.stats}
* Parses the set JNDI Context and passes bindings to the enumerateBindings
* method when complete.
*/
private static Properties parseJNDIContext() throws NamingException {
NamingEnumeration bindings = ic.listBindings("");
Properties properties = new Properties();
// Hunt one level below context for available SyncProvider objects
enumerateBindings(bindings, properties);
return properties;
}
/** {@collect.stats}
* Scans each binding on JNDI context and determines if any binding is an
* instance of SyncProvider, if so, add this to the registry and continue to
* scan the current context using a re-entrant call to this method until all
* bindings have been enumerated.
*/
private static void enumerateBindings(NamingEnumeration bindings,
Properties properties) throws NamingException {
boolean syncProviderObj = false; // move to parameters ?
try {
Binding bd = null;
Object elementObj = null;
String element = null;
while (bindings.hasMore()) {
bd = (Binding)bindings.next();
element = bd.getName();
elementObj = bd.getObject();
if (!(ic.lookup(element) instanceof Context)) {
// skip directories/sub-contexts
if (ic.lookup(element) instanceof SyncProvider) {
syncProviderObj = true;
}
}
if (syncProviderObj) {
SyncProvider sync = (SyncProvider)elementObj;
properties.put(SyncFactory.ROWSET_SYNC_PROVIDER,
sync.getProviderID());
syncProviderObj = false; // reset
}
}
} catch (javax.naming.NotContextException e) {
bindings.next();
// Re-entrant call into method
enumerateBindings(bindings, properties);
}
}
}
/** {@collect.stats}
* Internal class that defines the lazy reference construct for each registered
* SyncProvider implementation.
*/
class ProviderImpl extends SyncProvider {
private String className = null;
private String vendorName = null;
private String ver = null;
private int index;
public void setClassname(String classname) {
className = classname;
}
public String getClassname() {
return className;
}
public void setVendor(String vendor) {
vendorName = vendor;
}
public String getVendor() {
return vendorName;
}
public void setVersion(String providerVer) {
ver = providerVer;
}
public String getVersion() {
return ver;
}
public void setIndex(int i) {
index = i;
}
public int getIndex() {
return index;
}
public int getDataSourceLock() throws SyncProviderException {
int dsLock = 0;
try
{
dsLock = SyncFactory.getInstance(className).getDataSourceLock();
} catch(SyncFactoryException sfEx) {
throw new SyncProviderException(sfEx.getMessage());
}
return dsLock;
}
public int getProviderGrade() {
int grade = 0;
try
{
grade = SyncFactory.getInstance(className).getProviderGrade();
} catch(SyncFactoryException sfEx) {
//
}
return grade;
}
public String getProviderID() {
return className;
}
/*
public javax.sql.RowSetInternal getRowSetInternal() {
try
{
return SyncFactory.getInstance(className).getRowSetInternal();
} catch(SyncFactoryException sfEx) {
//
}
}
*/
public javax.sql.RowSetReader getRowSetReader() {
RowSetReader rsReader = null;;
try
{
rsReader = SyncFactory.getInstance(className).getRowSetReader();
} catch(SyncFactoryException sfEx) {
//
}
return rsReader;
}
public javax.sql.RowSetWriter getRowSetWriter() {
RowSetWriter rsWriter = null;
try
{
rsWriter = SyncFactory.getInstance(className).getRowSetWriter();
} catch(SyncFactoryException sfEx) {
//
}
return rsWriter;
}
public void setDataSourceLock(int param)
throws SyncProviderException {
try
{
SyncFactory.getInstance(className).setDataSourceLock(param);
} catch(SyncFactoryException sfEx) {
throw new SyncProviderException(sfEx.getMessage());
}
}
public int supportsUpdatableView() {
int view = 0;
try
{
view = SyncFactory.getInstance(className).supportsUpdatableView();
} catch(SyncFactoryException sfEx) {
//
}
return view;
}
}
| 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 javax.sql.rowset.spi;
import java.sql.SQLException;
import java.io.Writer;
import javax.sql.RowSetWriter;
import javax.sql.rowset.*;
/** {@collect.stats}
* A specialized interface that facilitates an extension of the
* <code>SyncProvider</code> abstract class for XML orientated
* synchronization providers.
* <p>
* <code>SyncProvider</code> implementations that supply XML data writer
* capabilities such as output XML stream capabilities can implement this
* interface to provider standard <code>XmlWriter</code> objects to
* <code>WebRowSet</code> implementations.
* <P>
* Writing a <code>WebRowSet</code> object includes printing the
* rowset's data, metadata, and properties, all with the
* appropriate XML tags.
*/
public interface XmlWriter extends RowSetWriter {
/** {@collect.stats}
* Writes the given <code>WebRowSet</code> object to the specified
* <code>java.io.Writer</code> output stream as an XML document.
* This document includes the rowset's data, metadata, and properties
* plus the appropriate XML tags.
* <P>
* The <code>caller</code> parameter must be a <code>WebRowSet</code>
* object whose <code>XmlWriter</code> field contains a reference to
* this <code>XmlWriter</code> object.
*
* @param caller the <code>WebRowSet</code> instance to be written,
* for which this <code>XmlWriter</code> object is the writer
* @param writer the <code>java.io.Writer</code> object that serves
* as the output stream for writing <code>caller</code> as
* an XML document
* @throws SQLException if a database access error occurs or
* this <code>XmlWriter</code> object is not the writer
* for the given <code>WebRowSet</code> object
*/
public void writeXML(WebRowSet caller, java.io.Writer writer)
throws SQLException;
}
| Java |
/*
* Copyright (c) 2003, 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 javax.sql.rowset.spi;
import java.sql.SQLException;
/** {@collect.stats}
* Indicates an error with <code>SyncFactory</code> mechanism. A disconnected
* RowSet implementation cannot be used without a <code>SyncProvider</code>
* being successfully instantiated
*
* @author Jonathan Bruce
* @see javax.sql.rowset.spi.SyncFactory
* @see javax.sql.rowset.spi.SyncFactoryException
*/
public class SyncFactoryException extends java.sql.SQLException {
/** {@collect.stats}
* Creates new <code>SyncFactoryException</code> without detail message.
*/
public SyncFactoryException() {
}
/** {@collect.stats}
* Constructs an <code>SyncFactoryException</code> with the specified
* detail message.
*
* @param msg the detail message.
*/
public SyncFactoryException(String msg) {
super(msg);
}
static final long serialVersionUID = -4354595476433200352L;
}
| 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 javax.sql.rowset.spi;
import java.sql.SQLException;
import java.io.Reader;
import javax.sql.RowSetReader;
import javax.sql.rowset.*;
/** {@collect.stats}
* A specialized interface that facilitates an extension of the
* <code>SyncProvider</code> abstract class for XML orientated
* synchronization providers.
* <P>
* <code>SyncProvider</code> implementations that supply XML data reader
* capabilities such as output XML stream capabilities can implement this
* interface to provider standard <code>XmlReader</code> objects to
* <code>WebRowSet</code> implementations.
* <p>
* An <code>XmlReader</code> object is registered as the
* XML reader for a <code>WebRowSet</code> by being assigned to the
* rowset's <code>xmlReader</code> field. When the <code>WebRowSet</code>
* object's <code>readXml</code> method is invoked, it in turn invokes
* its XML reader's <code>readXML</code> method.
*/
public interface XmlReader extends RowSetReader {
/** {@collect.stats}
* Reads and parses the given <code>WebRowSet</code> object from the given
* input stream in XML format. The <code>xmlReader</code> field of the
* given <code>WebRowSet</code> object must contain this
* <code>XmlReader</code> object.
* <P>
* If a parsing error occurs, the exception that is thrown will
* include information about the location of the error in the
* original XML document.
*
* @param caller the <code>WebRowSet</code> object to be parsed, whose
* <code>xmlReader</code> field must contain a reference to
* this <code>XmlReader</code> object
* @param reader the <code>java.io.Reader</code> object from which
* <code>caller</code> will be read
* @throws SQLException if a database access error occurs or
* this <code>XmlReader</code> object is not the reader
* for the given rowset
*/
public void readXML(WebRowSet caller, java.io.Reader reader)
throws SQLException;
}
| 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 javax.sql.rowset.spi;
import java.sql.SQLException;
import javax.sql.rowset.*;
/** {@collect.stats}
* Indicates an error with the <code>SyncProvider</code> mechanism. This exception
* is created by a <code>SyncProvider</code> abstract class extension if it
* encounters violations in reading from or writing to the originating data source.
* <P>
* If it is implemented to do so, the <code>SyncProvider</code> object may also create a
* <code>SyncResolver</code> object and either initialize the <code>SyncProviderException</code>
* object with it at construction time or set it with the <code>SyncProvider</code> object at
* a later time.
* <P>
* The method <code>acceptChanges</code> will throw this exception after the writer
* has finished checking for conflicts and has found one or more conflicts. An
* application may catch a <code>SyncProviderException</code> object and call its
* <code>getSyncResolver</code> method to get its <code>SyncResolver</code> object.
* See the code fragment in the interface comment for
* <a href="SyncResolver.html"><code>SyncResolver</code></a> for an example.
* This <code>SyncResolver</code> object will mirror the <code>RowSet</code>
* object that generated the exception, except that it will contain only the values
* from the data source that are in conflict. All other values in the <code>SyncResolver</code>
* object will be <code>null</code>.
* <P>
* The <code>SyncResolver</code> object may be used to examine and resolve
* each conflict in a row and then go to the next row with a conflict to
* repeat the procedure.
* <P>
* A <code>SyncProviderException</code> object may or may not contain a description of the
* condition causing the exception. The inherited method <code>getMessage</code> may be
* called to retrieve the description if there is one.
*
* @author Jonathan Bruce
* @see javax.sql.rowset.spi.SyncFactory
* @see javax.sql.rowset.spi.SyncResolver
* @see javax.sql.rowset.spi.SyncFactoryException
*/
public class SyncProviderException extends java.sql.SQLException {
/** {@collect.stats}
* The instance of <code>javax.sql.rowset.spi.SyncResolver</code> that
* this <code>SyncProviderException</code> object will return when its
* <code>getSyncResolver</code> method is called.
*/
private SyncResolver syncResolver = null;
/** {@collect.stats}
* Creates a new <code>SyncProviderException</code> object without a detail message.
*/
public SyncProviderException() {
super();
}
/** {@collect.stats}
* Constructs a <code>SyncProviderException</code> object with the specified
* detail message.
*
* @param msg the detail message
*/
public SyncProviderException(String msg) {
super(msg);
}
/** {@collect.stats}
* Constructs a <code>SyncProviderException</code> object with the specified
* <code>SyncResolver</code> instance.
*
* @param syncResolver the <code>SyncResolver</code> instance used to
* to process the synchronization conflicts
* @throws IllegalArgumentException if the <code>SyncResolver</code> object
* is <code>null</code>.
*/
public SyncProviderException(SyncResolver syncResolver) {
if (syncResolver == null) {
throw new IllegalArgumentException("Cannot instantiate a SyncProviderException " +
"with a null SyncResolver object");
} else {
this.syncResolver = syncResolver;
}
}
/** {@collect.stats}
* Retrieves the <code>SyncResolver</code> object that has been set for
* this <code>SyncProviderException</code> object, or
* if none has been set, an instance of the default <code>SyncResolver</code>
* implementation included in the reference implementation.
* <P>
* If a <code>SyncProviderException</code> object is thrown, an application
* may use this method to generate a <code>SyncResolver</code> object
* with which to resolve the conflict or conflicts that caused the
* exception to be thrown.
*
* @return the <code>SyncResolver</code> object set for this
* <code>SyncProviderException</code> object or, if none has
* been set, an instance of the default <code>SyncResolver</code>
* implementation. In addition, the default <code>SyncResolver</code>
* implementation is also returned if the <code>SyncResolver()</code> or
* <code>SyncResolver(String)</code> constructors are used to instantiate
* the <code>SyncResolver</code> instance.
*/
public SyncResolver getSyncResolver() {
if (syncResolver != null) {
return syncResolver;
} else {
try {
syncResolver = new com.sun.rowset.internal.SyncResolverImpl();
} catch (SQLException sqle) {
}
return syncResolver;
}
}
/** {@collect.stats}
* Sets the <code>SyncResolver</code> object for this
* <code>SyncProviderException</code> object to the one supplied.
* If the argument supplied is <code>null</code>, a call to the method
* <code>getSyncResolver</code> will return the default reference
* implementation of the <code>SyncResolver</code> interface.
*
* @param syncResolver the <code>SyncResolver</code> object to be set;
* cannot be <code>null</code>
* @throws IllegalArgumentException if the <code>SyncResolver</code> object
* is <code>null</code>.
* @see #getSyncResolver
*/
public void setSyncResolver(SyncResolver syncResolver) {
if (syncResolver == null) {
throw new IllegalArgumentException("Cannot set a null SyncResolver " +
"object");
} else {
this.syncResolver = syncResolver;
}
}
static final long serialVersionUID = -939908523620640692L;
}
| Java |
/*
* Copyright (c) 2003, 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 javax.sql.rowset.spi;
import javax.sql.*;
/** {@collect.stats}
* The synchronization mechanism that provides reader/writer capabilities for
* disconnected <code>RowSet</code> objects.
* A <code>SyncProvider</code> implementation is a class that extends the
* <code>SyncProvider</code> abstract class.
* <P>
* A <code>SyncProvider</code> implementation is
* identified by a unique ID, which is its fully qualified class name.
* This name must be registered with the
* <code>SyncFactory</code> SPI, thus making the implementation available to
* all <code>RowSet</code> implementations.
* The factory mechanism in the reference implementation uses this name to instantiate
* the implementation, which can then provide a <code>RowSet</code> object with its
* reader (a <code>javax.sql.RowSetReader</code> object) and its writer (a
* <code>javax.sql.RowSetWriter</code> object).
* <P>
* The Jdbc <code>RowSet</code> Implementations specification provides two
* reference implementations of the <code>SyncProvider</code> abstract class:
* <code>RIOptimisticProvider</code> and <code>RIXMLProvider</code>.
* The <code>RIOptimisticProvider</code> can set any <code>RowSet</code>
* implementation with a <code>RowSetReader</code> object and a
* <code>RowSetWriter</code> object. However, only the <code>RIXMLProvider</code>
* implementation can set an <code>XmlReader</code> object and an
* <code>XmlWriter</code> object. A <code>WebRowSet</code> object uses the
* <code>XmlReader</code> object to read data in XML format to populate itself with that
* data. It uses the <code>XmlWriter</code> object to write itself to a stream or
* <code>java.io.Writer</code> object in XML format.
* <P>
* <h3>1.0 Naming Convention for Implementations</h3>
* As a guide to naming <code>SyncProvider</code>
* implementations, the following should be noted:
* <UL>
* <li>The name for a <code>SyncProvider</code> implementation
* is its fully qualified class name.
* <li>It is recommended that vendors supply a
* <code>SyncProvider</code> implementation in a package named <code>providers</code>.
* </UL>
* <p>
* For instance, if a vendor named Fred, Inc. offered a
* <code>SyncProvider</code> implementation, you could have the following:
* <PRE>
* Vendor name: Fred, Inc.
* Domain name of vendor: com.fred
* Package name: com.fred.providers
* SyncProvider implementation class name: HighAvailabilityProvider
*
* Fully qualified class name of SyncProvider implementation:
* com.fred.providers.HighAvailabilityProvider
* </PRE>
* <P>
* The following line of code uses the fully qualified name to register
* this implementation with the <code>SyncFactory</code> static instance.
* <PRE>
* SyncFactory.registerProvider(
* "com.fred.providers.HighAvailabilityProvider");
* </PRE>
* <P>
* The default <code>SyncProvider</code> object provided with the reference
* implementation uses the following name:
* <pre>
* com.sun.rowset.providers.RIOptimisticProvider
* </pre>
* <p>
* A vendor can register a <code>SyncProvider</code> implementation class name
* with Sun Microsystems, Inc. by sending email to jdbc@sun.com.
* Sun will maintain a database listing the
* available <code>SyncProvider</code> implementations for use with compliant
* <code>RowSet</code> implementations. This database will be similar to the
* one already maintained to list available JDBC drivers.
* <P>
* Vendors should refer to the reference implementation synchronization
* providers for additional guidance on how to implement a new
* <code>SyncProvider</code> implementation.
*
* <h3>2.0 How a <code>RowSet</code> Object Gets Its Provider</h3>
*
* A disconnected <code>Rowset</code> object may get access to a
* <code>SyncProvider</code> object in one of the following two ways:
* <UL>
* <LI>Using a constructor<BR>
* <PRE>
* CachedRowSet crs = new CachedRowSet(
* "com.fred.providers.HighAvailabilitySyncProvider");
* </PRE>
* <LI>Using the <code>setSyncProvider</code> method
* <PRE>
* CachedRowSet crs = new CachedRowSet();
* crs.setSyncProvider("com.fred.providers.HighAvailabilitySyncProvider");
* </PRE>
* </UL>
* <p>
* By default, the reference implementations of the <code>RowSet</code> synchronization
* providers are always available to the Java platform.
* If no other pluggable synchronization providers have been correctly
* registered, the <code>SyncFactory</code> will automatically generate
* an instance of the default <code>SyncProvider</code> reference implementation.
* Thus, in the preceding code fragment, if no implementation named
* <code>com.fred.providers.HighAvailabilitySyncProvider</code> has been
* registered with the <code>SyncFactory</code> instance, <i>crs</i> will be
* assigned the default provider in the reference implementation, which is
* <code>com.sun.rowset.providers.RIOptimisticProvider</code>.
* <p>
* <h3>3.0 Violations and Synchronization Issues</h3>
* If an update between a disconnected <code>RowSet</code> object
* and a data source violates
* the original query or the underlying data source constraints, this will
* result in undefined behavior for all disconnected <code>RowSet</code> implementations
* and their designated <code>SyncProvider</code> implementations.
* Not defining the behavior when such violations occur offers greater flexibility
* for a <code>SyncProvider</code>
* implementation to determine its own best course of action.
* <p>
* A <code>SyncProvider</code> implementation
* may choose to implement a specific handler to
* handle a subset of query violations.
* However if an original query violation or a more general data source constraint
* violation is not handled by the <code>SyncProvider</code> implementation,
* all <code>SyncProvider</code>
* objects must throw a <code>SyncProviderException</code>.
* <p>
* <h3>4.0 Updatable SQL VIEWs</h3>
* It is possible for any disconnected or connected <code>RowSet</code> object to be populated
* from an SQL query that is formulated originally from an SQL <code>VIEW</code>.
* While in many cases it is possible for an update to be performed to an
* underlying view, such an update requires additional metadata, which may vary.
* The <code>SyncProvider</code> class provides two constants to indicate whether
* an implementation supports updating an SQL <code>VIEW</code>.
* <ul>
* <li><code><b>NONUPDATABLE_VIEW_SYNC</b></code> - Indicates that a <code>SyncProvider</code>
* implementation does not support synchronization with an SQL <code>VIEW</code> as the
* underlying source of data for the <code>RowSet</code> object.
* <li><code><b>UPDATABLE_VIEW_SYNC</b></code> - Indicates that a
* <code>SyncProvider</code> implementation
* supports synchronization with an SQL <code>VIEW</code> as the underlying source
* of data.
* </ul>
* <P>
* The default is for a <code>RowSet</code> object not to be updatable if it was
* populated with data from an SQL <code>VIEW</code>.
* <P>
* <h3>5.0 <code>SyncProvider</code> Constants</h3>
* The <code>SyncProvider</code> class provides three sets of constants that
* are used as return values or parameters for <code>SyncProvider</code> methods.
* <code>SyncProvider</code> objects may be implemented to perform synchronization
* between a <code>RowSet</code> object and its underlying data source with varying
* degrees of of care. The first group of constants indicate how synchronization
* is handled. For example, <code>GRADE_NONE</code> indicates that a
* <code>SyncProvider</code> object will not take any care to see what data is
* valid and will simply write the <code>RowSet</code> data to the data source.
* <code>GRADE_MODIFIED_AT_COMMIT</code> indicates that the provider will check
* only modified data for validity. Other grades check all data for validity
* or set locks when data is modified or loaded.
* <OL>
* <LI>Constants to indicate the synchronization grade of a
* <code>SyncProvider</code> object
* <UL>
* <LI>SyncProvider.GRADE_NONE
* <LI>SyncProvider.GRADE_MODIFIED_AT_COMMIT
* <LI>SyncProvider.GRADE_CHECK_ALL_AT_COMMIT
* <LI>SyncProvider.GRADE_LOCK_WHEN_MODIFIED
* <LI>SyncProvider.GRADE_LOCK_WHEN_LOADED
* </UL>
* <LI>Constants to indicate what locks are set on the data source
* <UL>
* <LI>SyncProvider.DATASOURCE_NO_LOCK
* <LI>SyncProvider.DATASOURCE_ROW_LOCK
* <LI>SyncProvider.DATASOURCE_TABLE_LOCK
* <LI>SyncProvider.DATASOURCE_DB_LOCK
* </UL>
* <LI>Constants to indicate whether a <code>SyncProvider</code> object can
* perform updates to an SQL <code>VIEW</code> <BR>
* These constants are explained in the preceding section (4.0).
* <UL>
* <LI>SyncProvider.UPDATABLE_VIEW_SYNC
* <LI>SyncProvider.NONUPDATABLE_VIEW_SYNC
* </UL>
* </OL>
*
* @author Jonathan Bruce
* @see javax.sql.rowset.spi.SyncFactory
* @see javax.sql.rowset.spi.SyncFactoryException
*/
public abstract class SyncProvider {
/** {@collect.stats}
* Creates a default <code>SyncProvider</code> object.
*/
public SyncProvider() {
}
/** {@collect.stats}
* Returns the unique identifier for this <code>SyncProvider</code> object.
*
* @return a <code>String</code> object with the fully qualified class name of
* this <code>SyncProvider</code> object
*/
public abstract String getProviderID();
/** {@collect.stats}
* Returns a <code>javax.sql.RowSetReader</code> object, which can be used to
* populate a <code>RowSet</code> object with data.
*
* @return a <code>javax.sql.RowSetReader</code> object
*/
public abstract RowSetReader getRowSetReader();
/** {@collect.stats}
* Returns a <code>javax.sql.RowSetWriter</code> object, which can be
* used to write a <code>RowSet</code> object's data back to the
* underlying data source.
*
* @return a <code>javax.sql.RowSetWriter</code> object
*/
public abstract RowSetWriter getRowSetWriter();
/** {@collect.stats}
* Returns a constant indicating the
* grade of synchronization a <code>RowSet</code> object can expect from
* this <code>SyncProvider</code> object.
*
* @return an int that is one of the following constants:
* SyncProvider.GRADE_NONE,
* SyncProvider.GRADE_CHECK_MODIFIED_AT_COMMIT,
* SyncProvider.GRADE_CHECK_ALL_AT_COMMIT,
* SyncProvider.GRADE_LOCK_WHEN_MODIFIED,
* SyncProvider.GRADE_LOCK_WHEN_LOADED
*/
public abstract int getProviderGrade();
/** {@collect.stats}
* Sets a lock on the underlying data source at the level indicated by
* <i>datasource_lock</i>. This should cause the
* <code>SyncProvider</code> to adjust its behavior by increasing or
* decreasing the level of optimism it provides for a successful
* synchronization.
*
* @param datasource_lock one of the following constants indicating the severity
* level of data source lock required:
* <pre>
* SyncProvider.DATASOURCE_NO_LOCK,
* SyncProvider.DATASOURCE_ROW_LOCK,
* SyncProvider.DATASOURCE_TABLE_LOCK,
* SyncProvider.DATASOURCE_DB_LOCK,
* </pre>
* @throws SyncProviderException if an unsupported data source locking level
* is set.
* @see #getDataSourceLock
*/
public abstract void setDataSourceLock(int datasource_lock)
throws SyncProviderException;
/** {@collect.stats}
* Returns the current data source lock severity level active in this
* <code>SyncProvider</code> implementation.
*
* @return a constant indicating the current level of data source lock
* active in this <code>SyncProvider</code> object;
* one of the following:
* <pre>
* SyncProvider.DATASOURCE_NO_LOCK,
* SyncProvider.DATASOURCE_ROW_LOCK,
* SyncProvider.DATASOURCE_TABLE_LOCK,
* SyncProvider.DATASOURCE_DB_LOCK
* </pre>
* @throws SyncProviderExceptiom if an error occurs determining the data
* source locking level.
* @see #setDataSourceLock
*/
public abstract int getDataSourceLock()
throws SyncProviderException;
/** {@collect.stats}
* Returns whether this <code>SyncProvider</code> implementation
* can perform synchronization between a <code>RowSet</code> object
* and the SQL <code>VIEW</code> in the data source from which
* the <code>RowSet</code> object got its data.
*
* @return an <code>int</code> saying whether this <code>SyncProvider</code>
* object supports updating an SQL <code>VIEW</code>; one of the
* following:
* SyncProvider.UPDATABLE_VIEW_SYNC,
* SyncProvider.NONUPDATABLE_VIEW_SYNC
*/
public abstract int supportsUpdatableView();
/** {@collect.stats}
* Returns the release version of this <code>SyncProvider</code> instance.
*
* @return a <code>String</code> detailing the release version of the
* <code>SyncProvider</code> implementation
*/
public abstract String getVersion();
/** {@collect.stats}
* Returns the vendor name of this <code>SyncProvider</code> instance
*
* @return a <code>String</code> detailing the vendor name of this
* <code>SyncProvider</code> implementation
*/
public abstract String getVendor();
/*
* Standard description of synchronization grades that a SyncProvider
* could provide.
*/
/** {@collect.stats}
* Indicates that no synchronization with the originating data source is
* provided. A <code>SyncProvider</code>
* implementation returning this grade will simply attempt to write
* updates in the <code>RowSet</code> object to the underlying data
* source without checking the validity of any data.
*
*/
public static int GRADE_NONE = 1;
/** {@collect.stats}
* Indicates a low level optimistic synchronization grade with
* respect to the originating data source.
*
* A <code>SyncProvider</code> implementation
* returning this grade will check only rows that have changed.
*
*/
public static int GRADE_CHECK_MODIFIED_AT_COMMIT = 2;
/** {@collect.stats}
* Indicates a high level optimistic synchronization grade with
* respect to the originating data source.
*
* A <code>SyncProvider</code> implementation
* returning this grade will check all rows, including rows that have not
* changed.
*/
public static int GRADE_CHECK_ALL_AT_COMMIT = 3;
/** {@collect.stats}
* Indicates a pessimistic synchronization grade with
* respect to the originating data source.
*
* A <code>SyncProvider</code>
* implementation returning this grade will lock the row in the originating
* data source.
*/
public static int GRADE_LOCK_WHEN_MODIFIED = 4;
/** {@collect.stats}
* Indicates the most pessimistic synchronization grade with
* respect to the originating
* data source. A <code>SyncProvider</code>
* implementation returning this grade will lock the entire view and/or
* table affected by the original statement used to populate a
* <code>RowSet</code> object.
*/
public static int GRADE_LOCK_WHEN_LOADED = 5;
/** {@collect.stats}
* Indicates that no locks remain on the originating data source. This is the default
* lock setting for all <code>SyncProvider</code> implementations unless
* otherwise directed by a <code>RowSet</code> object.
*/
public static int DATASOURCE_NO_LOCK = 1;
/** {@collect.stats}
* Indicates that a lock is placed on the rows that are touched by the original
* SQL statement used to populate the <code>RowSet</code> object
* that is using this <code>SyncProvider</code> object.
*/
public static int DATASOURCE_ROW_LOCK = 2;
/** {@collect.stats}
* Indicates that a lock is placed on all tables that are touched by the original
* SQL statement used to populate the <code>RowSet</code> object
* that is using this <code>SyncProvider</code> object.
*/
public static int DATASOURCE_TABLE_LOCK = 3;
/** {@collect.stats}
* Indicates that a lock is placed on the entire data source that is the source of
* data for the <code>RowSet</code> object
* that is using this <code>SyncProvider</code> object.
*/
public static int DATASOURCE_DB_LOCK = 4;
/** {@collect.stats}
* Indicates that a <code>SyncProvider</code> implementation
* supports synchronization between a <code>RowSet</code> object and
* the SQL <code>VIEW</code> used to populate it.
*/
public static int UPDATABLE_VIEW_SYNC = 5;
/** {@collect.stats}
* Indicates that a <code>SyncProvider</code> implementation
* does <B>not</B> support synchronization between a <code>RowSet</code>
* object and the SQL <code>VIEW</code> used to populate it.
*/
public static int NONUPDATABLE_VIEW_SYNC = 6;
}
| 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 javax.sql.rowset;
import java.sql.*;
import javax.sql.*;
import java.io.*;
import java.lang.reflect.*;
/** {@collect.stats}
* Provides implementations for the methods that set and get
* metadata information about a <code>RowSet</code> object's columns.
* A <code>RowSetMetaDataImpl</code> object keeps track of the
* number of columns in the rowset and maintains an internal array
* of column attributes for each column.
* <P>
* A <code>RowSet</code> object creates a <code>RowSetMetaDataImpl</code>
* object internally in order to set and retrieve information about
* its columns.
* <P>
* NOTE: All metadata in a <code>RowSetMetaDataImpl</code> object
* should be considered as unavailable until the <code>RowSet</code> object
* that it describes is populated.
* Therefore, any <code>RowSetMetaDataImpl</code> method that retrieves information
* is defined as having unspecified behavior when it is called
* before the <code>RowSet</code> object contains data.
*/
public class RowSetMetaDataImpl implements RowSetMetaData, Serializable {
/** {@collect.stats}
* The number of columns in the <code>RowSet</code> object that created
* this <code>RowSetMetaDataImpl</code> object.
* @serial
*/
private int colCount;
/** {@collect.stats}
* An array of <code>ColInfo</code> objects used to store information
* about each column in the <code>RowSet</code> object for which
* this <code>RowSetMetaDataImpl</code> object was created. The first
* <code>ColInfo</code> object in this array contains information about
* the first column in the <code>RowSet</code> object, the second element
* contains information about the second column, and so on.
* @serial
*/
private ColInfo[] colInfo;
/** {@collect.stats}
* Checks to see that the designated column is a valid column number for
* the <code>RowSet</code> object for which this <code>RowSetMetaDataImpl</code>
* was created. To be valid, a column number must be greater than
* <code>0</code> and less than or equal to the number of columns in a row.
* @throws <code>SQLException</code> with the message "Invalid column index"
* if the given column number is out of the range of valid column
* numbers for the <code>RowSet</code> object
*/
private void checkColRange(int col) throws SQLException {
if (col <= 0 || col > colCount) {
throw new SQLException("Invalid column index :"+col);
}
}
/** {@collect.stats}
* Checks to see that the given SQL type is a valid column type and throws an
* <code>SQLException</code> object if it is not.
* To be valid, a SQL type must be one of the constant values
* in the <code><a href="../../sql/Types.html">java.sql.Types</a></code>
* class.
*
* @param SQLType an <code>int</code> defined in the class <code>java.sql.Types</code>
* @throws SQLException if the given <code>int</code> is not a constant defined in the
* class <code>java.sql.Types</code>
*/
private void checkColType(int SQLType) throws SQLException {
try {
Class c = java.sql.Types.class;
Field[] publicFields = c.getFields();
int fieldValue = 0;
for (int i = 0; i < publicFields.length; i++) {
fieldValue = publicFields[i].getInt(c);
if (fieldValue == SQLType) {
return;
}
}
} catch (Exception e) {
throw new SQLException(e.getMessage());
}
throw new SQLException("Invalid SQL type for column");
}
/** {@collect.stats}
* Sets to the given number the number of columns in the <code>RowSet</code>
* object for which this <code>RowSetMetaDataImpl</code> object was created.
*
* @param columnCount an <code>int</code> giving the number of columns in the
* <code>RowSet</code> object
* @throws SQLException if the given number is equal to or less than zero
*/
public void setColumnCount(int columnCount) throws SQLException {
if (columnCount <= 0) {
throw new SQLException("Invalid column count. Cannot be less " +
"or equal to zero");
}
colCount = columnCount;
// If the colCount is Integer.MAX_VALUE,
// we do not initialize the colInfo object.
// even if we try to initialize the colCount with
// colCount = Integer.MAx_VALUE-1, the colInfo
// initialization fails throwing an ERROR
// OutOfMemory Exception. So we do not initialize
// colInfo at Integer.MAX_VALUE. This is to pass TCK.
if(!(colCount == Integer.MAX_VALUE)) {
colInfo = new ColInfo[colCount + 1];
for (int i=1; i <= colCount; i++) {
colInfo[i] = new ColInfo();
}
}
}
/** {@collect.stats}
* Sets whether the designated column is automatically
* numbered, thus read-only, to the given <code>boolean</code>
* value.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns
* in the rowset, inclusive
* @param property <code>true</code> if the given column is
* automatically incremented; <code>false</code>
* otherwise
* @throws <code>SQLException</code> if a database access error occurs or
* the given index is out of bounds
*/
public void setAutoIncrement(int columnIndex, boolean property) throws SQLException {
checkColRange(columnIndex);
colInfo[columnIndex].autoIncrement = property;
}
/** {@collect.stats}
* Sets whether the name of the designated column is case sensitive to
* the given <code>boolean</code>.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns
* in the rowset, inclusive
* @param property <code>true</code> to indicate that the column
* name is case sensitive; <code>false</code> otherwise
* @throws SQLException if a database access error occurs or
* the given column number is out of bounds
*/
public void setCaseSensitive(int columnIndex, boolean property) throws SQLException {
checkColRange(columnIndex);
colInfo[columnIndex].caseSensitive = property;
}
/** {@collect.stats}
* Sets whether a value stored in the designated column can be used
* in a <code>WHERE</code> clause to the given <code>boolean</code> value.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number
* of columns in the rowset, inclusive
* @param property <code>true</code> to indicate that a column
* value can be used in a <code>WHERE</code> clause;
* <code>false</code> otherwise
*
* @throws <code>SQLException</code> if a database access error occurs or
* the given column number is out of bounds
*/
public void setSearchable(int columnIndex, boolean property)
throws SQLException {
checkColRange(columnIndex);
colInfo[columnIndex].searchable = property;
}
/** {@collect.stats}
* Sets whether a value stored in the designated column is a cash
* value to the given <code>boolean</code>.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns,
* inclusive between <code>1</code> and the number of columns, inclusive
* @param property true if the value is a cash value; false otherwise.
* @throws <code>SQLException</code> if a database access error occurs
* or the given column number is out of bounds
*/
public void setCurrency(int columnIndex, boolean property)
throws SQLException {
checkColRange(columnIndex);
colInfo[columnIndex].currency = property;
}
/** {@collect.stats}
* Sets whether a value stored in the designated column can be set
* to <code>NULL</code> to the given constant from the interface
* <code>ResultSetMetaData</code>.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @param property one of the following <code>ResultSetMetaData</code> constants:
* <code>columnNoNulls</code>,
* <code>columnNullable</code>, or
* <code>columnNullableUnknown</code>
*
* @throws <code>SQLException</code> if a database access error occurs,
* the given column number is out of bounds, or the value supplied
* for the <i>property</i> parameter is not one of the following
* constants:
* <code>ResultSetMetaData.columnNoNulls</code>,
* <code>ResultSetMetaData.columnNullable</code>, or
* <code>ResultSetMetaData.columnNullableUnknown</code>
*/
public void setNullable(int columnIndex, int property) throws SQLException {
if ((property < ResultSetMetaData.columnNoNulls) ||
property > ResultSetMetaData.columnNullableUnknown) {
throw new SQLException("Invalid nullable constant set. Must be " +
"either columnNoNulls, columnNullable or columnNullableUnknown");
}
checkColRange(columnIndex);
colInfo[columnIndex].nullable = property;
}
/** {@collect.stats}
* Sets whether a value stored in the designated column is a signed
* number to the given <code>boolean</code>.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @param property <code>true</code> to indicate that a column
* value is a signed number;
* <code>false</code> to indicate that it is not
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public void setSigned(int columnIndex, boolean property) throws SQLException {
checkColRange(columnIndex);
colInfo[columnIndex].signed = property;
}
/** {@collect.stats}
* Sets the normal maximum number of chars in the designated column
* to the given number.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @param size the maximum size of the column in chars; must be
* <code>0</code> or more
* @throws SQLException if a database access error occurs,
* the given column number is out of bounds, or <i>size</i> is
* less than <code>0</code>
*/
public void setColumnDisplaySize(int columnIndex, int size) throws SQLException {
if (size < 0) {
throw new SQLException("Invalid column display size. Cannot be less " +
"than zero");
}
checkColRange(columnIndex);
colInfo[columnIndex].columnDisplaySize = size;
}
/** {@collect.stats}
* Sets the suggested column label for use in printouts and
* displays, if any, to <i>label</i>. If <i>label</i> is
* <code>null</code>, the column label is set to an empty string
* ("").
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @param label the column label to be used in printouts and displays; if the
* column label is <code>null</code>, an empty <code>String</code> is
* set
* @throws SQLException if a database access error occurs
* or the given column index is out of bounds
*/
public void setColumnLabel(int columnIndex, String label) throws SQLException {
checkColRange(columnIndex);
if (label != null) {
colInfo[columnIndex].columnLabel = new String(label);
} else {
colInfo[columnIndex].columnLabel = new String("");
}
}
/** {@collect.stats}
* Sets the column name of the designated column to the given name.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @param columnName a <code>String</code> object indicating the column name;
* if the given name is <code>null</code>, an empty <code>String</code>
* is set
* @throws SQLException if a database access error occurs or the given column
* index is out of bounds
*/
public void setColumnName(int columnIndex, String columnName) throws SQLException {
checkColRange(columnIndex);
if (columnName != null) {
colInfo[columnIndex].columnName = new String(columnName);
} else {
colInfo[columnIndex].columnName = new String("");
}
}
/** {@collect.stats}
* Sets the designated column's table's schema name, if any, to
* <i>schemaName</i>. If <i>schemaName</i> is <code>null</code>,
* the schema name is set to an empty string ("").
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @param schemaName the schema name for the table from which a value in the
* designated column was derived; may be an empty <code>String</code>
* or <code>null</code>
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public void setSchemaName(int columnIndex, String schemaName) throws SQLException {
checkColRange(columnIndex);
if (schemaName != null ) {
colInfo[columnIndex].schemaName = new String(schemaName);
} else {
colInfo[columnIndex].schemaName = new String("");
}
}
/** {@collect.stats}
* Sets the total number of decimal digits in a value stored in the
* designated column to the given number.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @param precision the total number of decimal digits; must be <code>0</code>
* or more
* @throws SQLException if a database access error occurs,
* <i>columnIndex</i> is out of bounds, or <i>precision</i>
* is less than <code>0</code>
*/
public void setPrecision(int columnIndex, int precision) throws SQLException {
if (precision < 0) {
throw new SQLException("Invalid precision value. Cannot be less " +
"than zero");
}
checkColRange(columnIndex);
colInfo[columnIndex].colPrecision = precision;
}
/** {@collect.stats}
* Sets the number of digits to the right of the decimal point in a value
* stored in the designated column to the given number.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @param scale the number of digits to the right of the decimal point; must be
* zero or greater
* @throws SQLException if a database access error occurs,
* <i>columnIndex</i> is out of bounds, or <i>scale</i>
* is less than <code>0</code>
*/
public void setScale(int columnIndex, int scale) throws SQLException {
if (scale < 0) {
throw new SQLException("Invalid scale size. Cannot be less " +
"than zero");
}
checkColRange(columnIndex);
colInfo[columnIndex].colScale = scale;
}
/** {@collect.stats}
* Sets the name of the table from which the designated column
* was derived to the given table name.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @param tableName the column's table name; may be <code>null</code> or an
* empty string
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public void setTableName(int columnIndex, String tableName) throws SQLException {
checkColRange(columnIndex);
if (tableName != null) {
colInfo[columnIndex].tableName = new String(tableName);
} else {
colInfo[columnIndex].tableName = new String("");
}
}
/** {@collect.stats}
* Sets the catalog name of the table from which the designated
* column was derived to <i>catalogName</i>. If <i>catalogName</i>
* is <code>null</code>, the catalog name is set to an empty string.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @param catalogName the column's table's catalog name; if the catalogName
* is <code>null</code>, an empty <code>String</code> is set
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public void setCatalogName(int columnIndex, String catalogName) throws SQLException {
checkColRange(columnIndex);
if (catalogName != null)
colInfo[columnIndex].catName = new String(catalogName);
else
colInfo[columnIndex].catName = new String("");
}
/** {@collect.stats}
* Sets the SQL type code for values stored in the designated column
* to the given type code from the class <code>java.sql.Types</code>.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @param SQLType the designated column's SQL type, which must be one of the
* constants in the class <code>java.sql.Types</code>
* @throws SQLException if a database access error occurs,
* the given column number is out of bounds, or the column type
* specified is not one of the constants in
* <code>java.sql.Types</code>
* @see java.sql.Types
*/
public void setColumnType(int columnIndex, int SQLType) throws SQLException {
// examine java.sql.Type reflectively, loop on the fields and check
// this. Separate out into a private method
checkColType(SQLType);
checkColRange(columnIndex);
colInfo[columnIndex].colType = SQLType;
}
/** {@collect.stats}
* Sets the type name used by the data source for values stored in the
* designated column to the given type name.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @param typeName the data source-specific type name; if <i>typeName</i> is
* <code>null</code>, an empty <code>String</code> is set
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public void setColumnTypeName(int columnIndex, String typeName)
throws SQLException {
checkColRange(columnIndex);
if (typeName != null) {
colInfo[columnIndex].colTypeName = new String(typeName);
} else {
colInfo[columnIndex].colTypeName = new String("");
}
}
/** {@collect.stats}
* Retrieves the number of columns in the <code>RowSet</code> object
* for which this <code>RowSetMetaDataImpl</code> object was created.
*
* @return the number of columns
* @throws SQLException if an error occurs determining the column count
*/
public int getColumnCount() throws SQLException {
return colCount;
}
/** {@collect.stats}
* Retrieves whether a value stored in the designated column is
* automatically numbered, and thus readonly.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return <code>true</code> if the column is automatically numbered;
* <code>false</code> otherwise
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public boolean isAutoIncrement(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].autoIncrement;
}
/** {@collect.stats}
* Indicates whether the case of the designated column's name
* matters.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return <code>true</code> if the column name is case sensitive;
* <code>false</code> otherwise
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public boolean isCaseSensitive(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].caseSensitive;
}
/** {@collect.stats}
* Indicates whether a value stored in the designated column
* can be used in a <code>WHERE</code> clause.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return <code>true</code> if a value in the designated column can be used in a
* <code>WHERE</code> clause; <code>false</code> otherwise
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public boolean isSearchable(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].searchable;
}
/** {@collect.stats}
* Indicates whether a value stored in the designated column
* is a cash value.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return <code>true</code> if a value in the designated column is a cash value;
* <code>false</code> otherwise
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public boolean isCurrency(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].currency;
}
/** {@collect.stats}
* Retrieves a constant indicating whether it is possible
* to store a <code>NULL</code> value in the designated column.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return a constant from the <code>ResultSetMetaData</code> interface;
* either <code>columnNoNulls</code>,
* <code>columnNullable</code>, or
* <code>columnNullableUnknown</code>
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public int isNullable(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].nullable;
}
/** {@collect.stats}
* Indicates whether a value stored in the designated column is
* a signed number.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return <code>true</code> if if a value in the designated column is a signed
* number; <code>false</code> otherwise
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public boolean isSigned(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].signed;
}
/** {@collect.stats}
* Retrieves the normal maximum width in chars of the designated column.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return the maximum number of chars that can be displayed in the designated
* column
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public int getColumnDisplaySize(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].columnDisplaySize;
}
/** {@collect.stats}
* Retrieves the the suggested column title for the designated
* column for use in printouts and displays.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return the suggested column name to use in printouts and displays
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public String getColumnLabel(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].columnLabel;
}
/** {@collect.stats}
* Retrieves the name of the designated column.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return the column name of the designated column
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public String getColumnName(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].columnName;
}
/** {@collect.stats}
* Retrieves the schema name of the table from which the value
* in the designated column was derived.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns,
* inclusive
* @return the schema name or an empty <code>String</code> if no schema
* name is available
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public String getSchemaName(int columnIndex) throws SQLException {
checkColRange(columnIndex);
String str ="";
if(colInfo[columnIndex].schemaName == null){
} else {
str = colInfo[columnIndex].schemaName;
}
return str;
}
/** {@collect.stats}
* Retrieves the total number of digits for values stored in
* the designated column.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return the precision for values stored in the designated column
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public int getPrecision(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].colPrecision;
}
/** {@collect.stats}
* Retrieves the number of digits to the right of the decimal point
* for values stored in the designated column.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return the scale for values stored in the designated column
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public int getScale(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].colScale;
}
/** {@collect.stats}
* Retrieves the name of the table from which the value
* in the designated column was derived.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return the table name or an empty <code>String</code> if no table name
* is available
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public String getTableName(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].tableName;
}
/** {@collect.stats}
* Retrieves the catalog name of the table from which the value
* in the designated column was derived.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return the catalog name of the column's table or an empty
* <code>String</code> if no catalog name is available
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public String getCatalogName(int columnIndex) throws SQLException {
checkColRange(columnIndex);
String str ="";
if(colInfo[columnIndex].catName == null){
} else {
str = colInfo[columnIndex].catName;
}
return str;
}
/** {@collect.stats}
* Retrieves the type code (one of the <code>java.sql.Types</code>
* constants) for the SQL type of the value stored in the
* designated column.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return an <code>int</code> representing the SQL type of values
* stored in the designated column
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
* @see java.sql.Types
*/
public int getColumnType(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].colType;
}
/** {@collect.stats}
* Retrieves the DBMS-specific type name for values stored in the
* designated column.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return the type name used by the data source
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public String getColumnTypeName(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].colTypeName;
}
/** {@collect.stats}
* Indicates whether the designated column is definitely
* not writable, thus readonly.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return <code>true</code> if this <code>RowSet</code> object is read-Only
* and thus not updatable; <code>false</code> otherwise
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public boolean isReadOnly(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].readOnly;
}
/** {@collect.stats}
* Indicates whether it is possible for a write operation on
* the designated column to succeed. A return value of
* <code>true</code> means that a write operation may or may
* not succeed.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return <code>true</code> if a write operation on the designated column may
* will succeed; <code>false</code> otherwise
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public boolean isWritable(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return colInfo[columnIndex].writable;
}
/** {@collect.stats}
* Indicates whether a write operation on the designated column
* will definitely succeed.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return <code>true</code> if a write operation on the designated column will
* definitely succeed; <code>false</code> otherwise
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public boolean isDefinitelyWritable(int columnIndex)
throws SQLException { return true;}
/** {@collect.stats}
* Retrieves the fully-qualified name of the class in the Java
* programming language to which a value in the designated column
* will be mapped. For example, if the value is an <code>int</code>,
* the class name returned by this method will be
* <code>java.lang.Integer</code>.
* <P>
* If the value in the designated column has a custom mapping,
* this method returns the name of the class that implements
* <code>SQLData</code>. When the method <code>ResultSet.getObject</code>
* is called to retrieve a value from the designated column, it will
* create an instance of this class or one of its subclasses.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return the fully-qualified name of the class in the Java programming
* language that would be used by the method <code>RowSet.getObject</code> to
* retrieve the value in the specified column. This is the class
* name used for custom mapping when there is a custom mapping.
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public String getColumnClassName(int columnIndex) throws SQLException {
String className = (new String()).getClass().getName();
int sqlType = getColumnType(columnIndex);
switch (sqlType) {
case Types.NUMERIC:
case Types.DECIMAL:
className = (new java.math.BigDecimal(0)).getClass().getName ();
break;
case Types.BIT:
className = (new Boolean(false)).getClass().getName ();
break;
case Types.TINYINT:
className = (new Byte("0")).getClass().getName ();
break;
case Types.SMALLINT:
className = (new Short("0")).getClass().getName ();
break;
case Types.INTEGER:
className = (new Integer(0)).getClass().getName ();
break;
case Types.BIGINT:
className = (new Long(0)).getClass().getName ();
break;
case Types.REAL:
className = (new Float(0)).getClass().getName ();
break;
case Types.FLOAT:
case Types.DOUBLE:
className = (new Double(0)).getClass().getName();
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
byte[] b = {};
className = (b.getClass()).getName();
break;
case Types.DATE:
className = (new java.sql.Date(123456)).getClass().getName ();
break;
case Types.TIME:
className = (new java.sql.Time(123456)).getClass().getName ();
break;
case Types.TIMESTAMP:
className = (new java.sql.Timestamp(123456)).getClass().getName ();
break;
case Types.BLOB:
byte[] blob = {};
className = (blob.getClass()).getName();
break;
case Types.CLOB:
char[] c = {};
className = (c.getClass()).getName();
break;
}
return className;
}
/** {@collect.stats}
* Returns an object that implements the given interface to allow access to non-standard methods,
* or standard methods not exposed by the proxy.
* The result may be either the object found to implement the interface or a proxy for that object.
* If the receiver implements the interface then that is the object. If the receiver is a wrapper
* and the wrapped object implements the interface then that is the object. Otherwise the object is
* the result of calling <code>unwrap</code> recursively on the wrapped object. If the receiver is not a
* wrapper and does not implement the interface, then an <code>SQLException</code> is thrown.
*
* @param iface A Class defining an interface that the result must implement.
* @return an object that implements the interface. May be a proxy for the actual implementing object.
* @throws java.sql.SQLException If no object found that implements the interface
* @since 1.6
*/
public <T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException {
return (T)this;
}
/** {@collect.stats}
* Returns true if this either implements the interface argument or is directly or indirectly a wrapper
* for an object that does. Returns false otherwise. If this implements the interface then return true,
* else if this is a wrapper then return the result of recursively calling <code>isWrapperFor</code> on the wrapped
* object. If this does not implement the interface and is not a wrapper, return false.
* This method should be implemented as a low-cost operation compared to <code>unwrap</code> so that
* callers can use this method to avoid expensive <code>unwrap</code> calls that may fail. If this method
* returns true then calling <code>unwrap</code> with the same argument should succeed.
*
* @param interfaces a Class defining an interface.
* @return true if this implements the interface or directly or indirectly wraps an object that does.
* @throws java.sql.SQLException if an error occurs while determining whether this is a wrapper
* for an object with the given interface.
* @since 1.6
*/ public boolean isWrapperFor(Class<?> interfaces) throws SQLException {
return false;
}
static final long serialVersionUID = 6893806403181801867L;
private class ColInfo implements Serializable {
/** {@collect.stats}
* The field that indicates whether the value in this column is a number
* that is incremented automatically, which makes the value read-only.
* <code>true</code> means that the value in this column
* is automatically numbered; <code>false</code> means that it is not.
*
* @serial
*/
public boolean autoIncrement;
/** {@collect.stats}
* The field that indicates whether the value in this column is case sensitive.
* <code>true</code> means that it is; <code>false</code> that it is not.
*
* @serial
*/
public boolean caseSensitive;
/** {@collect.stats}
* The field that indicates whether the value in this column is a cash value
* <code>true</code> means that it is; <code>false</code> that it is not.
*
* @serial
*/
public boolean currency;
/** {@collect.stats}
* The field that indicates whether the value in this column is nullable.
* The possible values are the <code>ResultSet</code> constants
* <code>columnNoNulls</code>, <code>columnNullable</code>, and
* <code>columnNullableUnknown</code>.
*
* @serial
*/
public int nullable;
/** {@collect.stats}
* The field that indicates whether the value in this column is a signed number.
* <code>true</code> means that it is; <code>false</code> that it is not.
*
* @serial
*/
public boolean signed;
/** {@collect.stats}
* The field that indicates whether the value in this column can be used in
* a <code>WHERE</code> clause.
* <code>true</code> means that it can; <code>false</code> that it cannot.
*
* @serial
*/
public boolean searchable;
/** {@collect.stats}
* The field that indicates the normal maximum width in characters for
* this column.
*
* @serial
*/
public int columnDisplaySize;
/** {@collect.stats}
* The field that holds the suggested column title for this column, to be
* used in printing and displays.
*
* @serial
*/
public String columnLabel;
/** {@collect.stats}
* The field that holds the name of this column.
*
* @serial
*/
public String columnName;
/** {@collect.stats}
* The field that holds the schema name for the table from which this column
* was derived.
*
* @serial
*/
public String schemaName;
/** {@collect.stats}
* The field that holds the precision of the value in this column. For number
* types, the precision is the total number of decimal digits; for character types,
* it is the maximum number of characters; for binary types, it is the maximum
* length in bytes.
*
* @serial
*/
public int colPrecision;
/** {@collect.stats}
* The field that holds the scale (number of digits to the right of the decimal
* point) of the value in this column.
*
* @serial
*/
public int colScale;
/** {@collect.stats}
* The field that holds the name of the table from which this column
* was derived. This value may be the empty string if there is no
* table name, such as when this column is produced by a join.
*
* @serial
*/
public String tableName ="";
/** {@collect.stats}
* The field that holds the catalog name for the table from which this column
* was derived. If the DBMS does not support catalogs, the value may be the
* empty string.
*
* @serial
*/
public String catName;
/** {@collect.stats}
* The field that holds the type code from the class <code>java.sql.Types</code>
* indicating the type of the value in this column.
*
* @serial
*/
public int colType;
/** {@collect.stats}
* The field that holds the the type name used by this particular data source
* for the value stored in this column.
*
* @serial
*/
public String colTypeName;
/** {@collect.stats}
* The field that holds the updatablity boolean per column of a RowSet
*
* @serial
*/
public boolean readOnly = false;
/** {@collect.stats}
* The field that hold the writable boolean per column of a RowSet
*
*@serial
*/
public boolean writable = true;
}
}
| Java |
/*
* Copyright (c) 2003, 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 javax.sql.rowset;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.io.*;
import java.math.*;
/** {@collect.stats}
* The standard interface that all standard implementations of
* <code>FilteredRowSet</code> must implement. The <code>FilteredRowSetImpl</code> class
* provides the reference implementation which may be extended if required.
* Alternatively, a vendor is free to implement its own version
* by implementing this interface.
*
* <h3>1.0 Background</h3>
*
* There are occasions when a <code>RowSet</code> object has a need to provide a degree
* of filtering to its contents. One possible solution is to provide
* a query language for all standard <code>RowSet</code> implementations; however,
* this is an impractical approach for lightweight components such as disconnected
* <code>RowSet</code>
* objects. The <code>FilteredRowSet</code> interface seeks to address this need
* without supplying a heavyweight query language along with the processing that
* such a query language would require.
* <p>
* A JDBC <code>FilteredRowSet</code> standard implementation implements the
* <code>RowSet</code> interfaces and extends the
* <code>CachedRowSet</code><sup><font size=-2>TM</font></sup> class. The
* <code>CachedRowSet</code> class provides a set of protected cursor manipulation
* methods, which a <code>FilteredRowSet</code> implementation can override
* to supply filtering support.
*
* <h3>2.0 Predicate Sharing</h3>
*
* If a <code>FilteredRowSet</code> implementation is shared using the
* inherited <code>createShared</code> method in parent interfaces, the
* <code>Predicate</code> should be shared without modification by all
* <code>FilteredRowSet</code> instance clones.
*
* <h3>3.0 Usage</h3>
* <p>
* By implementing a <code>Predicate</code> (see example in <a href="Predicate.html">Predicate</a>
* class JavaDoc), a <code>FilteredRowSet</code> could then be used as described
* below.
* <P>
* <code>
* <pre>
* FilteredRowSet frs = new FilteredRowSetImpl();
* frs.populate(rs);
*
* Range name = new Range("Alpha", "Bravo", "columnName");
* frs.setFilter(name);
*
* frs.next() // only names from "Alpha" to "Bravo" will be returned
* </pre>
* </code>
* In the example above, we initialize a <code>Range</code> object which
* implements the <code>Predicate</code> interface. This object expresses
* the following constraints: All rows outputted or modified from this
* <code>FilteredRowSet</code> object must fall between the values 'Alpha' and
* 'Bravo' both values inclusive, in the column 'columnName'. If a filter is
* applied to a <code>FilteredRowSet</code> object that contains no data that
* falls within the range of the filter, no rows are returned.
* <p>
* This framework allows multiple classes implementing predicates to be
* used in combination to achieved the required filtering result with
* out the need for query language processing.
* <p>
* <h3>4.0 Updating a <code>FilteredRowSet</code> Object</h3>
* The predicate set on a <code>FilteredRowSet</code> object
* applies a criterion on all rows in a
* <code>RowSet</code> object to manage a subset of rows in a <code>RowSet</code>
* object. This criterion governs the subset of rows that are visible and also
* defines which rows can be modified, deleted or inserted.
* <p>
* Therefore, the predicate set on a <code>FilteredRowSet</code> object must be
* considered as bi-directional and the set criterion as the gating mechanism
* for all views and updates to the <code>FilteredRowSet</code> object. Any attempt
* to update the <code>FilteredRowSet</code> that violates the criterion will
* result in a <code>SQLException</code> object being thrown.
* <p>
* The <code>FilteredRowSet</code> range criterion can be modified by applying
* a new <code>Predicate</code> object to the <code>FilteredRowSet</code>
* instance at any time. This is possible if no additional references to the
* <code>FilteredRowSet</code> object are detected. A new filter has has an
* immediate effect on criterion enforcement within the
* <code>FilteredRowSet</code> object, and all subsequent views and updates will be
* subject to similar enforcement.
* <p>
* <h3>5.0 Behavior of Rows Outside the Filter</h3>
* Rows that fall outside of the filter set on a <code>FilteredRowSet</code>
* object cannot be modified until the filter is removed or a
* new filter is applied.
* <p>
* Furthermore, only rows that fall within the bounds of a filter will be
* synchronized with the data source.
*
* @author Jonathan Bruce
*/
public interface FilteredRowSet extends WebRowSet {
/** {@collect.stats}
* Applies the given <code>Predicate</code> object to this
* <code>FilteredRowSet</code>
* object. The filter applies controls both to inbound and outbound views,
* constraining which rows are visible and which
* rows can be manipulated.
* <p>
* A new <code>Predicate</code> object may be set at any time. This has the
* effect of changing constraints on the <code>RowSet</code> object's data.
* In addition, modifying the filter at runtime presents issues whereby
* multiple components may be operating on one <code>FilteredRowSet</code> object.
* Application developers must take responsibility for managing multiple handles
* to <code>FilteredRowSet</code> objects when their underling <code>Predicate</code>
* objects change.
*
* @param p a <code>Predicate</code> object defining the filter for this
* <code>FilteredRowSet</code> object. Setting a <b>null</b> value
* will clear the predicate, allowing all rows to become visible.
*
* @throws SQLException if an error occurs when setting the
* <code>Predicate</code> object
*/
public void setFilter(Predicate p) throws SQLException;
/** {@collect.stats}
* Retrieves the active filter for this <code>FilteredRowSet</code> object.
*
* @return p the <code>Predicate</code> for this <code>FilteredRowSet</code>
* object; <code>null</code> if no filter has been set.
*/
public Predicate getFilter() ;
}
| 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 javax.sql.rowset;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.io.*;
import java.math.*;
import java.io.*;
/** {@collect.stats}
* The standard interface that all standard implementations of
* <code>JdbcRowSet</code> must implement.
*
* <h3>1.0 Overview</h3>
* A wrapper around a <code>ResultSet</code> object that makes it possible
* to use the result set as a JavaBeans<sup><font size=-2>TM</font></sup>
* component. Thus, a <code>JdbcRowSet</code> object can be one of the Beans that
* a tool makes available for composing an application. Because
* a <code>JdbcRowSet</code> is a connected rowset, that is, it continually
* maintains its connection to a database using a JDBC technology-enabled
* driver, it also effectively makes the driver a JavaBeans component.
* <P>
* Because it is always connected to its database, an instance of
* <code>JdbcRowSet</code>
* can simply take calls invoked on it and in turn call them on its
* <code>ResultSet</code> object. As a consequence, a result set can, for
* example, be a component in a Swing application.
* <P>
* Another advantage of a <code>JdbcRowSet</code> object is that it can be
* used to make a <code>ResultSet</code> object scrollable and updatable. All
* <code>RowSet</code> objects are by default scrollable and updatable. If
* the driver and database being used do not support scrolling and/or updating
* of result sets, an application can populate a <code>JdbcRowSet</code> object
* with the data of a <code>ResultSet</code> object and then operate on the
* <code>JdbcRowSet</code> object as if it were the <code>ResultSet</code>
* object.
* <P>
* <h3>2.0 Creating a <code>JdbcRowSet</code> Object</h3>
* The reference implementation of the <code>JdbcRowSet</code> interface,
* <code>JdbcRowSetImpl</code>, provides an implementation of
* the default constructor. A new instance is initialized with
* default values, which can be set with new values as needed. A
* new instance is not really functional until its <code>execute</code>
* method is called. In general, this method does the following:
* <UL>
* <LI> establishes a connection with a database
* <LI> creates a <code>PreparedStatement</code> object and sets any of its
* placeholder parameters
* <LI> executes the statement to create a <code>ResultSet</code> object
* </UL>
* If the <code>execute</code> method is successful, it will set the
* appropriate private <code>JdbcRowSet</code> fields with the following:
* <UL>
* <LI> a <code>Connection</code> object -- the connection between the rowset
* and the database
* <LI> a <code>PreparedStatement</code> object -- the query that produces
* the result set
* <LI> a <code>ResultSet</code> object -- the result set that the rowset's
* command produced and that is being made, in effect, a JavaBeans
* component
* </UL>
* If these fields have not been set, meaning that the <code>execute</code>
* method has not executed successfully, no methods other than
* <code>execute</code> and <code>close</code> may be called on the
* rowset. All other public methods will throw an exception.
* <P>
* Before calling the <code>execute</code> method, however, the command
* and properties needed for establishing a connection must be set.
* The following code fragment creates a <code>JdbcRowSetImpl</code> object,
* sets the command and connection properties, sets the placeholder parameter,
* and then invokes the method <code>execute</code>.
* <PRE>
* JdbcRowSetImpl jrs = new JdbcRowSetImpl();
* jrs.setCommand("SELECT * FROM TITLES WHERE TYPE = ?");
* jrs.setURL("jdbc:myDriver:myAttribute");
* jrs.setUsername("cervantes");
* jrs.setPassword("sancho");
* jrs.setString(1, "BIOGRAPHY");
* jrs.execute();
* </PRE>
* The variable <code>jrs</code> now represents an instance of
* <code>JdbcRowSetImpl</code> that is a thin wrapper around the
* <code>ResultSet</code> object containing all the rows in the
* table <code>TITLES</code> where the type of book is biography.
* At this point, operations called on <code>jrs</code> will
* affect the rows in the result set, which is effectively a JavaBeans
* component.
* <P>
* The implementation of the <code>RowSet</code> method <code>execute</code> in the
* <code>JdbcRowSet</code> reference implementation differs from that in the
* <code>CachedRowSet</code><sup><font size=-2>TM</font></sup>
* reference implementation to account for the different
* requirements of connected and disconnected <code>RowSet</code> objects.
* <p>
*
* @author Jonathan Bruce
*/
public interface JdbcRowSet extends RowSet, Joinable {
/** {@collect.stats}
* Retrieves a <code>boolean</code> indicating whether rows marked
* for deletion appear in the set of current rows. If <code>true</code> is
* returned, deleted rows are visible with the current rows. If
* <code>false</code> is returned, rows are not visible with the set of
* current rows. The default value is <code>false</code>.
* <P>
* Standard rowset implementations may choose to restrict this behavior
* for security considerations or for certain deployment
* scenarios. The visibility of deleted rows is implementation-defined
* and does not represent standard behavior.
* <P>
* Note: Allowing deleted rows to remain visible complicates the behavior
* of some standard JDBC <code>RowSet</code> implementations methods.
* However, most rowset users can simply ignore this extra detail because
* only very specialized applications will likely want to take advantage of
* this feature.
*
* @return <code>true</code> if deleted rows are visible;
* <code>false</code> otherwise
* @exception SQLException if a rowset implementation is unable to
* to determine whether rows marked for deletion remain visible
* @see #setShowDeleted
*/
public boolean getShowDeleted() throws SQLException;
/** {@collect.stats}
* Sets the property <code>showDeleted</code> to the given
* <code>boolean</code> value. This property determines whether
* rows marked for deletion continue to appear in the set of current rows.
* If the value is set to <code>true</code>, deleted rows are immediately
* visible with the set of current rows. If the value is set to
* <code>false</code>, the deleted rows are set as invisible with the
* current set of rows.
* <P>
* Standard rowset implementations may choose to restrict this behavior
* for security considerations or for certain deployment
* scenarios. This is left as implementation-defined and does not
* represent standard behavior.
*
* @param b <code>true</code> if deleted rows should be shown;
* <code>false</code> otherwise
* @exception SQLException if a rowset implementation is unable to
* to reset whether deleted rows should be visible
* @see #getShowDeleted
*/
public void setShowDeleted(boolean b) throws SQLException;
/** {@collect.stats}
* Retrieves the first warning reported by calls on this <code>JdbcRowSet</code>
* object.
* If a second warning was reported on this <code>JdbcRowSet</code> object,
* it will be chained to the first warning and can be retrieved by
* calling the method <code>RowSetWarning.getNextWarning</code> on the
* first warning. Subsequent warnings on this <code>JdbcRowSet</code>
* object will be chained to the <code>RowSetWarning</code> objects
* returned by the method <code>RowSetWarning.getNextWarning</code>.
*
* The warning chain is automatically cleared each time a new row is read.
* This method may not be called on a <code>RowSet</code> object
* that has been closed;
* doing so will cause an <code>SQLException</code> to be thrown.
* <P>
* Because it is always connected to its data source, a <code>JdbcRowSet</code>
* object can rely on the presence of active
* <code>Statement</code>, <code>Connection</code>, and <code>ResultSet</code>
* instances. This means that applications can obtain additional
* <code>SQLWarning</code>
* notifications by calling the <code>getNextWarning</code> methods that
* they provide.
* Disconnected <code>Rowset</code> objects, such as a
* <code>CachedRowSet</code> object, do not have access to
* these <code>getNextWarning</code> methods.
*
* @return the first <code>RowSetWarning</code>
* object reported on this <code>JdbcRowSet</code> object
* or <code>null</code> if there are none
* @throws SQLException if this method is called on a closed
* <code>JdbcRowSet</code> object
* @see RowSetWarning
*/
public RowSetWarning getRowSetWarnings() throws SQLException;
/** {@collect.stats}
* Each <code>JdbcRowSet</code> contains a <code>Connection</code> object from
* the <code>ResultSet</code> or JDBC properties passed to it's constructors.
* This method wraps the <code>Connection</code> commit method to allow flexible
* auto commit or non auto commit transactional control support.
* <p>
* Makes all changes made since the previous commit/rollback permanent
* and releases any database locks currently held by this Connection
* object. This method should be used only when auto-commit mode has
* been disabled.
*
* @throws SQLException if a database access error occurs or this
* Connection object within this <code>JdbcRowSet</code> is in auto-commit mode
* @see java.sql.Connection#setAutoCommit
*/
public void commit() throws SQLException;
/** {@collect.stats}
* Each <code>JdbcRowSet</code> contains a <code>Connection</code> object from
* the original <code>ResultSet</code> or JDBC properties passed to it. This
* method wraps the <code>Connection</code>'s <code>getAutoCommit</code> method
* to allow an application to determine the <code>JdbcRowSet</code> transaction
* behavior.
* <p>
* Sets this connection's auto-commit mode to the given state. If a
* connection is in auto-commit mode, then all its SQL statements will
* be executed and committed as individual transactions. Otherwise, its
* SQL statements are grouped into transactions that are terminated by a
* call to either the method commit or the method rollback. By default,
* new connections are in auto-commit mode.
*
* @throws SQLException if a database access error occurs
* @see java.sql.Connection#getAutoCommit()
*/
public boolean getAutoCommit() throws SQLException;
/** {@collect.stats}
* Each <code>JdbcRowSet</code> contains a <code>Connection</code> object from
* the original <code>ResultSet</code> or JDBC properties passed to it. This
* method wraps the <code>Connection</code>'s <code>getAutoCommit</code> method
* to allow an application to set the <code>JdbcRowSet</code> transaction behavior.
* <p>
* Sets the current auto-commit mode for this <code>Connection</code> object.
*
* @throws SQLException if a database access error occurs
* @see java.sql.Connection#setAutoCommit(boolean)
*/
public void setAutoCommit(boolean autoCommit) throws SQLException;
/** {@collect.stats}
* Each <code>JdbcRowSet</code> contains a <code>Connection</code> object from
* the original <code>ResultSet</code> or JDBC properties passed to it.
* Undoes all changes made in the current transaction and releases any
* database locks currently held by this <code>Connection</code> object. This method
* should be used only when auto-commit mode has been disabled.
*
* @throws SQLException if a database access error occurs or this <code>Connection</code>
* object within this <code>JdbcRowSet</code> is in auto-commit mode.
* @see #rollback(Savepoint)
*/
public void rollback() throws SQLException;
/** {@collect.stats}
* Each <code>JdbcRowSet</code> contains a <code>Connection</code> object from
* the original <code>ResultSet</code> or JDBC properties passed to it.
* Undoes all changes made in the current transaction to the last set savepoint
* and releases any database locks currently held by this <code>Connection</code>
* object. This method should be used only when auto-commit mode has been disabled.
*
* @throws SQLException if a database access error occurs or this <code>Connection</code>
* object within this <code>JdbcRowSet</code> is in auto-commit mode.
* @see #rollback
*/
public void rollback(Savepoint s) throws SQLException;
}
| 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 javax.sql.rowset;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.io.*;
import java.math.*;
import org.xml.sax.*;
/** {@collect.stats}
* The standard interface that all implementations of a <code>WebRowSet</code>
* must implement.
* <P>
* <h3>1.0 Overview</h3>
* The <code>WebRowSetImpl</code> provides the standard
* reference implementation, which may be extended if required.
* <P>
* The standard WebRowSet XML Schema definition is available at the following
* URI:
* <ul>
* <pre>
* <a href="http://java.sun.com/xml/ns/jdbc/webrowset.xsd">http://java.sun.com/xml/ns/jdbc/webrowset.xsd</a>
* </pre>
* </ul>
* It describes the standard XML document format required when describing a
* <code>RowSet</code> object in XML and must be used be all standard implementations
* of the <code>WebRowSet</code> interface to ensure interoperability. In addition,
* the <code>WebRowSet</code> schema uses specific SQL/XML Schema annotations,
* thus ensuring greater cross
* platform inter-operability. This is an effort currently under way at the ISO
* organization. The SQL/XML definition is available at the following URI:
* <ul>
* <pre>
* <a href="http://standards.iso.org/iso/9075/2002/12/sqlxml">http://standards.iso.org/iso/9075/2002/12/sqlxml</a>
* </pre>
* </ul>
* The schema definition describes the internal data of a <code>RowSet</code> object
* in three distinct areas:
* <UL>
* <li><b>properties</b></li>
* These properties describe the standard synchronization provider properties in
* addition to the more general <code>RowSet</code> properties.
* <p>
* <li><b>metadata</b></li>
* This describes the metadata associated with the tabular structure governed by a
* <code>WebRowSet</code> object. The metadata described is closely aligned with the
* metadata accessible in the underlying <code>java.sql.ResultSet</code> interface.
* <p>
* <li><b>data</b></li>
* This describes the original data (the state of data since the last population
* or last synchronization of the <code>WebRowSet</code> object) and the current
* data. By keeping track of the delta between the original data and the current data,
* a <code>WebRowSet</code> maintains
* the ability to synchronize changes in its data back to the originating data source.
* </ul>
* <P>
* <h3>2.0 WebRowSet States</h3>
* The following sections demonstrates how a <code>WebRowSet</code> implementation
* should use the XML Schema to describe update, insert, and delete operations
* and to describe the state of a <code>WebRowSet</code> object in XML.
* <p>
* <h4>2.1 State 1 - Outputting a <code>WebRowSet</code> Object to XML</h3>
* In this example, a <code>WebRowSet</code> object is created and populated with a simple 2 column,
* 5 row table from a data source. Having the 5 rows in a <code>WebRowSet</code> object
* makes it possible to describe them in XML. The
* metadata describing the various standard JavaBeans properties as defined
* in the RowSet interface plus the standard properties defined in
* the <code>CachedRowSet</code><sup><font size=-2>TM</font></sup> interface
* provide key details that describe WebRowSet
* properties. Outputting the WebRowSet object to XML using the standard
* <code>writeXml</code> methods describes the internal properties as follows:
* <PRE>
* <<font color=red>properties</font>>
* <<font color=red>command</font>>select co1, col2 from test_table<<font color=red>/command</font>>
* <<font color=red>concurrency</font>>1<<font color=red>/concurrency</font>>
* <<font color=red>datasource/</font>>
* <<font color=red>escape-processing</font>>true<<font color=red>/escape-processing</font>>
* <<font color=red>fetch-direction</font>>0<<font color=red>/fetch-direction</font>>
* <<font color=red>fetch-size</font>>0<<font color=red>/fetch-size</font>>
* <<font color=red>isolation-level</font>>1<<font color=red>/isolation-level</font>>
* <<font color=red>key-columns/</font>>
* <<font color=red>map/</font>>
* <<font color=red>max-field-size</font>>0<<font color=red>/max-field-size</font>>
* <<font color=red>max-rows</font>>0<<font color=red>/max-rows</font>>
* <<font color=red>query-timeout</font>>0<<font color=red>/query-timeout</font>>
* <<font color=red>read-only</font>>false<<font color=red>/read-only</font>>
* <<font color=red>rowset-type</font>>TRANSACTION_READ_UNCOMMITED<<font color=red>/rowset-type</font>>
* <<font color=red>show-deleted</font>>false<<font color=red>/show-deleted</font>>
* <<font color=red>table-name/</font>>
* <<font color=red>url</font>>jdbc:thin:oracle<<font color=red>/url</font>>
* <<font color=red>sync-provider</font>>
* <<font color=red>sync-provider-name</font>>.com.rowset.provider.RIOptimisticProvider<<font color=red>/sync-provider-name</font>>
* <<font color=red>sync-provider-vendor</font>>Sun Microsystems<<font color=red>/sync-provider-vendor</font>>
* <<font color=red>sync-provider-version</font>>1.0<<font color=red>/sync-provider-name</font>>
* <<font color=red>sync-provider-grade</font>>LOW<<font color=red>/sync-provider-grade</font>>
* <<font color=red>data-source-lock</font>>NONE<<font color=red>/data-source-lock</font>>
* <<font color=red>/sync-provider</font>>
* <<font color=red>/properties</font>>
* </PRE>
* The meta-data describing the make up of the WebRowSet is described
* in XML as detailed below. Note both columns are described between the
* <code>column-definition</code> tags.
* <PRE>
* <<font color=red>metadata</font>>
* <<font color=red>column-count</font>>2<<font color=red>/column-count</font>>
* <<font color=red>column-definition</font>>
* <<font color=red>column-index</font>>1<<font color=red>/column-index</font>>
* <<font color=red>auto-increment</font>>false<<font color=red>/auto-increment</font>>
* <<font color=red>case-sensitive</font>>true<<font color=red>/case-sensitive</font>>
* <<font color=red>currency</font>>false<<font color=red>/currency</font>>
* <<font color=red>nullable</font>>1<<font color=red>/nullable</font>>
* <<font color=red>signed</font>>false<<font color=red>/signed</font>>
* <<font color=red>searchable</font>>true<<font color=red>/searchable</font>>
* <<font color=red>column-display-size</font>>10<<font color=red>/column-display-size</font>>
* <<font color=red>column-label</font>>COL1<<font color=red>/column-label</font>>
* <<font color=red>column-name</font>>COL1<<font color=red>/column-name</font>>
* <<font color=red>schema-name/</font>>
* <<font color=red>column-precision</font>>10<<font color=red>/column-precision</font>>
* <<font color=red>column-scale</font>>0<<font color=red>/column-scale</font>>
* <<font color=red>table-name/</font>>
* <<font color=red>catalog-name/</font>>
* <<font color=red>column-type</font>>1<<font color=red>/column-type</font>>
* <<font color=red>column-type-name</font>>CHAR<<font color=red>/column-type-name</font>>
* <<font color=red>/column-definition</font>>
* <<font color=red>column-definition</font>>
* <<font color=red>column-index</font>>2<<font color=red>/column-index</font>>
* <<font color=red>auto-increment</font>>false<<font color=red>/auto-increment</font>>
* <<font color=red>case-sensitive</font>>false<<font color=red>/case-sensitive</font>>
* <<font color=red>currency</font>>false<<font color=red>/currency</font>>
* <<font color=red>nullable</font>>1<<font color=red>/nullable</font>>
* <<font color=red>signed</font>>true<<font color=red>/signed</font>>
* <<font color=red>searchable</font>>true<<font color=red>/searchable</font>>
* <<font color=red>column-display-size</font>>39<<font color=red>/column-display-size</font>>
* <<font color=red>column-label</font>>COL2<<font color=red>/column-label</font>>
* <<font color=red>column-name</font>>COL2<<font color=red>/column-name</font>>
* <<font color=red>schema-name/</font>>
* <<font color=red>column-precision</font>>38<<font color=red>/column-precision</font>>
* <<font color=red>column-scale</font>>0<<font color=red>/column-scale</font>>
* <<font color=red>table-name/</font>>
* <<font color=red>catalog-name/</font>>
* <<font color=red>column-type</font>>3<<font color=red>/column-type</font>>
* <<font color=red>column-type-name</font>>NUMBER<<font color=red>/column-type-name</font>>
* <<font color=red>/column-definition</font>>
* <<font color=red>/metadata</font>>
* </PRE>
* Having detailed how the properties and metadata are described, the following details
* how the contents of a <code>WebRowSet</code> object is described in XML. Note, that
* this describes a <code>WebRowSet</code> object that has not undergone any
* modifications since its instantiation.
* A <code>currentRow</code> tag is mapped to each row of the table structure that the
* <code>WebRowSet</code> object provides. A <code>columnValue</code> tag may contain
* either the <code>stringData</code> or <code>binaryData</code> tag, according to
* the SQL type that
* the XML value is mapping back to. The <code>binaryData</code> tag contains data in the
* Base64 encoding and is typically used for <code>BLOB</code> and <code>CLOB</code> type data.
* <PRE>
* <<font color=red>data</font>>
* <<font color=red>currentRow</font>>
* <<font color=red>columnValue</font>>
* firstrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* 1
* <<font color=red>/columnValue</font>>
* <<font color=red>/currentRow</font>>
* <<font color=red>currentRow</font>>
* <<font color=red>columnValue</font>>
* secondrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* 2
* <<font color=red>/columnValue</font>>
* <<font color=red>/currentRow</font>>
* <<font color=red>currentRow</font>>
* <<font color=red>columnValue</font>>
* thirdrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* 3
* <<font color=red>/columnValue</font>>
* <<font color=red>/currentRow</font>>
* <<font color=red>currentRow</font>>
* <<font color=red>columnValue</font>>
* fourthrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* 4
* <<font color=red>/columnValue</font>>
* <<font color=red>/currentRow</font>>
* <<font color=red>/data</font>>
* </PRE>
* <h4>2.2 State 2 - Deleting a Row</h4>
* Deleting a row in a <code>WebRowSet</code> object involves simply moving to the row
* to be deleted and then calling the method <code>deleteRow</code>, as in any other
* <code>RowSet</code> object. The following
* two lines of code, in which <i>wrs</i> is a <code>WebRowSet</code> object, delete
* the third row.
* <PRE>
* wrs.absolute(3);
* wrs.deleteRow();
* </PRE>
* The XML description shows the third row is marked as a <code>deleteRow</code>,
* which eliminates the third row in the <code>WebRowSet</code> object.
* <PRE>
* <<font color=red>data</font>>
* <<font color=red>currentRow</font>>
* <<font color=red>columnValue</font>>
* firstrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* 1
* <<font color=red>/columnValue</font>>
* <<font color=red>/currentRow</font>>
* <<font color=red>currentRow</font>>
* <<font color=red>columnValue</font>>
* secondrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* 2
* <<font color=red>/columnValue</font>>
* <<font color=red>/currentRow</font>>
* <<font color=red>deleteRow</font>>
* <<font color=red>columnValue</font>>
* thirdrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* 3
* <<font color=red>/columnValue</font>>
* <<font color=red>/deleteRow</font>>
* <<font color=red>currentRow</font>>
* <<font color=red>columnValue</font>>
* fourthrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* 4
* <<font color=red>/columnValue</font>>
* <<font color=red>/currentRow</font>>
* <<font color=red>/data</font>>
* </PRE>
* <h4>2.3 State 3 - Inserting a Row</h4>
* A <code>WebRowSet</code> object can insert a new row by moving to the insert row,
* calling the appropriate updater methods for each column in the row, and then
* calling the method <code>insertRow</code>.
* <PRE>
* wrs.moveToInsertRow();
* wrs.updateString(1, "fifththrow");
* wrs.updateString(2, "5");
* wrs.insertRow();
* </PRE>
* The following code fragment changes the second column value in the row just inserted.
* Note that this code applies when new rows are inserted right after the current row,
* which is why the method <code>next</code> moves the cursor to the correct row.
* Calling the method <code>acceptChanges</code> writes the change to the data source.
*
* <PRE>
* wrs.moveToCurrentRow();
* wrs.next();
* wrs.updateString(2, "V");
* wrs.acceptChanges();
* :
* </PRE>
* Describing this in XML demonstrates where the Java code inserts a new row and then
* performs an update on the newly inserted row on an individual field.
* <PRE>
* <<font color=red>data</font>>
* <<font color=red>currentRow</font>>
* <<font color=red>columnValue</font>>
* firstrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* 1
* <<font color=red>/columnValue</font>>
* <<font color=red>/currentRow</font>>
* <<font color=red>currentRow</font>>
* <<font color=red>columnValue</font>>
* secondrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* 2
* <<font color=red>/columnValue</font>>
* <<font color=red>/currentRow</font>>
* <<font color=red>currentRow</font>>
* <<font color=red>columnValue</font>>
* newthirdrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* III
* <<font color=red>/columnValue</font>>
* <<font color=red>/currentRow</font>>
* <<font color=red>insertRow</font>>
* <<font color=red>columnValue</font>>
* fifthrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* 5
* <<font color=red>/columnValue</font>>
* <<font color=red>updateValue</font>>
* V
* <<font color=red>/updateValue</font>>
* <<font color=red>/insertRow</font>>
* <<font color=red>currentRow</font>>
* <<font color=red>columnValue</font>>
* fourthrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* 4
* <<font color=red>/columnValue</font>>
* <<font color=red>/currentRow</font>>
* <<font color=red>/date</font>>
* </PRE>
* <h4>2.4 State 4 - Modifying a Row</h4>
* Modifying a row produces specific XML that records both the new value and the
* value that was replaced. The value that was replaced becomes the original value,
* and the new value becomes the current value. The following
* code moves the cursor to a specific row, performs some modifications, and updates
* the row when complete.
* <PRE>
* wrs.absolute(5);
* wrs.updateString(1, "new4thRow");
* wrs.updateString(2, "IV");
* wrs.updateRow();
* </PRE>
* In XML, this is described by the <code>modifyRow</code> tag. Both the original and new
* values are contained within the tag for original row tracking purposes.
* <PRE>
* <<font color=red>data</font>>
* <<font color=red>currentRow</font>>
* <<font color=red>columnValue</font>>
* firstrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* 1
* <<font color=red>/columnValue</font>>
* <<font color=red>/currentRow</font>>
* <<font color=red>currentRow</font>>
* <<font color=red>columnValue</font>>
* secondrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* 2
* <<font color=red>/columnValue</font>>
* <<font color=red>/currentRow</font>>
* <<font color=red>currentRow</font>>
* <<font color=red>columnValue</font>>
* newthirdrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* III
* <<font color=red>/columnValue</font>>
* <<font color=red>/currentRow</font>>
* <<font color=red>currentRow</font>>
* <<font color=red>columnValue</font>>
* fifthrow
* <<font color=red>/columnValue</font>>
* <<font color=red>columnValue</font>>
* 5
* <<font color=red>/columnValue</font>>
* <<font color=red>/currentRow</font>>
* <<font color=red>modifyRow</font>>
* <<font color=red>columnValue</font>>
* fourthrow
* <<font color=red>/columnValue</font>>
* <<font color=red>updateValue</font>>
* new4thRow
* <<font color=red>/updateValue</font>>
* <<font color=red>columnValue</font>>
* 4
* <<font color=red>/columnValue</font>>
* <<font color=red>updateValue</font>>
* IV
* <<font color=red>/updateValue</font>>
* <<font color=red>/modifyRow</font>>
* <<font color=red>/data</font>>
* </PRE>
*
* @see javax.sql.rowset.JdbcRowSet
* @see javax.sql.rowset.CachedRowSet
* @see javax.sql.rowset.FilteredRowSet
* @see javax.sql.rowset.JoinRowSet
*/
public interface WebRowSet extends CachedRowSet {
/** {@collect.stats}
* Reads a <code>WebRowSet</code> object in its XML format from the given
* <code>Reader</code> object.
*
* @param reader the <code>java.io.Reader</code> stream from which this
* <code>WebRowSet</code> object will be populated
* @throws SQLException if a database access error occurs
*/
public void readXml(java.io.Reader reader) throws SQLException;
/** {@collect.stats}
* Reads a stream based XML input to populate this <code>WebRowSet</code>
* object.
*
* @param iStream the <code>java.io.InputStream</code> from which this
* <code>WebRowSet</code> object will be populated
* @throws SQLException if a data source access error occurs
* @throws IOException if an IO exception occurs
*/
public void readXml(java.io.InputStream iStream) throws SQLException, IOException;
/** {@collect.stats}
* Populates this <code>WebRowSet</code> object with
* the contents of the given <code>ResultSet</code> object and writes its
* data, properties, and metadata
* to the given <code>Writer</code> object in XML format.
* <p>
* NOTE: The <code>WebRowSet</code> cursor may be moved to write out the
* contents to the XML data source. If implemented in this way, the cursor <b>must</b>
* be returned to its position just prior to the <code>writeXml()</code> call.
*
* @param rs the <code>ResultSet</code> object with which to populate this
* <code>WebRowSet</code> object
* @param writer the <code>java.io.Writer</code> object to write to.
* @throws SQLException if an error occurs writing out the rowset
* contents in XML format
*/
public void writeXml(ResultSet rs, java.io.Writer writer) throws SQLException;
/** {@collect.stats}
* Populates this <code>WebRowSet</code> object with
* the contents of the given <code>ResultSet</code> object and writes its
* data, properties, and metadata
* to the given <code>OutputStream</code> object in XML format.
* <p>
* NOTE: The <code>WebRowSet</code> cursor may be moved to write out the
* contents to the XML data source. If implemented in this way, the cursor <b>must</b>
* be returned to its position just prior to the <code>writeXml()</code> call.
*
* @param rs the <code>ResultSet</code> object with which to populate this
* <code>WebRowSet</code> object
* @param oStream the <code>java.io.OutputStream</code> to write to
* @throws SQLException if a data source access error occurs
* @throws IOException if a IO exception occurs
*/
public void writeXml(ResultSet rs, java.io.OutputStream oStream) throws SQLException, IOException;
/** {@collect.stats}
* Writes the data, properties, and metadata for this <code>WebRowSet</code> object
* to the given <code>Writer</code> object in XML format.
*
* @param writer the <code>java.io.Writer</code> stream to write to
* @throws SQLException if an error occurs writing out the rowset
* contents to XML
*/
public void writeXml(java.io.Writer writer) throws SQLException;
/** {@collect.stats}
* Writes the data, properties, and metadata for this <code>WebRowSet</code> object
* to the given <code>OutputStream</code> object in XML format.
*
* @param oStream the <code>java.io.OutputStream</code> stream to write to
* @throws SQLException if a data source access error occurs
* @throws IOException if a IO exception occurs
*/
public void writeXml(java.io.OutputStream oStream) throws SQLException, IOException;
/** {@collect.stats}
* The public identifier for the XML Schema definition that defines the XML
* tags and their valid values for a <code>WebRowSet</code> implementation.
*/
public static String PUBLIC_XML_SCHEMA =
"--//Sun Microsystems, Inc.//XSD Schema//EN";
/** {@collect.stats}
* The URL for the XML Schema definition file that defines the XML tags and
* their valid values for a <code>WebRowSet</code> implementation.
*/
public static String SCHEMA_SYSTEM_ID = "http://java.sun.com/xml/ns/jdbc/webrowset.xsd";
}
| 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 javax.sql.rowset;
import java.sql.*;
import javax.sql.*;
import java.util.*;
import java.io.*;
import java.math.*;
import java.io.Serializable;
import javax.sql.rowset.serial.*;
/** {@collect.stats}
* An abstract class providing a <code>RowSet</code> object with its basic functionality.
* The basic functions include having properties and sending event notifications,
* which all JavaBeans<sup><font size=-2>TM</font></sup> components must implement.
* <P>
* <h3>1.0 Overview</h3>
* The <code>BaseRowSet</code> class provides the core functionality
* for all <code>RowSet</code> implementations,
* and all standard implementations <b>may</b> use this class in combination with
* one or more <code>RowSet</code> interfaces in order to provide a standard
* vendor-specific implementation. To clarify, all implementations must implement
* at least one of the <code>RowSet</code> interfaces (<code>JdbcRowSet</code>,
* <code>CachedRowSet</code>, <code>JoinRowSet</code>, <code>FilteredRowSet</code>,
* or <code>WebRowSet</code>). This means that any implementation that extends
* the <code>BaseRowSet</code> class must also implement one of the <code>RowSet</code>
* interfaces.
* <p>
* The <code>BaseRowSet</code> class provides the following:
* <p>
* <UL>
* <LI><b>Properties</b>
* <ul>
* <li>Fields for storing current properties
* <li>Methods for getting and setting properties
* </ul>
* <p>
* <LI><b>Event notification</b>
* <P>
* <LI><b>A complete set of setter methods</b> for setting the parameters in a
* <code>RowSet</code> object's command
* <p>
* <LI> <b>Streams</b>
* <ul>
* <li>Fields for storing stream instances
* <li>Constants for indicating the type of a stream
* </ul>
* <p>
* </UL>
*
* <h3>2.0 Setting Properties</h3>
* All rowsets maintain a set of properties, which will usually be set using
* a tool. The number and kinds of properties a rowset has will vary,
* depending on what the <code>RowSet</code> implementation does and how it gets
* its data. For example,
* rowsets that get their data from a <code>ResultSet</code> object need to
* set the properties that are required for making a database connection.
* If a <code>RowSet</code> object uses the <code>DriverManager</code> facility to make a
* connection, it needs to set a property for the JDBC URL that identifies the
* appropriate driver, and it needs to set the properties that give the
* user name and password.
* If, on the other hand, the rowset uses a <code>DataSource</code> object
* to make the connection, which is the preferred method, it does not need to
* set the property for the JDBC URL. Instead, it needs to set the property
* for the logical name of the data source along with the properties for
* the user name and password.
* <P>
* NOTE: In order to use a <code>DataSource</code> object for making a
* connection, the <code>DataSource</code> object must have been registered
* with a naming service that uses the Java Naming and Directory
* Interface<sup><font size=-2>TM</font></sup> (JNDI) API. This registration
* is usually done by a person acting in the capacity of a system administrator.
* <P>
* <h3>3.0 Setting the Command and Its Parameters</h3>
* When a rowset gets its data from a relational database, it executes a command (a query)
* that produces a <code>ResultSet</code> object. This query is the command that is set
* for the <code>RowSet</code> object's command property. The rowset populates itself with data by reading the
* data from the <code>ResultSet</code> object into itself. If the query
* contains placeholders for values to be set, the <code>BaseRowSet</code> setter methods
* are used to set these values. All setter methods allow these values to be set
* to <code>null</code> if required.
* <P>
* The following code fragment illustrates how the
* <code>CachedRowSet</code><sup><font size=-2>TM</font></sup>
* object <code>crs</code> might have its command property set. Note that if a
* tool is used to set properties, this is the code that the tool would use.
* <PRE>
* crs.setCommand("SELECT FIRST_NAME, LAST_NAME, ADDRESS FROM CUSTOMERS" +
* "WHERE CREDIT_LIMIT > ? AND REGION = ?");
* </PRE>
* <P>
* In this example, the values for <code>CREDIT_LIMIT</code> and
* <code>REGION</code> are placeholder parameters, which are indicated with a
* question mark (?). The first question mark is placeholder parameter number
* <code>1</code>, the second question mark is placeholder parameter number
* <code>2</code>, and so on. Any placeholder parameters must be set with
* values before the query can be executed. To set these
* placeholder parameters, the <code>BaseRowSet</code> class provides a set of setter
* methods, similar to those provided by the <code>PreparedStatement</code>
* interface, for setting values of each data type. A <code>RowSet</code> object stores the
* parameter values internally, and its <code>execute</code> method uses them internally
* to set values for the placeholder parameters
* before it sends the command to the DBMS to be executed.
* <P>
* The following code fragment demonstrates
* setting the two parameters in the query from the previous example.
* <PRE>
* crs.setInt(1, 5000);
* crs.setString(2, "West");
* </PRE>
* If the <code>execute</code> method is called at this point, the query
* sent to the DBMS will be:
* <PRE>
* "SELECT FIRST_NAME, LAST_NAME, ADDRESS FROM CUSTOMERS" +
* "WHERE CREDIT_LIMIT > 5000 AND REGION = 'West'"
* </PRE>
* NOTE: Setting <code>Array</code>, <code>Clob</code>, <code>Blob</code> and
* <code>Ref</code> objects as a command parameter, stores these values as
* <code>SerialArray</code>, <code>SerialClob</code>, <code>SerialBlob</code>
* and <code>SerialRef</code> objects respectively.
*
* <h3>4.0 Handling of Parameters Behind the Scenes</h3>
*
* NOTE: The <code>BaseRowSet</code> class provides two kinds of setter methods,
* those that set properties and those that set placeholder parameters. The setter
* methods discussed in this section are those that set placeholder parameters.
* <P>
* The placeholder parameters set with the <code>BaseRowSet</code> setter methods
* are stored as objects in an internal <code>Hashtable</code> object.
* Primitives are stored as their <code>Object</code> type. For example, <code>byte</code>
* is stored as <code>Byte</code> object, and <code>int</code> is stored as
* an <code>Integer</code> object.
* When the method <code>execute</code> is called, the values in the
* <code>Hashtable</code> object are substituted for the appropriate placeholder
* parameters in the command.
* <P)>
* A call to the method <code>getParams</code> returns the values stored in the
* <code>Hashtable</code> object as an array of <code>Object</code> instances.
* An element in this array may be a simple <code>Object</code> instance or an
* array (which is a type of <code>Object</code>). The particular setter method used
* determines whether an element in this array is an <code>Object</code> or an array.
* <P>
* The majority of methods for setting placeholder parameters take two parameters,
* with the first parameter
* indicating which placeholder parameter is to be set, and the second parameter
* giving the value to be set. Methods such as <code>setInt</code>,
* <code>setString</code>, <code>setBoolean</code>, and <code>setLong</code> fall into
* this category. After these methods have been called, a call to the method
* <code>getParams</code> will return an array with the values that have been set. Each
* element in the array is an <code>Object</code> instance representing the
* values that have been set. The order of these values in the array is determined by the
* <code>int</code> (the first parameter) passed to the setter method. The values in the
* array are the values (the second parameter) passed to the setter method.
* In other words, the first element in the array is the value
* to be set for the first placeholder parameter in the <code>RowSet</code> object's
* command. The second element is the value to
* be set for the second placeholder parameter, and so on.
* <P>
* Several setter methods send the driver and DBMS information beyond the value to be set.
* When the method <code>getParams</code> is called after one of these setter methods has
* been used, the elements in the array will themselves be arrays to accommodate the
* additional information. In this category, the method <code>setNull</code> is a special case
* because one version takes only
* two parameters (<code>setNull(int parameterIndex, int SqlType)</code>). Nevertheless,
* it requires
* an array to contain the information that will be passed to the driver and DBMS. The first
* element in this array is the value to be set, which is <code>null</code>, and the
* second element is the <code>int</code> supplied for <i>sqlType</i>, which
* indicates the type of SQL value that is being set to <code>null</code>. This information
* is needed by some DBMSs and is therefore required in order to ensure that applications
* are portable.
* The other version is intended to be used when the value to be set to <code>null</code>
* is a user-defined type. It takes three parameters
* (<code>setNull(int parameterIndex, int sqlType, String typeName)</code>) and also
* requires an array to contain the information to be passed to the driver and DBMS.
* The first two elements in this array are the same as for the first version of
* <code>setNull</code>. The third element, <i>typeName</i>, gives the SQL name of
* the user-defined type. As is true with the other setter methods, the number of the
* placeholder parameter to be set is indicated by an element's position in the array
* returned by <code>getParams</code>. So, for example, if the parameter
* supplied to <code>setNull</code> is <code>2</code>, the second element in the array
* returned by <code>getParams</code> will be an array of two or three elements.
* <P>
* Some methods, such as <code>setObject</code> and <code>setDate</code> have versions
* that take more than two parameters, with the extra parameters giving information
* to the driver or the DBMS. For example, the methods <code>setDate</code>,
* <code>setTime</code>, and <code>setTimestamp</code> can take a <code>Calendar</code>
* object as their third parameter. If the DBMS does not store time zone information,
* the drivern uses the <code>Calendar</code> object to construct the <code>Date</code>,
* <code>Time</code>, or <code>Timestamp</code> object being set. As is true with other
* methods that provide additional information, the element in the array returned
* by <code>getParams</code> is an array instead of a simple <code>Object</code> instance.
* <P>
* The methods <code>setAsciiStream</code>, <code>setBinaryStream</code>,
* <code>setCharacterStream</code>, and <code>setUnicodeStream</code> (which is
* deprecated, so applications should use <code>getCharacterStream</code> instead)
* take three parameters, so for them, the element in the array returned by
* <code>getParams</code> is also an array. What is different about these setter
* methods is that in addition to the information provided by parameters, the array contains
* one of the <code>BaseRowSet</code> constants indicating the type of stream being set.
* <p>
* NOTE: The method <code>getParams</code> is called internally by
* <code>RowSet</code> implementations extending this class; it is not normally called by an
* application programmer directly.
*
* <h3>5.0 Event Notification</h3>
* The <code>BaseRowSet</code> class provides the event notification
* mechanism for rowsets. It contains the field
* <code>listeners</code>, methods for adding and removing listeners, and
* methods for notifying listeners of changes.
* <P>
* A listener is an object that has implemented the <code>RowSetListener</code> interface.
* If it has been added to a <code>RowSet</code> object's list of listeners, it will be notified
* when an event occurs on that <code>RowSet</code> object. Each listener's
* implementation of the <code>RowSetListener</code> methods defines what that object
* will do when it is notified that an event has occurred.
* <P>
* There are three possible events for a <code>RowSet</code> object:
* <OL>
* <LI>the cursor moves
* <LI>an individual row is changed (updated, deleted, or inserted)
* <LI>the contents of the entire <code>RowSet</code> object are changed
* </OL>
* <P>
* The <code>BaseRowSet</code> method used for the notification indicates the
* type of event that has occurred. For example, the method
* <code>notifyRowChanged</code> indicates that a row has been updated,
* deleted, or inserted. Each of the notification methods creates a
* <code>RowSetEvent</code> object, which is supplied to the listener in order to
* identify the <code>RowSet</code> object on which the event occurred.
* What the listener does with this information, which may be nothing, depends on how it was
* implemented.
* <p>
* <h3>6.0 Default Behavior</h3>
* A default <code>BaseRowSet</code> object is initialized with many starting values.
*
* The following is true of a default <code>RowSet</code> instance that extends
* the <code>BaseRowSet</code> class:
* <UL>
* <LI>Has a scrollable cursor and does not show changes
* made by others.
* <LI>Is updatable.
* <LI>Does not show rows that have been deleted.
* <LI>Has no time limit for how long a driver may take to
* execute the <code>RowSet</code> object's command.
* <LI>Has no limit for the number of rows it may contain.
* <LI>Has no limit for the number of bytes a column may contain. NOTE: This
* limit applies only to columns that hold values of the
* following types: <code>BINARY</code>, <code>VARBINARY</code>,
* <code>LONGVARBINARY</code>, <code>CHAR</code>, <code>VARCHAR</code>,
* and <code>LONGVARCHAR</code>.
* <LI>Will not see uncommitted data (make "dirty" reads).
* <LI>Has escape processing turned on.
* <LI>Has its connection's type map set to <code>null</code>.
* <LI>Has an empty <code>Vector</code> object for storing the values set
* for the placeholder parameters in the <code>RowSet</code> object's command.
* </UL>
* <p>
* If other values are desired, an application must set the property values
* explicitly. For example, the following line of code sets the maximum number
* of rows for the <code>CachedRowSet</code> object <i>crs</i> to 500.
* <PRE>
* crs.setMaxRows(500);
* </PRE>
* Methods implemented in extensions of this <code>BaseRowSet</code> class <b>must</b> throw an
* <code>SQLException</code> object for any violation of the defined assertions. Also, if the
* extending class overrides and reimplements any <code>BaseRowSet</code> method and encounters
* connectivity or underlying data source issues, that method <b>may</b> in addition throw an
* <code>SQLException</code> object for that reason.
*/
public abstract class BaseRowSet implements Serializable, Cloneable {
/** {@collect.stats}
* A constant indicating to a <code>RowSetReaderImpl</code> object
* that a given parameter is a Unicode stream. This
* <code>RowSetReaderImpl</code> object is provided as an extension of the
* <code>SyncProvider</code> abstract class defined in the
* <code>SyncFactory</code> static factory SPI mechanism.
*/
public static final int UNICODE_STREAM_PARAM = 0;
/** {@collect.stats}
* A constant indicating to a <code>RowSetReaderImpl</code> object
* that a given parameter is a binary stream. A
* <code>RowSetReaderImpl</code> object is provided as an extension of the
* <code>SyncProvider</code> abstract class defined in the
* <code>SyncFactory</code> static factory SPI mechanism.
*/
public static final int BINARY_STREAM_PARAM = 1;
/** {@collect.stats}
* A constant indicating to a <code>RowSetReaderImpl</code> object
* that a given parameter is an ASCII stream. A
* <code>RowSetReaderImpl</code> object is provided as an extension of the
* <code>SyncProvider</code> abstract class defined in the
* <code>SyncFactory</code> static factory SPI mechanism.
*/
public static final int ASCII_STREAM_PARAM = 2;
/** {@collect.stats}
* The <code>InputStream</code> object that will be
* returned by the method <code>getBinaryStream</code>, which is
* specified in the <code>ResultSet</code> interface.
* @serial
*/
protected java.io.InputStream binaryStream;
/** {@collect.stats}
* The <code>InputStream</code> object that will be
* returned by the method <code>getUnicodeStream</code>,
* which is specified in the <code>ResultSet</code> interface.
* @serial
*/
protected java.io.InputStream unicodeStream;
/** {@collect.stats}
* The <code>InputStream</code> object that will be
* returned by the method <code>getAsciiStream</code>,
* which is specified in the <code>ResultSet</code> interface.
* @serial
*/
protected java.io.InputStream asciiStream;
/** {@collect.stats}
* The <code>Reader</code> object that will be
* returned by the method <code>getCharacterStream</code>,
* which is specified in the <code>ResultSet</code> interface.
* @serial
*/
protected java.io.Reader charStream;
/** {@collect.stats}
* The query that will be sent to the DBMS for execution when the
* method <code>execute</code> is called.
* @serial
*/
private String command;
/** {@collect.stats}
* The JDBC URL the reader, writer, or both supply to the method
* <code>DriverManager.getConnection</code> when the
* <code>DriverManager</code> is used to get a connection.
* <P>
* The JDBC URL identifies the driver to be used to make the conndection.
* This URL can be found in the documentation supplied by the driver
* vendor.
* @serial
*/
private String URL;
/** {@collect.stats}
* The logical name of the data source that the reader/writer should use
* in order to retrieve a <code>DataSource</code> object from a Java
* Directory and Naming Interface (JNDI) naming service.
* @serial
*/
private String dataSource;
/** {@collect.stats}
* The user name the reader, writer, or both supply to the method
* <code>DriverManager.getConnection</code> when the
* <code>DriverManager</code> is used to get a connection.
* @serial
*/
private transient String username;
/** {@collect.stats}
* The password the reader, writer, or both supply to the method
* <code>DriverManager.getConnection</code> when the
* <code>DriverManager</code> is used to get a connection.
* @serial
*/
private transient String password;
/** {@collect.stats}
* A constant indicating the type of this JDBC <code>RowSet</code>
* object. It must be one of the following <code>ResultSet</code>
* constants: <code>TYPE_FORWARD_ONLY</code>,
* <code>TYPE_SCROLL_INSENSITIVE</code>, or
* <code>TYPE_SCROLL_SENSITIVE</code>.
* @serial
*/
private int rowSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
/** {@collect.stats}
* A <code>boolean</code> indicating whether deleted rows are visible in this
* JDBC <code>RowSet</code> object .
* @serial
*/
private boolean showDeleted = false; // default is false
/** {@collect.stats}
* The maximum number of seconds the driver
* will wait for a command to execute. This limit applies while
* this JDBC <code>RowSet</code> object is connected to its data
* source, that is, while it is populating itself with
* data and while it is writing data back to the data source.
* @serial
*/
private int queryTimeout = 0; // default is no timeout
/** {@collect.stats}
* The maximum number of rows the reader should read.
* @serial
*/
private int maxRows = 0; // default is no limit
/** {@collect.stats}
* The maximum field size the reader should read.
* @serial
*/
private int maxFieldSize = 0; // default is no limit
/** {@collect.stats}
* A constant indicating the concurrency of this JDBC <code>RowSet</code>
* object. It must be one of the following <code>ResultSet</code>
* constants: <code>CONCUR_READ_ONLY</code> or
* <code>CONCUR_UPDATABLE</code>.
* @serial
*/
private int concurrency = ResultSet.CONCUR_UPDATABLE;
/** {@collect.stats}
* A <code>boolean</code> indicating whether this JDBC <code>RowSet</code>
* object is read-only. <code>true</code> indicates that it is read-only;
* <code>false</code> that it is writable.
* @serial
*/
private boolean readOnly;
/** {@collect.stats}
* A <code>boolean</code> indicating whether the reader for this
* JDBC <code>RowSet</code> object should perform escape processing.
* <code>true</code> means that escape processing is turned on;
* <code>false</code> that it is not. The default is <code>true</code>.
* @serial
*/
private boolean escapeProcessing;
/** {@collect.stats}
* A constant indicating the isolation level of the connection
* for this JDBC <code>RowSet</code> object . It must be one of
* the following <code>Connection</code> constants:
* <code>TRANSACTION_NONE</code>,
* <code>TRANSACTION_READ_UNCOMMITTED</code>,
* <code>TRANSACTION_READ_COMMITTED</code>,
* <code>TRANSACTION_REPEATABLE_READ</code> or
* <code>TRANSACTION_SERIALIZABLE</code>.
* @serial
*/
private int isolation;
/** {@collect.stats}
* A constant used as a hint to the driver that indicates the direction in
* which data from this JDBC <code>RowSet</code> object is going
* to be fetched. The following <code>ResultSet</code> constants are
* possible values:
* <code>FETCH_FORWARD</code>,
* <code>FETCH_REVERSE</code>,
* <code>FETCH_UNKNOWN</code>.
* <P>
* Unused at this time.
* @serial
*/
private int fetchDir = ResultSet.FETCH_FORWARD; // default fetch direction
/** {@collect.stats}
* A hint to the driver that indicates the expected number of rows
* in this JDBC <code>RowSet</code> object .
* <P>
* Unused at this time.
* @serial
*/
private int fetchSize = 0; // default fetchSize
/** {@collect.stats}
* The <code>java.util.Map</code> object that contains entries mapping
* SQL type names to classes in the Java programming language for the
* custom mapping of user-defined types.
* @serial
*/
private Map map;
/** {@collect.stats}
* A <code>Vector</code> object that holds the list of listeners
* that have registered with this <code>RowSet</code> object.
* @serial
*/
private Vector listeners;
/** {@collect.stats}
* A <code>Vector</code> object that holds the parameters set
* for this <code>RowSet</code> object's current command.
* @serial
*/
private Hashtable params; // could be transient?
/** {@collect.stats}
* Constructs a new <code>BaseRowSet</code> object initialized with
* a default <code>Vector</code> object for its <code>listeners</code>
* field. The other default values with which it is initialized are listed
* in Section 6.0 of the class comment for this class.
*/
public BaseRowSet() {
// allocate the listeners collection
listeners = new Vector();
}
/** {@collect.stats}
* Performs the necessary internal configurations and initializations
* to allow any JDBC <code>RowSet</code> implementation to start using
* the standard facilities provided by a <code>BaseRowSet</code>
* instance. This method <b>should</b> be called after the <code>RowSet</code> object
* has been instantiated to correctly initialize all parameters. This method
* <b>should</b> never be called by an application, but is called from with
* a <code>RowSet</code> implementation extending this class.
*/
protected void initParams() {
params = new Hashtable();
}
//--------------------------------------------------------------------
// Events
//--------------------------------------------------------------------
/** {@collect.stats}
* The listener will be notified whenever an event occurs on this <code>RowSet</code>
* object.
* <P>
* A listener might, for example, be a table or graph that needs to
* be updated in order to accurately reflect the current state of
* the <code>RowSet</code> object.
* <p>
* <b>Note</b>: if the <code>RowSetListener</code> object is
* <code>null</code>, this method silently discards the <code>null</code>
* value and does not add a null reference to the set of listeners.
* <p>
* <b>Note</b>: if the listener is already set, and the new <code>RowSetListerner</code>
* instance is added to the set of listeners already registered to receive
* event notifications from this <code>RowSet</code>.
*
* @param listener an object that has implemented the
* <code>javax.sql.RowSetListener</code> interface and wants to be notified
* of any events that occur on this <code>RowSet</code> object; May be
* null.
* @see #removeRowSetListener
*/
public void addRowSetListener(RowSetListener listener) {
listeners.add(listener);
}
/** {@collect.stats}
* Removes the designated object from this <code>RowSet</code> object's list of listeners.
* If the given argument is not a registered listener, this method
* does nothing.
*
* <b>Note</b>: if the <code>RowSetListener</code> object is
* <code>null</code>, this method silently discards the <code>null</code>
* value.
*
* @param listener a <code>RowSetListener</code> object that is on the list
* of listeners for this <code>RowSet</code> object
* @see #addRowSetListener
*/
public void removeRowSetListener(RowSetListener listener) {
listeners.remove(listener);
}
/** {@collect.stats}
* Determine if instance of this class extends the RowSet interface.
*/
private void checkforRowSetInterface() throws SQLException {
if ((this instanceof javax.sql.RowSet) == false) {
throw new SQLException("The class extending abstract class BaseRowSet " +
"must implement javax.sql.RowSet or one of it's sub-interfaces.");
}
}
/** {@collect.stats}
* Notifies all of the listeners registered with this
* <code>RowSet</code> object that its cursor has moved.
* <P>
* When an application calls a method to move the cursor,
* that method moves the cursor and then calls this method
* internally. An application <b>should</b> never invoke
* this method directly.
*
* @throws SQLException if the class extending the <code>BaseRowSet</code>
* abstract class does not implement the <code>RowSet</code> interface or
* one of it's sub-interfaces.
*/
protected void notifyCursorMoved() throws SQLException {
checkforRowSetInterface();
if (listeners.isEmpty() == false) {
RowSetEvent event = new RowSetEvent((RowSet)this);
for (Iterator i = listeners.iterator(); i.hasNext(); ) {
((RowSetListener)i.next()).cursorMoved(event);
}
}
}
/** {@collect.stats}
* Notifies all of the listeners registered with this <code>RowSet</code> object that
* one of its rows has changed.
* <P>
* When an application calls a method that changes a row, such as
* the <code>CachedRowSet</code> methods <code>insertRow</code>,
* <code>updateRow</code>, or <code>deleteRow</code>,
* that method calls <code>notifyRowChanged</code>
* internally. An application <b>should</b> never invoke
* this method directly.
*
* @throws SQLException if the class extending the <code>BaseRowSet</code>
* abstract class does not implement the <code>RowSet</code> interface or
* one of it's sub-interfaces.
*/
protected void notifyRowChanged() throws SQLException {
checkforRowSetInterface();
if (listeners.isEmpty() == false) {
RowSetEvent event = new RowSetEvent((RowSet)this);
for (Iterator i = listeners.iterator(); i.hasNext(); ) {
((RowSetListener)i.next()).rowChanged(event);
}
}
}
/** {@collect.stats}
* Notifies all of the listeners registered with this <code>RowSet</code>
* object that its entire contents have changed.
* <P>
* When an application calls methods that change the entire contents
* of the <code>RowSet</code> object, such as the <code>CachedRowSet</code> methods
* <code>execute</code>, <code>populate</code>, <code>restoreOriginal</code>,
* or <code>release</code>, that method calls <code>notifyRowSetChanged</code>
* internally (either directly or indirectly). An application <b>should</b>
* never invoke this method directly.
*
* @throws SQLException if the class extending the <code>BaseRowSet</code>
* abstract class does not implement the <code>RowSet</code> interface or
* one of it's sub-interfaces.
*/
protected void notifyRowSetChanged() throws SQLException {
checkforRowSetInterface();
if (listeners.isEmpty() == false) {
RowSetEvent event = new RowSetEvent((RowSet)this);
for (Iterator i = listeners.iterator(); i.hasNext(); ) {
((RowSetListener)i.next()).rowSetChanged(event);
}
}
}
/** {@collect.stats}
* Retrieves the SQL query that is the command for this
* <code>RowSet</code> object. The command property contains the query that
* will be executed to populate this <code>RowSet</code> object.
* <P>
* The SQL query returned by this method is used by <code>RowSet</code> methods
* such as <code>execute</code> and <code>populate</code>, which may be implemented
* by any class that extends the <code>BaseRowSet</code> abstract class and
* implements one or more of the standard JSR-114 <code>RowSet</code>
* interfaces.
* <P>
* The command is used by the <code>RowSet</code> object's
* reader to obtain a <code>ResultSet</code> object. The reader then
* reads the data from the <code>ResultSet</code> object and uses it to
* to populate this <code>RowSet</code> object.
* <P>
* The default value for the <code>command</code> property is <code>null</code>.
*
* @return the <code>String</code> that is the value for this
* <code>RowSet</code> object's <code>command</code> property;
* may be <code>null</code>
* @see #setCommand
*/
public String getCommand() {
return command;
}
/** {@collect.stats}
* Sets this <code>RowSet</code> object's <code>command</code> property to
* the given <code>String</code> object and clears the parameters, if any,
* that were set for the previous command.
* <P>
* The <code>command</code> property may not be needed if the <code>RowSet</code>
* object gets its data from a source that does not support commands,
* such as a spreadsheet or other tabular file.
* Thus, this property is optional and may be <code>null</code>.
*
* @param cmd a <code>String</code> object containing an SQL query
* that will be set as this <code>RowSet</code> object's command
* property; may be <code>null</code> but may not be an empty string
* @throws SQLException if an empty string is provided as the command value
* @see #getCommand
*/
public void setCommand(String cmd) throws SQLException {
// cmd equal to null or
// cmd with length 0 (implies url =="")
// are not independent events.
if(cmd == null) {
command = null;
} else if (cmd.length() == 0) {
throw new SQLException("Invalid command string detected. " +
"Cannot be of length less than 0");
} else {
// "unbind" any parameters from any previous command.
if(params == null){
throw new SQLException("Set initParams() before setCommand");
}
params.clear();
command = new String(cmd);
}
}
/** {@collect.stats}
* Retrieves the JDBC URL that this <code>RowSet</code> object's
* <code>javax.sql.Reader</code> object uses to make a connection
* with a relational database using a JDBC technology-enabled driver.
*<P>
* The <code>Url</code> property will be <code>null</code> if the underlying data
* source is a non-SQL data source, such as a spreadsheet or an XML
* data source.
*
* @return a <code>String</code> object that contains the JDBC URL
* used to establish the connection for this <code>RowSet</code>
* object; may be <code>null</code> (default value) if not set
* @throws SQLException if an error occurs retrieving the URL value
* @see #setUrl
*/
public String getUrl() throws SQLException {
return URL;
}
/** {@collect.stats}
* Sets the Url property for this <code>RowSet</code> object
* to the given <code>String</code> object and sets the dataSource name
* property to <code>null</code>. The Url property is a
* JDBC URL that is used when
* the connection is created using a JDBC technology-enabled driver
* ("JDBC driver") and the <code>DriverManager</code>.
* The correct JDBC URL for the specific driver to be used can be found
* in the driver documentation. Although there are guidelines for for how
* a JDBC URL is formed,
* a driver vendor can specify any <code>String</code> object except
* one with a length of <code>0</code> (an empty string).
* <P>
* Setting the Url property is optional if connections are established using
* a <code>DataSource</code> object instead of the <code>DriverManager</code>.
* The driver will use either the URL property or the
* dataSourceName property to create a connection, whichever was
* specified most recently. If an application uses a JDBC URL, it
* must load a JDBC driver that accepts the JDBC URL before it uses the
* <code>RowSet</code> object to connect to a database. The <code>RowSet</code>
* object will use the URL internally to create a database connection in order
* to read or write data.
*
* @param url a <code>String</code> object that contains the JDBC URL
* that will be used to establish the connection to a database for this
* <code>RowSet</code> object; may be <code>null</code> but must not
* be an empty string
* @throws SQLException if an error occurs setting the Url property or the
* parameter supplied is a string with a length of <code>0</code> (an
* empty string)
* @see #getUrl
*/
public void setUrl(String url) throws SQLException {
if(url == null) {
url = null;
} else if (url.length() < 1) {
throw new SQLException("Invalid url string detected. " +
"Cannot be of length less than 1");
} else {
URL = new String(url);
}
dataSource = null;
}
/** {@collect.stats}
* Returns the logical name that when supplied to a naming service
* that uses the Java Naming and Directory Interface (JNDI) API, will
* retrieve a <code>javax.sql.DataSource</code> object. This
* <code>DataSource</code> object can be used to establish a connection
* to the data source that it represents.
* <P>
* Users should set either the url or the data source name property.
* The driver will use the property set most recently to establish a
* connection.
*
* @return a <code>String</code> object that identifies the
* <code>DataSource</code> object to be used for making a
* connection; if no logical name has been set, <code>null</code>
* is returned.
* @see #setDataSourceName
*/
public String getDataSourceName() {
return dataSource;
}
/** {@collect.stats}
* Sets the <code>DataSource</code> name property for this <code>RowSet</code>
* object to the given logical name and sets this <code>RowSet</code> object's
* Url property to <code>null</code>. The name must have been bound to a
* <code>DataSource</code> object in a JNDI naming service so that an
* application can do a lookup using that name to retrieve the
* <code>DataSource</code> object bound to it. The <code>DataSource</code>
* object can then be used to establish a connection to the data source it
* represents.
* <P>
* Users should set either the Url property or the dataSourceName property.
* If both properties are set, the driver will use the property set most recently.
*
* @param name a <code>String</code> object with the name that can be supplied
* to a naming service based on JNDI technology to retrieve the
* <code>DataSource</code> object that can be used to get a connection;
* may be <code>null</code> but must not be an empty string
* @throws SQLException if an empty string is provided as the <code>DataSource</code>
* name
* @see #getDataSourceName
*/
public void setDataSourceName(String name) throws SQLException {
if (name == null) {
dataSource = null;
} else if (name.equals("")) {
throw new SQLException("DataSource name cannot be empty string");
} else {
dataSource = new String(name);
}
URL = null;
}
/** {@collect.stats}
* Returns the user name used to create a database connection. Because it
* is not serialized, the username property is set at runtime before
* calling the method <code>execute</code>.
*
* @return the <code>String</code> object containing the user name that
* is supplied to the data source to create a connection; may be
* <code>null</code> (default value) if not set
* @see #setUsername
*/
public String getUsername() {
return username;
}
/** {@collect.stats}
* Sets the username property for this <code>RowSet</code> object
* to the given user name. Because it
* is not serialized, the username property is set at run time before
* calling the method <code>execute</code>.
*
* @param name the <code>String</code> object containing the user name that
* is supplied to the data source to create a connection. It may be null.
* @see #getUsername
*/
public void setUsername(String name) {
if(name == null)
{
username = null;
} else {
username = new String(name);
}
}
/** {@collect.stats}
* Returns the password used to create a database connection for this
* <code>RowSet</code> object. Because the password property is not
* serialized, it is set at run time before calling the method
* <code>execute</code>. The default value is <code>null</code>
*
* @return the <code>String</code> object that represents the password
* that must be supplied to the database to create a connection
* @see #setPassword
*/
public String getPassword() {
return password;
}
/** {@collect.stats}
* Sets the password used to create a database connection for this
* <code>RowSet</code> object to the given <code>String</code>
* object. Because the password property is not
* serialized, it is set at run time before calling the method
* <code>execute</code>.
*
* @param pass the <code>String</code> object that represents the password
* that is supplied to the database to create a connection. It may be
* null.
* @see #getPassword
*/
public void setPassword(String pass) {
if(pass == null)
{
password = null;
} else {
password = new String(pass);
}
}
/** {@collect.stats}
* Sets the type for this <code>RowSet</code> object to the specified type.
* The default type is <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>.
*
* @param type one of the following constants:
* <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or
* <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
* @throws SQLException if the parameter supplied is not one of the
* following constants:
* <code>ResultSet.TYPE_FORWARD_ONLY</code> or
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>
* <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
* @see #getConcurrency
* @see #getType
*/
public void setType(int type) throws SQLException {
if ((type != ResultSet.TYPE_FORWARD_ONLY) &&
(type != ResultSet.TYPE_SCROLL_INSENSITIVE) &&
(type != ResultSet.TYPE_SCROLL_SENSITIVE)) {
throw new SQLException("Invalid type of RowSet set. Must be either " +
"ResultSet.TYPE_FORWARD_ONLY or ResultSet.TYPE_SCROLL_INSENSITIVE " +
"or ResultSet.TYPE_SCROLL_SENSITIVE.");
}
this.rowSetType = type;
}
/** {@collect.stats}
* Returns the type of this <code>RowSet</code> object. The type is initially
* determined by the statement that created the <code>RowSet</code> object.
* The <code>RowSet</code> object can call the method
* <code>setType</code> at any time to change its
* type. The default is <code>TYPE_SCROLL_INSENSITIVE</code>.
*
* @return the type of this JDBC <code>RowSet</code>
* object, which must be one of the following:
* <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or
* <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
* @throws SQLException if an error occurs getting the type of
* of this <code>RowSet</code> object
* @see #setType
*/
public int getType() throws SQLException {
return rowSetType;
}
/** {@collect.stats}
* Sets the concurrency for this <code>RowSet</code> object to
* the specified concurrency. The default concurrency for any <code>RowSet</code>
* object (connected or disconnected) is <code>ResultSet.CONCUR_UPDATABLE</code>,
* but this method may be called at any time to change the concurrency.
* <P>
* @param concurrency one of the following constants:
* <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>
* @throws SQLException if the parameter supplied is not one of the
* following constants:
* <code>ResultSet.CONCUR_UPDATABLE</code> or
* <code>ResultSet.CONCUR_READ_ONLY</code>
* @see #getConcurrency
* @see #isReadOnly
*/
public void setConcurrency(int concurrency) throws SQLException {
if((concurrency != ResultSet.CONCUR_READ_ONLY) &&
(concurrency != ResultSet.CONCUR_UPDATABLE)) {
throw new SQLException("Invalid concurrency set. Must be either " +
"ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE.");
}
this.concurrency = concurrency;
}
/** {@collect.stats}
* Returns a <code>boolean</code> indicating whether this
* <code>RowSet</code> object is read-only.
* Any attempts to update a read-only <code>RowSet</code> object will result in an
* <code>SQLException</code> being thrown. By default,
* rowsets are updatable if updates are possible.
*
* @return <code>true</code> if this <code>RowSet</code> object
* cannot be updated; <code>false</code> otherwise
* @see #setConcurrency
* @see #setReadOnly
*/
public boolean isReadOnly() {
return readOnly;
};
/** {@collect.stats}
* Sets this <code>RowSet</code> object's readOnly property to the given <code>boolean</code>.
*
* @param value <code>true</code> to indicate that this
* <code>RowSet</code> object is read-only;
* <code>false</code> to indicate that it is updatable
*/
public void setReadOnly(boolean value) {
readOnly = value;
}
/** {@collect.stats}
* Returns the transaction isolation property for this
* <code>RowSet</code> object's connection. This property represents
* the transaction isolation level requested for use in transactions.
* <P>
* For <code>RowSet</code> implementations such as
* the <code>CachedRowSet</code> that operate in a disconnected environment,
* the <code>SyncProvider</code> object
* offers complementary locking and data integrity options. The
* options described below are pertinent only to connected <code>RowSet</code>
* objects (<code>JdbcRowSet</code> objects).
*
* @return one of the following constants:
* <code>Connection.TRANSACTION_NONE</code>,
* <code>Connection.TRANSACTION_READ_UNCOMMITTED</code>,
* <code>Connection.TRANSACTION_READ_COMMITTED</code>,
* <code>Connection.TRANSACTION_REPEATABLE_READ</code>, or
* <code>Connection.TRANSACTION_SERIALIZABLE</code>
* @see javax.sql.rowset.spi.SyncFactory
* @see javax.sql.rowset.spi.SyncProvider
* @see #setTransactionIsolation
*/
public int getTransactionIsolation() {
return isolation;
};
/** {@collect.stats}
* Sets the transaction isolation property for this JDBC <code>RowSet</code> object to the given
* constant. The DBMS will use this transaction isolation level for
* transactions if it can.
* <p>
* For <code>RowSet</code> implementations such as
* the <code>CachedRowSet</code> that operate in a disconnected environment,
* the <code>SyncProvider</code> object being used
* offers complementary locking and data integrity options. The
* options described below are pertinent only to connected <code>RowSet</code>
* objects (<code>JdbcRowSet</code> objects).
*
* @param level one of the following constants, listed in ascending order:
* <code>Connection.TRANSACTION_NONE</code>,
* <code>Connection.TRANSACTION_READ_UNCOMMITTED</code>,
* <code>Connection.TRANSACTION_READ_COMMITTED</code>,
* <code>Connection.TRANSACTION_REPEATABLE_READ</code>, or
* <code>Connection.TRANSACTION_SERIALIZABLE</code>
* @throws SQLException if the given parameter is not one of the Connection
* constants
* @see javax.sql.rowset.spi.SyncFactory
* @see javax.sql.rowset.spi.SyncProvider
* @see #getTransactionIsolation
*/
public void setTransactionIsolation(int level) throws SQLException {
if ((level != Connection.TRANSACTION_NONE) &&
(level != Connection.TRANSACTION_READ_COMMITTED) &&
(level != Connection.TRANSACTION_READ_UNCOMMITTED) &&
(level != Connection.TRANSACTION_REPEATABLE_READ) &&
(level != Connection.TRANSACTION_SERIALIZABLE))
{
throw new SQLException("Invalid transaction isolation set. Must " +
"be either " +
"Connection.TRANSACTION_NONE or " +
"Connection.TRANSACTION_READ_UNCOMMITTED or " +
"Connection.TRANSACTION_READ_COMMITTED or " +
"Connection.RRANSACTION_REPEATABLE_READ or " +
"Connection.TRANSACTION_SERIALIZABLE");
}
this.isolation = level;
}
/** {@collect.stats}
* Retrieves the type map associated with the <code>Connection</code>
* object for this <code>RowSet</code> object.
* <P>
* Drivers that support the JDBC 3.0 API will create
* <code>Connection</code> objects with an associated type map.
* This type map, which is initially empty, can contain one or more
* fully-qualified SQL names and <code>Class</code> objects indicating
* the class to which the named SQL value will be mapped. The type mapping
* specified in the connection's type map is used for custom type mapping
* when no other type map supersedes it.
* <p>
* If a type map is explicitly supplied to a method that can perform
* custom mapping, that type map supersedes the connection's type map.
*
* @return the <code>java.util.Map</code> object that is the type map
* for this <code>RowSet</code> object's connection
*/
public java.util.Map<String,Class<?>> getTypeMap() {
return map;
}
/** {@collect.stats}
* Installs the given <code>java.util.Map</code> object as the type map
* associated with the <code>Connection</code> object for this
* <code>RowSet</code> object. The custom mapping indicated in
* this type map will be used unless a different type map is explicitly
* supplied to a method, in which case the type map supplied will be used.
*
* @param map a <code>java.util.Map</code> object that contains the
* mapping from SQL type names for user defined types (UDT) to classes in
* the Java programming language. Each entry in the <code>Map</code>
* object consists of the fully qualified SQL name of a UDT and the
* <code>Class</code> object for the <code>SQLData</code> implementation
* of that UDT. May be <code>null</code>.
*/
public void setTypeMap(java.util.Map<String,Class<?>> map) {
this.map = map;
}
/** {@collect.stats}
* Retrieves the maximum number of bytes that can be used for a column
* value in this <code>RowSet</code> object.
* This limit applies only to columns that hold values of the
* following types: <code>BINARY</code>, <code>VARBINARY</code>,
* <code>LONGVARBINARY</code>, <code>CHAR</code>, <code>VARCHAR</code>,
* and <code>LONGVARCHAR</code>. If the limit is exceeded, the excess
* data is silently discarded.
*
* @return an <code>int</code> indicating the current maximum column size
* limit; zero means that there is no limit
* @throws SQLException if an error occurs internally determining the
* maximum limit of the column size
*/
public int getMaxFieldSize() throws SQLException {
return maxFieldSize;
}
/** {@collect.stats}
* Sets the maximum number of bytes that can be used for a column
* value in this <code>RowSet</code> object to the given number.
* This limit applies only to columns that hold values of the
* following types: <code>BINARY</code>, <code>VARBINARY</code>,
* <code>LONGVARBINARY</code>, <code>CHAR</code>, <code>VARCHAR</code>,
* and <code>LONGVARCHAR</code>. If the limit is exceeded, the excess
* data is silently discarded. For maximum portability, it is advisable to
* use values greater than 256.
*
* @param max an <code>int</code> indicating the new maximum column size
* limit; zero means that there is no limit
* @throws SQLException if (1) an error occurs internally setting the
* maximum limit of the column size or (2) a size of less than 0 is set
*/
public void setMaxFieldSize(int max) throws SQLException {
if (max < 0) {
throw new SQLException("Invalid max field size set. Cannot be of " +
"value: " + max);
}
maxFieldSize = max;
}
/** {@collect.stats}
* Retrieves the maximum number of rows that this <code>RowSet</code> object may contain. If
* this limit is exceeded, the excess rows are silently dropped.
*
* @return an <code>int</code> indicating the current maximum number of
* rows; zero means that there is no limit
* @throws SQLException if an error occurs internally determining the
* maximum limit of rows that a <code>Rowset</code> object can contain
*/
public int getMaxRows() throws SQLException {
return maxRows;
}
/** {@collect.stats}
* Sets the maximum number of rows that this <code>RowSet</code> object may contain to
* the given number. If this limit is exceeded, the excess rows are
* silently dropped.
*
* @param max an <code>int</code> indicating the current maximum number
* of rows; zero means that there is no limit
* @throws SQLException if an error occurs internally setting the
* maximum limit on the number of rows that a JDBC <code>RowSet</code> object
* can contain; or if <i>max</i> is less than <code>0</code>; or
* if <i>max</i> is less than the <code>fetchSize</code> of the
* <code>RowSet</code>
*/
public void setMaxRows(int max) throws SQLException {
if (max < 0) {
throw new SQLException("Invalid max row size set. Cannot be of " +
"value: " + max);
} else if (max < this.getFetchSize()) {
throw new SQLException("Invalid max row size set. Cannot be less " +
"than the fetchSize.");
}
this.maxRows = max;
}
/** {@collect.stats}
* Sets to the given <code>boolean</code> whether or not the driver will
* scan for escape syntax and do escape substitution before sending SQL
* statements to the database. The default is for the driver to do escape
* processing.
* <P>
* Note: Since <code>PreparedStatement</code> objects have usually been
* parsed prior to making this call, disabling escape processing for
* prepared statements will likely have no effect.
*
* @param enable <code>true</code> to enable escape processing;
* <code>false</code> to disable it
* @throws SQLException if an error occurs setting the underlying JDBC
* technology-enabled driver to process the escape syntax
*/
public void setEscapeProcessing(boolean enable) throws SQLException {
escapeProcessing = enable;
}
/** {@collect.stats}
* Retrieves the maximum number of seconds the driver will wait for a
* query to execute. If the limit is exceeded, an <code>SQLException</code>
* is thrown.
*
* @return the current query timeout limit in seconds; zero means that
* there is no limit
* @throws SQLException if an error occurs in determining the query
* time-out value
*/
public int getQueryTimeout() throws SQLException {
return queryTimeout;
}
/** {@collect.stats}
* Sets to the given number the maximum number of seconds the driver will
* wait for a query to execute. If the limit is exceeded, an
* <code>SQLException</code> is thrown.
*
* @param seconds the new query time-out limit in seconds; zero means that
* there is no limit; must not be less than zero
* @throws SQLException if an error occurs setting the query
* time-out or if the query time-out value is less than 0
*/
public void setQueryTimeout(int seconds) throws SQLException {
if (seconds < 0) {
throw new SQLException("Invalid query timeout value set. Cannot be " +
"of value: " + seconds);
}
this.queryTimeout = seconds;
}
/** {@collect.stats}
* Retrieves a <code>boolean</code> indicating whether rows marked
* for deletion appear in the set of current rows.
* The default value is <code>false</code>.
* <P>
* Note: Allowing deleted rows to remain visible complicates the behavior
* of some of the methods. However, most <code>RowSet</code> object users
* can simply ignore this extra detail because only sophisticated
* applications will likely want to take advantage of this feature.
*
* @return <code>true</code> if deleted rows are visible;
* <code>false</code> otherwise
* @throws SQLException if an error occurs determining if deleted rows
* are visible or not
* @see #setShowDeleted
*/
public boolean getShowDeleted() throws SQLException {
return showDeleted;
}
/** {@collect.stats}
* Sets the property <code>showDeleted</code> to the given
* <code>boolean</code> value, which determines whether
* rows marked for deletion appear in the set of current rows.
*
* @param value <code>true</code> if deleted rows should be shown;
* <code>false</code> otherwise
* @throws SQLException if an error occurs setting whether deleted
* rows are visible or not
* @see #getShowDeleted
*/
public void setShowDeleted(boolean value) throws SQLException {
showDeleted = value;
}
/** {@collect.stats}
* Ascertains whether escape processing is enabled for this
* <code>RowSet</code> object.
*
* @return <code>true</code> if escape processing is turned on;
* <code>false</code> otherwise
* @throws SQLException if an error occurs determining if escape
* processing is enabled or not or if the internal escape
* processing trigger has not been enabled
*/
public boolean getEscapeProcessing() throws SQLException {
return escapeProcessing;
}
/** {@collect.stats}
* Gives the driver a performance hint as to the direction in
* which the rows in this <code>RowSet</code> object will be
* processed. The driver may ignore this hint.
* <P>
* A <code>RowSet</code> object inherits the default properties of the
* <code>ResultSet</code> object from which it got its data. That
* <code>ResultSet</code> object's default fetch direction is set by
* the <code>Statement</code> object that created it.
* <P>
* This method applies to a <code>RowSet</code> object only while it is
* connected to a database using a JDBC driver.
* <p>
* A <code>RowSet</code> object may use this method at any time to change
* its setting for the fetch direction.
*
* @param direction one of <code>ResultSet.FETCH_FORWARD</code>,
* <code>ResultSet.FETCH_REVERSE</code>, or
* <code>ResultSet.FETCH_UNKNOWN</code>
* @throws SQLException if (1) the <code>RowSet</code> type is
* <code>TYPE_FORWARD_ONLY</code> and the given fetch direction is not
* <code>FETCH_FORWARD</code> or (2) the given fetch direction is not
* one of the following:
* ResultSet.FETCH_FORWARD,
* ResultSet.FETCH_REVERSE, or
* ResultSet.FETCH_UNKNOWN
* @see #getFetchDirection
*/
public void setFetchDirection(int direction) throws SQLException {
// Changed the condition checking to the below as there were two
// conditions that had to be checked
// 1. RowSet is TYPE_FORWARD_ONLY and direction is not FETCH_FORWARD
// 2. Direction is not one of the valid values
if (((getType() == ResultSet.TYPE_FORWARD_ONLY) && (direction != ResultSet.FETCH_FORWARD)) ||
((direction != ResultSet.FETCH_FORWARD) &&
(direction != ResultSet.FETCH_REVERSE) &&
(direction != ResultSet.FETCH_UNKNOWN))) {
throw new SQLException("Invalid Fetch Direction");
}
fetchDir = direction;
}
/** {@collect.stats}
* Retrieves this <code>RowSet</code> object's current setting for the
* fetch direction. The default type is <code>ResultSet.FETCH_FORWARD</code>
*
* @return one of <code>ResultSet.FETCH_FORWARD</code>,
* <code>ResultSet.FETCH_REVERSE</code>, or
* <code>ResultSet.FETCH_UNKNOWN</code>
* @throws SQLException if an error occurs in determining the
* current fetch direction for fetching rows
* @see #setFetchDirection
*/
public int getFetchDirection() throws SQLException {
//Added the following code to throw a
//SQL Exception if the fetchDir is not
//set properly.Bug id:4914155
// This checking is not necessary!
/*
if((fetchDir != ResultSet.FETCH_FORWARD) &&
(fetchDir != ResultSet.FETCH_REVERSE) &&
(fetchDir != ResultSet.FETCH_UNKNOWN)) {
throw new SQLException("Fetch Direction Invalid");
}
*/
return (fetchDir);
}
/** {@collect.stats}
* Sets the fetch size for this <code>RowSet</code> object to the given number of
* rows. The fetch size gives a JDBC technology-enabled driver ("JDBC driver")
* a hint as to the
* number of rows that should be fetched from the database when more rows
* are needed for this <code>RowSet</code> object. If the fetch size specified
* is zero, the driver ignores the value and is free to make its own best guess
* as to what the fetch size should be.
* <P>
* A <code>RowSet</code> object inherits the default properties of the
* <code>ResultSet</code> object from which it got its data. That
* <code>ResultSet</code> object's default fetch size is set by
* the <code>Statement</code> object that created it.
* <P>
* This method applies to a <code>RowSet</code> object only while it is
* connected to a database using a JDBC driver.
* For connected <code>RowSet</code> implementations such as
* <code>JdbcRowSet</code>, this method has a direct and immediate effect
* on the underlying JDBC driver.
* <P>
* A <code>RowSet</code> object may use this method at any time to change
* its setting for the fetch size.
* <p>
* For <code>RowSet</code> implementations such as
* <code>CachedRowSet</code>, which operate in a disconnected environment,
* the <code>SyncProvider</code> object being used
* may leverage the fetch size to poll the data source and
* retrieve a number of rows that do not exceed the fetch size and that may
* form a subset of the actual rows returned by the original query. This is
* an implementation variance determined by the specific <code>SyncProvider</code>
* object employed by the disconnected <code>RowSet</code> object.
* <P>
*
* @param rows the number of rows to fetch; <code>0</code> to let the
* driver decide what the best fetch size is; must not be less
* than <code>0</code> or more than the maximum number of rows
* allowed for this <code>RowSet</code> object (the number returned
* by a call to the method {@link #getMaxRows})
* @throws SQLException if the specified fetch size is less than <code>0</code>
* or more than the limit for the maximum number of rows
* @see #getFetchSize
*/
public void setFetchSize(int rows) throws SQLException {
//Added this checking as maxRows can be 0 when this function is called
//maxRows = 0 means rowset can hold any number of rows, os this checking
// is needed to take care of this condition.
if (getMaxRows() == 0 && rows >= 0) {
fetchSize = rows;
return;
}
if ((rows < 0) || (rows > getMaxRows())) {
throw new SQLException("Invalid fetch size set. Cannot be of " +
"value: " + rows);
}
fetchSize = rows;
}
/** {@collect.stats}
* Returns the fetch size for this <code>RowSet</code> object. The default
* value is zero.
*
* @return the number of rows suggested as the fetch size when this <code>RowSet</code> object
* needs more rows from the database
* @throws SQLException if an error occurs determining the number of rows in the
* current fetch size
* @see #setFetchSize
*/
public int getFetchSize() throws SQLException {
return fetchSize;
}
/** {@collect.stats}
* Returns the concurrency for this <code>RowSet</code> object.
* The default is <code>CONCUR_UPDATABLE</code> for both connected and
* disconnected <code>RowSet</code> objects.
* <P>
* An application can call the method <code>setConcurrency</code> at any time
* to change a <code>RowSet</code> object's concurrency.
* <p>
* @return the concurrency type for this <code>RowSet</code>
* object, which must be one of the following:
* <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>
* @throws SQLException if an error occurs getting the concurrency
* of this <code>RowSet</code> object
* @see #setConcurrency
* @see #isReadOnly
*/
public int getConcurrency() throws SQLException {
return concurrency;
}
//-----------------------------------------------------------------------
// Parameters
//-----------------------------------------------------------------------
/** {@collect.stats}
* Checks the given index to see whether it is less than <code>1</code> and
* throws an <code>SQLException</code> object if it is.
* <P>
* This method is called by many methods internally; it is never
* called by an application directly.
*
* @param idx an <code>int</code> indicating which parameter is to be
* checked; the first parameter is <code>1</code>
* @throws SQLException if the parameter is less than <code>1</code>
*/
private void checkParamIndex(int idx) throws SQLException {
if ((idx < 1)) {
throw new SQLException("Invalid Parameter Index");
}
}
//---------------------------------------------------------------------
// setter methods for setting the parameters in a <code>RowSet</code> object's command
//---------------------------------------------------------------------
/** {@collect.stats}
* Sets the designated parameter to SQL <code>NULL</code>.
* Note that the parameter's SQL type must be specified using one of the
* type codes defined in <code>java.sql.Types</code>. This SQL type is
* specified in the second parameter.
* <p>
* Note that the second parameter tells the DBMS the data type of the value being
* set to <code>NULL</code>. Some DBMSs require this information, so it is required
* in order to make code more portable.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <P>
* Calls made to the method <code>getParams</code> after this version of
* <code>setNull</code>
* has been called will return an <code>Object</code> array containing the parameter values that
* have been set. In that array, the element that represents the values
* set with this method will itself be an array. The first element of that array
* is <code>null</code>.
* The second element is the value set for <i>sqlType</i>.
* The parameter number is indicated by an element's position in the array
* returned by the method <code>getParams</code>,
* with the first element being the value for the first placeholder parameter, the
* second element being the value for the second placeholder parameter, and so on.
* In other words, if the second placeholder parameter is being set to
* <code>null</code>, the array containing it will be the second element in
* the array returned by <code>getParams</code>.
* <P>
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param sqlType an <code>int</code> that is one of the SQL type codes
* defined in the class {@link java.sql.Types}. If a non-standard
* <i>sqlType</i> is supplied, this method will not throw a
* <code>SQLException</code>. This allows implicit support for
* non-standard SQL types.
* @throws SQLException if a database access error occurs or the given
* parameter index is out of bounds
* @see #getParams
*/
public void setNull(int parameterIndex, int sqlType) throws SQLException {
Object nullVal[];
checkParamIndex(parameterIndex);
nullVal = new Object[2];
nullVal[0] = null;
nullVal[1] = new Integer(sqlType);
if (params == null){
throw new SQLException("Set initParams() before setNull");
}
params.put(new Integer(parameterIndex - 1), nullVal);
}
/** {@collect.stats}
* Sets the designated parameter to SQL <code>NULL</code>.
*
* Although this version of the method <code>setNull</code> is intended
* for user-defined
* and <code>REF</code> parameters, this method may be used to set a null
* parameter for any JDBC type. The following are user-defined types:
* <code>STRUCT</code>, <code>DISTINCT</code>, and <code>JAVA_OBJECT</code>,
* and named array types.
*
* <P><B>Note:</B> To be portable, applications must give the
* SQL type code and the fully qualified SQL type name when specifying
* a <code>NULL</code> user-defined or <code>REF</code> parameter.
* In the case of a user-defined type, the name is the type name of
* the parameter itself. For a <code>REF</code> parameter, the name is
* the type name of the referenced type. If a JDBC technology-enabled
* driver does not need the type code or type name information,
* it may ignore it.
* <P>
* If the parameter does not have a user-defined or <code>REF</code> type,
* the given <code>typeName</code> parameter is ignored.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <P>
* Calls made to the method <code>getParams</code> after this version of
* <code>setNull</code>
* has been called will return an <code>Object</code> array containing the parameter values that
* have been set. In that array, the element that represents the values
* set with this method will itself be an array. The first element of that array
* is <code>null</code>.
* The second element is the value set for <i>sqlType</i>, and the third
* element is the value set for <i>typeName</i>.
* The parameter number is indicated by an element's position in the array
* returned by the method <code>getParams</code>,
* with the first element being the value for the first placeholder parameter, the
* second element being the value for the second placeholder parameter, and so on.
* In other words, if the second placeholder parameter is being set to
* <code>null</code>, the array containing it will be the second element in
* the array returned by <code>getParams</code>.
* <P>
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param sqlType a value from <code>java.sql.Types</code>
* @param typeName the fully qualified name of an SQL user-defined type,
* which is ignored if the parameter is not a user-defined
* type or <code>REF</code> value
* @throws SQLException if an error occurs or the given parameter index
* is out of bounds
* @see #getParams
*/
public void setNull(int parameterIndex, int sqlType, String typeName)
throws SQLException {
Object nullVal[];
checkParamIndex(parameterIndex);
nullVal = new Object[3];
nullVal[0] = null;
nullVal[1] = new Integer(sqlType);
nullVal[2] = new String(typeName);
if(params == null){
throw new SQLException("Set initParams() before setNull");
}
params.put(new Integer(parameterIndex - 1), nullVal);
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>boolean</code> in the
* Java programming language. The driver converts this to an SQL
* <code>BIT</code> value when it sends it to the database.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code>, <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <p>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the parameter value
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
checkParamIndex(parameterIndex);
if(params == null){
throw new SQLException("Set initParams() before setNull");
}
params.put(new Integer(parameterIndex - 1), new Boolean(x));
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>byte</code> in the Java
* programming language. The driver converts this to an SQL
* <code>TINYINT</code> value when it sends it to the database.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <p>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the parameter value
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setByte(int parameterIndex, byte x) throws SQLException {
checkParamIndex(parameterIndex);
if(params == null){
throw new SQLException("Set initParams() before setByte");
}
params.put(new Integer(parameterIndex - 1), new Byte(x));
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>short</code> in the
* Java programming language. The driver converts this to an SQL
* <code>SMALLINT</code> value when it sends it to the database.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <p>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <p>
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the parameter value
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setShort(int parameterIndex, short x) throws SQLException {
checkParamIndex(parameterIndex);
if(params == null){
throw new SQLException("Set initParams() before setShort");
}
params.put(new Integer(parameterIndex - 1), new Short(x));
}
/** {@collect.stats}
* Sets the designated parameter to an <code>int</code> in the Java
* programming language. The driver converts this to an SQL
* <code>INTEGER</code> value when it sends it to the database.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the parameter value
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setInt(int parameterIndex, int x) throws SQLException {
checkParamIndex(parameterIndex);
if(params == null){
throw new SQLException("Set initParams() before setInt");
}
params.put(new Integer(parameterIndex - 1), new Integer(x));
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>long</code> in the Java
* programming language. The driver converts this to an SQL
* <code>BIGINT</code> value when it sends it to the database.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the parameter value
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setLong(int parameterIndex, long x) throws SQLException {
checkParamIndex(parameterIndex);
if(params == null){
throw new SQLException("Set initParams() before setLong");
}
params.put(new Integer(parameterIndex - 1), new Long(x));
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>float</code> in the
* Java programming language. The driver converts this to an SQL
* <code>FLOAT</code> value when it sends it to the database.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the parameter value
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setFloat(int parameterIndex, float x) throws SQLException {
checkParamIndex(parameterIndex);
if(params == null){
throw new SQLException("Set initParams() before setFloat");
}
params.put(new Integer(parameterIndex - 1), new Float(x));
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>double</code> in the
* Java programming language. The driver converts this to an SQL
* <code>DOUBLE</code> value when it sends it to the database.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* S
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the parameter value
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setDouble(int parameterIndex, double x) throws SQLException {
checkParamIndex(parameterIndex);
if(params == null){
throw new SQLException("Set initParams() before setDouble");
}
params.put(new Integer(parameterIndex - 1), new Double(x));
}
/** {@collect.stats}
* Sets the designated parameter to the given
* <code>java.lang.BigDecimal</code> value. The driver converts this to
* an SQL <code>NUMERIC</code> value when it sends it to the database.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* Note: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the parameter value
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setBigDecimal(int parameterIndex, java.math.BigDecimal x) throws SQLException {
checkParamIndex(parameterIndex);
if(params == null){
throw new SQLException("Set initParams() before setBigDecimal");
}
params.put(new Integer(parameterIndex - 1), x);
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>String</code>
* value. The driver converts this to an SQL
* <code>VARCHAR</code> or <code>LONGVARCHAR</code> value
* (depending on the argument's size relative to the driver's limits
* on <code>VARCHAR</code> values) when it sends it to the database.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <p>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <p>
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the parameter value
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setString(int parameterIndex, String x) throws SQLException {
checkParamIndex(parameterIndex);
if(params == null){
throw new SQLException("Set initParams() before setString");
}
params.put(new Integer(parameterIndex - 1), x);
}
/** {@collect.stats}
* Sets the designated parameter to the given array of bytes.
* The driver converts this to an SQL
* <code>VARBINARY</code> or <code>LONGVARBINARY</code> value
* (depending on the argument's size relative to the driver's limits
* on <code>VARBINARY</code> values) when it sends it to the database.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <p>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the parameter value
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setBytes(int parameterIndex, byte x[]) throws SQLException {
checkParamIndex(parameterIndex);
if(params == null){
throw new SQLException("Set initParams() before setBytes");
}
params.put(new Integer(parameterIndex - 1), x);
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.Date</code>
* value. The driver converts this to an SQL
* <code>DATE</code> value when it sends it to the database.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <P>
* Calls made to the method <code>getParams</code> after this version
* of <code>setDate</code>
* has been called will return an array with the value to be set for
* placeholder parameter number <i>parameterIndex</i> being the <code>Date</code>
* object supplied as the second parameter.
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the parameter value
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setDate(int parameterIndex, java.sql.Date x) throws SQLException {
checkParamIndex(parameterIndex);
if(params == null){
throw new SQLException("Set initParams() before setDate");
}
params.put(new Integer(parameterIndex - 1), x);
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.Time</code>
* value. The driver converts this to an SQL <code>TIME</code> value
* when it sends it to the database.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <P>
* Calls made to the method <code>getParams</code> after this version
* of the method <code>setTime</code>
* has been called will return an array of the parameters that have been set.
* The parameter to be set for parameter placeholder number <i>parameterIndex</i>
* will be the <code>Time</code> object that was set as the second parameter
* to this method.
* <P>
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x a <code>java.sql.Time</code> object, which is to be set as the value
* for placeholder parameter <i>parameterIndex</i>
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setTime(int parameterIndex, java.sql.Time x) throws SQLException {
checkParamIndex(parameterIndex);
if(params == null){
throw new SQLException("Set initParams() before setTime");
}
params.put(new Integer(parameterIndex - 1), x);
}
/** {@collect.stats}
* Sets the designated parameter to the given
* <code>java.sql.Timestamp</code> value.
* The driver converts this to an SQL <code>TIMESTAMP</code> value when it
* sends it to the database.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <P>
* Calls made to the method <code>getParams</code> after this version of
* <code>setTimestamp</code>
* has been called will return an array with the value for parameter placeholder
* number <i>parameterIndex</i> being the <code>Timestamp</code> object that was
* supplied as the second parameter to this method.
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x a <code>java.sql.Timestamp</code> object
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setTimestamp(int parameterIndex, java.sql.Timestamp x) throws SQLException {
checkParamIndex(parameterIndex);
if(params == null){
throw new SQLException("Set initParams() before setTimestamp");
}
params.put(new Integer(parameterIndex - 1), x);
}
/** {@collect.stats}
* Sets the designated parameter to the given
* <code>java.io.InputStream</code> object,
* which will have the specified number of bytes.
* The contents of the stream will be read and sent to the database.
* This method throws an <code>SQLException</code> object if the number of bytes
* read and sent to the database is not equal to <i>length</i>.
* <P>
* When a very large ASCII value is input to a <code>LONGVARCHAR</code>
* parameter, it may be more practical to send it via a
* <code>java.io.InputStream</code> object. A JDBC technology-enabled
* driver will read the data from the stream as needed until it reaches
* end-of-file. The driver will do any necessary conversion from ASCII to
* the database <code>CHAR</code> format.
*
* <P><B>Note:</B> This stream object can be either a standard
* Java stream object or your own subclass that implements the
* standard interface.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* Note: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <P>
* Calls made to the method <code>getParams</code> after <code>setAsciiStream</code>
* has been called will return an array containing the parameter values that
* have been set. The element in the array that represents the values
* set with this method will itself be an array. The first element of that array
* is the given <code>java.io.InputStream</code> object.
* The second element is the value set for <i>length</i>.
* The third element is an internal <code>BaseRowSet</code> constant
* specifying that the stream passed to this method is an ASCII stream.
* The parameter number is indicated by an element's position in the array
* returned by the method <code>getParams</code>,
* with the first element being the value for the first placeholder parameter, the
* second element being the value for the second placeholder parameter, and so on.
* In other words, if the input stream being set is the value for the second
* placeholder parameter, the array containing it will be the second element in
* the array returned by <code>getParams</code>.
* <P>
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is element number <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the Java input stream that contains the ASCII parameter value
* @param length the number of bytes in the stream. This is the number of bytes
* the driver will send to the DBMS; lengths of 0 or less are
* are undefined but will cause an invalid length exception to be
* thrown in the underlying JDBC driver.
* @throws SQLException if an error occurs, the parameter index is out of bounds,
* or when connected to a data source, the number of bytes the driver reads
* and sends to the database is not equal to the number of bytes specified
* in <i>length</i>
* @see #getParams
*/
public void setAsciiStream(int parameterIndex, java.io.InputStream x, int length) throws SQLException {
Object asciiStream[];
checkParamIndex(parameterIndex);
asciiStream = new Object[3];
asciiStream[0] = x;
asciiStream[1] = new Integer(length);
asciiStream[2] = new Integer(ASCII_STREAM_PARAM);
if(params == null){
throw new SQLException("Set initParams() before setAsciiStream");
}
params.put(new Integer(parameterIndex - 1), asciiStream);
}
/** {@collect.stats}
* Sets the designated parameter in this <code>RowSet</code> object's command
* to the given input stream.
* When a very large ASCII value is input to a <code>LONGVARCHAR</code>
* parameter, it may be more practical to send it via a
* <code>java.io.InputStream</code>. Data will be read from the stream
* as needed until end-of-file is reached. The JDBC driver will
* do any necessary conversion from ASCII to the database char format.
*
* <P><B>Note:</B> This stream object can either be a standard
* Java stream object or your own subclass that implements the
* standard interface.
* <P><B>Note:</B> Consult your JDBC driver documentation to determine if
* it might be more efficient to use a version of
* <code>setAsciiStream</code> which takes a length parameter.
*
* @param parameterIndex the first parameter is 1, the second is 2, ...
* @param x the Java input stream that contains the ASCII parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>PreparedStatement</code>
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
* @since 1.6
*/
public void setAsciiStream(int parameterIndex, java.io.InputStream x)
throws SQLException {
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.io.InputStream</code>
* object, which will have the specified number of bytes.
* The contents of the stream will be read and sent to the database.
* This method throws an <code>SQLException</code> object if the number of bytes
* read and sent to the database is not equal to <i>length</i>.
* <P>
* When a very large binary value is input to a
* <code>LONGVARBINARY</code> parameter, it may be more practical
* to send it via a <code>java.io.InputStream</code> object.
* A JDBC technology-enabled driver will read the data from the
* stream as needed until it reaches end-of-file.
*
* <P><B>Note:</B> This stream object can be either a standard
* Java stream object or your own subclass that implements the
* standard interface.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
*<P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <P>
* Calls made to the method <code>getParams</code> after <code>setBinaryStream</code>
* has been called will return an array containing the parameter values that
* have been set. In that array, the element that represents the values
* set with this method will itself be an array. The first element of that array
* is the given <code>java.io.InputStream</code> object.
* The second element is the value set for <i>length</i>.
* The third element is an internal <code>BaseRowSet</code> constant
* specifying that the stream passed to this method is a binary stream.
* The parameter number is indicated by an element's position in the array
* returned by the method <code>getParams</code>,
* with the first element being the value for the first placeholder parameter, the
* second element being the value for the second placeholder parameter, and so on.
* In other words, if the input stream being set is the value for the second
* placeholder parameter, the array containing it will be the second element in
* the array returned by <code>getParams</code>.
* <P>
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is element number <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the input stream that contains the binary value to be set
* @param length the number of bytes in the stream; lengths of 0 or less are
* are undefined but will cause an invalid length exception to be
* thrown in the underlying JDBC driver.
* @throws SQLException if an error occurs, the parameter index is out of bounds,
* or when connected to a data source, the number of bytes the driver
* reads and sends to the database is not equal to the number of bytes
* specified in <i>length</i>
* @see #getParams
*/
public void setBinaryStream(int parameterIndex, java.io.InputStream x, int length) throws SQLException {
Object binaryStream[];
checkParamIndex(parameterIndex);
binaryStream = new Object[3];
binaryStream[0] = x;
binaryStream[1] = new Integer(length);
binaryStream[2] = new Integer(BINARY_STREAM_PARAM);
if(params == null){
throw new SQLException("Set initParams() before setBinaryStream");
}
params.put(new Integer(parameterIndex - 1), binaryStream);
}
/** {@collect.stats}
* Sets the designated parameter in this <code>RowSet</code> object's command
* to the given input stream.
* When a very large binary value is input to a <code>LONGVARBINARY</code>
* parameter, it may be more practical to send it via a
* <code>java.io.InputStream</code> object. The data will be read from the
* stream as needed until end-of-file is reached.
*
* <P><B>Note:</B> This stream object can either be a standard
* Java stream object or your own subclass that implements the
* standard interface.
* <P><B>Note:</B> Consult your JDBC driver documentation to determine if
* it might be more efficient to use a version of
* <code>setBinaryStream</code> which takes a length parameter.
*
* @param parameterIndex the first parameter is 1, the second is 2, ...
* @param x the java input stream which contains the binary parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>PreparedStatement</code>
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
* @since 1.6
*/
public void setBinaryStream(int parameterIndex, java.io.InputStream x)
throws SQLException {
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given
* <code>java.io.InputStream</code> object, which will have the specified
* number of bytes. The contents of the stream will be read and sent
* to the database.
* This method throws an <code>SQLException</code> if the number of bytes
* read and sent to the database is not equal to <i>length</i>.
* <P>
* When a very large Unicode value is input to a
* <code>LONGVARCHAR</code> parameter, it may be more practical
* to send it via a <code>java.io.InputStream</code> object.
* A JDBC technology-enabled driver will read the data from the
* stream as needed, until it reaches end-of-file.
* The driver will do any necessary conversion from Unicode to the
* database <code>CHAR</code> format.
* The byte format of the Unicode stream must be Java UTF-8, as
* defined in the Java Virtual Machine Specification.
*
* <P><B>Note:</B> This stream object can be either a standard
* Java stream object or your own subclass that implements the
* standard interface.
* <P>
* This method is deprecated; the method <code>getCharacterStream</code>
* should be used in its place.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Calls made to the method <code>getParams</code> after <code>setUnicodeStream</code>
* has been called will return an array containing the parameter values that
* have been set. In that array, the element that represents the values
* set with this method will itself be an array. The first element of that array
* is the given <code>java.io.InputStream</code> object.
* The second element is the value set for <i>length</i>.
* The third element is an internal <code>BaseRowSet</code> constant
* specifying that the stream passed to this method is a Unicode stream.
* The parameter number is indicated by an element's position in the array
* returned by the method <code>getParams</code>,
* with the first element being the value for the first placeholder parameter, the
* second element being the value for the second placeholder parameter, and so on.
* In other words, if the input stream being set is the value for the second
* placeholder parameter, the array containing it will be the second element in
* the array returned by <code>getParams</code>.
* <P>
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is element number <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the <code>java.io.InputStream</code> object that contains the
* UNICODE parameter value
* @param length the number of bytes in the input stream
* @throws SQLException if an error occurs, the parameter index is out of bounds,
* or the number of bytes the driver reads and sends to the database is
* not equal to the number of bytes specified in <i>length</i>
* @deprecated getCharacterStream should be used in its place
* @see #getParams
*/
public void setUnicodeStream(int parameterIndex, java.io.InputStream x, int length) throws SQLException {
Object unicodeStream[];
checkParamIndex(parameterIndex);
unicodeStream = new Object[3];
unicodeStream[0] = x;
unicodeStream[1] = new Integer(length);
unicodeStream[2] = new Integer(UNICODE_STREAM_PARAM);
if(params == null){
throw new SQLException("Set initParams() before setUnicodeStream");
}
params.put(new Integer(parameterIndex - 1), unicodeStream);
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.io.Reader</code>
* object, which will have the specified number of characters. The
* contents of the reader will be read and sent to the database.
* This method throws an <code>SQLException</code> if the number of bytes
* read and sent to the database is not equal to <i>length</i>.
* <P>
* When a very large Unicode value is input to a
* <code>LONGVARCHAR</code> parameter, it may be more practical
* to send it via a <code>Reader</code> object.
* A JDBC technology-enabled driver will read the data from the
* stream as needed until it reaches end-of-file.
* The driver will do any necessary conversion from Unicode to the
* database <code>CHAR</code> format.
* The byte format of the Unicode stream must be Java UTF-8, as
* defined in the Java Virtual Machine Specification.
*
* <P><B>Note:</B> This stream object can be either a standard
* Java stream object or your own subclass that implements the
* standard interface.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <P>
* Calls made to the method <code>getParams</code> after
* <code>setCharacterStream</code>
* has been called will return an array containing the parameter values that
* have been set. In that array, the element that represents the values
* set with this method will itself be an array. The first element of that array
* is the given <code>java.io.Reader</code> object.
* The second element is the value set for <i>length</i>.
* The parameter number is indicated by an element's position in the array
* returned by the method <code>getParams</code>,
* with the first element being the value for the first placeholder parameter, the
* second element being the value for the second placeholder parameter, and so on.
* In other words, if the reader being set is the value for the second
* placeholder parameter, the array containing it will be the second element in
* the array returned by <code>getParams</code>.
* <P>
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is element number <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param reader the <code>Reader</code> object that contains the
* Unicode data
* @param length the number of characters in the stream; lengths of 0 or
* less are undefined but will cause an invalid length exception to
* be thrown in the underlying JDBC driver.
* @throws SQLException if an error occurs, the parameter index is out of bounds,
* or when connected to a data source, the number of bytes the driver
* reads and sends to the database is not equal to the number of bytes
* specified in <i>length</i>
* @see #getParams
*/
public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
Object charStream[];
checkParamIndex(parameterIndex);
charStream = new Object[2];
charStream[0] = reader;
charStream[1] = new Integer(length);
if(params == null){
throw new SQLException("Set initParams() before setCharacterStream");
}
params.put(new Integer(parameterIndex - 1), charStream);
}
/** {@collect.stats}
* Sets the designated parameter in this <code>RowSet</code> object's command
* to the given <code>Reader</code>
* object.
* When a very large UNICODE value is input to a <code>LONGVARCHAR</code>
* parameter, it may be more practical to send it via a
* <code>java.io.Reader</code> object. The data will be read from the stream
* as needed until end-of-file is reached. The JDBC driver will
* do any necessary conversion from UNICODE to the database char format.
*
* <P><B>Note:</B> This stream object can either be a standard
* Java stream object or your own subclass that implements the
* standard interface.
* <P><B>Note:</B> Consult your JDBC driver documentation to determine if
* it might be more efficient to use a version of
* <code>setCharacterStream</code> which takes a length parameter.
*
* @param parameterIndex the first parameter is 1, the second is 2, ...
* @param reader the <code>java.io.Reader</code> object that contains the
* Unicode data
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>PreparedStatement</code>
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
* @since 1.6
*/
public void setCharacterStream(int parameterIndex,
java.io.Reader reader) throws SQLException {
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to an <code>Object</code> in the Java
* programming language. The second parameter must be an
* <code>Object</code> type. For integral values, the
* <code>java.lang</code> equivalent
* objects should be used. For example, use the class <code>Integer</code>
* for an <code>int</code>.
* <P>
* The driver converts this object to the specified
* target SQL type before sending it to the database.
* If the object has a custom mapping (is of a class implementing
* <code>SQLData</code>), the driver should call the method
* <code>SQLData.writeSQL</code> to write the object to the SQL
* data stream. If, on the other hand, the object is of a class
* implementing <code>Ref</code>, <code>Blob</code>, <code>Clob</code>,
* <code>Struct</code>, or <code>Array</code>,
* the driver should pass it to the database as a value of the
* corresponding SQL type.
* <P>
* <p>Note that this method may be used to pass database-
* specific abstract data types.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <P>
* Calls made to the method <code>getParams</code> after this version of
* <code>setObject</code>
* has been called will return an array containing the parameter values that
* have been set. In that array, the element that represents the values
* set with this method will itself be an array. The first element of that array
* is the given <code>Object</code> instance, and the
* second element is the value set for <i>targetSqlType</i>. The
* third element is the value set for <i>scale</i>, which the driver will
* ignore if the type of the object being set is not
* <code>java.sql.Types.NUMERIC</code> or <code>java.sql.Types.DECIMAL</code>.
* The parameter number is indicated by an element's position in the array
* returned by the method <code>getParams</code>,
* with the first element being the value for the first placeholder parameter, the
* second element being the value for the second placeholder parameter, and so on.
* In other words, if the object being set is the value for the second
* placeholder parameter, the array containing it will be the second element in
* the array returned by <code>getParams</code>.
*<P>
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is element number <i>parameterIndex</i> -1.
*
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the <code>Object</code> containing the input parameter value;
* must be an <code>Object</code> type
* @param targetSqlType the SQL type (as defined in <code>java.sql.Types</code>)
* to be sent to the database. The <code>scale</code> argument may
* further qualify this type. If a non-standard <i>targetSqlType</i>
* is supplied, this method will not throw a <code>SQLException</code>.
* This allows implicit support for non-standard SQL types.
* @param scale for the types <code>java.sql.Types.DECIMAL</code> and
* <code>java.sql.Types.NUMERIC</code>, this is the number
* of digits after the decimal point. For all other types, this
* value will be ignored.
* @throws SQLException if an error occurs or the parameter index is out of bounds
* @see #getParams
*/
public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException {
Object obj[];
checkParamIndex(parameterIndex);
obj = new Object[3];
obj[0] = x;
obj[1] = new Integer(targetSqlType);
obj[2] = new Integer(scale);
if(params == null){
throw new SQLException("Set initParams() before setObject");
}
params.put(new Integer(parameterIndex - 1), obj);
}
/** {@collect.stats}
* Sets the value of the designated parameter with the given
* <code>Object</code> value.
* This method is like <code>setObject(int parameterIndex, Object x, int
* targetSqlType, int scale)</code> except that it assumes a scale of zero.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <P>
* Calls made to the method <code>getParams</code> after this version of
* <code>setObject</code>
* has been called will return an array containing the parameter values that
* have been set. In that array, the element that represents the values
* set with this method will itself be an array. The first element of that array
* is the given <code>Object</code> instance.
* The second element is the value set for <i>targetSqlType</i>.
* The parameter number is indicated by an element's position in the array
* returned by the method <code>getParams</code>,
* with the first element being the value for the first placeholder parameter, the
* second element being the value for the second placeholder parameter, and so on.
* In other words, if the object being set is the value for the second
* placeholder parameter, the array containing it will be the second element in
* the array returned by <code>getParams</code>.
* <P>
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is element number <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the <code>Object</code> containing the input parameter value;
* must be an <code>Object</code> type
* @param targetSqlType the SQL type (as defined in <code>java.sql.Types</code>)
* to be sent to the database. If a non-standard <i>targetSqlType</i>
* is supplied, this method will not throw a <code>SQLException</code>.
* This allows implicit support for non-standard SQL types.
* @throws SQLException if an error occurs or the parameter index
* is out of bounds
* @see #getParams
*/
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
Object obj[];
checkParamIndex(parameterIndex);
obj = new Object[2];
obj[0] = x;
obj[1] = new Integer(targetSqlType);
if (params == null){
throw new SQLException("Set initParams() before setObject");
}
params.put(new Integer(parameterIndex - 1), obj);
}
/** {@collect.stats}
* Sets the designated parameter to an <code>Object</code> in the Java
* programming language. The second parameter must be an
* <code>Object</code>
* type. For integral values, the <code>java.lang</code> equivalent
* objects should be used. For example, use the class <code>Integer</code>
* for an <code>int</code>.
* <P>
* The JDBC specification defines a standard mapping from
* Java <code>Object</code> types to SQL types. The driver will
* use this standard mapping to convert the given object
* to its corresponding SQL type before sending it to the database.
* If the object has a custom mapping (is of a class implementing
* <code>SQLData</code>), the driver should call the method
* <code>SQLData.writeSQL</code> to write the object to the SQL
* data stream.
* <P>
* If, on the other hand, the object is of a class
* implementing <code>Ref</code>, <code>Blob</code>, <code>Clob</code>,
* <code>Struct</code>, or <code>Array</code>,
* the driver should pass it to the database as a value of the
* corresponding SQL type.
* <P>
* This method throws an exception if there
* is an ambiguity, for example, if the object is of a class
* implementing more than one interface.
* <P>
* Note that this method may be used to pass database-specific
* abstract data types.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <p>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <P>
* After this method has been called, a call to the
* method <code>getParams</code>
* will return an object array of the current command parameters, which will
* include the <code>Object</code> set for placeholder parameter number
* <code>parameterIndex</code>.
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is element number <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x the object containing the input parameter value
* @throws SQLException if an error occurs the
* parameter index is out of bounds, or there
* is ambiguity in the implementation of the
* object being set
* @see #getParams
*/
public void setObject(int parameterIndex, Object x) throws SQLException {
checkParamIndex(parameterIndex);
if (params == null) {
throw new SQLException("Set initParams() before setObject");
}
params.put(new Integer(parameterIndex - 1), x);
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>Ref</code> object in
* the Java programming language. The driver converts this to an SQL
* <code>REF</code> value when it sends it to the database. Internally, the
* <code>Ref</code> is represented as a <code>SerialRef</code> to ensure
* serializability.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <p>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <p>
* After this method has been called, a call to the
* method <code>getParams</code>
* will return an object array of the current command parameters, which will
* include the <code>Ref</code> object set for placeholder parameter number
* <code>parameterIndex</code>.
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is element number <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param ref a <code>Ref</code> object representing an SQL <code>REF</code>
* value; cannot be null
* @throws SQLException if an error occurs; the parameter index is out of
* bounds or the <code>Ref</code> object is <code>null</code>; or
* the <code>Ref</code> object returns a <code>null</code> base type
* name.
* @see #getParams
* @see javax.sql.rowset.serial.SerialRef
*/
public void setRef (int parameterIndex, Ref ref) throws SQLException {
checkParamIndex(parameterIndex);
if (params == null) {
throw new SQLException("Set initParams() before setRef");
}
params.put(new Integer(parameterIndex - 1), new SerialRef(ref));
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>Blob</code> object in
* the Java programming language. The driver converts this to an SQL
* <code>BLOB</code> value when it sends it to the database. Internally,
* the <code>Blob</code> is represented as a <code>SerialBlob</code>
* to ensure serializability.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <p>
* After this method has been called, a call to the
* method <code>getParams</code>
* will return an object array of the current command parameters, which will
* include the <code>Blob</code> object set for placeholder parameter number
* <code>parameterIndex</code>.
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is element number <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x a <code>Blob</code> object representing an SQL
* <code>BLOB</code> value
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
* @see javax.sql.rowset.serial.SerialBlob
*/
public void setBlob (int parameterIndex, Blob x) throws SQLException {
checkParamIndex(parameterIndex);
if(params == null){
throw new SQLException("Set initParams() before setBlob");
}
params.put(new Integer(parameterIndex - 1), new SerialBlob(x));
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>Clob</code> object in
* the Java programming language. The driver converts this to an SQL
* <code>CLOB</code> value when it sends it to the database. Internally, the
* <code>Clob</code> is represented as a <code>SerialClob</code> to ensure
* serializability.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <p>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <p>
* After this method has been called, a call to the
* method <code>getParams</code>
* will return an object array of the current command parameters, which will
* include the <code>Clob</code> object set for placeholder parameter number
* <code>parameterIndex</code>.
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is element number <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x a <code>Clob</code> object representing an SQL
* <code>CLOB</code> value; cannot be null
* @throws SQLException if an error occurs; the parameter index is out of
* bounds or the <code>Clob</code> is null
* @see #getParams
* @see javax.sql.rowset.serial.SerialBlob
*/
public void setClob (int parameterIndex, Clob x) throws SQLException {
checkParamIndex(parameterIndex);
if(params == null){
throw new SQLException("Set initParams() before setClob");
}
params.put(new Integer(parameterIndex - 1), new SerialClob(x));
}
/** {@collect.stats}
* Sets the designated parameter to an <code>Array</code> object in the
* Java programming language. The driver converts this to an SQL
* <code>ARRAY</code> value when it sends it to the database. Internally,
* the <code>Array</code> is represented as a <code>SerialArray</code>
* to ensure serializability.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* Note: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <p>
* After this method has been called, a call to the
* method <code>getParams</code>
* will return an object array of the current command parameters, which will
* include the <code>Array</code> object set for placeholder parameter number
* <code>parameterIndex</code>.
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is element number <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param array an <code>Array</code> object representing an SQL
* <code>ARRAY</code> value; cannot be null. The <code>Array</code> object
* passed to this method must return a non-null Object for all
* <code>getArray()</code> method calls. A null value will cause a
* <code>SQLException</code> to be thrown.
* @throws SQLException if an error occurs; the parameter index is out of
* bounds or the <code>ARRAY</code> is null
* @see #getParams
* @see javax.sql.rowset.serial.SerialArray
*/
public void setArray (int parameterIndex, Array array) throws SQLException {
checkParamIndex(parameterIndex);
if (params == null){
throw new SQLException("Set initParams() before setArray");
}
params.put(new Integer(parameterIndex - 1), new SerialArray(array));
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.Date</code>
* object.
* When the DBMS does not store time zone information, the driver will use
* the given <code>Calendar</code> object to construct the SQL <code>DATE</code>
* value to send to the database. With a
* <code>Calendar</code> object, the driver can calculate the date
* taking into account a custom time zone. If no <code>Calendar</code>
* object is specified, the driver uses the time zone of the Virtual Machine
* that is running the application.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <P>
* Calls made to the method <code>getParams</code> after this version of
* <code>setDate</code>
* has been called will return an array containing the parameter values that
* have been set. In that array, the element that represents the values
* set with this method will itself be an array. The first element of that array
* is the given <code>java.sql.Date</code> object.
* The second element is the value set for <i>cal</i>.
* The parameter number is indicated by an element's position in the array
* returned by the method <code>getParams</code>,
* with the first element being the value for the first placeholder parameter, the
* second element being the value for the second placeholder parameter, and so on.
* In other words, if the date being set is the value for the second
* placeholder parameter, the array containing it will be the second element in
* the array returned by <code>getParams</code>.
* <P>
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x a <code>java.sql.Date</code> object representing an SQL
* <code>DATE</code> value
* @param cal a <code>java.util.Calendar</code> object to use when
* when constructing the date
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setDate(int parameterIndex, java.sql.Date x, Calendar cal) throws SQLException {
Object date[];
checkParamIndex(parameterIndex);
date = new Object[2];
date[0] = x;
date[1] = cal;
if(params == null){
throw new SQLException("Set initParams() before setDate");
}
params.put(new Integer(parameterIndex - 1), date);
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.Time</code>
* object. The driver converts this
* to an SQL <code>TIME</code> value when it sends it to the database.
* <P>
* When the DBMS does not store time zone information, the driver will use
* the given <code>Calendar</code> object to construct the SQL <code>TIME</code>
* value to send to the database. With a
* <code>Calendar</code> object, the driver can calculate the date
* taking into account a custom time zone. If no <code>Calendar</code>
* object is specified, the driver uses the time zone of the Virtual Machine
* that is running the application.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <P>
* Calls made to the method <code>getParams</code> after this version of
* <code>setTime</code>
* has been called will return an array containing the parameter values that
* have been set. In that array, the element that represents the values
* set with this method will itself be an array. The first element of that array
* is the given <code>java.sql.Time</code> object.
* The second element is the value set for <i>cal</i>.
* The parameter number is indicated by an element's position in the array
* returned by the method <code>getParams</code>,
* with the first element being the value for the first placeholder parameter, the
* second element being the value for the second placeholder parameter, and so on.
* In other words, if the time being set is the value for the second
* placeholder parameter, the array containing it will be the second element in
* the array returned by <code>getParams</code>.
* <P>
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x a <code>java.sql.Time</code> object
* @param cal the <code>java.util.Calendar</code> object the driver can use to
* construct the time
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setTime(int parameterIndex, java.sql.Time x, Calendar cal) throws SQLException {
Object time[];
checkParamIndex(parameterIndex);
time = new Object[2];
time[0] = x;
time[1] = cal;
if(params == null){
throw new SQLException("Set initParams() before setTime");
}
params.put(new Integer(parameterIndex - 1), time);
}
/** {@collect.stats}
* Sets the designated parameter to the given
* <code>java.sql.Timestamp</code> object. The driver converts this
* to an SQL <code>TIMESTAMP</code> value when it sends it to the database.
* <P>
* When the DBMS does not store time zone information, the driver will use
* the given <code>Calendar</code> object to construct the SQL <code>TIMESTAMP</code>
* value to send to the database. With a
* <code>Calendar</code> object, the driver can calculate the timestamp
* taking into account a custom time zone. If no <code>Calendar</code>
* object is specified, the driver uses the time zone of the Virtual Machine
* that is running the application.
* <P>
* The parameter value set by this method is stored internally and
* will be supplied as the appropriate parameter in this <code>RowSet</code>
* object's command when the method <code>execute</code> is called.
* Methods such as <code>execute</code> and <code>populate</code> must be
* provided in any class that extends this class and implements one or
* more of the standard JSR-114 <code>RowSet</code> interfaces.
* <P>
* NOTE: <code>JdbcRowSet</code> does not require the <code>populate</code> method
* as it is undefined in this class.
* <P>
* Calls made to the method <code>getParams</code> after this version of
* <code>setTimestamp</code>
* has been called will return an array containing the parameter values that
* have been set. In that array, the element that represents the values
* set with this method will itself be an array. The first element of that array
* is the given <code>java.sql.Timestamp</code> object.
* The second element is the value set for <i>cal</i>.
* The parameter number is indicated by an element's position in the array
* returned by the method <code>getParams</code>,
* with the first element being the value for the first placeholder parameter, the
* second element being the value for the second placeholder parameter, and so on.
* In other words, if the timestamp being set is the value for the second
* placeholder parameter, the array containing it will be the second element in
* the array returned by <code>getParams</code>.
* <P>
* Note that because the numbering of elements in an array starts at zero,
* the array element that corresponds to placeholder parameter number
* <i>parameterIndex</i> is <i>parameterIndex</i> -1.
*
* @param parameterIndex the ordinal number of the placeholder parameter
* in this <code>RowSet</code> object's command that is to be set.
* The first parameter is 1, the second is 2, and so on; must be
* <code>1</code> or greater
* @param x a <code>java.sql.Timestamp</code> object
* @param cal the <code>java.util.Calendar</code> object the driver can use to
* construct the timestamp
* @throws SQLException if an error occurs or the
* parameter index is out of bounds
* @see #getParams
*/
public void setTimestamp(int parameterIndex, java.sql.Timestamp x, Calendar cal) throws SQLException {
Object timestamp[];
checkParamIndex(parameterIndex);
timestamp = new Object[2];
timestamp[0] = x;
timestamp[1] = cal;
if(params == null){
throw new SQLException("Set initParams() before setTimestamp");
}
params.put(new Integer(parameterIndex - 1), timestamp);
}
/** {@collect.stats}
* Clears all of the current parameter values in this <code>RowSet</code>
* object's internal representation of the parameters to be set in
* this <code>RowSet</code> object's command when it is executed.
* <P>
* In general, parameter values remain in force for repeated use in
* this <code>RowSet</code> object's command. Setting a parameter value with the
* setter methods automatically clears the value of the
* designated parameter and replaces it with the new specified value.
* <P>
* This method is called internally by the <code>setCommand</code>
* method to clear all of the parameters set for the previous command.
* <P>
* Furthermore, this method differs from the <code>initParams</code>
* method in that it maintains the schema of the <code>RowSet</code> object.
*
* @throws SQLException if an error occurs clearing the parameters
*/
public void clearParameters() throws SQLException {
params.clear();
}
/** {@collect.stats}
* Retrieves an array containing the parameter values (both Objects and
* primitives) that have been set for this
* <code>RowSet</code> object's command and throws an <code>SQLException</code> object
* if all parameters have not been set. Before the command is sent to the
* DBMS to be executed, these parameters will be substituted
* for placeholder parameters in the <code>PreparedStatement</code> object
* that is the command for a <code>RowSet</code> implementation extending
* the <code>BaseRowSet</code> class.
* <P>
* Each element in the array that is returned is an <code>Object</code> instance
* that contains the values of the parameters supplied to a setter method.
* The order of the elements is determined by the value supplied for
* <i>parameterIndex</i>. If the setter method takes only the parameter index
* and the value to be set (possibly null), the array element will contain the value to be set
* (which will be expressed as an <code>Object</code>). If there are additional
* parameters, the array element will itself be an array containing the value to be set
* plus any additional parameter values supplied to the setter method. If the method
* sets a stream, the array element includes the type of stream being supplied to the
* method. These additional parameters are for the use of the driver or the DBMS and may or
* may not be used.
* <P>
* NOTE: Stored parameter values of types <code>Array</code>, <code>Blob</code>,
* <code>Clob</code> and <code>Ref</code> are returned as <code>SerialArray</code>,
* <code>SerialBlob</code>, <code>SerialClob</code> and <code>SerialRef</code>
* respectively.
*
* @return an array of <code>Object</code> instances that includes the
* parameter values that may be set in this <code>RowSet</code> object's
* command; an empty array if no parameters have been set
* @throws SQLException if an error occurs retrieveing the object array of
* parameters of this <code>RowSet</code> object or if not all parameters have
* been set
*/
public Object[] getParams() throws SQLException {
if (params == null) {
initParams();
Object [] paramsArray = new Object[params.size()];
return paramsArray;
} else {
// The parameters may be set in random order
// but all must be set, check to verify all
// have been set till the last parameter
// else throw exception.
Object[] paramsArray = new Object[params.size()];
for (int i = 0; i < params.size(); i++) {
paramsArray[i] = params.get(new Integer(i));
if (paramsArray[i] == null) {
throw new SQLException("missing parameter: " + (i + 1));
} //end if
} //end for
return paramsArray;
} //end if
} //end getParams
/** {@collect.stats}
* Sets the designated parameter to SQL <code>NULL</code>.
*
* <P><B>Note:</B> You must specify the parameter's SQL type.
*
* @param parameterName the name of the parameter
* @param sqlType the SQL type code defined in <code>java.sql.Types</code>
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since 1.4
*/
public void setNull(String parameterName, int sqlType) throws SQLException {
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to SQL <code>NULL</code>.
* This version of the method <code>setNull</code> should
* be used for user-defined types and REF type parameters. Examples
* of user-defined types include: STRUCT, DISTINCT, JAVA_OBJECT, and
* named array types.
*
* <P><B>Note:</B> To be portable, applications must give the
* SQL type code and the fully-qualified SQL type name when specifying
* a NULL user-defined or REF parameter. In the case of a user-defined type
* the name is the type name of the parameter itself. For a REF
* parameter, the name is the type name of the referenced type. If
* a JDBC driver does not need the type code or type name information,
* it may ignore it.
*
* Although it is intended for user-defined and Ref parameters,
* this method may be used to set a null parameter of any JDBC type.
* If the parameter does not have a user-defined or REF type, the given
* typeName is ignored.
*
*
* @param parameterName the name of the parameter
* @param sqlType a value from <code>java.sql.Types</code>
* @param typeName the fully-qualified name of an SQL user-defined type;
* ignored if the parameter is not a user-defined type or
* SQL <code>REF</code> value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since 1.4
*/
public void setNull (String parameterName, int sqlType, String typeName)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given Java <code>boolean</code> value.
* The driver converts this
* to an SQL <code>BIT</code> or <code>BOOLEAN</code> value when it sends it to the database.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setBoolean(String parameterName, boolean x) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given Java <code>byte</code> value.
* The driver converts this
* to an SQL <code>TINYINT</code> value when it sends it to the database.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setByte(String parameterName, byte x) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given Java <code>short</code> value.
* The driver converts this
* to an SQL <code>SMALLINT</code> value when it sends it to the database.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setShort(String parameterName, short x) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given Java <code>int</code> value.
* The driver converts this
* to an SQL <code>INTEGER</code> value when it sends it to the database.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setInt(String parameterName, int x) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given Java <code>long</code> value.
* The driver converts this
* to an SQL <code>BIGINT</code> value when it sends it to the database.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setLong(String parameterName, long x) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given Java <code>float</code> value.
* The driver converts this
* to an SQL <code>FLOAT</code> value when it sends it to the database.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setFloat(String parameterName, float x) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given Java <code>double</code> value.
* The driver converts this
* to an SQL <code>DOUBLE</code> value when it sends it to the database.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setDouble(String parameterName, double x) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given
* <code>java.math.BigDecimal</code> value.
* The driver converts this to an SQL <code>NUMERIC</code> value when
* it sends it to the database.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given Java <code>String</code> value.
* The driver converts this
* to an SQL <code>VARCHAR</code> or <code>LONGVARCHAR</code> value
* (depending on the argument's
* size relative to the driver's limits on <code>VARCHAR</code> values)
* when it sends it to the database.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setString(String parameterName, String x) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given Java array of bytes.
* The driver converts this to an SQL <code>VARBINARY</code> or
* <code>LONGVARBINARY</code> (depending on the argument's size relative
* to the driver's limits on <code>VARBINARY</code> values) when it sends
* it to the database.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setBytes(String parameterName, byte x[]) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.Timestamp</code> value.
* The driver
* converts this to an SQL <code>TIMESTAMP</code> value when it sends it to the
* database.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setTimestamp(String parameterName, java.sql.Timestamp x)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given input stream, which will have
* the specified number of bytes.
* When a very large ASCII value is input to a <code>LONGVARCHAR</code>
* parameter, it may be more practical to send it via a
* <code>java.io.InputStream</code>. Data will be read from the stream
* as needed until end-of-file is reached. The JDBC driver will
* do any necessary conversion from ASCII to the database char format.
*
* <P><B>Note:</B> This stream object can either be a standard
* Java stream object or your own subclass that implements the
* standard interface.
*
* @param parameterName the name of the parameter
* @param x the Java input stream that contains the ASCII parameter value
* @param length the number of bytes in the stream
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since 1.4
*/
public void setAsciiStream(String parameterName, java.io.InputStream x, int length)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given input stream, which will have
* the specified number of bytes.
* When a very large binary value is input to a <code>LONGVARBINARY</code>
* parameter, it may be more practical to send it via a
* <code>java.io.InputStream</code> object. The data will be read from the stream
* as needed until end-of-file is reached.
*
* <P><B>Note:</B> This stream object can either be a standard
* Java stream object or your own subclass that implements the
* standard interface.
*
* @param parameterName the name of the parameter
* @param x the java input stream which contains the binary parameter value
* @param length the number of bytes in the stream
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since 1.4
*/
public void setBinaryStream(String parameterName, java.io.InputStream x,
int length) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>Reader</code>
* object, which is the given number of characters long.
* When a very large UNICODE value is input to a <code>LONGVARCHAR</code>
* parameter, it may be more practical to send it via a
* <code>java.io.Reader</code> object. The data will be read from the stream
* as needed until end-of-file is reached. The JDBC driver will
* do any necessary conversion from UNICODE to the database char format.
*
* <P><B>Note:</B> This stream object can either be a standard
* Java stream object or your own subclass that implements the
* standard interface.
*
* @param parameterName the name of the parameter
* @param reader the <code>java.io.Reader</code> object that
* contains the UNICODE data used as the designated parameter
* @param length the number of characters in the stream
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since 1.4
*/
public void setCharacterStream(String parameterName,
java.io.Reader reader,
int length) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given input stream.
* When a very large ASCII value is input to a <code>LONGVARCHAR</code>
* parameter, it may be more practical to send it via a
* <code>java.io.InputStream</code>. Data will be read from the stream
* as needed until end-of-file is reached. The JDBC driver will
* do any necessary conversion from ASCII to the database char format.
*
* <P><B>Note:</B> This stream object can either be a standard
* Java stream object or your own subclass that implements the
* standard interface.
* <P><B>Note:</B> Consult your JDBC driver documentation to determine if
* it might be more efficient to use a version of
* <code>setAsciiStream</code> which takes a length parameter.
*
* @param parameterName the name of the parameter
* @param x the Java input stream that contains the ASCII parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
* @since 1.6
*/
public void setAsciiStream(String parameterName, java.io.InputStream x)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given input stream.
* When a very large binary value is input to a <code>LONGVARBINARY</code>
* parameter, it may be more practical to send it via a
* <code>java.io.InputStream</code> object. The data will be read from the
* stream as needed until end-of-file is reached.
*
* <P><B>Note:</B> This stream object can either be a standard
* Java stream object or your own subclass that implements the
* standard interface.
* <P><B>Note:</B> Consult your JDBC driver documentation to determine if
* it might be more efficient to use a version of
* <code>setBinaryStream</code> which takes a length parameter.
*
* @param parameterName the name of the parameter
* @param x the java input stream which contains the binary parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
* @since 1.6
*/
public void setBinaryStream(String parameterName, java.io.InputStream x)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>Reader</code>
* object.
* When a very large UNICODE value is input to a <code>LONGVARCHAR</code>
* parameter, it may be more practical to send it via a
* <code>java.io.Reader</code> object. The data will be read from the stream
* as needed until end-of-file is reached. The JDBC driver will
* do any necessary conversion from UNICODE to the database char format.
*
* <P><B>Note:</B> This stream object can either be a standard
* Java stream object or your own subclass that implements the
* standard interface.
* <P><B>Note:</B> Consult your JDBC driver documentation to determine if
* it might be more efficient to use a version of
* <code>setCharacterStream</code> which takes a length parameter.
*
* @param parameterName the name of the parameter
* @param reader the <code>java.io.Reader</code> object that contains the
* Unicode data
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
* @since 1.6
*/
public void setCharacterStream(String parameterName,
java.io.Reader reader) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter in this <code>RowSet</code> object's command
* to a <code>Reader</code> object. The
* <code>Reader</code> reads the data till end-of-file is reached. The
* driver does the necessary conversion from Java character format to
* the national character set in the database.
* <P><B>Note:</B> This stream object can either be a standard
* Java stream object or your own subclass that implements the
* standard interface.
* <P><B>Note:</B> Consult your JDBC driver documentation to determine if
* it might be more efficient to use a version of
* <code>setNCharacterStream</code> which takes a length parameter.
*
* @param parameterIndex of the first parameter is 1, the second is 2, ...
* @param value the parameter value
* @throws SQLException if the driver does not support national
* character sets; if the driver can detect that a data conversion
* error could occur ; if a database access error occurs; or
* this method is called on a closed <code>PreparedStatement</code>
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
* @since 1.6
*/
public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the value of the designated parameter with the given object. The second
* argument must be an object type; for integral values, the
* <code>java.lang</code> equivalent objects should be used.
*
* <p>The given Java object will be converted to the given targetSqlType
* before being sent to the database.
*
* If the object has a custom mapping (is of a class implementing the
* interface <code>SQLData</code>),
* the JDBC driver should call the method <code>SQLData.writeSQL</code> to write it
* to the SQL data stream.
* If, on the other hand, the object is of a class implementing
* <code>Ref</code>, <code>Blob</code>, <code>Clob</code>, <code>NClob</code>,
* <code>Struct</code>, <code>java.net.URL</code>,
* or <code>Array</code>, the driver should pass it to the database as a
* value of the corresponding SQL type.
* <P>
* Note that this method may be used to pass datatabase-
* specific abstract data types.
*
* @param parameterName the name of the parameter
* @param x the object containing the input parameter value
* @param targetSqlType the SQL type (as defined in java.sql.Types) to be
* sent to the database. The scale argument may further qualify this type.
* @param scale for java.sql.Types.DECIMAL or java.sql.Types.NUMERIC types,
* this is the number of digits after the decimal point. For all other
* types, this value will be ignored.
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if <code>targetSqlType</code> is
* a <code>ARRAY</code>, <code>BLOB</code>, <code>CLOB</code>,
* <code>DATALINK</code>, <code>JAVA_OBJECT</code>, <code>NCHAR</code>,
* <code>NCLOB</code>, <code>NVARCHAR</code>, <code>LONGNVARCHAR</code>,
* <code>REF</code>, <code>ROWID</code>, <code>SQLXML</code>
* or <code>STRUCT</code> data type and the JDBC driver does not support
* this data type
* @see Types
* @see #getParams
* @since 1.4
*/
public void setObject(String parameterName, Object x, int targetSqlType, int scale)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the value of the designated parameter with the given object.
* This method is like the method <code>setObject</code>
* above, except that it assumes a scale of zero.
*
* @param parameterName the name of the parameter
* @param x the object containing the input parameter value
* @param targetSqlType the SQL type (as defined in java.sql.Types) to be
* sent to the database
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if <code>targetSqlType</code> is
* a <code>ARRAY</code>, <code>BLOB</code>, <code>CLOB</code>,
* <code>DATALINK</code>, <code>JAVA_OBJECT</code>, <code>NCHAR</code>,
* <code>NCLOB</code>, <code>NVARCHAR</code>, <code>LONGNVARCHAR</code>,
* <code>REF</code>, <code>ROWID</code>, <code>SQLXML</code>
* or <code>STRUCT</code> data type and the JDBC driver does not support
* this data type
* @see #getParams
* @since 1.4
*/
public void setObject(String parameterName, Object x, int targetSqlType)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the value of the designated parameter with the given object.
* The second parameter must be of type <code>Object</code>; therefore, the
* <code>java.lang</code> equivalent objects should be used for built-in types.
*
* <p>The JDBC specification specifies a standard mapping from
* Java <code>Object</code> types to SQL types. The given argument
* will be converted to the corresponding SQL type before being
* sent to the database.
*
* <p>Note that this method may be used to pass datatabase-
* specific abstract data types, by using a driver-specific Java
* type.
*
* If the object is of a class implementing the interface <code>SQLData</code>,
* the JDBC driver should call the method <code>SQLData.writeSQL</code>
* to write it to the SQL data stream.
* If, on the other hand, the object is of a class implementing
* <code>Ref</code>, <code>Blob</code>, <code>Clob</code>, <code>NClob</code>,
* <code>Struct</code>, <code>java.net.URL</code>,
* or <code>Array</code>, the driver should pass it to the database as a
* value of the corresponding SQL type.
* <P>
* This method throws an exception if there is an ambiguity, for example, if the
* object is of a class implementing more than one of the interfaces named above.
*
* @param parameterName the name of the parameter
* @param x the object containing the input parameter value
* @exception SQLException if a database access error occurs,
* this method is called on a closed <code>CallableStatement</code> or if the given
* <code>Object</code> parameter is ambiguous
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setObject(String parameterName, Object x) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>InputStream</code> object. The inputstream must contain the number
* of characters specified by length otherwise a <code>SQLException</code> will be
* generated when the <code>PreparedStatement</code> is executed.
* This method differs from the <code>setBinaryStream (int, InputStream, int)</code>
* method because it informs the driver that the parameter value should be
* sent to the server as a <code>BLOB</code>. When the <code>setBinaryStream</code> method is used,
* the driver may have to do extra work to determine whether the parameter
* data should be sent to the server as a <code>LONGVARBINARY</code> or a <code>BLOB</code>
* @param parameterIndex index of the first parameter is 1,
* the second is 2, ...
* @param inputStream An object that contains the data to set the parameter
* value to.
* @param length the number of bytes in the parameter data.
* @throws SQLException if a database access error occurs,
* this method is called on a closed <code>PreparedStatement</code>,
* if parameterIndex does not correspond
* to a parameter marker in the SQL statement, if the length specified
* is less than zero or if the number of bytes in the inputstream does not match
* the specfied length.
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
*
* @since 1.6
*/
public void setBlob(int parameterIndex, InputStream inputStream, long length)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>InputStream</code> object.
* This method differs from the <code>setBinaryStream (int, InputStream)</code>
* method because it informs the driver that the parameter value should be
* sent to the server as a <code>BLOB</code>. When the <code>setBinaryStream</code> method is used,
* the driver may have to do extra work to determine whether the parameter
* data should be sent to the server as a <code>LONGVARBINARY</code> or a <code>BLOB</code>
*
* <P><B>Note:</B> Consult your JDBC driver documentation to determine if
* it might be more efficient to use a version of
* <code>setBlob</code> which takes a length parameter.
*
* @param parameterIndex index of the first parameter is 1,
* the second is 2, ...
* @param inputStream An object that contains the data to set the parameter
* value to.
* @throws SQLException if a database access error occurs,
* this method is called on a closed <code>PreparedStatement</code> or
* if parameterIndex does not correspond
* to a parameter marker in the SQL statement,
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
*
* @since 1.6
*/
public void setBlob(int parameterIndex, InputStream inputStream)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>InputStream</code> object. The <code>inputstream</code> must contain the number
* of characters specified by length, otherwise a <code>SQLException</code> will be
* generated when the <code>CallableStatement</code> is executed.
* This method differs from the <code>setBinaryStream (int, InputStream, int)</code>
* method because it informs the driver that the parameter value should be
* sent to the server as a <code>BLOB</code>. When the <code>setBinaryStream</code> method is used,
* the driver may have to do extra work to determine whether the parameter
* data should be sent to the server as a <code>LONGVARBINARY</code> or a <code>BLOB</code>
*
* @param parameterName the name of the parameter to be set
* the second is 2, ...
*
* @param inputStream An object that contains the data to set the parameter
* value to.
* @param length the number of bytes in the parameter data.
* @throws SQLException if parameterIndex does not correspond
* to a parameter marker in the SQL statement, or if the length specified
* is less than zero; if the number of bytes in the inputstream does not match
* the specfied length; if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
*
* @since 1.6
*/
public void setBlob(String parameterName, InputStream inputStream, long length)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.Blob</code> object.
* The driver converts this to an SQL <code>BLOB</code> value when it
* sends it to the database.
*
* @param parameterName the name of the parameter
* @param x a <code>Blob</code> object that maps an SQL <code>BLOB</code> value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since 1.6
*/
public void setBlob (String parameterName, Blob x) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>InputStream</code> object.
* This method differs from the <code>setBinaryStream (int, InputStream)</code>
* method because it informs the driver that the parameter value should be
* sent to the server as a <code>BLOB</code>. When the <code>setBinaryStream</code> method is used,
* the driver may have to do extra work to determine whether the parameter
* data should be send to the server as a <code>LONGVARBINARY</code> or a <code>BLOB</code>
*
* <P><B>Note:</B> Consult your JDBC driver documentation to determine if
* it might be more efficient to use a version of
* <code>setBlob</code> which takes a length parameter.
*
* @param parameterName the name of the parameter
* @param inputStream An object that contains the data to set the parameter
* value to.
* @throws SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
*
* @since 1.6
*/
public void setBlob(String parameterName, InputStream inputStream)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>Reader</code> object. The reader must contain the number
* of characters specified by length otherwise a <code>SQLException</code> will be
* generated when the <code>PreparedStatement</code> is executed.
*This method differs from the <code>setCharacterStream (int, Reader, int)</code> method
* because it informs the driver that the parameter value should be sent to
* the server as a <code>CLOB</code>. When the <code>setCharacterStream</code> method is used, the
* driver may have to do extra work to determine whether the parameter
* data should be sent to the server as a <code>LONGVARCHAR</code> or a <code>CLOB</code>
* @param parameterIndex index of the first parameter is 1, the second is 2, ...
* @param reader An object that contains the data to set the parameter value to.
* @param length the number of characters in the parameter data.
* @throws SQLException if a database access error occurs, this method is called on
* a closed <code>PreparedStatement</code>, if parameterIndex does not correspond to a parameter
* marker in the SQL statement, or if the length specified is less than zero.
*
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
* @since 1.6
*/
public void setClob(int parameterIndex, Reader reader, long length)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>Reader</code> object.
* This method differs from the <code>setCharacterStream (int, Reader)</code> method
* because it informs the driver that the parameter value should be sent to
* the server as a <code>CLOB</code>. When the <code>setCharacterStream</code> method is used, the
* driver may have to do extra work to determine whether the parameter
* data should be sent to the server as a <code>LONGVARCHAR</code> or a <code>CLOB</code>
*
* <P><B>Note:</B> Consult your JDBC driver documentation to determine if
* it might be more efficient to use a version of
* <code>setClob</code> which takes a length parameter.
*
* @param parameterIndex index of the first parameter is 1, the second is 2, ...
* @param reader An object that contains the data to set the parameter value to.
* @throws SQLException if a database access error occurs, this method is called on
* a closed <code>PreparedStatement</code>or if parameterIndex does not correspond to a parameter
* marker in the SQL statement
*
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
* @since 1.6
*/
public void setClob(int parameterIndex, Reader reader)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>Reader</code> object. The <code>reader</code> must contain the number
* of characters specified by length otherwise a <code>SQLException</code> will be
* generated when the <code>CallableStatement</code> is executed.
* This method differs from the <code>setCharacterStream (int, Reader, int)</code> method
* because it informs the driver that the parameter value should be sent to
* the server as a <code>CLOB</code>. When the <code>setCharacterStream</code> method is used, the
* driver may have to do extra work to determine whether the parameter
* data should be send to the server as a <code>LONGVARCHAR</code> or a <code>CLOB</code>
* @param parameterName the name of the parameter to be set
* @param reader An object that contains the data to set the parameter value to.
* @param length the number of characters in the parameter data.
* @throws SQLException if parameterIndex does not correspond to a parameter
* marker in the SQL statement; if the length specified is less than zero;
* a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
*
* @since 1.6
*/
public void setClob(String parameterName, Reader reader, long length)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.Clob</code> object.
* The driver converts this to an SQL <code>CLOB</code> value when it
* sends it to the database.
*
* @param parameterName the name of the parameter
* @param x a <code>Clob</code> object that maps an SQL <code>CLOB</code> value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since 1.6
*/
public void setClob (String parameterName, Clob x) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>Reader</code> object.
* This method differs from the <code>setCharacterStream (int, Reader)</code> method
* because it informs the driver that the parameter value should be sent to
* the server as a <code>CLOB</code>. When the <code>setCharacterStream</code> method is used, the
* driver may have to do extra work to determine whether the parameter
* data should be send to the server as a <code>LONGVARCHAR</code> or a <code>CLOB</code>
*
* <P><B>Note:</B> Consult your JDBC driver documentation to determine if
* it might be more efficient to use a version of
* <code>setClob</code> which takes a length parameter.
*
* @param parameterName the name of the parameter
* @param reader An object that contains the data to set the parameter value to.
* @throws SQLException if a database access error occurs or this method is called on
* a closed <code>CallableStatement</code>
*
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
* @since 1.6
*/
public void setClob(String parameterName, Reader reader)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.Date</code> value
* using the default time zone of the virtual machine that is running
* the application.
* The driver converts this
* to an SQL <code>DATE</code> value when it sends it to the database.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setDate(String parameterName, java.sql.Date x)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.Date</code> value,
* using the given <code>Calendar</code> object. The driver uses
* the <code>Calendar</code> object to construct an SQL <code>DATE</code> value,
* which the driver then sends to the database. With a
* a <code>Calendar</code> object, the driver can calculate the date
* taking into account a custom timezone. If no
* <code>Calendar</code> object is specified, the driver uses the default
* timezone, which is that of the virtual machine running the application.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @param cal the <code>Calendar</code> object the driver will use
* to construct the date
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setDate(String parameterName, java.sql.Date x, Calendar cal)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.Time</code> value.
* The driver converts this
* to an SQL <code>TIME</code> value when it sends it to the database.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setTime(String parameterName, java.sql.Time x)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.Time</code> value,
* using the given <code>Calendar</code> object. The driver uses
* the <code>Calendar</code> object to construct an SQL <code>TIME</code> value,
* which the driver then sends to the database. With a
* a <code>Calendar</code> object, the driver can calculate the time
* taking into account a custom timezone. If no
* <code>Calendar</code> object is specified, the driver uses the default
* timezone, which is that of the virtual machine running the application.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @param cal the <code>Calendar</code> object the driver will use
* to construct the time
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setTime(String parameterName, java.sql.Time x, Calendar cal)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.Timestamp</code> value,
* using the given <code>Calendar</code> object. The driver uses
* the <code>Calendar</code> object to construct an SQL <code>TIMESTAMP</code> value,
* which the driver then sends to the database. With a
* a <code>Calendar</code> object, the driver can calculate the timestamp
* taking into account a custom timezone. If no
* <code>Calendar</code> object is specified, the driver uses the default
* timezone, which is that of the virtual machine running the application.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @param cal the <code>Calendar</code> object the driver will use
* to construct the timestamp
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @see #getParams
* @since 1.4
*/
public void setTimestamp(String parameterName, java.sql.Timestamp x, Calendar cal)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.SQLXML</code> object. The driver converts this to an
* SQL <code>XML</code> value when it sends it to the database.
* @param parameterIndex index of the first parameter is 1, the second is 2, ...
* @param xmlObject a <code>SQLXML</code> object that maps an SQL <code>XML</code> value
* @throws SQLException if a database access error occurs, this method
* is called on a closed result set,
* 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.
* @since 1.6
*/
public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.SQLXML</code> object. The driver converts this to an
* <code>SQL XML</code> value when it sends it to the database.
* @param parameterName the name of the parameter
* @param xmlObject a <code>SQLXML</code> object that maps an <code>SQL XML</code> value
* @throws SQLException if a database access error occurs, this method
* is called on a closed result set,
* 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.
* @since 1.6
*/
public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.RowId</code> object. The
* driver converts this to a SQL <code>ROWID</code> value when it sends it
* to the database
*
* @param parameterIndex the first parameter is 1, the second is 2, ...
* @param x the parameter value
* @throws SQLException if a database access error occurs
*
* @since 1.6
*/
public void setRowId(int parameterIndex, RowId x) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.sql.RowId</code> object. The
* driver converts this to a SQL <code>ROWID</code> when it sends it to the
* database.
*
* @param parameterName the name of the parameter
* @param x the parameter value
* @throws SQLException if a database access error occurs
* @since 1.6
*/
public void setRowId(String parameterName, RowId x) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated paramter to the given <code>String</code> object.
* 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 database.
*
* @param parameterIndex of the first parameter is 1, the second is 2, ...
* @param value the parameter value
* @throws SQLException if the driver does not support national
* character sets; if the driver can detect that a data conversion
* error could occur ; or if a database access error occurs
* @since 1.6
*/
public void setNString(int parameterIndex, String value) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated paramter to the given <code>String</code> object.
* The driver converts this to a SQL <code>NCHAR</code> or
* <code>NVARCHAR</code> or <code>LONGNVARCHAR</code>
* @param parameterName the name of the column to be set
* @param value the parameter value
* @throws SQLException if the driver does not support national
* character sets; if the driver can detect that a data conversion
* error could occur; or if a database access error occurs
* @since 1.6
*/
public void setNString(String parameterName, String value)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>Reader</code> object. The
* <code>Reader</code> reads the data till end-of-file is reached. The
* driver does the necessary conversion from Java character format to
* the national character set in the database.
* @param parameterIndex of the first parameter is 1, the second is 2, ...
* @param value the parameter value
* @param length the number of characters in the parameter data.
* @throws SQLException if the driver does not support national
* character sets; if the driver can detect that a data conversion
* error could occur ; or if a database access error occurs
* @since 1.6
*/
public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>Reader</code> object. The
* <code>Reader</code> reads the data till end-of-file is reached. The
* driver does the necessary conversion from Java character format to
* the national character set in the database.
* @param parameterName the name of the column to be set
* @param value the parameter value
* @param length the number of characters in the parameter data.
* @throws SQLException if the driver does not support national
* character sets; if the driver can detect that a data conversion
* error could occur; or if a database access error occurs
* @since 1.6
*/
public void setNCharacterStream(String parameterName, Reader value, long length)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>Reader</code> object. The
* <code>Reader</code> reads the data till end-of-file is reached. The
* driver does the necessary conversion from Java character format to
* the national character set in the database.
* <P><B>Note:</B> This stream object can either be a standard
* Java stream object or your own subclass that implements the
* standard interface.
* <P><B>Note:</B> Consult your JDBC driver documentation to determine if
* it might be more efficient to use a version of
* <code>setNCharacterStream</code> which takes a length parameter.
*
* @param parameterName the name of the parameter
* @param value the parameter value
* @throws SQLException if the driver does not support national
* character sets; if the driver can detect that a data conversion
* error could occur ; if a database access error occurs; or
* this method is called on a closed <code>CallableStatement</code>
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
* @since 1.6
*/
public void setNCharacterStream(String parameterName, Reader value) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>java.sql.NClob</code> object. The object
* implements the <code>java.sql.NClob</code> interface. This <code>NClob</code>
* object maps to a SQL <code>NCLOB</code>.
* @param parameterName the name of the column to be set
* @param value the parameter value
* @throws SQLException if the driver does not support national
* character sets; if the driver can detect that a data conversion
* error could occur; or if a database access error occurs
* @since 1.6
*/
public void setNClob(String parameterName, NClob value) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>Reader</code> object. The <code>reader</code> must contain * the number
* of characters specified by length otherwise a <code>SQLException</code> will be
* generated when the <code>CallableStatement</code> is executed.
* This method differs from the <code>setCharacterStream (int, Reader, int)</code> method
* because it informs the driver that the parameter value should be sent to
* the server as a <code>NCLOB</code>. When the <code>setCharacterStream</code> method is used, the
* driver may have to do extra work to determine whether the parameter
* data should be send to the server as a <code>LONGNVARCHAR</code> or a <code>NCLOB</code>
*
* @param parameterName the name of the parameter to be set
* @param reader An object that contains the data to set the parameter value to.
* @param length the number of characters in the parameter data.
* @throws SQLException if parameterIndex does not correspond to a parameter
* marker in the SQL statement; if the length specified is less than zero;
* if the driver does not support national
* character sets; if the driver can detect that a data conversion
* error could occur; if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since 1.6
*/
public void setNClob(String parameterName, Reader reader, long length)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>Reader</code> object.
* This method differs from the <code>setCharacterStream (int, Reader)</code> method
* because it informs the driver that the parameter value should be sent to
* the server as a <code>NCLOB</code>. When the <code>setCharacterStream</code> method is used, the
* driver may have to do extra work to determine whether the parameter
* data should be send to the server as a <code>LONGNVARCHAR</code> or a <code>NCLOB</code>
* <P><B>Note:</B> Consult your JDBC driver documentation to determine if
* it might be more efficient to use a version of
* <code>setNClob</code> which takes a length parameter.
*
* @param parameterName the name of the parameter
* @param reader An object that contains the data to set the parameter value to.
* @throws SQLException if the driver does not support national character sets;
* if the driver can detect that a data conversion
* error could occur; if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
*
* @since 1.6
*/
public void setNClob(String parameterName, Reader reader)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>Reader</code> object. The reader must contain the number
* of characters specified by length otherwise a <code>SQLException</code> will be
* generated when the <code>PreparedStatement</code> is executed.
* This method differs from the <code>setCharacterStream (int, Reader, int)</code> method
* because it informs the driver that the parameter value should be sent to
* the server as a <code>NCLOB</code>. When the <code>setCharacterStream</code> method is used, the
* driver may have to do extra work to determine whether the parameter
* data should be sent to the server as a <code>LONGNVARCHAR</code> or a <code>NCLOB</code>
* @param parameterIndex index of the first parameter is 1, the second is 2, ...
* @param reader An object that contains the data to set the parameter value to.
* @param length the number of characters in the parameter data.
* @throws SQLException if parameterIndex does not correspond to a parameter
* marker in the SQL statement; if the length specified is less than zero;
* if the driver does not support national character sets;
* if the driver can detect that a data conversion
* error could occur; if a database access error occurs or
* this method is called on a closed <code>PreparedStatement</code>
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
*
* @since 1.6
*/
public void setNClob(int parameterIndex, Reader reader, long length)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>java.sql.NClob</code> object. The driver converts this oa
* SQL <code>NCLOB</code> value when it sends it to the database.
* @param parameterIndex of the first parameter is 1, the second is 2, ...
* @param value the parameter value
* @throws SQLException if the driver does not support national
* character sets; if the driver can detect that a data conversion
* error could occur ; or if a database access error occurs
* @since 1.6
*/
public void setNClob(int parameterIndex, NClob value) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to a <code>Reader</code> object.
* This method differs from the <code>setCharacterStream (int, Reader)</code> method
* because it informs the driver that the parameter value should be sent to
* the server as a <code>NCLOB</code>. When the <code>setCharacterStream</code> method is used, the
* driver may have to do extra work to determine whether the parameter
* data should be sent to the server as a <code>LONGNVARCHAR</code> or a <code>NCLOB</code>
* <P><B>Note:</B> Consult your JDBC driver documentation to determine if
* it might be more efficient to use a version of
* <code>setNClob</code> which takes a length parameter.
*
* @param parameterIndex index of the first parameter is 1, the second is 2, ...
* @param reader An object that contains the data to set the parameter value to.
* @throws SQLException if parameterIndex does not correspond to a parameter
* marker in the SQL statement;
* if the driver does not support national character sets;
* if the driver can detect that a data conversion
* error could occur; if a database access error occurs or
* this method is called on a closed <code>PreparedStatement</code>
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
*
* @since 1.6
*/
public void setNClob(int parameterIndex, Reader reader)
throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
/** {@collect.stats}
* Sets the designated parameter to the given <code>java.net.URL</code> value.
* The driver converts this to an SQL <code>DATALINK</code> value
* when it sends it to the database.
*
* @param parameterIndex the first parameter is 1, the second is 2, ...
* @param x the <code>java.net.URL</code> object to be set
* @exception SQLException if a database access error occurs or
* this method is called on a closed <code>PreparedStatement</code>
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
* @since 1.4
*/
public void setURL(int parameterIndex, java.net.URL x) throws SQLException{
throw new SQLFeatureNotSupportedException("Feature not supported");
}
static final long serialVersionUID = 4886719666485113312L;
} //end class
| Java |
/*
* Copyright (c) 2003, 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 javax.sql.rowset;
import java.sql.SQLException;
/** {@collect.stats}
* An extension of <code>SQLException</code> that provides information
* about database warnings set on <code>RowSet</code> objects.
* Warnings are silently chained to the object whose method call
* caused it to be reported.
* This class complements the <code>SQLWarning</code> class.
* <P>
* Rowset warnings may be retrieved from <code>JdbcRowSet</code>,
* <code>CachedRowSet</code><sup><font size=-2>TM</font></sup>,
* <code>WebRowSet</code>, <code>FilteredRowSet</code>, or <code>JoinRowSet</code>
* implementations. To retrieve the first warning reported on any
* <code>RowSet</code>
* implementation, use the method <code>getRowSetWarnings</code> defined
* in the <code>JdbcRowSet</code> interface or the <code>CachedRowSet</code>
* interface. To retrieve a warning chained to the first warning, use the
* <code>RowSetWarning</code> method
* <code>getNextWarning</code>. To retrieve subsequent warnings, call
* <code>getNextWarning</code> on each <code>RowSetWarning</code> object that is
* returned.
* <P>
* The inherited methods <code>getMessage</code>, <code>getSQLState</code>,
* and <code>getErrorCode</code> retrieve information contained in a
* <code>RowSetWarning</code> object.
*/
public class RowSetWarning extends SQLException {
/** {@collect.stats}
* RowSetWarning object handle.
*/
private RowSetWarning rwarning;
/** {@collect.stats}
* Constructs a <code>RowSetWarning</code> object
* with the given value for the reason; SQLState defaults to null,
* and vendorCode defaults to 0.
*
* @param reason a <code>String</code> object giving a description
* of the warning; if the <code>String</code> is <code>null</code>,
* this constructor behaves like the default (zero parameter)
* <code>RowSetWarning</code> constructor
*/
public RowSetWarning(String reason) {
super(reason);
}
/** {@collect.stats}
* Constructs a default <code>RowSetWarning</code> object. The reason
* defaults to <code>null</code>, SQLState defaults to null and vendorCode
* defaults to 0.
*/
public RowSetWarning() {
super();
}
/** {@collect.stats}
* Constructs a <code>RowSetWarning</code> object initialized with the
* given values for the reason and SQLState. The vendor code defaults to 0.
*
* If the <code>reason</code> or <code>SQLState</code> parameters are <code>null</code>,
* this constructor behaves like the default (zero parameter)
* <code>RowSetWarning</code> constructor.
*
* @param reason a <code>String</code> giving a description of the
* warning;
* @param SQLState an XOPEN code identifying the warning; if a non standard
* XOPEN <i>SQLState</i> is supplied, no exception is thrown.
*/
public RowSetWarning(java.lang.String reason, java.lang.String SQLState) {
super(reason, SQLState);
}
/** {@collect.stats}
* Constructs a fully specified <code>RowSetWarning</code> object initialized
* with the given values for the reason, SQLState and vendorCode.
*
* If the <code>reason</code>, or the <code>SQLState</code>
* parameters are <code>null</code>, this constructor behaves like the default
* (zero parameter) <code>RowSetWarning</code> constructor.
*
* @param reason a <code>String</code> giving a description of the
* warning;
* @param SQLState an XOPEN code identifying the warning; if a non standard
* XPOEN <i>SQLState</i> is supplied, no exception is thrown.
* @param vendorCode a database vendor-specific warning code
*/
public RowSetWarning(java.lang.String reason, java.lang.String SQLState, int vendorCode) {
super(reason, SQLState, vendorCode);
}
/** {@collect.stats}
* Retrieves the warning chained to this <code>RowSetWarning</code>
* object.
*
* @return the <code>RowSetWarning</code> object chained to this one; if no
* <code>RowSetWarning</code> object is chained to this one,
* <code>null</code> is returned (default value)
* @see #setNextWarning
*/
public RowSetWarning getNextWarning() {
return rwarning;
}
/** {@collect.stats}
* Sets <i>warning</i> as the next warning, that is, the warning chained
* to this <code>RowSetWarning</code> object.
*
* @param warning the <code>RowSetWarning</code> object to be set as the
* next warning; if the <code>RowSetWarning</code> is null, this
* represents the finish point in the warning chain
* @see #getNextWarning
*/
public void setNextWarning(RowSetWarning warning) {
rwarning = warning;
}
static final long serialVersionUID = 6678332766434564774L;
}
| Java |
/*
* Copyright (c) 2000, 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 javax.sql;
import java.sql.*;
/** {@collect.stats}
* An object that implements the <code>RowSetWriter</code> interface,
* called a <i>writer</i>. A writer may be registered with a <code>RowSet</code>
* object that supports the reader/writer paradigm.
* <P>
* If a disconnected <code>RowSet</code> object modifies some of its data,
* and it has a writer associated with it, it may be implemented so that it
* calls on the writer's <code>writeData</code> method internally
* to write the updates back to the data source. In order to do this, the writer
* must first establish a connection with the rowset's data source.
* <P>
* If the data to be updated has already been changed in the data source, there
* is a conflict, in which case the writer will not write
* the changes to the data source. The algorithm the writer uses for preventing
* or limiting conflicts depends entirely on its implementation.
*
* @since 1.4
*/
public interface RowSetWriter {
/** {@collect.stats}
* Writes the changes in this <code>RowSetWriter</code> object's
* rowset back to the data source from which it got its data.
*
* @param caller the <code>RowSet</code> object (1) that has implemented the
* <code>RowSetInternal</code> interface, (2) with which this writer is
* registered, and (3) that called this method internally
* @return <code>true</code> if the modified data was written; <code>false</code>
* if not, which will be the case if there is a conflict
* @exception SQLException if a database access error occurs
*/
boolean writeData(RowSetInternal caller) throws SQLException;
}
| 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 javax.sql;
import java.sql.Connection;
import java.sql.SQLException;
/** {@collect.stats}
* An object that provides hooks for connection pool management.
* A <code>PooledConnection</code> object
* represents a physical connection to a data source. The connection
* can be recycled rather than being closed when an application is
* finished with it, thus reducing the number of connections that
* need to be made.
* <P>
* An application programmer does not use the <code>PooledConnection</code>
* interface directly; rather, it is used by a middle tier infrastructure
* that manages the pooling of connections.
* <P>
* When an application calls the method <code>DataSource.getConnection</code>,
* it gets back a <code>Connection</code> object. If connection pooling is
* being done, that <code>Connection</code> object is actually a handle to
* a <code>PooledConnection</code> object, which is a physical connection.
* <P>
* The connection pool manager, typically the application server, maintains
* a pool of <code>PooledConnection</code> objects. If there is a
* <code>PooledConnection</code> object available in the pool, the
* connection pool manager returns a <code>Connection</code> object that
* is a handle to that physical connection.
* If no <code>PooledConnection</code> object is available, the
* connection pool manager calls the <code>ConnectionPoolDataSource</code>
* method <code>getPoolConnection</code> to create a new physical connection. The
* JDBC driver implementing <code>ConnectionPoolDataSource</code> creates a
* new <code>PooledConnection</code> object and returns a handle to it.
* <P>
* When an application closes a connection, it calls the <code>Connection</code>
* method <code>close</code>. When connection pooling is being done,
* the connection pool manager is notified because it has registered itself as
* a <code>ConnectionEventListener</code> object using the
* <code>ConnectionPool</code> method <code>addConnectionEventListener</code>.
* The connection pool manager deactivates the handle to
* the <code>PooledConnection</code> object and returns the
* <code>PooledConnection</code> object to the pool of connections so that
* it can be used again. Thus, when an application closes its connection,
* the underlying physical connection is recycled rather than being closed.
* <P>
* The physical connection is not closed until the connection pool manager
* calls the <code>PooledConnection</code> method <code>close</code>.
* This method is generally called to have an orderly shutdown of the server or
* if a fatal error has made the connection unusable.
*
* <p>
* A connection pool manager is often also a statement pool manager, maintining
* a pool of <code>PreparedStatement</code> objects.
* When an application closes a prepared statement, it calls the
* <code>PreparedStatement</code>
* method <code>close</code>. When <code>Statement</code> pooling is being done,
* the pool manager is notified because it has registered itself as
* a <code>StatementEventListener</code> object using the
* <code>ConnectionPool</code> method <code>addStatementEventListener</code>.
* Thus, when an application closes its <code>PreparedStatement</code>,
* the underlying prepared statement is recycled rather than being closed.
* <P>
*
* @since 1.4
*/
public interface PooledConnection {
/** {@collect.stats}
* Creates and returns a <code>Connection</code> object that is a handle
* for the physical connection that
* this <code>PooledConnection</code> object represents.
* The connection pool manager calls this method when an application has
* called the method <code>DataSource.getConnection</code> and there are
* no <code>PooledConnection</code> objects available. See the
* {@link PooledConnection interface description} for more information.
*
* @return a <code>Connection</code> object that is a handle to
* this <code>PooledConnection</code> object
* @exception SQLException if a database access error occurs
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since 1.4
*/
Connection getConnection() throws SQLException;
/** {@collect.stats}
* Closes the physical connection that this <code>PooledConnection</code>
* object represents. An application never calls this method directly;
* it is called by the connection pool module, or manager.
* <P>
* See the {@link PooledConnection interface description} for more
* information.
*
* @exception SQLException if a database access error occurs
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since 1.4
*/
void close() throws SQLException;
/** {@collect.stats}
* Registers the given event listener so that it will be notified
* when an event occurs on this <code>PooledConnection</code> object.
*
* @param listener a component, usually the connection pool manager,
* that has implemented the
* <code>ConnectionEventListener</code> interface and wants to be
* notified when the connection is closed or has an error
* @see #removeConnectionEventListener
*/
void addConnectionEventListener(ConnectionEventListener listener);
/** {@collect.stats}
* Removes the given event listener from the list of components that
* will be notified when an event occurs on this
* <code>PooledConnection</code> object.
*
* @param listener a component, usually the connection pool manager,
* that has implemented the
* <code>ConnectionEventListener</code> interface and
* been registered with this <code>PooledConnection</code> object as
* a listener
* @see #addConnectionEventListener
*/
void removeConnectionEventListener(ConnectionEventListener listener);
/** {@collect.stats}
* Registers a <code>StatementEventListener</code> with this <code>PooledConnection</code> object. Components that
* wish to be notified when <code>PreparedStatement</code>s created by the
* connection are closed or are detected to be invalid may use this method
* to register a <code>StatementEventListener</code> with this <code>PooledConnection</code> object.
* <p>
* @param listener an component which implements the <code>StatementEventListener</code>
* interface that is to be registered with this <code>PooledConnection</code> object
* <p>
* @since 1.6
*/
public void addStatementEventListener(StatementEventListener listener);
/** {@collect.stats}
* Removes the specified <code>StatementEventListener</code> from the list of
* components that will be notified when the driver detects that a
* <code>PreparedStatement</code> has been closed or is invalid.
* <p>
* @param listener the component which implements the
* <code>StatementEventListener</code> interface that was previously
* registered with this <code>PooledConnection</code> object
* <p>
* @since 1.6
*/
public void removeStatementEventListener(StatementEventListener listener);
}
| Java |
/*
* Copyright (c) 2000, 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 javax.sql;
/** {@collect.stats}
* An interface that must be implemented by a
* component that wants to be notified when a significant
* event happens in the life of a <code>RowSet</code> object.
* A component becomes a listener by being registered with a
* <code>RowSet</code> object via the method <code>RowSet.addRowSetListener</code>.
* How a registered component implements this interface determines what it does
* when it is notified of an event.
*
* @since 1.4
*/
public interface RowSetListener extends java.util.EventListener {
/** {@collect.stats}
* Notifies registered listeners that a <code>RowSet</code> object
* in the given <code>RowSetEvent</code> object has changed its entire contents.
* <P>
* The source of the event can be retrieved with the method
* <code>event.getSource</code>.
*
* @param event a <code>RowSetEvent</code> object that contains
* the <code>RowSet</code> object that is the source of the event
*/
void rowSetChanged(RowSetEvent event);
/** {@collect.stats}
* Notifies registered listeners that a <code>RowSet</code> object
* has had a change in one of its rows.
* <P>
* The source of the event can be retrieved with the method
* <code>event.getSource</code>.
*
* @param event a <code>RowSetEvent</code> object that contains
* the <code>RowSet</code> object that is the source of the event
*/
void rowChanged(RowSetEvent event);
/** {@collect.stats}
* Notifies registered listeners that a <code>RowSet</code> object's
* cursor has moved.
* <P>
* The source of the event can be retrieved with the method
* <code>event.getSource</code>.
*
* @param event a <code>RowSetEvent</code> object that contains
* the <code>RowSet</code> object that is the source of the event
*/
void cursorMoved(RowSetEvent event);
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.security.GeneralSecurityException;
/** {@collect.stats}
* This exception is thrown when an output buffer provided by the user
* is too short to hold the operation result.
*
* @author Jan Luehe
*
* @since 1.4
*/
public class ShortBufferException extends GeneralSecurityException {
private static final long serialVersionUID = 8427718640832943747L;
/** {@collect.stats}
* Constructs a ShortBufferException with no detail
* message. A detail message is a String that describes this
* particular exception.
*/
public ShortBufferException() {
super();
}
/** {@collect.stats}
* Constructs a ShortBufferException with the specified
* detail message.
*
* @param msg the detail message.
*/
public ShortBufferException(String msg) {
super(msg);
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto.interfaces;
import javax.crypto.spec.DHParameterSpec;
/** {@collect.stats}
* The interface to a Diffie-Hellman key.
*
* @author Jan Luehe
*
* @see javax.crypto.spec.DHParameterSpec
* @see DHPublicKey
* @see DHPrivateKey
* @since 1.4
*/
public interface DHKey {
/** {@collect.stats}
* Returns the key parameters.
*
* @return the key parameters
*/
DHParameterSpec getParams();
}
| Java |
/*
* Copyright (c) 2001, 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 javax.crypto.interfaces;
import java.math.BigInteger;
/** {@collect.stats}
* The interface to a PBE key.
*
* @author Valerie Peng
*
* @see javax.crypto.spec.PBEKeySpec
* @see javax.crypto.SecretKey
* @since 1.4
*/
public interface PBEKey extends javax.crypto.SecretKey {
/** {@collect.stats}
* The class fingerprint that is set to indicate serialization
* compatibility since J2SE 1.4.
*/
static final long serialVersionUID = -1430015993304333921L;
/** {@collect.stats}
* Returns the password.
*
* <p> Note: this method should return a copy of the password. It is
* the caller's responsibility to zero out the password information after
* it is no longer needed.
*
* @return the password.
*/
char[] getPassword();
/** {@collect.stats}
* Returns the salt or null if not specified.
*
* <p> Note: this method should return a copy of the salt. It is
* the caller's responsibility to zero out the salt information after
* it is no longer needed.
*
* @return the salt.
*/
byte[] getSalt();
/** {@collect.stats}
* Returns the iteration count or 0 if not specified.
*
* @return the iteration count.
*/
int getIterationCount();
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto.interfaces;
import java.math.BigInteger;
/** {@collect.stats}
* The interface to a Diffie-Hellman private key.
*
* @author Jan Luehe
*
* @see DHKey
* @see DHPublicKey
* @since 1.4
*/
public interface DHPrivateKey extends DHKey, java.security.PrivateKey {
/** {@collect.stats}
* The class fingerprint that is set to indicate serialization
* compatibility since J2SE 1.4.
*/
static final long serialVersionUID = 2211791113380396553L;
/** {@collect.stats}
* Returns the private value, <code>x</code>.
*
* @return the private value, <code>x</code>
*/
BigInteger getX();
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto.interfaces;
import java.math.BigInteger;
/** {@collect.stats}
* The interface to a Diffie-Hellman public key.
*
* @author Jan Luehe
*
* @see DHKey
* @see DHPrivateKey
* @since 1.4
*/
public interface DHPublicKey extends DHKey, java.security.PublicKey {
/** {@collect.stats}
* The class fingerprint that is set to indicate serialization
* compatibility since J2SE 1.4.
*/
static final long serialVersionUID = -6628103563352519193L;
/** {@collect.stats}
* Returns the public value, <code>y</code>.
*
* @return the public value, <code>y</code>
*/
BigInteger getY();
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.security.GeneralSecurityException;
/** {@collect.stats}
* This exception is thrown when a particular padding mechanism is
* requested but is not available in the environment.
*
* @author Jan Luehe
*
* @since 1.4
*/
public class NoSuchPaddingException extends GeneralSecurityException {
private static final long serialVersionUID = -4572885201200175466L;
/** {@collect.stats}
* Constructs a NoSuchPaddingException with no detail
* message. A detail message is a String that describes this
* particular exception.
*/
public NoSuchPaddingException() {
super();
}
/** {@collect.stats}
* Constructs a NoSuchPaddingException with the specified
* detail message.
*
* @param msg the detail message.
*/
public NoSuchPaddingException(String msg) {
super(msg);
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.io.*;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.InvalidKeyException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
/** {@collect.stats}
* This class enables a programmer to create an object and protect its
* confidentiality with a cryptographic algorithm.
*
* <p> Given any Serializable object, one can create a SealedObject
* that encapsulates the original object, in serialized
* format (i.e., a "deep copy"), and seals (encrypts) its serialized contents,
* using a cryptographic algorithm such as DES, to protect its
* confidentiality. The encrypted content can later be decrypted (with
* the corresponding algorithm using the correct decryption key) and
* de-serialized, yielding the original object.
*
* <p> Note that the Cipher object must be fully initialized with the
* correct algorithm, key, padding scheme, etc., before being applied
* to a SealedObject.
*
* <p> The original object that was sealed can be recovered in two different
* ways: <p>
*
* <ul>
*
* <li>by using the {@link #getObject(javax.crypto.Cipher) getObject}
* method that takes a <code>Cipher</code> object.
*
* <p> This method requires a fully initialized <code>Cipher</code> object,
* initialized with the
* exact same algorithm, key, padding scheme, etc., that were used to seal the
* object.
*
* <p> This approach has the advantage that the party who unseals the
* sealed object does not require knowledge of the decryption key. For example,
* after one party has initialized the cipher object with the required
* decryption key, it could hand over the cipher object to
* another party who then unseals the sealed object.
*
* <p>
*
* <li>by using one of the
* {@link #getObject(java.security.Key) getObject} methods
* that take a <code>Key</code> object.
*
* <p> In this approach, the <code>getObject</code> method creates a cipher
* object for the appropriate decryption algorithm and initializes it with the
* given decryption key and the algorithm parameters (if any) that were stored
* in the sealed object.
*
* <p> This approach has the advantage that the party who
* unseals the object does not need to keep track of the parameters (e.g., an
* IV) that were used to seal the object.
*
* </ul>
*
* @author Li Gong
* @author Jan Luehe
* @see Cipher
* @since 1.4
*/
public class SealedObject implements Serializable {
static final long serialVersionUID = 4482838265551344752L;
/** {@collect.stats}
* The serialized object contents in encrypted format.
*
* @serial
*/
private byte[] encryptedContent = null;
/** {@collect.stats}
* The algorithm that was used to seal this object.
*
* @serial
*/
private String sealAlg = null;
/** {@collect.stats}
* The algorithm of the parameters used.
*
* @serial
*/
private String paramsAlg = null;
/** {@collect.stats}
* The cryptographic parameters used by the sealing Cipher,
* encoded in the default format.
* <p>
* That is, <code>cipher.getParameters().getEncoded()</code>.
*
* @serial
*/
protected byte[] encodedParams = null;
/** {@collect.stats}
* Constructs a SealedObject from any Serializable object.
*
* <p>The given object is serialized, and its serialized contents are
* encrypted using the given Cipher, which must be fully initialized.
*
* <p>Any algorithm parameters that may be used in the encryption
* operation are stored inside of the new <code>SealedObject</code>.
*
* @param object the object to be sealed; can be null.
* @param c the cipher used to seal the object.
*
* @exception NullPointerException if the given cipher is null.
* @exception IOException if an error occurs during serialization
* @exception IllegalBlockSizeException if the given cipher is a block
* cipher, no padding has been requested, and the total input length
* (i.e., the length of the serialized object contents) is not a multiple
* of the cipher's block size
*/
public SealedObject(Serializable object, Cipher c) throws IOException,
IllegalBlockSizeException
{
/*
* Serialize the object
*/
// creating a stream pipe-line, from a to b
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutput a = new ObjectOutputStream(b);
byte[] content;
try {
// write and flush the object content to byte array
a.writeObject(object);
a.flush();
content = b.toByteArray();
} finally {
a.close();
}
/*
* Seal the object
*/
try {
this.encryptedContent = c.doFinal(content);
}
catch (BadPaddingException ex) {
// if sealing is encryption only
// Should never happen??
}
// Save the parameters
if (c.getParameters() != null) {
this.encodedParams = c.getParameters().getEncoded();
this.paramsAlg = c.getParameters().getAlgorithm();
}
// Save the encryption algorithm
this.sealAlg = c.getAlgorithm();
}
/** {@collect.stats}
* Constructs a SealedObject object from the passed-in SealedObject.
*
* @param so a SealedObject object
* @exception NullPointerException if the given sealed object is null.
*/
protected SealedObject(SealedObject so) {
this.encryptedContent = (byte[]) so.encryptedContent.clone();
this.sealAlg = so.sealAlg;
this.paramsAlg = so.paramsAlg;
if (so.encodedParams != null) {
this.encodedParams = (byte[]) so.encodedParams.clone();
} else {
this.encodedParams = null;
}
}
/** {@collect.stats}
* Returns the algorithm that was used to seal this object.
*
* @return the algorithm that was used to seal this object.
*/
public final String getAlgorithm() {
return this.sealAlg;
}
/** {@collect.stats}
* Retrieves the original (encapsulated) object.
*
* <p>This method creates a cipher for the algorithm that had been used in
* the sealing operation.
* If the default provider package provides an implementation of that
* algorithm, an instance of Cipher containing that implementation is used.
* If the algorithm is not available in the default package, other
* packages are searched.
* The Cipher object is initialized for decryption, using the given
* <code>key</code> and the parameters (if any) that had been used in the
* sealing operation.
*
* <p>The encapsulated object is unsealed and de-serialized, before it is
* returned.
*
* @param key the key used to unseal the object.
*
* @return the original object.
*
* @exception IOException if an error occurs during de-serialiazation.
* @exception ClassNotFoundException if an error occurs during
* de-serialiazation.
* @exception NoSuchAlgorithmException if the algorithm to unseal the
* object is not available.
* @exception InvalidKeyException if the given key cannot be used to unseal
* the object (e.g., it has the wrong algorithm).
* @exception NullPointerException if <code>key</code> is null.
*/
public final Object getObject(Key key)
throws IOException, ClassNotFoundException, NoSuchAlgorithmException,
InvalidKeyException
{
if (key == null) {
throw new NullPointerException("key is null");
}
try {
return unseal(key, null);
} catch (NoSuchProviderException nspe) {
// we've already caught NoSuchProviderException's and converted
// them into NoSuchAlgorithmException's with details about
// the failing algorithm
throw new NoSuchAlgorithmException("algorithm not found");
} catch (IllegalBlockSizeException ibse) {
throw new InvalidKeyException(ibse.getMessage());
} catch (BadPaddingException bpe) {
throw new InvalidKeyException(bpe.getMessage());
}
}
/** {@collect.stats}
* Retrieves the original (encapsulated) object.
*
* <p>The encapsulated object is unsealed (using the given Cipher,
* assuming that the Cipher is already properly initialized) and
* de-serialized, before it is returned.
*
* @param c the cipher used to unseal the object
*
* @return the original object.
*
* @exception NullPointerException if the given cipher is null.
* @exception IOException if an error occurs during de-serialiazation
* @exception ClassNotFoundException if an error occurs during
* de-serialiazation
* @exception IllegalBlockSizeException if the given cipher is a block
* cipher, no padding has been requested, and the total input length is
* not a multiple of the cipher's block size
* @exception BadPaddingException if the given cipher has been
* initialized for decryption, and padding has been specified, but
* the input data does not have proper expected padding bytes
*/
public final Object getObject(Cipher c)
throws IOException, ClassNotFoundException, IllegalBlockSizeException,
BadPaddingException
{
/*
* Unseal the object
*/
byte[] content = c.doFinal(this.encryptedContent);
/*
* De-serialize it
*/
// creating a stream pipe-line, from b to a
ByteArrayInputStream b = new ByteArrayInputStream(content);
ObjectInput a = new extObjectInputStream(b);
try {
Object obj = a.readObject();
return obj;
} finally {
a.close();
}
}
/** {@collect.stats}
* Retrieves the original (encapsulated) object.
*
* <p>This method creates a cipher for the algorithm that had been used in
* the sealing operation, using an implementation of that algorithm from
* the given <code>provider</code>.
* The Cipher object is initialized for decryption, using the given
* <code>key</code> and the parameters (if any) that had been used in the
* sealing operation.
*
* <p>The encapsulated object is unsealed and de-serialized, before it is
* returned.
*
* @param key the key used to unseal the object.
* @param provider the name of the provider of the algorithm to unseal
* the object.
*
* @return the original object.
*
* @exception IllegalArgumentException if the given provider is null
* or empty.
* @exception IOException if an error occurs during de-serialiazation.
* @exception ClassNotFoundException if an error occurs during
* de-serialiazation.
* @exception NoSuchAlgorithmException if the algorithm to unseal the
* object is not available.
* @exception NoSuchProviderException if the given provider is not
* configured.
* @exception InvalidKeyException if the given key cannot be used to unseal
* the object (e.g., it has the wrong algorithm).
* @exception NullPointerException if <code>key</code> is null.
*/
public final Object getObject(Key key, String provider)
throws IOException, ClassNotFoundException, NoSuchAlgorithmException,
NoSuchProviderException, InvalidKeyException
{
if (key == null) {
throw new NullPointerException("key is null");
}
if (provider == null || provider.length() == 0) {
throw new IllegalArgumentException("missing provider");
}
try {
return unseal(key, provider);
} catch (IllegalBlockSizeException ibse) {
throw new InvalidKeyException(ibse.getMessage());
} catch (BadPaddingException bpe) {
throw new InvalidKeyException(bpe.getMessage());
}
}
private Object unseal(Key key, String provider)
throws IOException, ClassNotFoundException, NoSuchAlgorithmException,
NoSuchProviderException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException
{
/*
* Create the parameter object.
*/
AlgorithmParameters params = null;
if (this.encodedParams != null) {
try {
if (provider != null)
params = AlgorithmParameters.getInstance(this.paramsAlg,
provider);
else
params = AlgorithmParameters.getInstance(this.paramsAlg);
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.paramsAlg
+ " not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
params.init(this.encodedParams);
}
/*
* Create and initialize the cipher.
*/
Cipher c;
try {
if (provider != null)
c = Cipher.getInstance(this.sealAlg, provider);
else
c = Cipher.getInstance(this.sealAlg);
} catch (NoSuchPaddingException nspe) {
throw new NoSuchAlgorithmException("Padding that was used in "
+ "sealing operation not "
+ "available");
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.sealAlg+" not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
try {
if (params != null)
c.init(Cipher.DECRYPT_MODE, key, params);
else
c.init(Cipher.DECRYPT_MODE, key);
} catch (InvalidAlgorithmParameterException iape) {
// this should never happen, because we use the exact same
// parameters that were used in the sealing operation
throw new RuntimeException(iape.getMessage());
}
/*
* Unseal the object
*/
byte[] content = c.doFinal(this.encryptedContent);
/*
* De-serialize it
*/
// creating a stream pipe-line, from b to a
ByteArrayInputStream b = new ByteArrayInputStream(content);
ObjectInput a = new extObjectInputStream(b);
try {
Object obj = a.readObject();
return obj;
} finally {
a.close();
}
}
/** {@collect.stats}
* Restores the state of the SealedObject from a stream.
* @param s the object input stream.
* @exception NullPointerException if s is null.
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException
{
s.defaultReadObject();
if (encryptedContent != null)
encryptedContent = (byte[])encryptedContent.clone();
if (encodedParams != null)
encodedParams = (byte[])encodedParams.clone();
}
}
final class extObjectInputStream extends ObjectInputStream {
private static ClassLoader systemClassLoader = null;
extObjectInputStream(InputStream in)
throws IOException, StreamCorruptedException {
super(in);
}
protected Class resolveClass(ObjectStreamClass v)
throws IOException, ClassNotFoundException
{
try {
/*
* Calling the super.resolveClass() first
* will let us pick up bug fixes in the super
* class (e.g., 4171142).
*/
return super.resolveClass(v);
} catch (ClassNotFoundException cnfe) {
/*
* This is a workaround for bug 4224921.
*/
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (loader == null) {
if (systemClassLoader == null) {
systemClassLoader = ClassLoader.getSystemClassLoader();
}
loader = systemClassLoader;
if (loader == null) {
throw new ClassNotFoundException(v.getName());
}
}
return Class.forName(v.getName(), false, loader);
}
}
}
| Java |
/*
* Copyright (c) 1999, 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 javax.crypto;
import java.security.*;
import java.net.*;
import java.util.*;
import java.util.jar.*;
/** {@collect.stats}
* The JCE security manager.
*
* <p>The JCE security manager is responsible for determining the maximum
* allowable cryptographic strength for a given applet/application, for a given
* algorithm, by consulting the configured jurisdiction policy files and
* the cryptographic permissions bundled with the applet/application.
*
* <p>Note that this security manager is never installed, only instantiated.
*
* @author Jan Luehe
*
* @since 1.4
*/
final class JceSecurityManager extends SecurityManager {
private static final CryptoPermissions defaultPolicy;
private static final CryptoPermissions exemptPolicy;
private static final CryptoAllPermission allPerm;
private static final Vector TrustedCallersCache = new Vector(2);
private static final Map exemptCache = new HashMap();
// singleton instance
static final JceSecurityManager INSTANCE;
static {
defaultPolicy = JceSecurity.getDefaultPolicy();
exemptPolicy = JceSecurity.getExemptPolicy();
allPerm = CryptoAllPermission.INSTANCE;
INSTANCE = (JceSecurityManager)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return new JceSecurityManager();
}
});
}
private JceSecurityManager() {
// empty
}
/** {@collect.stats}
* Returns the maximum allowable crypto strength for the given
* applet/application, for the given algorithm.
*/
CryptoPermission getCryptoPermission(String alg) {
// Need to convert to uppercase since the crypto perm
// lookup is case sensitive.
alg = alg.toUpperCase(Locale.ENGLISH);
// If CryptoAllPermission is granted by default, we return that.
// Otherwise, this will be the permission we return if anything goes
// wrong.
CryptoPermission defaultPerm = getDefaultPermission(alg);
if (defaultPerm == CryptoAllPermission.INSTANCE) {
return defaultPerm;
}
// Determine the codebase of the caller of the JCE API.
// This is the codebase of the first class which is not in
// javax.crypto.* packages.
// NOTE: javax.crypto.* package maybe subject to package
// insertion, so need to check its classloader as well.
Class[] context = getClassContext();
URL callerCodeBase = null;
int i;
for (i=0; i<context.length; i++) {
Class cls = context[i];
callerCodeBase = JceSecurity.getCodeBase(cls);
if (callerCodeBase != null) {
break;
} else {
if (cls.getName().startsWith("javax.crypto.")) {
// skip jce classes since they aren't the callers
continue;
}
// use default permission when the caller is system classes
return defaultPerm;
}
}
if (i == context.length) {
return defaultPerm;
}
CryptoPermissions appPerms;
synchronized (this.getClass()) {
if (exemptCache.containsKey(callerCodeBase)) {
appPerms = (CryptoPermissions)exemptCache.get(callerCodeBase);
} else {
appPerms = getAppPermissions(callerCodeBase);
exemptCache.put(callerCodeBase, appPerms);
}
}
if (appPerms == null) {
return defaultPerm;
}
// If the app was granted the special CryptoAllPermission, return that.
if (appPerms.implies(allPerm)) {
return allPerm;
}
// Check if the crypto permissions granted to the app contain a
// crypto permission for the requested algorithm that does not require
// any exemption mechanism to be enforced.
// Return that permission, if present.
PermissionCollection appPc = appPerms.getPermissionCollection(alg);
if (appPc == null) {
return defaultPerm;
}
Enumeration enum_ = appPc.elements();
while (enum_.hasMoreElements()) {
CryptoPermission cp = (CryptoPermission)enum_.nextElement();
if (cp.getExemptionMechanism() == null) {
return cp;
}
}
// Check if the jurisdiction file for exempt applications contains
// any entries for the requested algorithm.
// If not, return the default permission.
PermissionCollection exemptPc =
exemptPolicy.getPermissionCollection(alg);
if (exemptPc == null) {
return defaultPerm;
}
// In the jurisdiction file for exempt applications, go through the
// list of CryptoPermission entries for the requested algorithm, and
// stop at the first entry:
// - that is implied by the collection of crypto permissions granted
// to the app, and
// - whose exemption mechanism is available from one of the
// registered CSPs
enum_ = exemptPc.elements();
while (enum_.hasMoreElements()) {
CryptoPermission cp = (CryptoPermission)enum_.nextElement();
try {
ExemptionMechanism.getInstance(cp.getExemptionMechanism());
if (cp.getAlgorithm().equals(
CryptoPermission.ALG_NAME_WILDCARD)) {
CryptoPermission newCp;
if (cp.getCheckParam()) {
newCp = new CryptoPermission(
alg, cp.getMaxKeySize(),
cp.getAlgorithmParameterSpec(),
cp.getExemptionMechanism());
} else {
newCp = new CryptoPermission(
alg, cp.getMaxKeySize(),
cp.getExemptionMechanism());
}
if (appPerms.implies(newCp)) {
return newCp;
}
}
if (appPerms.implies(cp)) {
return cp;
}
} catch (Exception e) {
continue;
}
}
return defaultPerm;
}
private static CryptoPermissions getAppPermissions(URL callerCodeBase) {
// Check if app is exempt, and retrieve the permissions bundled with it
try {
return JceSecurity.verifyExemptJar(callerCodeBase);
} catch (Exception e) {
// Jar verification fails
return null;
}
}
/** {@collect.stats}
* Returns the default permission for the given algorithm.
*/
private CryptoPermission getDefaultPermission(String alg) {
Enumeration enum_ =
defaultPolicy.getPermissionCollection(alg).elements();
return (CryptoPermission)enum_.nextElement();
}
// See bug 4341369 & 4334690 for more info.
boolean isCallerTrusted() {
// Get the caller and its codebase.
Class[] context = getClassContext();
URL callerCodeBase = null;
int i;
for (i=0; i<context.length; i++) {
callerCodeBase = JceSecurity.getCodeBase(context[i]);
if (callerCodeBase != null) {
break;
}
}
// The caller is in the JCE framework.
if (i == context.length) {
return true;
}
//The caller has been verified.
if (TrustedCallersCache.contains(context[i])) {
return true;
}
// Check whether the caller is a trusted provider.
try {
JceSecurity.verifyProviderJar(callerCodeBase);
} catch (Exception e2) {
return false;
}
TrustedCallersCache.addElement(context[i]);
return true;
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.security.GeneralSecurityException;
/** {@collect.stats}
* This exception is thrown when a particular padding mechanism is
* expected for the input data but the data is not padded properly.
*
* @author Gigi Ankney
* @since 1.4
*/
public class BadPaddingException extends GeneralSecurityException {
private static final long serialVersionUID = -5315033893984728443L;
/** {@collect.stats}
* Constructs a BadPaddingException with no detail
* message. A detail message is a String that describes this
* particular exception.
*/
public BadPaddingException() {
super();
}
/** {@collect.stats}
* Constructs a BadPaddingException with the specified
* detail message.
*
* @param msg the detail message.
*/
public BadPaddingException(String msg) {
super(msg);
}
}
| Java |
/*
* Copyright (c) 1999, 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 javax.crypto;
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Vector;
import javax.crypto.spec.*;
/** {@collect.stats}
* The CryptoPermission class extends the
* java.security.Permission class. A
* CryptoPermission object is used to represent
* the ability of an application/applet to use certain
* algorithms with certain key sizes and other
* restrictions in certain environments. <p>
*
* @see java.security.Permission
*
* @author Jan Luehe
* @author Sharon Liu
* @since 1.4
*/
class CryptoPermission extends java.security.Permission {
private static final long serialVersionUID = 8987399626114087514L;
private String alg;
private int maxKeySize = Integer.MAX_VALUE; // no restriction on maxKeySize
private String exemptionMechanism = null;
private AlgorithmParameterSpec algParamSpec = null;
private boolean checkParam = false; // no restriction on param
static final String ALG_NAME_WILDCARD = "*";
/** {@collect.stats}
* Constructor that takes an algorithm name.
*
* This constructor implies that the given algorithm can be
* used without any restrictions.
*
* @param alg the algorithm name.
*/
CryptoPermission(String alg) {
super(null);
this.alg = alg;
}
/** {@collect.stats}
* Constructor that takes an algorithm name and a maximum
* key size.
*
* This constructor implies that the given algorithm can be
* used with a key size up to <code>maxKeySize</code>.
*
* @param alg the algorithm name.
*
* @param maxKeySize the maximum allowable key size,
* specified in number of bits.
*/
CryptoPermission(String alg, int maxKeySize) {
super(null);
this.alg = alg;
this.maxKeySize = maxKeySize;
}
/** {@collect.stats}
* Constructor that takes an algorithm name, a maximum
* key size, and an AlgorithmParameterSpec object.
*
* This constructor implies that the given algorithm can be
* used with a key size up to <code>maxKeySize</code>, and
* algorithm
* parameters up to the limits set in <code>algParamSpec</code>.
*
* @param alg the algorithm name.
*
* @param maxKeySize the maximum allowable key size,
* specified in number of bits.
*
* @param algParamSpec the limits for allowable algorithm
* parameters.
*/
CryptoPermission(String alg,
int maxKeySize,
AlgorithmParameterSpec algParamSpec) {
super(null);
this.alg = alg;
this.maxKeySize = maxKeySize;
this.checkParam = true;
this.algParamSpec = algParamSpec;
}
/** {@collect.stats}
* Constructor that takes an algorithm name and the name of
* an exemption mechanism.
*
* This constructor implies that the given algorithm can be
* used without any key size or algorithm parameter restrictions
* provided that the specified exemption mechanism is enforced.
*
* @param alg the algorithm name.
*
* @param exemptionMechanism the name of the exemption mechanism.
*/
CryptoPermission(String alg,
String exemptionMechanism) {
super(null);
this.alg = alg;
this.exemptionMechanism = exemptionMechanism;
}
/** {@collect.stats}
* Constructor that takes an algorithm name, a maximum key
* size, and the name of an exemption mechanism.
*
* This constructor implies that the given algorithm can be
* used with a key size up to <code>maxKeySize</code>
* provided that the
* specified exemption mechanism is enforced.
*
* @param alg the algorithm name.
* @param maxKeySize the maximum allowable key size,
* specified in number of bits.
* @param exemptionMechanism the name of the exemption
* mechanism.
*/
CryptoPermission(String alg,
int maxKeySize,
String exemptionMechanism) {
super(null);
this.alg = alg;
this.exemptionMechanism = exemptionMechanism;
this.maxKeySize = maxKeySize;
}
/** {@collect.stats}
* Constructor that takes an algorithm name, a maximum key
* size, the name of an exemption mechanism, and an
* AlgorithmParameterSpec object.
*
* This constructor implies that the given algorithm can be
* used with a key size up to <code>maxKeySize</code>
* and algorithm
* parameters up to the limits set in <code>algParamSpec</code>
* provided that
* the specified exemption mechanism is enforced.
*
* @param alg the algorithm name.
* @param maxKeySize the maximum allowable key size,
* specified in number of bits.
* @param algParamSpec the limit for allowable algorithm
* parameter spec.
* @param exemptionMechanism the name of the exemption
* mechanism.
*/
CryptoPermission(String alg,
int maxKeySize,
AlgorithmParameterSpec algParamSpec,
String exemptionMechanism) {
super(null);
this.alg = alg;
this.exemptionMechanism = exemptionMechanism;
this.maxKeySize = maxKeySize;
this.checkParam = true;
this.algParamSpec = algParamSpec;
}
/** {@collect.stats}
* Checks if the specified permission is "implied" by
* this object.
* <p>
* More specifically, this method returns true if:<p>
* <ul>
* <li> <i>p</i> is an instance of CryptoPermission, and<p>
* <li> <i>p</i>'s algorithm name equals or (in the case of wildcards)
* is implied by this permission's algorithm name, and<p>
* <li> <i>p</i>'s maximum allowable key size is less or
* equal to this permission's maximum allowable key size, and<p>
* <li> <i>p</i>'s algorithm parameter spec equals or is
* implied by this permission's algorithm parameter spec, and<p>
* <li> <i>p</i>'s exemptionMechanism equals or
* is implied by this permission's
* exemptionMechanism (a <code>null</code> exemption mechanism
* implies any other exemption mechanism).
* </ul>
*
* @param p the permission to check against.
*
* @return true if the specified permission is equal to or
* implied by this permission, false otherwise.
*/
public boolean implies(Permission p) {
if (!(p instanceof CryptoPermission))
return false;
CryptoPermission cp = (CryptoPermission)p;
if ((!alg.equalsIgnoreCase(cp.alg)) &&
(!alg.equalsIgnoreCase(ALG_NAME_WILDCARD))) {
return false;
}
// alg is the same as cp's alg or
// alg is a wildcard.
if (cp.maxKeySize <= this.maxKeySize) {
// check algParamSpec.
if (!impliesParameterSpec(cp.checkParam, cp.algParamSpec)) {
return false;
}
// check exemptionMechanism.
if (impliesExemptionMechanism(cp.exemptionMechanism)) {
return true;
}
}
return false;
}
/** {@collect.stats}
* Checks two CryptoPermission objects for equality. Checks that
* <code>obj</code> is a CryptoPermission, and has the same
* algorithm name,
* exemption mechanism name, maximum allowable key size and
* algorithm parameter spec
* as this object.
* <P>
* @param obj the object to test for equality with this object.
* @return true if <code>obj</code> is equal to this object.
*/
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof CryptoPermission))
return false;
CryptoPermission that = (CryptoPermission) obj;
if (!(alg.equalsIgnoreCase(that.alg)) ||
(maxKeySize != that.maxKeySize)) {
return false;
}
if (this.checkParam != that.checkParam) {
return false;
}
return (equalObjects(this.exemptionMechanism,
that.exemptionMechanism) &&
equalObjects(this.algParamSpec,
that.algParamSpec));
}
/** {@collect.stats}
* Returns the hash code value for this object.
*
* @return a hash code value for this object.
*/
public int hashCode() {
int retval = alg.hashCode();
retval ^= maxKeySize;
if (exemptionMechanism != null) {
retval ^= exemptionMechanism.hashCode();
}
if (checkParam) retval ^= 100;
if (algParamSpec != null) {
retval ^= algParamSpec.hashCode();
}
return retval;
}
/** {@collect.stats}
* There is no action defined for a CryptoPermission
* onject.
*/
public String getActions()
{
return null;
}
/** {@collect.stats}
* Returns a new PermissionCollection object for storing
* CryptoPermission objects.
*
* @return a new PermissionCollection object suitable for storing
* CryptoPermissions.
*/
public PermissionCollection newPermissionCollection() {
return new CryptoPermissionCollection();
}
/** {@collect.stats}
* Returns the algorithm name associated with
* this CryptoPermission object.
*/
final String getAlgorithm() {
return alg;
}
/** {@collect.stats}
* Returns the exemption mechanism name
* associated with this CryptoPermission
* object.
*/
final String getExemptionMechanism() {
return exemptionMechanism;
}
/** {@collect.stats}
* Returns the maximum allowable key size associated
* with this CryptoPermission object.
*/
final int getMaxKeySize() {
return maxKeySize;
}
/** {@collect.stats}
* Returns true if there is a limitation on the
* AlgorithmParameterSpec associated with this
* CryptoPermission object and false if otherwise.
*/
final boolean getCheckParam() {
return checkParam;
}
/** {@collect.stats}
* Returns the AlgorithmParameterSpec
* associated with this CryptoPermission
* object.
*/
final AlgorithmParameterSpec getAlgorithmParameterSpec() {
return algParamSpec;
}
/** {@collect.stats}
* Returns a string describing this CryptoPermission. The convention is to
* specify the class name, the algorithm name, the maximum allowable
* key size, and the name of the exemption mechanism, in the following
* format: '("ClassName" "algorithm" "keysize" "exemption_mechanism")'.
*
* @return information about this CryptoPermission.
*/
public String toString() {
StringBuilder buf = new StringBuilder(100);
buf.append("(CryptoPermission " + alg + " " + maxKeySize);
if (algParamSpec != null) {
if (algParamSpec instanceof RC2ParameterSpec) {
buf.append(" , effective " +
((RC2ParameterSpec)algParamSpec).getEffectiveKeyBits());
} else if (algParamSpec instanceof RC5ParameterSpec) {
buf.append(" , rounds " +
((RC5ParameterSpec)algParamSpec).getRounds());
}
}
if (exemptionMechanism != null) { // OPTIONAL
buf.append(" " + exemptionMechanism);
}
buf.append(")");
return buf.toString();
}
private boolean impliesExemptionMechanism(String exemptionMechanism) {
if (this.exemptionMechanism == null) {
return true;
}
if (exemptionMechanism == null) {
return false;
}
if (this.exemptionMechanism.equals(exemptionMechanism)) {
return true;
}
return false;
}
private boolean impliesParameterSpec(boolean checkParam,
AlgorithmParameterSpec algParamSpec) {
if ((this.checkParam) && checkParam) {
if (algParamSpec == null) {
return true;
} else if (this.algParamSpec == null) {
return false;
}
if (this.algParamSpec.getClass() != algParamSpec.getClass()) {
return false;
}
if (algParamSpec instanceof RC2ParameterSpec) {
if (((RC2ParameterSpec)algParamSpec).getEffectiveKeyBits() <=
((RC2ParameterSpec)
(this.algParamSpec)).getEffectiveKeyBits()) {
return true;
}
}
if (algParamSpec instanceof RC5ParameterSpec) {
if (((RC5ParameterSpec)algParamSpec).getRounds() <=
((RC5ParameterSpec)this.algParamSpec).getRounds()) {
return true;
}
}
if (algParamSpec instanceof PBEParameterSpec) {
if (((PBEParameterSpec)algParamSpec).getIterationCount() <=
((PBEParameterSpec)this.algParamSpec).getIterationCount()) {
return true;
}
}
// For classes we don't know, the following
// may be the best try.
if (this.algParamSpec.equals(algParamSpec)) {
return true;
}
return false;
} else if (this.checkParam) {
return false;
} else {
return true;
}
}
private boolean equalObjects(Object obj1, Object obj2) {
if (obj1 == null) {
return (obj2 == null ? true : false);
}
return obj1.equals(obj2);
}
}
/** {@collect.stats}
* A CryptoPermissionCollection stores a set of CryptoPermission
* permissions.
*
* @see java.security.Permission
* @see java.security.Permissions
* @see java.security.PermissionCollection
*
* @author Sharon Liu
*/
final class CryptoPermissionCollection extends PermissionCollection
implements Serializable {
private static final long serialVersionUID = -511215555898802763L;
private Vector permissions;
/** {@collect.stats}
* Creates an empty CryptoPermissionCollection
* object.
*/
CryptoPermissionCollection() {
permissions = new Vector(3);
}
/** {@collect.stats}
* Adds a permission to the CryptoPermissionCollection.
*
* @param permission the Permission object to add.
*
* @exception SecurityException - if this CryptoPermissionCollection
* object has been marked <i>readOnly</i>.
*/
public void add(Permission permission)
{
if (isReadOnly())
throw new SecurityException("attempt to add a Permission " +
"to a readonly PermissionCollection");
if (!(permission instanceof CryptoPermission))
return;
permissions.addElement(permission);
}
/** {@collect.stats}
* Check and see if this CryptoPermission object implies
* the given Permission object.
*
* @param p the Permission object to compare
*
* @return true if the given permission is implied by this
* CryptoPermissionCollection, false if not.
*/
public boolean implies(Permission permission) {
if (!(permission instanceof CryptoPermission))
return false;
CryptoPermission cp = (CryptoPermission)permission;
Enumeration e = permissions.elements();
while (e.hasMoreElements()) {
CryptoPermission x = (CryptoPermission) e.nextElement();
if (x.implies(cp)) {
return true;
}
}
return false;
}
/** {@collect.stats}
* Returns an enumeration of all the CryptoPermission objects
* in the container.
*
* @return an enumeration of all the CryptoPermission objects.
*/
public Enumeration elements()
{
return permissions.elements();
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
/** {@collect.stats}
* The NullCipher class is a class that provides an
* "identity cipher" -- one that does not tranform the plaintext. As
* a consequence, the ciphertext is identical to the plaintext. All
* initialization methods do nothing, while the blocksize is set to 1
* byte.
*
* @author Li Gong
* @since 1.4
*/
public class NullCipher extends Cipher {
public NullCipher() {
super(new NullCipherSpi(), null);
}
}
| Java |
/*
* Copyright (c) 1999, 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 javax.crypto;
import java.security.GeneralSecurityException;
/** {@collect.stats}
* This is the generic ExemptionMechanism exception.
*
* @since 1.4
*/
public class ExemptionMechanismException extends GeneralSecurityException {
private static final long serialVersionUID = 1572699429277957109L;
/** {@collect.stats}
* Constructs a ExemptionMechanismException with no detailed message.
* (A detailed message is a String that describes this particular
* exception.)
*/
public ExemptionMechanismException() {
super();
}
/** {@collect.stats}
* Constructs a ExemptionMechanismException with the specified
* detailed message. (A detailed message is a String that describes
* this particular exception.)
*
* @param msg the detailed message.
*/
public ExemptionMechanismException(String msg) {
super(msg);
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.util.StringTokenizer;
import java.util.NoSuchElementException;
import java.security.AlgorithmParameters;
import java.security.Provider;
import java.security.Key;
import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.InvalidKeyException;
import java.security.InvalidAlgorithmParameterException;
import java.security.ProviderException;
import java.security.spec.AlgorithmParameterSpec;
import java.nio.ByteBuffer;
/** {@collect.stats}
* This class defines the <i>Service Provider Interface</i> (<b>SPI</b>)
* for the <code>Cipher</code> class.
* All the abstract methods in this class must be implemented by each
* cryptographic service provider who wishes to supply the implementation
* of a particular cipher algorithm.
*
* <p>In order to create an instance of <code>Cipher</code>, which
* encapsulates an instance of this <code>CipherSpi</code> class, an
* application calls one of the
* {@link Cipher#getInstance(java.lang.String) getInstance}
* factory methods of the
* {@link Cipher Cipher} engine class and specifies the requested
* <i>transformation</i>.
* Optionally, the application may also specify the name of a provider.
*
* <p>A <i>transformation</i> is a string that describes the operation (or
* set of operations) to be performed on the given input, to produce some
* output. A transformation always includes the name of a cryptographic
* algorithm (e.g., <i>DES</i>), and may be followed by a feedback mode and
* padding scheme.
*
* <p> A transformation is of the form:<p>
*
* <ul>
* <li>"<i>algorithm/mode/padding</i>" or
* <p>
* <li>"<i>algorithm</i>"
* </ul>
*
* <P> (in the latter case,
* provider-specific default values for the mode and padding scheme are used).
* For example, the following is a valid transformation:<p>
*
* <pre>
* Cipher c = Cipher.getInstance("<i>DES/CBC/PKCS5Padding</i>");
* </pre>
*
* <p>A provider may supply a separate class for each combination
* of <i>algorithm/mode/padding</i>, or may decide to provide more generic
* classes representing sub-transformations corresponding to
* <i>algorithm</i> or <i>algorithm/mode</i> or <i>algorithm//padding</i>
* (note the double slashes),
* in which case the requested mode and/or padding are set automatically by
* the <code>getInstance</code> methods of <code>Cipher</code>, which invoke
* the {@link #engineSetMode(java.lang.String) engineSetMode} and
* {@link #engineSetPadding(java.lang.String) engineSetPadding}
* methods of the provider's subclass of <code>CipherSpi</code>.
*
* <p>A <code>Cipher</code> property in a provider master class may have one of
* the following formats:
*
* <ul>
*
* <li>
* <pre>
* // provider's subclass of "CipherSpi" implements "algName" with
* // pluggable mode and padding
* <code>Cipher.</code><i>algName</i>
* </pre>
*
* <li>
* <pre>
* // provider's subclass of "CipherSpi" implements "algName" in the
* // specified "mode", with pluggable padding
* <code>Cipher.</code><i>algName/mode</i>
* </pre>
*
* <li>
* <pre>
* // provider's subclass of "CipherSpi" implements "algName" with the
* // specified "padding", with pluggable mode
* <code>Cipher.</code><i>algName//padding</i>
* </pre>
*
* <li>
* <pre>
* // provider's subclass of "CipherSpi" implements "algName" with the
* // specified "mode" and "padding"
* <code>Cipher.</code><i>algName/mode/padding</i>
* </pre>
*
* </ul>
*
* <p>For example, a provider may supply a subclass of <code>CipherSpi</code>
* that implements <i>DES/ECB/PKCS5Padding</i>, one that implements
* <i>DES/CBC/PKCS5Padding</i>, one that implements
* <i>DES/CFB/PKCS5Padding</i>, and yet another one that implements
* <i>DES/OFB/PKCS5Padding</i>. That provider would have the following
* <code>Cipher</code> properties in its master class:<p>
*
* <ul>
*
* <li>
* <pre>
* <code>Cipher.</code><i>DES/ECB/PKCS5Padding</i>
* </pre>
*
* <li>
* <pre>
* <code>Cipher.</code><i>DES/CBC/PKCS5Padding</i>
* </pre>
*
* <li>
* <pre>
* <code>Cipher.</code><i>DES/CFB/PKCS5Padding</i>
* </pre>
*
* <li>
* <pre>
* <code>Cipher.</code><i>DES/OFB/PKCS5Padding</i>
* </pre>
*
* </ul>
*
* <p>Another provider may implement a class for each of the above modes
* (i.e., one class for <i>ECB</i>, one for <i>CBC</i>, one for <i>CFB</i>,
* and one for <i>OFB</i>), one class for <i>PKCS5Padding</i>,
* and a generic <i>DES</i> class that subclasses from <code>CipherSpi</code>.
* That provider would have the following
* <code>Cipher</code> properties in its master class:<p>
*
* <ul>
*
* <li>
* <pre>
* <code>Cipher.</code><i>DES</i>
* </pre>
*
* </ul>
*
* <p>The <code>getInstance</code> factory method of the <code>Cipher</code>
* engine class follows these rules in order to instantiate a provider's
* implementation of <code>CipherSpi</code> for a
* transformation of the form "<i>algorithm</i>":
*
* <ol>
* <li>
* Check if the provider has registered a subclass of <code>CipherSpi</code>
* for the specified "<i>algorithm</i>".
* <p>If the answer is YES, instantiate this
* class, for whose mode and padding scheme default values (as supplied by
* the provider) are used.
* <p>If the answer is NO, throw a <code>NoSuchAlgorithmException</code>
* exception.
* </ol>
*
* <p>The <code>getInstance</code> factory method of the <code>Cipher</code>
* engine class follows these rules in order to instantiate a provider's
* implementation of <code>CipherSpi</code> for a
* transformation of the form "<i>algorithm/mode/padding</i>":
*
* <ol>
* <li>
* Check if the provider has registered a subclass of <code>CipherSpi</code>
* for the specified "<i>algorithm/mode/padding</i>" transformation.
* <p>If the answer is YES, instantiate it.
* <p>If the answer is NO, go to the next step.<p>
* <li>
* Check if the provider has registered a subclass of <code>CipherSpi</code>
* for the sub-transformation "<i>algorithm/mode</i>".
* <p>If the answer is YES, instantiate it, and call
* <code>engineSetPadding(<i>padding</i>)</code> on the new instance.
* <p>If the answer is NO, go to the next step.<p>
* <li>
* Check if the provider has registered a subclass of <code>CipherSpi</code>
* for the sub-transformation "<i>algorithm//padding</i>" (note the double
* slashes).
* <p>If the answer is YES, instantiate it, and call
* <code>engineSetMode(<i>mode</i>)</code> on the new instance.
* <p>If the answer is NO, go to the next step.<p>
* <li>
* Check if the provider has registered a subclass of <code>CipherSpi</code>
* for the sub-transformation "<i>algorithm</i>".
* <p>If the answer is YES, instantiate it, and call
* <code>engineSetMode(<i>mode</i>)</code> and
* <code>engineSetPadding(<i>padding</i>)</code> on the new instance.
* <p>If the answer is NO, throw a <code>NoSuchAlgorithmException</code>
* exception.
* </ol>
*
* @author Jan Luehe
* @see KeyGenerator
* @see SecretKey
* @since 1.4
*/
public abstract class CipherSpi {
/** {@collect.stats}
* Sets the mode of this cipher.
*
* @param mode the cipher mode
*
* @exception NoSuchAlgorithmException if the requested cipher mode does
* not exist
*/
protected abstract void engineSetMode(String mode)
throws NoSuchAlgorithmException;
/** {@collect.stats}
* Sets the padding mechanism of this cipher.
*
* @param padding the padding mechanism
*
* @exception NoSuchPaddingException if the requested padding mechanism
* does not exist
*/
protected abstract void engineSetPadding(String padding)
throws NoSuchPaddingException;
/** {@collect.stats}
* Returns the block size (in bytes).
*
* @return the block size (in bytes), or 0 if the underlying algorithm is
* not a block cipher
*/
protected abstract int engineGetBlockSize();
/** {@collect.stats}
* Returns the length in bytes that an output buffer would
* need to be in order to hold the result of the next <code>update</code>
* or <code>doFinal</code> operation, given the input length
* <code>inputLen</code> (in bytes).
*
* <p>This call takes into account any unprocessed (buffered) data from a
* previous <code>update</code> call, and padding.
*
* <p>The actual output length of the next <code>update</code> or
* <code>doFinal</code> call may be smaller than the length returned by
* this method.
*
* @param inputLen the input length (in bytes)
*
* @return the required output buffer size (in bytes)
*/
protected abstract int engineGetOutputSize(int inputLen);
/** {@collect.stats}
* Returns the initialization vector (IV) in a new buffer.
*
* <p> This is useful in the context of password-based encryption or
* decryption, where the IV is derived from a user-provided passphrase.
*
* @return the initialization vector in a new buffer, or null if the
* underlying algorithm does not use an IV, or if the IV has not yet
* been set.
*/
protected abstract byte[] engineGetIV();
/** {@collect.stats}
* Returns the parameters used with this cipher.
*
* <p>The returned parameters may be the same that were used to initialize
* this cipher, or may contain a combination of default and random
* parameter values used by the underlying cipher implementation if this
* cipher requires algorithm parameters but was not initialized with any.
*
* @return the parameters used with this cipher, or null if this cipher
* does not use any parameters.
*/
protected abstract AlgorithmParameters engineGetParameters();
/** {@collect.stats}
* Initializes this cipher with a key and a source
* of randomness.
*
* <p>The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending on
* the value of <code>opmode</code>.
*
* <p>If this cipher requires any algorithm parameters that cannot be
* derived from the given <code>key</code>, the underlying cipher
* implementation is supposed to generate the required parameters itself
* (using provider-specific default or random values) if it is being
* initialized for encryption or key wrapping, and raise an
* <code>InvalidKeyException</code> if it is being
* initialized for decryption or key unwrapping.
* The generated parameters can be retrieved using
* {@link #engineGetParameters() engineGetParameters} or
* {@link #engineGetIV() engineGetIV} (if the parameter is an IV).
*
* <p>If this cipher (including its underlying feedback or padding scheme)
* requires any random bytes (e.g., for parameter generation), it will get
* them from <code>random</code>.
*
* <p>Note that when a Cipher object is initialized, it loses all
* previously-acquired state. In other words, initializing a Cipher is
* equivalent to creating a new instance of that Cipher and initializing
* it.
*
* @param opmode the operation mode of this cipher (this is one of
* the following:
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
* @param key the encryption key
* @param random the source of randomness
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher, or if this cipher is being initialized for
* decryption and requires algorithm parameters that cannot be
* determined from the given key.
*/
protected abstract void engineInit(int opmode, Key key,
SecureRandom random)
throws InvalidKeyException;
/** {@collect.stats}
* Initializes this cipher with a key, a set of
* algorithm parameters, and a source of randomness.
*
* <p>The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending on
* the value of <code>opmode</code>.
*
* <p>If this cipher requires any algorithm parameters and
* <code>params</code> is null, the underlying cipher implementation is
* supposed to generate the required parameters itself (using
* provider-specific default or random values) if it is being
* initialized for encryption or key wrapping, and raise an
* <code>InvalidAlgorithmParameterException</code> if it is being
* initialized for decryption or key unwrapping.
* The generated parameters can be retrieved using
* {@link #engineGetParameters() engineGetParameters} or
* {@link #engineGetIV() engineGetIV} (if the parameter is an IV).
*
* <p>If this cipher (including its underlying feedback or padding scheme)
* requires any random bytes (e.g., for parameter generation), it will get
* them from <code>random</code>.
*
* <p>Note that when a Cipher object is initialized, it loses all
* previously-acquired state. In other words, initializing a Cipher is
* equivalent to creating a new instance of that Cipher and initializing
* it.
*
* @param opmode the operation mode of this cipher (this is one of
* the following:
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
* @param key the encryption key
* @param params the algorithm parameters
* @param random the source of randomness
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this cipher,
* or if this cipher is being initialized for decryption and requires
* algorithm parameters and <code>params</code> is null.
*/
protected abstract void engineInit(int opmode, Key key,
AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException;
/** {@collect.stats}
* Initializes this cipher with a key, a set of
* algorithm parameters, and a source of randomness.
*
* <p>The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending on
* the value of <code>opmode</code>.
*
* <p>If this cipher requires any algorithm parameters and
* <code>params</code> is null, the underlying cipher implementation is
* supposed to generate the required parameters itself (using
* provider-specific default or random values) if it is being
* initialized for encryption or key wrapping, and raise an
* <code>InvalidAlgorithmParameterException</code> if it is being
* initialized for decryption or key unwrapping.
* The generated parameters can be retrieved using
* {@link #engineGetParameters() engineGetParameters} or
* {@link #engineGetIV() engineGetIV} (if the parameter is an IV).
*
* <p>If this cipher (including its underlying feedback or padding scheme)
* requires any random bytes (e.g., for parameter generation), it will get
* them from <code>random</code>.
*
* <p>Note that when a Cipher object is initialized, it loses all
* previously-acquired state. In other words, initializing a Cipher is
* equivalent to creating a new instance of that Cipher and initializing
* it.
*
* @param opmode the operation mode of this cipher (this is one of
* the following:
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
* @param key the encryption key
* @param params the algorithm parameters
* @param random the source of randomness
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this cipher,
* or if this cipher is being initialized for decryption and requires
* algorithm parameters and <code>params</code> is null.
*/
protected abstract void engineInit(int opmode, Key key,
AlgorithmParameters params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException;
/** {@collect.stats}
* Continues a multiple-part encryption or decryption operation
* (depending on how this cipher was initialized), processing another data
* part.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code> inclusive, are processed,
* and the result is stored in a new buffer.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
*
* @return the new buffer with the result, or null if the underlying
* cipher is a block cipher and the input data is too short to result in a
* new block.
*/
protected abstract byte[] engineUpdate(byte[] input, int inputOffset,
int inputLen);
/** {@collect.stats}
* Continues a multiple-part encryption or decryption operation
* (depending on how this cipher was initialized), processing another data
* part.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code> inclusive, are processed,
* and the result is stored in the <code>output</code> buffer, starting at
* <code>outputOffset</code> inclusive.
*
* <p>If the <code>output</code> buffer is too small to hold the result,
* a <code>ShortBufferException</code> is thrown.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
* @param output the buffer for the result
* @param outputOffset the offset in <code>output</code> where the result
* is stored
*
* @return the number of bytes stored in <code>output</code>
*
* @exception ShortBufferException if the given output buffer is too small
* to hold the result
*/
protected abstract int engineUpdate(byte[] input, int inputOffset,
int inputLen, byte[] output,
int outputOffset)
throws ShortBufferException;
/** {@collect.stats}
* Continues a multiple-part encryption or decryption operation
* (depending on how this cipher was initialized), processing another data
* part.
*
* <p>All <code>input.remaining()</code> bytes starting at
* <code>input.position()</code> are processed. The result is stored
* in the output buffer.
* Upon return, the input buffer's position will be equal
* to its limit; its limit will not have changed. The output buffer's
* position will have advanced by n, where n is the value returned
* by this method; the output buffer's limit will not have changed.
*
* <p>If <code>output.remaining()</code> bytes are insufficient to
* hold the result, a <code>ShortBufferException</code> is thrown.
*
* <p>Subclasses should consider overriding this method if they can
* process ByteBuffers more efficiently than byte arrays.
*
* @param input the input ByteBuffer
* @param output the output ByteByffer
*
* @return the number of bytes stored in <code>output</code>
*
* @exception ShortBufferException if there is insufficient space in the
* output buffer
*
* @throws NullPointerException if either parameter is <CODE>null</CODE>
* @since 1.5
*/
protected int engineUpdate(ByteBuffer input, ByteBuffer output)
throws ShortBufferException {
try {
return bufferCrypt(input, output, true);
} catch (IllegalBlockSizeException e) {
// never thrown for engineUpdate()
throw new ProviderException("Internal error in update()");
} catch (BadPaddingException e) {
// never thrown for engineUpdate()
throw new ProviderException("Internal error in update()");
}
}
/** {@collect.stats}
* Encrypts or decrypts data in a single-part operation,
* or finishes a multiple-part operation.
* The data is encrypted or decrypted, depending on how this cipher was
* initialized.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code> inclusive, and any input
* bytes that may have been buffered during a previous <code>update</code>
* operation, are processed, with padding (if requested) being applied.
* The result is stored in a new buffer.
*
* <p>Upon finishing, this method resets this cipher object to the state
* it was in when previously initialized via a call to
* <code>engineInit</code>.
* That is, the object is reset and available to encrypt or decrypt
* (depending on the operation mode that was specified in the call to
* <code>engineInit</code>) more data.
*
* <p>Note: if any exception is thrown, this cipher object may need to
* be reset before it can be used again.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
*
* @return the new buffer with the result
*
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size; or if this encryption algorithm is unable to
* process the input data provided.
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*/
protected abstract byte[] engineDoFinal(byte[] input, int inputOffset,
int inputLen)
throws IllegalBlockSizeException, BadPaddingException;
/** {@collect.stats}
* Encrypts or decrypts data in a single-part operation,
* or finishes a multiple-part operation.
* The data is encrypted or decrypted, depending on how this cipher was
* initialized.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code> inclusive, and any input
* bytes that may have been buffered during a previous <code>update</code>
* operation, are processed, with padding (if requested) being applied.
* The result is stored in the <code>output</code> buffer, starting at
* <code>outputOffset</code> inclusive.
*
* <p>If the <code>output</code> buffer is too small to hold the result,
* a <code>ShortBufferException</code> is thrown.
*
* <p>Upon finishing, this method resets this cipher object to the state
* it was in when previously initialized via a call to
* <code>engineInit</code>.
* That is, the object is reset and available to encrypt or decrypt
* (depending on the operation mode that was specified in the call to
* <code>engineInit</code>) more data.
*
* <p>Note: if any exception is thrown, this cipher object may need to
* be reset before it can be used again.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
* @param output the buffer for the result
* @param outputOffset the offset in <code>output</code> where the result
* is stored
*
* @return the number of bytes stored in <code>output</code>
*
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size; or if this encryption algorithm is unable to
* process the input data provided.
* @exception ShortBufferException if the given output buffer is too small
* to hold the result
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*/
protected abstract int engineDoFinal(byte[] input, int inputOffset,
int inputLen, byte[] output,
int outputOffset)
throws ShortBufferException, IllegalBlockSizeException,
BadPaddingException;
/** {@collect.stats}
* Encrypts or decrypts data in a single-part operation,
* or finishes a multiple-part operation.
* The data is encrypted or decrypted, depending on how this cipher was
* initialized.
*
* <p>All <code>input.remaining()</code> bytes starting at
* <code>input.position()</code> are processed. The result is stored
* in the output buffer.
* Upon return, the input buffer's position will be equal
* to its limit; its limit will not have changed. The output buffer's
* position will have advanced by n, where n is the value returned
* by this method; the output buffer's limit will not have changed.
*
* <p>If <code>output.remaining()</code> bytes are insufficient to
* hold the result, a <code>ShortBufferException</code> is thrown.
*
* <p>Upon finishing, this method resets this cipher object to the state
* it was in when previously initialized via a call to
* <code>engineInit</code>.
* That is, the object is reset and available to encrypt or decrypt
* (depending on the operation mode that was specified in the call to
* <code>engineInit</code>) more data.
*
* <p>Note: if any exception is thrown, this cipher object may need to
* be reset before it can be used again.
*
* <p>Subclasses should consider overriding this method if they can
* process ByteBuffers more efficiently than byte arrays.
*
* @param input the input ByteBuffer
* @param output the output ByteByffer
*
* @return the number of bytes stored in <code>output</code>
*
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size; or if this encryption algorithm is unable to
* process the input data provided.
* @exception ShortBufferException if there is insufficient space in the
* output buffer
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*
* @throws NullPointerException if either parameter is <CODE>null</CODE>
* @since 1.5
*/
protected int engineDoFinal(ByteBuffer input, ByteBuffer output)
throws ShortBufferException, IllegalBlockSizeException,
BadPaddingException {
return bufferCrypt(input, output, false);
}
// copied from sun.security.jca.JCAUtil
// will be changed to reference that method once that code has been
// integrated and promoted
static int getTempArraySize(int totalSize) {
return Math.min(4096, totalSize);
}
/** {@collect.stats}
* Implementation for encryption using ByteBuffers. Used for both
* engineUpdate() and engineDoFinal().
*/
private int bufferCrypt(ByteBuffer input, ByteBuffer output,
boolean isUpdate) throws ShortBufferException,
IllegalBlockSizeException, BadPaddingException {
if ((input == null) || (output == null)) {
throw new NullPointerException
("Input and output buffers must not be null");
}
int inPos = input.position();
int inLimit = input.limit();
int inLen = inLimit - inPos;
if (isUpdate && (inLen == 0)) {
return 0;
}
int outLenNeeded = engineGetOutputSize(inLen);
if (output.remaining() < outLenNeeded) {
throw new ShortBufferException("Need at least " + outLenNeeded
+ " bytes of space in output buffer");
}
boolean a1 = input.hasArray();
boolean a2 = output.hasArray();
if (a1 && a2) {
byte[] inArray = input.array();
int inOfs = input.arrayOffset() + inPos;
byte[] outArray = output.array();
int outPos = output.position();
int outOfs = output.arrayOffset() + outPos;
int n;
if (isUpdate) {
n = engineUpdate(inArray, inOfs, inLen, outArray, outOfs);
} else {
n = engineDoFinal(inArray, inOfs, inLen, outArray, outOfs);
}
input.position(inLimit);
output.position(outPos + n);
return n;
} else if (!a1 && a2) {
int outPos = output.position();
byte[] outArray = output.array();
int outOfs = output.arrayOffset() + outPos;
byte[] inArray = new byte[getTempArraySize(inLen)];
int total = 0;
while (inLen > 0) {
int chunk = Math.min(inLen, inArray.length);
input.get(inArray, 0, chunk);
int n;
if (isUpdate || (inLen != chunk)) {
n = engineUpdate(inArray, 0, chunk, outArray, outOfs);
} else {
n = engineDoFinal(inArray, 0, chunk, outArray, outOfs);
}
total += n;
outOfs += n;
inLen -= chunk;
}
output.position(outPos + total);
return total;
} else { // output is not backed by an accessible byte[]
byte[] inArray;
int inOfs;
if (a1) {
inArray = input.array();
inOfs = input.arrayOffset() + inPos;
} else {
inArray = new byte[getTempArraySize(inLen)];
inOfs = 0;
}
byte[] outArray = new byte[getTempArraySize(outLenNeeded)];
int outSize = outArray.length;
int total = 0;
boolean resized = false;
while (inLen > 0) {
int chunk = Math.min(inLen, outSize);
if ((a1 == false) && (resized == false)) {
input.get(inArray, 0, chunk);
inOfs = 0;
}
try {
int n;
if (isUpdate || (inLen != chunk)) {
n = engineUpdate(inArray, inOfs, chunk, outArray, 0);
} else {
n = engineDoFinal(inArray, inOfs, chunk, outArray, 0);
}
resized = false;
inOfs += chunk;
inLen -= chunk;
output.put(outArray, 0, n);
total += n;
} catch (ShortBufferException e) {
if (resized) {
// we just resized the output buffer, but it still
// did not work. Bug in the provider, abort
throw (ProviderException)new ProviderException
("Could not determine buffer size").initCause(e);
}
// output buffer is too small, realloc and try again
resized = true;
int newOut = engineGetOutputSize(chunk);
outArray = new byte[newOut];
}
}
input.position(inLimit);
return total;
}
}
/** {@collect.stats}
* Wrap a key.
*
* <p>This concrete method has been added to this previously-defined
* abstract class. (For backwards compatibility, it cannot be abstract.)
* It may be overridden by a provider to wrap a key.
* Such an override is expected to throw an IllegalBlockSizeException or
* InvalidKeyException (under the specified circumstances),
* if the given key cannot be wrapped.
* If this method is not overridden, it always throws an
* UnsupportedOperationException.
*
* @param key the key to be wrapped.
*
* @return the wrapped key.
*
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested, and the length of the encoding of the
* key to be wrapped is not a multiple of the block size.
*
* @exception InvalidKeyException if it is impossible or unsafe to
* wrap the key with this cipher (e.g., a hardware protected key is
* being passed to a software-only cipher).
*/
protected byte[] engineWrap(Key key)
throws IllegalBlockSizeException, InvalidKeyException
{
throw new UnsupportedOperationException();
}
/** {@collect.stats}
* Unwrap a previously wrapped key.
*
* <p>This concrete method has been added to this previously-defined
* abstract class. (For backwards compatibility, it cannot be abstract.)
* It may be overridden by a provider to unwrap a previously wrapped key.
* Such an override is expected to throw an InvalidKeyException if
* the given wrapped key cannot be unwrapped.
* If this method is not overridden, it always throws an
* UnsupportedOperationException.
*
* @param wrappedKey the key to be unwrapped.
*
* @param wrappedKeyAlgorithm the algorithm associated with the wrapped
* key.
*
* @param wrappedKeyType the type of the wrapped key. This is one of
* <code>SECRET_KEY</code>, <code>PRIVATE_KEY</code>, or
* <code>PUBLIC_KEY</code>.
*
* @return the unwrapped key.
*
* @exception NoSuchAlgorithmException if no installed providers
* can create keys of type <code>wrappedKeyType</code> for the
* <code>wrappedKeyAlgorithm</code>.
*
* @exception InvalidKeyException if <code>wrappedKey</code> does not
* represent a wrapped key of type <code>wrappedKeyType</code> for
* the <code>wrappedKeyAlgorithm</code>.
*/
protected Key engineUnwrap(byte[] wrappedKey,
String wrappedKeyAlgorithm,
int wrappedKeyType)
throws InvalidKeyException, NoSuchAlgorithmException
{
throw new UnsupportedOperationException();
}
/** {@collect.stats}
* Returns the key size of the given key object in bits.
* <p>This concrete method has been added to this previously-defined
* abstract class. It throws an <code>UnsupportedOperationException</code>
* if it is not overridden by the provider.
*
* @param key the key object.
*
* @return the key size of the given key object.
*
* @exception InvalidKeyException if <code>key</code> is invalid.
*/
protected int engineGetKeySize(Key key)
throws InvalidKeyException
{
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.util.*;
import java.util.regex.*;
import static java.util.Locale.ENGLISH;
import java.security.*;
import java.security.Provider.Service;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import javax.crypto.spec.*;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import sun.security.util.Debug;
import sun.security.jca.*;
import sun.security.jca.GetInstance.Instance;
/** {@collect.stats}
* This class provides the functionality of a cryptographic cipher for
* encryption and decryption. It forms the core of the Java Cryptographic
* Extension (JCE) framework.
*
* <p>In order to create a Cipher object, the application calls the
* Cipher's <code>getInstance</code> method, and passes the name of the
* requested <i>transformation</i> to it. Optionally, the name of a provider
* may be specified.
*
* <p>A <i>transformation</i> is a string that describes the operation (or
* set of operations) to be performed on the given input, to produce some
* output. A transformation always includes the name of a cryptographic
* algorithm (e.g., <i>DES</i>), and may be followed by a feedback mode and
* padding scheme.
*
* <p> A transformation is of the form:<p>
*
* <ul>
* <li>"<i>algorithm/mode/padding</i>" or
* <p>
* <li>"<i>algorithm</i>"
* </ul>
*
* <P> (in the latter case,
* provider-specific default values for the mode and padding scheme are used).
* For example, the following is a valid transformation:<p>
*
* <pre>
* Cipher c = Cipher.getInstance("<i>DES/CBC/PKCS5Padding</i>");
* </pre>
*
* Using modes such as <code>CFB</code> and <code>OFB<code>, block
* ciphers can encrypt data in units smaller than the cipher's actual
* block size. When requesting such a mode, you may optionally specify
* the number of bits to be processed at a time by appending this number
* to the mode name as shown in the "<code>DES/CFB8/NoPadding</code>" and
* "<code>DES/OFB32/PKCS5Padding</code>" transformations. If no such
* number is specified, a provider-specific default is used. (For
* example, the SunJCE provider uses a default of 64 bits for DES.)
* Thus, block ciphers can be turned into byte-oriented stream ciphers by
* using an 8 bit mode such as CFB8 or OFB8.
*
* @author Jan Luehe
* @see KeyGenerator
* @see SecretKey
* @since 1.4
*/
public class Cipher {
private static final Debug debug =
Debug.getInstance("jca", "Cipher");
/** {@collect.stats}
* Constant used to initialize cipher to encryption mode.
*/
public static final int ENCRYPT_MODE = 1;
/** {@collect.stats}
* Constant used to initialize cipher to decryption mode.
*/
public static final int DECRYPT_MODE = 2;
/** {@collect.stats}
* Constant used to initialize cipher to key-wrapping mode.
*/
public static final int WRAP_MODE = 3;
/** {@collect.stats}
* Constant used to initialize cipher to key-unwrapping mode.
*/
public static final int UNWRAP_MODE = 4;
/** {@collect.stats}
* Constant used to indicate the to-be-unwrapped key is a "public key".
*/
public static final int PUBLIC_KEY = 1;
/** {@collect.stats}
* Constant used to indicate the to-be-unwrapped key is a "private key".
*/
public static final int PRIVATE_KEY = 2;
/** {@collect.stats}
* Constant used to indicate the to-be-unwrapped key is a "secret key".
*/
public static final int SECRET_KEY = 3;
// The provider
private Provider provider;
// The provider implementation (delegate)
private CipherSpi spi;
// The transformation
private String transformation;
// Crypto permission representing the maximum allowable cryptographic
// strength that this Cipher object can be used for. (The cryptographic
// strength is a function of the keysize and algorithm parameters encoded
// in the crypto permission.)
private CryptoPermission cryptoPerm;
// The exemption mechanism that needs to be enforced
private ExemptionMechanism exmech;
// Flag which indicates whether or not this cipher has been initialized
private boolean initialized = false;
// The operation mode - store the operation mode after the
// cipher has been initialized.
private int opmode = 0;
// The OID for the KeyUsage extension in an X.509 v3 certificate
private static final String KEY_USAGE_EXTENSION_OID = "2.5.29.15";
// next SPI to try in provider selection
// null once provider is selected
private CipherSpi firstSpi;
// next service to try in provider selection
// null once provider is selected
private Service firstService;
// remaining services to try in provider selection
// null once provider is selected
private Iterator serviceIterator;
// list of transform Strings to lookup in the provider
private List transforms;
private final Object lock;
/** {@collect.stats}
* Creates a Cipher object.
*
* @param cipherSpi the delegate
* @param provider the provider
* @param transformation the transformation
*/
protected Cipher(CipherSpi cipherSpi,
Provider provider,
String transformation) {
// See bug 4341369 & 4334690 for more info.
// If the caller is trusted, then okey.
// Otherwise throw a NullPointerException.
if (!JceSecurityManager.INSTANCE.isCallerTrusted()) {
throw new NullPointerException();
}
this.spi = cipherSpi;
this.provider = provider;
this.transformation = transformation;
this.cryptoPerm = CryptoAllPermission.INSTANCE;
this.lock = null;
}
/** {@collect.stats}
* Creates a Cipher object. Called internally and by NullCipher.
*
* @param cipherSpi the delegate
* @param transformation the transformation
*/
Cipher(CipherSpi cipherSpi, String transformation) {
this.spi = cipherSpi;
this.transformation = transformation;
this.cryptoPerm = CryptoAllPermission.INSTANCE;
this.lock = null;
}
private Cipher(CipherSpi firstSpi, Service firstService,
Iterator serviceIterator, String transformation, List transforms) {
this.firstSpi = firstSpi;
this.firstService = firstService;
this.serviceIterator = serviceIterator;
this.transforms = transforms;
this.transformation = transformation;
this.lock = new Object();
}
private static String[] tokenizeTransformation(String transformation)
throws NoSuchAlgorithmException {
if (transformation == null) {
throw new NoSuchAlgorithmException("No transformation given");
}
/*
* array containing the components of a Cipher transformation:
*
* index 0: algorithm component (e.g., DES)
* index 1: feedback component (e.g., CFB)
* index 2: padding component (e.g., PKCS5Padding)
*/
String[] parts = new String[3];
int count = 0;
StringTokenizer parser = new StringTokenizer(transformation, "/");
try {
while (parser.hasMoreTokens() && count < 3) {
parts[count++] = parser.nextToken().trim();
}
if (count == 0 || count == 2 || parser.hasMoreTokens()) {
throw new NoSuchAlgorithmException("Invalid transformation"
+ " format:" +
transformation);
}
} catch (NoSuchElementException e) {
throw new NoSuchAlgorithmException("Invalid transformation " +
"format:" + transformation);
}
if ((parts[0] == null) || (parts[0].length() == 0)) {
throw new NoSuchAlgorithmException("Invalid transformation:" +
"algorithm not specified-"
+ transformation);
}
return parts;
}
// Provider attribute name for supported chaining mode
private final static String ATTR_MODE = "SupportedModes";
// Provider attribute name for supported padding names
private final static String ATTR_PAD = "SupportedPaddings";
// constants indicating whether the provider supports
// a given mode or padding
private final static int S_NO = 0; // does not support
private final static int S_MAYBE = 1; // unable to determine
private final static int S_YES = 2; // does support
/** {@collect.stats}
* Nested class to deal with modes and paddings.
*/
private static class Transform {
// transform string to lookup in the provider
final String transform;
// the mode/padding suffix in upper case. for example, if the algorithm
// to lookup is "DES/CBC/PKCS5Padding" suffix is "/CBC/PKCS5PADDING"
// if loopup is "DES", suffix is the empty string
// needed because aliases prevent straight transform.equals()
final String suffix;
// value to pass to setMode() or null if no such call required
final String mode;
// value to pass to setPadding() or null if no such call required
final String pad;
Transform(String alg, String suffix, String mode, String pad) {
this.transform = alg + suffix;
this.suffix = suffix.toUpperCase(Locale.ENGLISH);
this.mode = mode;
this.pad = pad;
}
// set mode and padding for the given SPI
void setModePadding(CipherSpi spi) throws NoSuchAlgorithmException,
NoSuchPaddingException {
if (mode != null) {
spi.engineSetMode(mode);
}
if (pad != null) {
spi.engineSetPadding(pad);
}
}
// check whether the given services supports the mode and
// padding described by this Transform
int supportsModePadding(Service s) {
int smode = supportsMode(s);
if (smode == S_NO) {
return smode;
}
int spad = supportsPadding(s);
// our constants are defined so that Math.min() is a tri-valued AND
return Math.min(smode, spad);
}
// separate methods for mode and padding
// called directly by Cipher only to throw the correct exception
int supportsMode(Service s) {
return supports(s, ATTR_MODE, mode);
}
int supportsPadding(Service s) {
return supports(s, ATTR_PAD, pad);
}
private static int supports(Service s, String attrName, String value) {
if (value == null) {
return S_YES;
}
String regexp = s.getAttribute(attrName);
if (regexp == null) {
return S_MAYBE;
}
return matches(regexp, value) ? S_YES : S_NO;
}
// Map<String,Pattern> for previously compiled patterns
// XXX use ConcurrentHashMap once available
private final static Map patternCache =
Collections.synchronizedMap(new HashMap());
private static boolean matches(String regexp, String str) {
Pattern pattern = (Pattern)patternCache.get(regexp);
if (pattern == null) {
pattern = Pattern.compile(regexp);
patternCache.put(regexp, pattern);
}
return pattern.matcher(str.toUpperCase(Locale.ENGLISH)).matches();
}
}
private static List getTransforms(String transformation)
throws NoSuchAlgorithmException {
String[] parts = tokenizeTransformation(transformation);
String alg = parts[0];
String mode = parts[1];
String pad = parts[2];
if ((mode != null) && (mode.length() == 0)) {
mode = null;
}
if ((pad != null) && (pad.length() == 0)) {
pad = null;
}
if ((mode == null) && (pad == null)) {
// DES
Transform tr = new Transform(alg, "", null, null);
return Collections.singletonList(tr);
} else { // if ((mode != null) && (pad != null)) {
// DES/CBC/PKCS5Padding
List list = new ArrayList(4);
list.add(new Transform(alg, "/" + mode + "/" + pad, null, null));
list.add(new Transform(alg, "/" + mode, null, pad));
list.add(new Transform(alg, "//" + pad, mode, null));
list.add(new Transform(alg, "", mode, pad));
return list;
}
}
// get the transform matching the specified service
private static Transform getTransform(Service s, List transforms) {
String alg = s.getAlgorithm().toUpperCase(Locale.ENGLISH);
for (Iterator t = transforms.iterator(); t.hasNext(); ) {
Transform tr = (Transform)t.next();
if (alg.endsWith(tr.suffix)) {
return tr;
}
}
return null;
}
/** {@collect.stats}
* Returns a <code>Cipher</code> object that implements the specified
* transformation.
*
* <p> This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new Cipher object encapsulating the
* CipherSpi implementation from the first
* Provider that supports the specified algorithm is returned.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param transformation the name of the transformation, e.g.,
* <i>DES/CBC/PKCS5Padding</i>.
* See Appendix A in the
* <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard transformation names.
*
* @return a cipher that implements the requested transformation.
*
* @exception NoSuchAlgorithmException if <code>transformation</code>
* is null, empty, in an invalid format,
* or if no Provider supports a CipherSpi implementation for the
* specified algorithm.
*
* @exception NoSuchPaddingException if <code>transformation</code>
* contains a padding scheme that is not available.
*
* @see java.security.Provider
*/
public static final Cipher getInstance(String transformation)
throws NoSuchAlgorithmException, NoSuchPaddingException
{
List transforms = getTransforms(transformation);
List cipherServices = new ArrayList(transforms.size());
for (Iterator t = transforms.iterator(); t.hasNext(); ) {
Transform transform = (Transform)t.next();
cipherServices.add(new ServiceId("Cipher", transform.transform));
}
List services = GetInstance.getServices(cipherServices);
// make sure there is at least one service from a signed provider
// and that it can use the specified mode and padding
Iterator t = services.iterator();
Exception failure = null;
while (t.hasNext()) {
Service s = (Service)t.next();
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
Transform tr = getTransform(s, transforms);
if (tr == null) {
// should never happen
continue;
}
int canuse = tr.supportsModePadding(s);
if (canuse == S_NO) {
// does not support mode or padding we need, ignore
continue;
}
if (canuse == S_YES) {
return new Cipher(null, s, t, transformation, transforms);
} else { // S_MAYBE, try out if it works
try {
CipherSpi spi = (CipherSpi)s.newInstance(null);
tr.setModePadding(spi);
return new Cipher(spi, s, t, transformation, transforms);
} catch (Exception e) {
failure = e;
}
}
}
throw new NoSuchAlgorithmException
("Cannot find any provider supporting " + transformation, failure);
}
/** {@collect.stats}
* Returns a <code>Cipher</code> object that implements the specified
* transformation.
*
* <p> A new Cipher object encapsulating the
* CipherSpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param transformation the name of the transformation,
* e.g., <i>DES/CBC/PKCS5Padding</i>.
* See Appendix A in the
* <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard transformation names.
*
* @param provider the name of the provider.
*
* @return a cipher that implements the requested transformation.
*
* @exception NoSuchAlgorithmException if <code>transformation</code>
* is null, empty, in an invalid format,
* or if a CipherSpi implementation for the specified algorithm
* is not available from the specified provider.
*
* @exception NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception NoSuchPaddingException if <code>transformation</code>
* contains a padding scheme that is not available.
*
* @exception IllegalArgumentException if the <code>provider</code>
* is null or empty.
*
* @see java.security.Provider
*/
public static final Cipher getInstance(String transformation,
String provider)
throws NoSuchAlgorithmException, NoSuchProviderException,
NoSuchPaddingException
{
if ((provider == null) || (provider.length() == 0)) {
throw new IllegalArgumentException("Missing provider");
}
Provider p = Security.getProvider(provider);
if (p == null) {
throw new NoSuchProviderException("No such provider: " +
provider);
}
return getInstance(transformation, p);
}
/** {@collect.stats}
* Returns a <code>Cipher</code> object that implements the specified
* transformation.
*
* <p> A new Cipher object encapsulating the
* CipherSpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param transformation the name of the transformation,
* e.g., <i>DES/CBC/PKCS5Padding</i>.
* See Appendix A in the
* <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard transformation names.
*
* @param provider the provider.
*
* @return a cipher that implements the requested transformation.
*
* @exception NoSuchAlgorithmException if <code>transformation</code>
* is null, empty, in an invalid format,
* or if a CipherSpi implementation for the specified algorithm
* is not available from the specified Provider object.
*
* @exception NoSuchPaddingException if <code>transformation</code>
* contains a padding scheme that is not available.
*
* @exception IllegalArgumentException if the <code>provider</code>
* is null.
*
* @see java.security.Provider
*/
public static final Cipher getInstance(String transformation,
Provider provider)
throws NoSuchAlgorithmException, NoSuchPaddingException
{
if (provider == null) {
throw new IllegalArgumentException("Missing provider");
}
Exception failure = null;
List transforms = getTransforms(transformation);
boolean providerChecked = false;
String paddingError = null;
for (Iterator t = transforms.iterator(); t.hasNext();) {
Transform tr = (Transform)t.next();
Service s = provider.getService("Cipher", tr.transform);
if (s == null) {
continue;
}
if (providerChecked == false) {
// for compatibility, first do the lookup and then verify
// the provider. this makes the difference between a NSAE
// and a SecurityException if the
// provider does not support the algorithm.
Exception ve = JceSecurity.getVerificationResult(provider);
if (ve != null) {
String msg = "JCE cannot authenticate the provider "
+ provider.getName();
throw new SecurityException(msg, ve);
}
providerChecked = true;
}
if (tr.supportsMode(s) == S_NO) {
continue;
}
if (tr.supportsPadding(s) == S_NO) {
paddingError = tr.pad;
continue;
}
try {
CipherSpi spi = (CipherSpi)s.newInstance(null);
tr.setModePadding(spi);
Cipher cipher = new Cipher(spi, transformation);
cipher.provider = s.getProvider();
cipher.initCryptoPermission();
return cipher;
} catch (Exception e) {
failure = e;
}
}
// throw NoSuchPaddingException if the problem is with padding
if (failure instanceof NoSuchPaddingException) {
throw (NoSuchPaddingException)failure;
}
if (paddingError != null) {
throw new NoSuchPaddingException
("Padding not supported: " + paddingError);
}
throw new NoSuchAlgorithmException
("No such algorithm: " + transformation, failure);
}
// If the requested crypto service is export-controlled,
// determine the maximum allowable keysize.
private void initCryptoPermission() throws NoSuchAlgorithmException {
if (JceSecurity.isRestricted() == false) {
cryptoPerm = CryptoAllPermission.INSTANCE;
exmech = null;
return;
}
cryptoPerm = getConfiguredPermission(transformation);
// Instantiate the exemption mechanism (if required)
String exmechName = cryptoPerm.getExemptionMechanism();
if (exmechName != null) {
exmech = ExemptionMechanism.getInstance(exmechName);
}
}
// max number of debug warnings to print from chooseFirstProvider()
private static int warnCount = 10;
/** {@collect.stats}
* Choose the Spi from the first provider available. Used if
* delayed provider selection is not possible because init()
* is not the first method called.
*/
void chooseFirstProvider() {
if (spi != null) {
return;
}
synchronized (lock) {
if (spi != null) {
return;
}
if (debug != null) {
int w = --warnCount;
if (w >= 0) {
debug.println("Cipher.init() not first method "
+ "called, disabling delayed provider selection");
if (w == 0) {
debug.println("Further warnings of this type will "
+ "be suppressed");
}
new Exception("Call trace").printStackTrace();
}
}
Exception lastException = null;
while ((firstService != null) || serviceIterator.hasNext()) {
Service s;
CipherSpi thisSpi;
if (firstService != null) {
s = firstService;
thisSpi = firstSpi;
firstService = null;
firstSpi = null;
} else {
s = (Service)serviceIterator.next();
thisSpi = null;
}
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
Transform tr = getTransform(s, transforms);
if (tr == null) {
// should never happen
continue;
}
if (tr.supportsModePadding(s) == S_NO) {
continue;
}
try {
if (thisSpi == null) {
Object obj = s.newInstance(null);
if (obj instanceof CipherSpi == false) {
continue;
}
thisSpi = (CipherSpi)obj;
}
tr.setModePadding(thisSpi);
initCryptoPermission();
spi = thisSpi;
provider = s.getProvider();
// not needed any more
firstService = null;
serviceIterator = null;
transforms = null;
return;
} catch (Exception e) {
lastException = e;
}
}
ProviderException e = new ProviderException
("Could not construct CipherSpi instance");
if (lastException != null) {
e.initCause(lastException);
}
throw e;
}
}
private final static int I_KEY = 1;
private final static int I_PARAMSPEC = 2;
private final static int I_PARAMS = 3;
private final static int I_CERT = 4;
private void implInit(CipherSpi thisSpi, int type, int opmode, Key key,
AlgorithmParameterSpec paramSpec, AlgorithmParameters params,
SecureRandom random) throws InvalidKeyException,
InvalidAlgorithmParameterException {
switch (type) {
case I_KEY:
checkCryptoPerm(thisSpi, key);
thisSpi.engineInit(opmode, key, random);
break;
case I_PARAMSPEC:
checkCryptoPerm(thisSpi, key, paramSpec);
thisSpi.engineInit(opmode, key, paramSpec, random);
break;
case I_PARAMS:
checkCryptoPerm(thisSpi, key, params);
thisSpi.engineInit(opmode, key, params, random);
break;
case I_CERT:
checkCryptoPerm(thisSpi, key);
thisSpi.engineInit(opmode, key, random);
break;
default:
throw new AssertionError("Internal Cipher error: " + type);
}
}
private void chooseProvider(int initType, int opmode, Key key,
AlgorithmParameterSpec paramSpec,
AlgorithmParameters params, SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
synchronized (lock) {
if (spi != null) {
implInit(spi, initType, opmode, key, paramSpec, params, random);
return;
}
Exception lastException = null;
while ((firstService != null) || serviceIterator.hasNext()) {
Service s;
CipherSpi thisSpi;
if (firstService != null) {
s = firstService;
thisSpi = firstSpi;
firstService = null;
firstSpi = null;
} else {
s = (Service)serviceIterator.next();
thisSpi = null;
}
// if provider says it does not support this key, ignore it
if (s.supportsParameter(key) == false) {
continue;
}
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
Transform tr = getTransform(s, transforms);
if (tr == null) {
// should never happen
continue;
}
if (tr.supportsModePadding(s) == S_NO) {
continue;
}
try {
if (thisSpi == null) {
thisSpi = (CipherSpi)s.newInstance(null);
}
tr.setModePadding(thisSpi);
initCryptoPermission();
implInit(thisSpi, initType, opmode, key, paramSpec,
params, random);
provider = s.getProvider();
this.spi = thisSpi;
firstService = null;
serviceIterator = null;
transforms = null;
return;
} catch (Exception e) {
// NoSuchAlgorithmException from newInstance()
// InvalidKeyException from init()
// RuntimeException (ProviderException) from init()
// SecurityException from crypto permission check
if (lastException == null) {
lastException = e;
}
}
}
// no working provider found, fail
if (lastException instanceof InvalidKeyException) {
throw (InvalidKeyException)lastException;
}
if (lastException instanceof InvalidAlgorithmParameterException) {
throw (InvalidAlgorithmParameterException)lastException;
}
if (lastException instanceof RuntimeException) {
throw (RuntimeException)lastException;
}
String kName = (key != null) ? key.getClass().getName() : "(null)";
throw new InvalidKeyException
("No installed provider supports this key: "
+ kName, lastException);
}
}
/** {@collect.stats}
* Returns the provider of this <code>Cipher</code> object.
*
* @return the provider of this <code>Cipher</code> object
*/
public final Provider getProvider() {
chooseFirstProvider();
return this.provider;
}
/** {@collect.stats}
* Returns the algorithm name of this <code>Cipher</code> object.
*
* <p>This is the same name that was specified in one of the
* <code>getInstance</code> calls that created this <code>Cipher</code>
* object..
*
* @return the algorithm name of this <code>Cipher</code> object.
*/
public final String getAlgorithm() {
return this.transformation;
}
/** {@collect.stats}
* Returns the block size (in bytes).
*
* @return the block size (in bytes), or 0 if the underlying algorithm is
* not a block cipher
*/
public final int getBlockSize() {
chooseFirstProvider();
return spi.engineGetBlockSize();
}
/** {@collect.stats}
* Returns the length in bytes that an output buffer would need to be in
* order to hold the result of the next <code>update</code> or
* <code>doFinal</code> operation, given the input length
* <code>inputLen</code> (in bytes).
*
* <p>This call takes into account any unprocessed (buffered) data from a
* previous <code>update</code> call, and padding.
*
* <p>The actual output length of the next <code>update</code> or
* <code>doFinal</code> call may be smaller than the length returned by
* this method.
*
* @param inputLen the input length (in bytes)
*
* @return the required output buffer size (in bytes)
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not yet been initialized)
*/
public final int getOutputSize(int inputLen) {
if (!initialized && !(this instanceof NullCipher)) {
throw new IllegalStateException("Cipher not initialized");
}
if (inputLen < 0) {
throw new IllegalArgumentException("Input size must be equal " +
"to or greater than zero");
}
chooseFirstProvider();
return spi.engineGetOutputSize(inputLen);
}
/** {@collect.stats}
* Returns the initialization vector (IV) in a new buffer.
*
* <p>This is useful in the case where a random IV was created,
* or in the context of password-based encryption or
* decryption, where the IV is derived from a user-supplied password.
*
* @return the initialization vector in a new buffer, or null if the
* underlying algorithm does not use an IV, or if the IV has not yet
* been set.
*/
public final byte[] getIV() {
chooseFirstProvider();
return spi.engineGetIV();
}
/** {@collect.stats}
* Returns the parameters used with this cipher.
*
* <p>The returned parameters may be the same that were used to initialize
* this cipher, or may contain a combination of default and random
* parameter values used by the underlying cipher implementation if this
* cipher requires algorithm parameters but was not initialized with any.
*
* @return the parameters used with this cipher, or null if this cipher
* does not use any parameters.
*/
public final AlgorithmParameters getParameters() {
chooseFirstProvider();
return spi.engineGetParameters();
}
/** {@collect.stats}
* Returns the exemption mechanism object used with this cipher.
*
* @return the exemption mechanism object used with this cipher, or
* null if this cipher does not use any exemption mechanism.
*/
public final ExemptionMechanism getExemptionMechanism() {
chooseFirstProvider();
return exmech;
}
//
// Crypto permission check code below
//
private void checkCryptoPerm(CipherSpi checkSpi, Key key)
throws InvalidKeyException {
if (cryptoPerm == CryptoAllPermission.INSTANCE) {
return;
}
// Check if key size and default parameters are within legal limits
AlgorithmParameterSpec params;
try {
params = getAlgorithmParameterSpec(checkSpi.engineGetParameters());
} catch (InvalidParameterSpecException ipse) {
throw new InvalidKeyException
("Unsupported default algorithm parameters");
}
if (!passCryptoPermCheck(checkSpi, key, params)) {
throw new InvalidKeyException(
"Illegal key size or default parameters");
}
}
private void checkCryptoPerm(CipherSpi checkSpi, Key key,
AlgorithmParameterSpec params) throws InvalidKeyException,
InvalidAlgorithmParameterException {
if (cryptoPerm == CryptoAllPermission.INSTANCE) {
return;
}
// Determine keysize and check if it is within legal limits
if (!passCryptoPermCheck(checkSpi, key, null)) {
throw new InvalidKeyException("Illegal key size");
}
if ((params != null) && (!passCryptoPermCheck(checkSpi, key, params))) {
throw new InvalidAlgorithmParameterException("Illegal parameters");
}
}
private void checkCryptoPerm(CipherSpi checkSpi, Key key,
AlgorithmParameters params)
throws InvalidKeyException, InvalidAlgorithmParameterException {
if (cryptoPerm == CryptoAllPermission.INSTANCE) {
return;
}
// Convert the specified parameters into specs and then delegate.
AlgorithmParameterSpec pSpec;
try {
pSpec = getAlgorithmParameterSpec(params);
} catch (InvalidParameterSpecException ipse) {
throw new InvalidAlgorithmParameterException
("Failed to retrieve algorithm parameter specification");
}
checkCryptoPerm(checkSpi, key, pSpec);
}
private boolean passCryptoPermCheck(CipherSpi checkSpi, Key key,
AlgorithmParameterSpec params)
throws InvalidKeyException {
String em = cryptoPerm.getExemptionMechanism();
int keySize = checkSpi.engineGetKeySize(key);
// Use the "algorithm" component of the cipher
// transformation so that the perm check would
// work when the key has the "aliased" algo.
String algComponent;
int index = transformation.indexOf('/');
if (index != -1) {
algComponent = transformation.substring(0, index);
} else {
algComponent = transformation;
}
CryptoPermission checkPerm =
new CryptoPermission(algComponent, keySize, params, em);
if (!cryptoPerm.implies(checkPerm)) {
if (debug != null) {
debug.println("Crypto Permission check failed");
debug.println("granted: " + cryptoPerm);
debug.println("requesting: " + checkPerm);
}
return false;
}
if (exmech == null) {
return true;
}
try {
if (!exmech.isCryptoAllowed(key)) {
if (debug != null) {
debug.println(exmech.getName() + " isn't enforced");
}
return false;
}
} catch (ExemptionMechanismException eme) {
if (debug != null) {
debug.println("Cannot determine whether "+
exmech.getName() + " has been enforced");
eme.printStackTrace();
}
return false;
}
return true;
}
// check if opmode is one of the defined constants
// throw InvalidParameterExeption if not
private static void checkOpmode(int opmode) {
if ((opmode < ENCRYPT_MODE) || (opmode > UNWRAP_MODE)) {
throw new InvalidParameterException("Invalid operation mode");
}
}
/** {@collect.stats}
* Initializes this cipher with a key.
*
* <p>The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending
* on the value of <code>opmode</code>.
*
* <p>If this cipher requires any algorithm parameters that cannot be
* derived from the given <code>key</code>, the underlying cipher
* implementation is supposed to generate the required parameters itself
* (using provider-specific default or random values) if it is being
* initialized for encryption or key wrapping, and raise an
* <code>InvalidKeyException</code> if it is being
* initialized for decryption or key unwrapping.
* The generated parameters can be retrieved using
* {@link #getParameters() getParameters} or
* {@link #getIV() getIV} (if the parameter is an IV).
*
* <p>If this cipher (including its underlying feedback or padding scheme)
* requires any random bytes (e.g., for parameter generation), it will get
* them using the {@link SecureRandom <code>SecureRandom</code>}
* implementation of the highest-priority
* installed provider as the source of randomness.
* (If none of the installed providers supply an implementation of
* SecureRandom, a system-provided source of randomness will be used.)
*
* <p>Note that when a Cipher object is initialized, it loses all
* previously-acquired state. In other words, initializing a Cipher is
* equivalent to creating a new instance of that Cipher and initializing
* it.
*
* @param opmode the operation mode of this cipher (this is one of
* the following:
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
* @param key the key
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher, or if this cipher is being initialized for
* decryption and requires algorithm parameters that cannot be
* determined from the given key, or if the given key has a keysize that
* exceeds the maximum allowable keysize (as determined from the
* configured jurisdiction policy files).
*/
public final void init(int opmode, Key key) throws InvalidKeyException {
init(opmode, key, JceSecurity.RANDOM);
}
/** {@collect.stats}
* Initializes this cipher with a key and a source of randomness.
*
* <p>The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending
* on the value of <code>opmode</code>.
*
* <p>If this cipher requires any algorithm parameters that cannot be
* derived from the given <code>key</code>, the underlying cipher
* implementation is supposed to generate the required parameters itself
* (using provider-specific default or random values) if it is being
* initialized for encryption or key wrapping, and raise an
* <code>InvalidKeyException</code> if it is being
* initialized for decryption or key unwrapping.
* The generated parameters can be retrieved using
* {@link #getParameters() getParameters} or
* {@link #getIV() getIV} (if the parameter is an IV).
*
* <p>If this cipher (including its underlying feedback or padding scheme)
* requires any random bytes (e.g., for parameter generation), it will get
* them from <code>random</code>.
*
* <p>Note that when a Cipher object is initialized, it loses all
* previously-acquired state. In other words, initializing a Cipher is
* equivalent to creating a new instance of that Cipher and initializing
* it.
*
* @param opmode the operation mode of this cipher (this is one of the
* following:
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
* @param key the encryption key
* @param random the source of randomness
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher, or if this cipher is being initialized for
* decryption and requires algorithm parameters that cannot be
* determined from the given key, or if the given key has a keysize that
* exceeds the maximum allowable keysize (as determined from the
* configured jurisdiction policy files).
*/
public final void init(int opmode, Key key, SecureRandom random)
throws InvalidKeyException
{
initialized = false;
checkOpmode(opmode);
if (spi != null) {
checkCryptoPerm(spi, key);
spi.engineInit(opmode, key, random);
} else {
try {
chooseProvider(I_KEY, opmode, key, null, null, random);
} catch (InvalidAlgorithmParameterException e) {
// should never occur
throw new InvalidKeyException(e);
}
}
initialized = true;
this.opmode = opmode;
}
/** {@collect.stats}
* Initializes this cipher with a key and a set of algorithm
* parameters.
*
* <p>The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending
* on the value of <code>opmode</code>.
*
* <p>If this cipher requires any algorithm parameters and
* <code>params</code> is null, the underlying cipher implementation is
* supposed to generate the required parameters itself (using
* provider-specific default or random values) if it is being
* initialized for encryption or key wrapping, and raise an
* <code>InvalidAlgorithmParameterException</code> if it is being
* initialized for decryption or key unwrapping.
* The generated parameters can be retrieved using
* {@link #getParameters() getParameters} or
* {@link #getIV() getIV} (if the parameter is an IV).
*
* <p>If this cipher (including its underlying feedback or padding scheme)
* requires any random bytes (e.g., for parameter generation), it will get
* them using the {@link SecureRandom <code>SecureRandom</code>}
* implementation of the highest-priority
* installed provider as the source of randomness.
* (If none of the installed providers supply an implementation of
* SecureRandom, a system-provided source of randomness will be used.)
*
* <p>Note that when a Cipher object is initialized, it loses all
* previously-acquired state. In other words, initializing a Cipher is
* equivalent to creating a new instance of that Cipher and initializing
* it.
*
* @param opmode the operation mode of this cipher (this is one of the
* following:
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
* @param key the encryption key
* @param params the algorithm parameters
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher, or its keysize exceeds the maximum allowable
* keysize (as determined from the configured jurisdiction policy files).
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this cipher,
* or this cipher is being initialized for decryption and requires
* algorithm parameters and <code>params</code> is null, or the given
* algorithm parameters imply a cryptographic strength that would exceed
* the legal limits (as determined from the configured jurisdiction
* policy files).
*/
public final void init(int opmode, Key key, AlgorithmParameterSpec params)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
init(opmode, key, params, JceSecurity.RANDOM);
}
/** {@collect.stats}
* Initializes this cipher with a key, a set of algorithm
* parameters, and a source of randomness.
*
* <p>The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending
* on the value of <code>opmode</code>.
*
* <p>If this cipher requires any algorithm parameters and
* <code>params</code> is null, the underlying cipher implementation is
* supposed to generate the required parameters itself (using
* provider-specific default or random values) if it is being
* initialized for encryption or key wrapping, and raise an
* <code>InvalidAlgorithmParameterException</code> if it is being
* initialized for decryption or key unwrapping.
* The generated parameters can be retrieved using
* {@link #getParameters() getParameters} or
* {@link #getIV() getIV} (if the parameter is an IV).
*
* <p>If this cipher (including its underlying feedback or padding scheme)
* requires any random bytes (e.g., for parameter generation), it will get
* them from <code>random</code>.
*
* <p>Note that when a Cipher object is initialized, it loses all
* previously-acquired state. In other words, initializing a Cipher is
* equivalent to creating a new instance of that Cipher and initializing
* it.
*
* @param opmode the operation mode of this cipher (this is one of the
* following:
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
* @param key the encryption key
* @param params the algorithm parameters
* @param random the source of randomness
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher, or its keysize exceeds the maximum allowable
* keysize (as determined from the configured jurisdiction policy files).
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this cipher,
* or this cipher is being initialized for decryption and requires
* algorithm parameters and <code>params</code> is null, or the given
* algorithm parameters imply a cryptographic strength that would exceed
* the legal limits (as determined from the configured jurisdiction
* policy files).
*/
public final void init(int opmode, Key key, AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
initialized = false;
checkOpmode(opmode);
if (spi != null) {
checkCryptoPerm(spi, key, params);
spi.engineInit(opmode, key, params, random);
} else {
chooseProvider(I_PARAMSPEC, opmode, key, params, null, random);
}
initialized = true;
this.opmode = opmode;
}
/** {@collect.stats}
* Initializes this cipher with a key and a set of algorithm
* parameters.
*
* <p>The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending
* on the value of <code>opmode</code>.
*
* <p>If this cipher requires any algorithm parameters and
* <code>params</code> is null, the underlying cipher implementation is
* supposed to generate the required parameters itself (using
* provider-specific default or random values) if it is being
* initialized for encryption or key wrapping, and raise an
* <code>InvalidAlgorithmParameterException</code> if it is being
* initialized for decryption or key unwrapping.
* The generated parameters can be retrieved using
* {@link #getParameters() getParameters} or
* {@link #getIV() getIV} (if the parameter is an IV).
*
* <p>If this cipher (including its underlying feedback or padding scheme)
* requires any random bytes (e.g., for parameter generation), it will get
* them using the {@link SecureRandom <code>SecureRandom</code>}
* implementation of the highest-priority
* installed provider as the source of randomness.
* (If none of the installed providers supply an implementation of
* SecureRandom, a system-provided source of randomness will be used.)
*
* <p>Note that when a Cipher object is initialized, it loses all
* previously-acquired state. In other words, initializing a Cipher is
* equivalent to creating a new instance of that Cipher and initializing
* it.
*
* @param opmode the operation mode of this cipher (this is one of the
* following: <code>ENCRYPT_MODE</code>,
* <code>DECRYPT_MODE</code>, <code>WRAP_MODE</code>
* or <code>UNWRAP_MODE</code>)
* @param key the encryption key
* @param params the algorithm parameters
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher, or its keysize exceeds the maximum allowable
* keysize (as determined from the configured jurisdiction policy files).
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this cipher,
* or this cipher is being initialized for decryption and requires
* algorithm parameters and <code>params</code> is null, or the given
* algorithm parameters imply a cryptographic strength that would exceed
* the legal limits (as determined from the configured jurisdiction
* policy files).
*/
public final void init(int opmode, Key key, AlgorithmParameters params)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
init(opmode, key, params, JceSecurity.RANDOM);
}
/** {@collect.stats}
* Initializes this cipher with a key, a set of algorithm
* parameters, and a source of randomness.
*
* <p>The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending
* on the value of <code>opmode</code>.
*
* <p>If this cipher requires any algorithm parameters and
* <code>params</code> is null, the underlying cipher implementation is
* supposed to generate the required parameters itself (using
* provider-specific default or random values) if it is being
* initialized for encryption or key wrapping, and raise an
* <code>InvalidAlgorithmParameterException</code> if it is being
* initialized for decryption or key unwrapping.
* The generated parameters can be retrieved using
* {@link #getParameters() getParameters} or
* {@link #getIV() getIV} (if the parameter is an IV).
*
* <p>If this cipher (including its underlying feedback or padding scheme)
* requires any random bytes (e.g., for parameter generation), it will get
* them from <code>random</code>.
*
* <p>Note that when a Cipher object is initialized, it loses all
* previously-acquired state. In other words, initializing a Cipher is
* equivalent to creating a new instance of that Cipher and initializing
* it.
*
* @param opmode the operation mode of this cipher (this is one of the
* following: <code>ENCRYPT_MODE</code>,
* <code>DECRYPT_MODE</code>, <code>WRAP_MODE</code>
* or <code>UNWRAP_MODE</code>)
* @param key the encryption key
* @param params the algorithm parameters
* @param random the source of randomness
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher, or its keysize exceeds the maximum allowable
* keysize (as determined from the configured jurisdiction policy files).
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this cipher,
* or this cipher is being initialized for decryption and requires
* algorithm parameters and <code>params</code> is null, or the given
* algorithm parameters imply a cryptographic strength that would exceed
* the legal limits (as determined from the configured jurisdiction
* policy files).
*/
public final void init(int opmode, Key key, AlgorithmParameters params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
initialized = false;
checkOpmode(opmode);
if (spi != null) {
checkCryptoPerm(spi, key, params);
spi.engineInit(opmode, key, params, random);
} else {
chooseProvider(I_PARAMS, opmode, key, null, params, random);
}
initialized = true;
this.opmode = opmode;
}
/** {@collect.stats}
* Initializes this cipher with the public key from the given certificate.
* <p> The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending
* on the value of <code>opmode</code>.
*
* <p>If the certificate is of type X.509 and has a <i>key usage</i>
* extension field marked as critical, and the value of the <i>key usage</i>
* extension field implies that the public key in
* the certificate and its corresponding private key are not
* supposed to be used for the operation represented by the value
* of <code>opmode</code>,
* an <code>InvalidKeyException</code>
* is thrown.
*
* <p> If this cipher requires any algorithm parameters that cannot be
* derived from the public key in the given certificate, the underlying
* cipher
* implementation is supposed to generate the required parameters itself
* (using provider-specific default or ramdom values) if it is being
* initialized for encryption or key wrapping, and raise an <code>
* InvalidKeyException</code> if it is being initialized for decryption or
* key unwrapping.
* The generated parameters can be retrieved using
* {@link #getParameters() getParameters} or
* {@link #getIV() getIV} (if the parameter is an IV).
*
* <p>If this cipher (including its underlying feedback or padding scheme)
* requires any random bytes (e.g., for parameter generation), it will get
* them using the
* <code>SecureRandom</code>
* implementation of the highest-priority
* installed provider as the source of randomness.
* (If none of the installed providers supply an implementation of
* SecureRandom, a system-provided source of randomness will be used.)
*
* <p>Note that when a Cipher object is initialized, it loses all
* previously-acquired state. In other words, initializing a Cipher is
* equivalent to creating a new instance of that Cipher and initializing
* it.
*
* @param opmode the operation mode of this cipher (this is one of the
* following:
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
* @param certificate the certificate
*
* @exception InvalidKeyException if the public key in the given
* certificate is inappropriate for initializing this cipher, or this
* cipher is being initialized for decryption or unwrapping keys and
* requires algorithm parameters that cannot be determined from the
* public key in the given certificate, or the keysize of the public key
* in the given certificate has a keysize that exceeds the maximum
* allowable keysize (as determined by the configured jurisdiction policy
* files).
*/
public final void init(int opmode, Certificate certificate)
throws InvalidKeyException
{
init(opmode, certificate, JceSecurity.RANDOM);
}
/** {@collect.stats}
* Initializes this cipher with the public key from the given certificate
* and
* a source of randomness.
*
* <p>The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping
* or key unwrapping, depending on
* the value of <code>opmode</code>.
*
* <p>If the certificate is of type X.509 and has a <i>key usage</i>
* extension field marked as critical, and the value of the <i>key usage</i>
* extension field implies that the public key in
* the certificate and its corresponding private key are not
* supposed to be used for the operation represented by the value of
* <code>opmode</code>,
* an <code>InvalidKeyException</code>
* is thrown.
*
* <p>If this cipher requires any algorithm parameters that cannot be
* derived from the public key in the given <code>certificate</code>,
* the underlying cipher
* implementation is supposed to generate the required parameters itself
* (using provider-specific default or random values) if it is being
* initialized for encryption or key wrapping, and raise an
* <code>InvalidKeyException</code> if it is being
* initialized for decryption or key unwrapping.
* The generated parameters can be retrieved using
* {@link #getParameters() getParameters} or
* {@link #getIV() getIV} (if the parameter is an IV).
*
* <p>If this cipher (including its underlying feedback or padding scheme)
* requires any random bytes (e.g., for parameter generation), it will get
* them from <code>random</code>.
*
* <p>Note that when a Cipher object is initialized, it loses all
* previously-acquired state. In other words, initializing a Cipher is
* equivalent to creating a new instance of that Cipher and initializing
* it.
*
* @param opmode the operation mode of this cipher (this is one of the
* following:
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
* @param certificate the certificate
* @param random the source of randomness
*
* @exception InvalidKeyException if the public key in the given
* certificate is inappropriate for initializing this cipher, or this
* cipher is being initialized for decryption or unwrapping keys and
* requires algorithm parameters that cannot be determined from the
* public key in the given certificate, or the keysize of the public key
* in the given certificate has a keysize that exceeds the maximum
* allowable keysize (as determined by the configured jurisdiction policy
* files).
*/
public final void init(int opmode, Certificate certificate,
SecureRandom random)
throws InvalidKeyException
{
initialized = false;
checkOpmode(opmode);
// Check key usage if the certificate is of
// type X.509.
if (certificate instanceof java.security.cert.X509Certificate) {
// Check whether the cert has a key usage extension
// marked as a critical extension.
X509Certificate cert = (X509Certificate)certificate;
Set critSet = cert.getCriticalExtensionOIDs();
if (critSet != null && !critSet.isEmpty()
&& critSet.contains(KEY_USAGE_EXTENSION_OID)) {
boolean[] keyUsageInfo = cert.getKeyUsage();
// keyUsageInfo[2] is for keyEncipherment;
// keyUsageInfo[3] is for dataEncipherment.
if ((keyUsageInfo != null) &&
(((opmode == Cipher.ENCRYPT_MODE) &&
(keyUsageInfo.length > 3) &&
(keyUsageInfo[3] == false)) ||
((opmode == Cipher.WRAP_MODE) &&
(keyUsageInfo.length > 2) &&
(keyUsageInfo[2] == false)))) {
throw new InvalidKeyException("Wrong key usage");
}
}
}
PublicKey publicKey =
(certificate==null? null:certificate.getPublicKey());
if (spi != null) {
checkCryptoPerm(spi, publicKey);
spi.engineInit(opmode, publicKey, random);
} else {
try {
chooseProvider(I_CERT, opmode, publicKey, null, null, random);
} catch (InvalidAlgorithmParameterException e) {
// should never occur
throw new InvalidKeyException(e);
}
}
initialized = true;
this.opmode = opmode;
}
/** {@collect.stats}
* Ensures that Cipher is in a valid state for update() and doFinal()
* calls - should be initialized and in ENCRYPT_MODE or DECRYPT_MODE.
* @throws IllegalStateException if Cipher object is not in valid state.
*/
private void checkCipherState() {
if (!(this instanceof NullCipher)) {
if (!initialized) {
throw new IllegalStateException("Cipher not initialized");
}
if ((opmode != Cipher.ENCRYPT_MODE) &&
(opmode != Cipher.DECRYPT_MODE)) {
throw new IllegalStateException("Cipher not initialized " +
"for encryption/decryption");
}
}
}
/** {@collect.stats}
* Continues a multiple-part encryption or decryption operation
* (depending on how this cipher was initialized), processing another data
* part.
*
* <p>The bytes in the <code>input</code> buffer are processed, and the
* result is stored in a new buffer.
*
* <p>If <code>input</code> has a length of zero, this method returns
* <code>null</code>.
*
* @param input the input buffer
*
* @return the new buffer with the result, or null if the underlying
* cipher is a block cipher and the input data is too short to result in a
* new block.
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
*/
public final byte[] update(byte[] input) {
checkCipherState();
// Input sanity check
if (input == null) {
throw new IllegalArgumentException("Null input buffer");
}
chooseFirstProvider();
if (input.length == 0) {
return null;
}
return spi.engineUpdate(input, 0, input.length);
}
/** {@collect.stats}
* Continues a multiple-part encryption or decryption operation
* (depending on how this cipher was initialized), processing another data
* part.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code> inclusive, are processed,
* and the result is stored in a new buffer.
*
* <p>If <code>inputLen</code> is zero, this method returns
* <code>null</code>.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
*
* @return the new buffer with the result, or null if the underlying
* cipher is a block cipher and the input data is too short to result in a
* new block.
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
*/
public final byte[] update(byte[] input, int inputOffset, int inputLen) {
checkCipherState();
// Input sanity check
if (input == null || inputOffset < 0
|| inputLen > (input.length - inputOffset) || inputLen < 0) {
throw new IllegalArgumentException("Bad arguments");
}
chooseFirstProvider();
if (inputLen == 0) {
return null;
}
return spi.engineUpdate(input, inputOffset, inputLen);
}
/** {@collect.stats}
* Continues a multiple-part encryption or decryption operation
* (depending on how this cipher was initialized), processing another data
* part.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code> inclusive, are processed,
* and the result is stored in the <code>output</code> buffer.
*
* <p>If the <code>output</code> buffer is too small to hold the result,
* a <code>ShortBufferException</code> is thrown. In this case, repeat this
* call with a larger output buffer. Use
* {@link #getOutputSize(int) getOutputSize} to determine how big
* the output buffer should be.
*
* <p>If <code>inputLen</code> is zero, this method returns
* a length of zero.
*
* <p>Note: this method should be copy-safe, which means the
* <code>input</code> and <code>output</code> buffers can reference
* the same byte array and no unprocessed input data is overwritten
* when the result is copied into the output buffer.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
* @param output the buffer for the result
*
* @return the number of bytes stored in <code>output</code>
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
* @exception ShortBufferException if the given output buffer is too small
* to hold the result
*/
public final int update(byte[] input, int inputOffset, int inputLen,
byte[] output)
throws ShortBufferException {
checkCipherState();
// Input sanity check
if (input == null || inputOffset < 0
|| inputLen > (input.length - inputOffset) || inputLen < 0) {
throw new IllegalArgumentException("Bad arguments");
}
chooseFirstProvider();
if (inputLen == 0) {
return 0;
}
return spi.engineUpdate(input, inputOffset, inputLen,
output, 0);
}
/** {@collect.stats}
* Continues a multiple-part encryption or decryption operation
* (depending on how this cipher was initialized), processing another data
* part.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code> inclusive, are processed,
* and the result is stored in the <code>output</code> buffer, starting at
* <code>outputOffset</code> inclusive.
*
* <p>If the <code>output</code> buffer is too small to hold the result,
* a <code>ShortBufferException</code> is thrown. In this case, repeat this
* call with a larger output buffer. Use
* {@link #getOutputSize(int) getOutputSize} to determine how big
* the output buffer should be.
*
* <p>If <code>inputLen</code> is zero, this method returns
* a length of zero.
*
* <p>Note: this method should be copy-safe, which means the
* <code>input</code> and <code>output</code> buffers can reference
* the same byte array and no unprocessed input data is overwritten
* when the result is copied into the output buffer.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
* @param output the buffer for the result
* @param outputOffset the offset in <code>output</code> where the result
* is stored
*
* @return the number of bytes stored in <code>output</code>
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
* @exception ShortBufferException if the given output buffer is too small
* to hold the result
*/
public final int update(byte[] input, int inputOffset, int inputLen,
byte[] output, int outputOffset)
throws ShortBufferException {
checkCipherState();
// Input sanity check
if (input == null || inputOffset < 0
|| inputLen > (input.length - inputOffset) || inputLen < 0
|| outputOffset < 0) {
throw new IllegalArgumentException("Bad arguments");
}
chooseFirstProvider();
if (inputLen == 0) {
return 0;
}
return spi.engineUpdate(input, inputOffset, inputLen,
output, outputOffset);
}
/** {@collect.stats}
* Continues a multiple-part encryption or decryption operation
* (depending on how this cipher was initialized), processing another data
* part.
*
* <p>All <code>input.remaining()</code> bytes starting at
* <code>input.position()</code> are processed. The result is stored
* in the output buffer.
* Upon return, the input buffer's position will be equal
* to its limit; its limit will not have changed. The output buffer's
* position will have advanced by n, where n is the value returned
* by this method; the output buffer's limit will not have changed.
*
* <p>If <code>output.remaining()</code> bytes are insufficient to
* hold the result, a <code>ShortBufferException</code> is thrown.
* In this case, repeat this call with a larger output buffer. Use
* {@link #getOutputSize(int) getOutputSize} to determine how big
* the output buffer should be.
*
* <p>Note: this method should be copy-safe, which means the
* <code>input</code> and <code>output</code> buffers can reference
* the same block of memory and no unprocessed input data is overwritten
* when the result is copied into the output buffer.
*
* @param input the input ByteBuffer
* @param output the output ByteByffer
*
* @return the number of bytes stored in <code>output</code>
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
* @exception IllegalArgumentException if input and output are the
* same object
* @exception ReadOnlyBufferException if the output buffer is read-only
* @exception ShortBufferException if there is insufficient space in the
* output buffer
* @since 1.5
*/
public final int update(ByteBuffer input, ByteBuffer output)
throws ShortBufferException {
checkCipherState();
if ((input == null) || (output == null)) {
throw new IllegalArgumentException("Buffers must not be null");
}
if (input == output) {
throw new IllegalArgumentException("Input and output buffers must "
+ "not be the same object, consider using buffer.duplicate()");
}
if (output.isReadOnly()) {
throw new ReadOnlyBufferException();
}
chooseFirstProvider();
return spi.engineUpdate(input, output);
}
/** {@collect.stats}
* Finishes a multiple-part encryption or decryption operation, depending
* on how this cipher was initialized.
*
* <p>Input data that may have been buffered during a previous
* <code>update</code> operation is processed, with padding (if requested)
* being applied.
* The result is stored in a new buffer.
*
* <p>Upon finishing, this method resets this cipher object to the state
* it was in when previously initialized via a call to <code>init</code>.
* That is, the object is reset and available to encrypt or decrypt
* (depending on the operation mode that was specified in the call to
* <code>init</code>) more data.
*
* <p>Note: if any exception is thrown, this cipher object may need to
* be reset before it can be used again.
*
* @return the new buffer with the result
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size; or if this encryption algorithm is unable to
* process the input data provided.
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*/
public final byte[] doFinal()
throws IllegalBlockSizeException, BadPaddingException {
checkCipherState();
chooseFirstProvider();
return spi.engineDoFinal(null, 0, 0);
}
/** {@collect.stats}
* Finishes a multiple-part encryption or decryption operation, depending
* on how this cipher was initialized.
*
* <p>Input data that may have been buffered during a previous
* <code>update</code> operation is processed, with padding (if requested)
* being applied.
* The result is stored in the <code>output</code> buffer, starting at
* <code>outputOffset</code> inclusive.
*
* <p>If the <code>output</code> buffer is too small to hold the result,
* a <code>ShortBufferException</code> is thrown. In this case, repeat this
* call with a larger output buffer. Use
* {@link #getOutputSize(int) getOutputSize} to determine how big
* the output buffer should be.
*
* <p>Upon finishing, this method resets this cipher object to the state
* it was in when previously initialized via a call to <code>init</code>.
* That is, the object is reset and available to encrypt or decrypt
* (depending on the operation mode that was specified in the call to
* <code>init</code>) more data.
*
* <p>Note: if any exception is thrown, this cipher object may need to
* be reset before it can be used again.
*
* @param output the buffer for the result
* @param outputOffset the offset in <code>output</code> where the result
* is stored
*
* @return the number of bytes stored in <code>output</code>
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size; or if this encryption algorithm is unable to
* process the input data provided.
* @exception ShortBufferException if the given output buffer is too small
* to hold the result
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*/
public final int doFinal(byte[] output, int outputOffset)
throws IllegalBlockSizeException, ShortBufferException,
BadPaddingException {
checkCipherState();
// Input sanity check
if ((output == null) || (outputOffset < 0)) {
throw new IllegalArgumentException("Bad arguments");
}
chooseFirstProvider();
return spi.engineDoFinal(null, 0, 0, output, outputOffset);
}
/** {@collect.stats}
* Encrypts or decrypts data in a single-part operation, or finishes a
* multiple-part operation. The data is encrypted or decrypted,
* depending on how this cipher was initialized.
*
* <p>The bytes in the <code>input</code> buffer, and any input bytes that
* may have been buffered during a previous <code>update</code> operation,
* are processed, with padding (if requested) being applied.
* The result is stored in a new buffer.
*
* <p>Upon finishing, this method resets this cipher object to the state
* it was in when previously initialized via a call to <code>init</code>.
* That is, the object is reset and available to encrypt or decrypt
* (depending on the operation mode that was specified in the call to
* <code>init</code>) more data.
*
* <p>Note: if any exception is thrown, this cipher object may need to
* be reset before it can be used again.
*
* @param input the input buffer
*
* @return the new buffer with the result
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size; or if this encryption algorithm is unable to
* process the input data provided.
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*/
public final byte[] doFinal(byte[] input)
throws IllegalBlockSizeException, BadPaddingException {
checkCipherState();
// Input sanity check
if (input == null) {
throw new IllegalArgumentException("Null input buffer");
}
chooseFirstProvider();
return spi.engineDoFinal(input, 0, input.length);
}
/** {@collect.stats}
* Encrypts or decrypts data in a single-part operation, or finishes a
* multiple-part operation. The data is encrypted or decrypted,
* depending on how this cipher was initialized.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code> inclusive, and any input
* bytes that may have been buffered during a previous <code>update</code>
* operation, are processed, with padding (if requested) being applied.
* The result is stored in a new buffer.
*
* <p>Upon finishing, this method resets this cipher object to the state
* it was in when previously initialized via a call to <code>init</code>.
* That is, the object is reset and available to encrypt or decrypt
* (depending on the operation mode that was specified in the call to
* <code>init</code>) more data.
*
* <p>Note: if any exception is thrown, this cipher object may need to
* be reset before it can be used again.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
*
* @return the new buffer with the result
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size; or if this encryption algorithm is unable to
* process the input data provided.
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*/
public final byte[] doFinal(byte[] input, int inputOffset, int inputLen)
throws IllegalBlockSizeException, BadPaddingException {
checkCipherState();
// Input sanity check
if (input == null || inputOffset < 0
|| inputLen > (input.length - inputOffset) || inputLen < 0) {
throw new IllegalArgumentException("Bad arguments");
}
chooseFirstProvider();
return spi.engineDoFinal(input, inputOffset, inputLen);
}
/** {@collect.stats}
* Encrypts or decrypts data in a single-part operation, or finishes a
* multiple-part operation. The data is encrypted or decrypted,
* depending on how this cipher was initialized.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code> inclusive, and any input
* bytes that may have been buffered during a previous <code>update</code>
* operation, are processed, with padding (if requested) being applied.
* The result is stored in the <code>output</code> buffer.
*
* <p>If the <code>output</code> buffer is too small to hold the result,
* a <code>ShortBufferException</code> is thrown. In this case, repeat this
* call with a larger output buffer. Use
* {@link #getOutputSize(int) getOutputSize} to determine how big
* the output buffer should be.
*
* <p>Upon finishing, this method resets this cipher object to the state
* it was in when previously initialized via a call to <code>init</code>.
* That is, the object is reset and available to encrypt or decrypt
* (depending on the operation mode that was specified in the call to
* <code>init</code>) more data.
*
* <p>Note: if any exception is thrown, this cipher object may need to
* be reset before it can be used again.
*
* <p>Note: this method should be copy-safe, which means the
* <code>input</code> and <code>output</code> buffers can reference
* the same byte array and no unprocessed input data is overwritten
* when the result is copied into the output buffer.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
* @param output the buffer for the result
*
* @return the number of bytes stored in <code>output</code>
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size; or if this encryption algorithm is unable to
* process the input data provided.
* @exception ShortBufferException if the given output buffer is too small
* to hold the result
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*/
public final int doFinal(byte[] input, int inputOffset, int inputLen,
byte[] output)
throws ShortBufferException, IllegalBlockSizeException,
BadPaddingException {
checkCipherState();
// Input sanity check
if (input == null || inputOffset < 0
|| inputLen > (input.length - inputOffset) || inputLen < 0) {
throw new IllegalArgumentException("Bad arguments");
}
chooseFirstProvider();
return spi.engineDoFinal(input, inputOffset, inputLen,
output, 0);
}
/** {@collect.stats}
* Encrypts or decrypts data in a single-part operation, or finishes a
* multiple-part operation. The data is encrypted or decrypted,
* depending on how this cipher was initialized.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code> inclusive, and any input
* bytes that may have been buffered during a previous
* <code>update</code> operation, are processed, with padding
* (if requested) being applied.
* The result is stored in the <code>output</code> buffer, starting at
* <code>outputOffset</code> inclusive.
*
* <p>If the <code>output</code> buffer is too small to hold the result,
* a <code>ShortBufferException</code> is thrown. In this case, repeat this
* call with a larger output buffer. Use
* {@link #getOutputSize(int) getOutputSize} to determine how big
* the output buffer should be.
*
* <p>Upon finishing, this method resets this cipher object to the state
* it was in when previously initialized via a call to <code>init</code>.
* That is, the object is reset and available to encrypt or decrypt
* (depending on the operation mode that was specified in the call to
* <code>init</code>) more data.
*
* <p>Note: if any exception is thrown, this cipher object may need to
* be reset before it can be used again.
*
* <p>Note: this method should be copy-safe, which means the
* <code>input</code> and <code>output</code> buffers can reference
* the same byte array and no unprocessed input data is overwritten
* when the result is copied into the output buffer.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
* @param output the buffer for the result
* @param outputOffset the offset in <code>output</code> where the result
* is stored
*
* @return the number of bytes stored in <code>output</code>
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size; or if this encryption algorithm is unable to
* process the input data provided.
* @exception ShortBufferException if the given output buffer is too small
* to hold the result
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*/
public final int doFinal(byte[] input, int inputOffset, int inputLen,
byte[] output, int outputOffset)
throws ShortBufferException, IllegalBlockSizeException,
BadPaddingException {
checkCipherState();
// Input sanity check
if (input == null || inputOffset < 0
|| inputLen > (input.length - inputOffset) || inputLen < 0
|| outputOffset < 0) {
throw new IllegalArgumentException("Bad arguments");
}
chooseFirstProvider();
return spi.engineDoFinal(input, inputOffset, inputLen,
output, outputOffset);
}
/** {@collect.stats}
* Encrypts or decrypts data in a single-part operation, or finishes a
* multiple-part operation. The data is encrypted or decrypted,
* depending on how this cipher was initialized.
*
* <p>All <code>input.remaining()</code> bytes starting at
* <code>input.position()</code> are processed. The result is stored
* in the output buffer.
* Upon return, the input buffer's position will be equal
* to its limit; its limit will not have changed. The output buffer's
* position will have advanced by n, where n is the value returned
* by this method; the output buffer's limit will not have changed.
*
* <p>If <code>output.remaining()</code> bytes are insufficient to
* hold the result, a <code>ShortBufferException</code> is thrown.
* In this case, repeat this call with a larger output buffer. Use
* {@link #getOutputSize(int) getOutputSize} to determine how big
* the output buffer should be.
*
* <p>Upon finishing, this method resets this cipher object to the state
* it was in when previously initialized via a call to <code>init</code>.
* That is, the object is reset and available to encrypt or decrypt
* (depending on the operation mode that was specified in the call to
* <code>init</code>) more data.
*
* <p>Note: if any exception is thrown, this cipher object may need to
* be reset before it can be used again.
*
* <p>Note: this method should be copy-safe, which means the
* <code>input</code> and <code>output</code> buffers can reference
* the same byte array and no unprocessed input data is overwritten
* when the result is copied into the output buffer.
*
* @param input the input ByteBuffer
* @param output the output ByteBuffer
*
* @return the number of bytes stored in <code>output</code>
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
* @exception IllegalArgumentException if input and output are the
* same object
* @exception ReadOnlyBufferException if the output buffer is read-only
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size; or if this encryption algorithm is unable to
* process the input data provided.
* @exception ShortBufferException if there is insufficient space in the
* output buffer
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
* @since 1.5
*/
public final int doFinal(ByteBuffer input, ByteBuffer output)
throws ShortBufferException, IllegalBlockSizeException,
BadPaddingException {
checkCipherState();
if ((input == null) || (output == null)) {
throw new IllegalArgumentException("Buffers must not be null");
}
if (input == output) {
throw new IllegalArgumentException("Input and output buffers must "
+ "not be the same object, consider using buffer.duplicate()");
}
if (output.isReadOnly()) {
throw new ReadOnlyBufferException();
}
chooseFirstProvider();
return spi.engineDoFinal(input, output);
}
/** {@collect.stats}
* Wrap a key.
*
* @param key the key to be wrapped.
*
* @return the wrapped key.
*
* @exception IllegalStateException if this cipher is in a wrong
* state (e.g., has not been initialized).
*
* @exception IllegalBlockSizeException if this cipher is a block
* cipher, no padding has been requested, and the length of the
* encoding of the key to be wrapped is not a
* multiple of the block size.
*
* @exception InvalidKeyException if it is impossible or unsafe to
* wrap the key with this cipher (e.g., a hardware protected key is
* being passed to a software-only cipher).
*/
public final byte[] wrap(Key key)
throws IllegalBlockSizeException, InvalidKeyException {
if (!(this instanceof NullCipher)) {
if (!initialized) {
throw new IllegalStateException("Cipher not initialized");
}
if (opmode != Cipher.WRAP_MODE) {
throw new IllegalStateException("Cipher not initialized " +
"for wrapping keys");
}
}
chooseFirstProvider();
return spi.engineWrap(key);
}
/** {@collect.stats}
* Unwrap a previously wrapped key.
*
* @param wrappedKey the key to be unwrapped.
*
* @param wrappedKeyAlgorithm the algorithm associated with the wrapped
* key.
*
* @param wrappedKeyType the type of the wrapped key. This must be one of
* <code>SECRET_KEY</code>, <code>PRIVATE_KEY</code>, or
* <code>PUBLIC_KEY</code>.
*
* @return the unwrapped key.
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized).
*
* @exception NoSuchAlgorithmException if no installed providers
* can create keys of type <code>wrappedKeyType</code> for the
* <code>wrappedKeyAlgorithm</code>.
*
* @exception InvalidKeyException if <code>wrappedKey</code> does not
* represent a wrapped key of type <code>wrappedKeyType</code> for
* the <code>wrappedKeyAlgorithm</code>.
*/
public final Key unwrap(byte[] wrappedKey,
String wrappedKeyAlgorithm,
int wrappedKeyType)
throws InvalidKeyException, NoSuchAlgorithmException {
if (!(this instanceof NullCipher)) {
if (!initialized) {
throw new IllegalStateException("Cipher not initialized");
}
if (opmode != Cipher.UNWRAP_MODE) {
throw new IllegalStateException("Cipher not initialized " +
"for unwrapping keys");
}
}
if ((wrappedKeyType != SECRET_KEY) &&
(wrappedKeyType != PRIVATE_KEY) &&
(wrappedKeyType != PUBLIC_KEY)) {
throw new InvalidParameterException("Invalid key type");
}
chooseFirstProvider();
return spi.engineUnwrap(wrappedKey,
wrappedKeyAlgorithm,
wrappedKeyType);
}
private AlgorithmParameterSpec getAlgorithmParameterSpec(
AlgorithmParameters params)
throws InvalidParameterSpecException {
if (params == null) {
return null;
}
String alg = params.getAlgorithm().toUpperCase(Locale.ENGLISH);
if (alg.equalsIgnoreCase("RC2")) {
return params.getParameterSpec(RC2ParameterSpec.class);
}
if (alg.equalsIgnoreCase("RC5")) {
return params.getParameterSpec(RC5ParameterSpec.class);
}
if (alg.startsWith("PBE")) {
return params.getParameterSpec(PBEParameterSpec.class);
}
if (alg.startsWith("DES")) {
return params.getParameterSpec(IvParameterSpec.class);
}
return null;
}
private static CryptoPermission getConfiguredPermission(
String transformation) throws NullPointerException,
NoSuchAlgorithmException {
if (transformation == null) throw new NullPointerException();
String[] parts = tokenizeTransformation(transformation);
return JceSecurityManager.INSTANCE.getCryptoPermission(parts[0]);
}
/** {@collect.stats}
* Returns the maximum key length for the specified transformation
* according to the installed JCE jurisdiction policy files. If
* JCE unlimited strength jurisdiction policy files are installed,
* Integer.MAX_VALUE will be returned.
* For more information on default key size in JCE jurisdiction
* policy files, please see Appendix E in the
* <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppE">
* Java Cryptography Architecture Reference Guide</a>.
*
* @param transformation the cipher transformation.
* @return the maximum key length in bits or Integer.MAX_VALUE.
* @exception NullPointerException if <code>transformation</code> is null.
* @exception NoSuchAlgorithmException if <code>transformation</code>
* is not a valid transformation, i.e. in the form of "algorithm" or
* "algorithm/mode/padding".
* @since 1.5
*/
public static final int getMaxAllowedKeyLength(String transformation)
throws NoSuchAlgorithmException {
CryptoPermission cp = getConfiguredPermission(transformation);
return cp.getMaxKeySize();
}
/** {@collect.stats}
* Returns an AlgorithmParameterSpec object which contains
* the maximum cipher parameter value according to the
* jurisdiction policy file. If JCE unlimited strength jurisdiction
* policy files are installed or there is no maximum limit on the
* parameters for the specified transformation in the policy file,
* null will be returned.
*
* @param transformation the cipher transformation.
* @return an AlgorithmParameterSpec which holds the maximum
* value or null.
* @exception NullPointerException if <code>transformation</code>
* is null.
* @exception NoSuchAlgorithmException if <code>transformation</code>
* is not a valid transformation, i.e. in the form of "algorithm" or
* "algorithm/mode/padding".
* @since 1.5
*/
public static final AlgorithmParameterSpec getMaxAllowedParameterSpec(
String transformation) throws NoSuchAlgorithmException {
CryptoPermission cp = getConfiguredPermission(transformation);
return cp.getAlgorithmParameterSpec();
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.util.*;
import java.security.*;
import java.security.Provider.Service;
import java.security.spec.*;
import sun.security.jca.*;
import sun.security.jca.GetInstance.Instance;
/** {@collect.stats}
* This class represents a factory for secret keys.
*
* <P> Key factories are used to convert <I>keys</I> (opaque
* cryptographic keys of type <code>Key</code>) into <I>key specifications</I>
* (transparent representations of the underlying key material), and vice
* versa.
* Secret key factories operate only on secret (symmetric) keys.
*
* <P> Key factories are bi-directional, i.e., they allow to build an opaque
* key object from a given key specification (key material), or to retrieve
* the underlying key material of a key object in a suitable format.
*
* <P> Application developers should refer to their provider's documentation
* to find out which key specifications are supported by the
* {@link #generateSecret(java.security.spec.KeySpec) generateSecret} and
* {@link #getKeySpec(javax.crypto.SecretKey, java.lang.Class) getKeySpec}
* methods.
* For example, the DES secret-key factory supplied by the "SunJCE" provider
* supports <code>DESKeySpec</code> as a transparent representation of DES
* keys, and that provider's secret-key factory for Triple DES keys supports
* <code>DESedeKeySpec</code> as a transparent representation of Triple DES
* keys.
*
* @author Jan Luehe
*
* @see SecretKey
* @see javax.crypto.spec.DESKeySpec
* @see javax.crypto.spec.DESedeKeySpec
* @see javax.crypto.spec.PBEKeySpec
* @since 1.4
*/
public class SecretKeyFactory {
// The provider
private Provider provider;
// The algorithm associated with this factory
private final String algorithm;
// The provider implementation (delegate)
private volatile SecretKeyFactorySpi spi;
// lock for mutex during provider selection
private final Object lock = new Object();
// remaining services to try in provider selection
// null once provider is selected
private Iterator serviceIterator;
/** {@collect.stats}
* Creates a SecretKeyFactory object.
*
* @param keyFacSpi the delegate
* @param provider the provider
* @param algorithm the secret-key algorithm
*/
protected SecretKeyFactory(SecretKeyFactorySpi keyFacSpi,
Provider provider, String algorithm) {
this.spi = keyFacSpi;
this.provider = provider;
this.algorithm = algorithm;
}
private SecretKeyFactory(String algorithm) throws NoSuchAlgorithmException {
this.algorithm = algorithm;
List list = GetInstance.getServices("SecretKeyFactory", algorithm);
serviceIterator = list.iterator();
// fetch and instantiate initial spi
if (nextSpi(null) == null) {
throw new NoSuchAlgorithmException
(algorithm + " SecretKeyFactory not available");
}
}
/** {@collect.stats}
* Returns a <code>SecretKeyFactory</code> object that converts
* secret keys of the specified algorithm.
*
* <p> This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new SecretKeyFactory object encapsulating the
* SecretKeyFactorySpi implementation from the first
* Provider that supports the specified algorithm is returned.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the standard name of the requested secret-key
* algorithm.
* See Appendix A in the <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard algorithm names.
*
* @return the new <code>SecretKeyFactory</code> object.
*
* @exception NullPointerException if the specified algorithm
* is null.
*
* @exception NoSuchAlgorithmException if no Provider supports a
* SecretKeyFactorySpi implementation for the
* specified algorithm.
*
* @see java.security.Provider
*/
public static final SecretKeyFactory getInstance(String algorithm)
throws NoSuchAlgorithmException {
return new SecretKeyFactory(algorithm);
}
/** {@collect.stats}
* Returns a <code>SecretKeyFactory</code> object that converts
* secret keys of the specified algorithm.
*
* <p> A new SecretKeyFactory object encapsulating the
* SecretKeyFactorySpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the standard name of the requested secret-key
* algorithm.
* See Appendix A in the <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard algorithm names.
*
* @param provider the name of the provider.
*
* @return the new <code>SecretKeyFactory</code> object.
*
* @exception NoSuchAlgorithmException if a SecretKeyFactorySpi
* implementation for the specified algorithm is not
* available from the specified provider.
*
* @exception NullPointerException if the specified algorithm
* is null.
*
* @throws NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception IllegalArgumentException if the <code>provider</code>
* is null or empty.
*
* @see java.security.Provider
*/
public static final SecretKeyFactory getInstance(String algorithm,
String provider) throws NoSuchAlgorithmException,
NoSuchProviderException {
Instance instance = JceSecurity.getInstance("SecretKeyFactory",
SecretKeyFactorySpi.class, algorithm, provider);
return new SecretKeyFactory((SecretKeyFactorySpi)instance.impl,
instance.provider, algorithm);
}
/** {@collect.stats}
* Returns a <code>SecretKeyFactory</code> object that converts
* secret keys of the specified algorithm.
*
* <p> A new SecretKeyFactory object encapsulating the
* SecretKeyFactorySpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param algorithm the standard name of the requested secret-key
* algorithm.
* See Appendix A in the <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard algorithm names.
*
* @param provider the provider.
*
* @return the new <code>SecretKeyFactory</code> object.
*
* @exception NullPointerException if the specified algorithm
* is null.
*
* @exception NoSuchAlgorithmException if a SecretKeyFactorySpi
* implementation for the specified algorithm is not available
* from the specified Provider object.
*
* @exception IllegalArgumentException if the <code>provider</code>
* is null.
*
* @see java.security.Provider
*/
public static final SecretKeyFactory getInstance(String algorithm,
Provider provider) throws NoSuchAlgorithmException {
Instance instance = JceSecurity.getInstance("SecretKeyFactory",
SecretKeyFactorySpi.class, algorithm, provider);
return new SecretKeyFactory((SecretKeyFactorySpi)instance.impl,
instance.provider, algorithm);
}
/** {@collect.stats}
* Returns the provider of this <code>SecretKeyFactory</code> object.
*
* @return the provider of this <code>SecretKeyFactory</code> object
*/
public final Provider getProvider() {
synchronized (lock) {
// disable further failover after this call
serviceIterator = null;
return provider;
}
}
/** {@collect.stats}
* Returns the algorithm name of this <code>SecretKeyFactory</code> object.
*
* <p>This is the same name that was specified in one of the
* <code>getInstance</code> calls that created this
* <code>SecretKeyFactory</code> object.
*
* @return the algorithm name of this <code>SecretKeyFactory</code>
* object.
*/
public final String getAlgorithm() {
return this.algorithm;
}
/** {@collect.stats}
* Update the active spi of this class and return the next
* implementation for failover. If no more implemenations are
* available, this method returns null. However, the active spi of
* this class is never set to null.
*/
private SecretKeyFactorySpi nextSpi(SecretKeyFactorySpi oldSpi) {
synchronized (lock) {
// somebody else did a failover concurrently
// try that spi now
if ((oldSpi != null) && (oldSpi != spi)) {
return spi;
}
if (serviceIterator == null) {
return null;
}
while (serviceIterator.hasNext()) {
Service s = (Service)serviceIterator.next();
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
try {
Object obj = s.newInstance(null);
if (obj instanceof SecretKeyFactorySpi == false) {
continue;
}
SecretKeyFactorySpi spi = (SecretKeyFactorySpi)obj;
provider = s.getProvider();
this.spi = spi;
return spi;
} catch (NoSuchAlgorithmException e) {
// ignore
}
}
serviceIterator = null;
return null;
}
}
/** {@collect.stats}
* Generates a <code>SecretKey</code> object from the provided key
* specification (key material).
*
* @param keySpec the specification (key material) of the secret key
*
* @return the secret key
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this secret-key factory to produce a secret key.
*/
public final SecretKey generateSecret(KeySpec keySpec)
throws InvalidKeySpecException {
if (serviceIterator == null) {
return spi.engineGenerateSecret(keySpec);
}
Exception failure = null;
SecretKeyFactorySpi mySpi = spi;
do {
try {
return mySpi.engineGenerateSecret(keySpec);
} catch (Exception e) {
if (failure == null) {
failure = e;
}
mySpi = nextSpi(mySpi);
}
} while (mySpi != null);
if (failure instanceof InvalidKeySpecException) {
throw (InvalidKeySpecException)failure;
}
throw new InvalidKeySpecException
("Could not generate secret key", failure);
}
/** {@collect.stats}
* Returns a specification (key material) of the given key object
* in the requested format.
*
* @param key the key
* @param keySpec the requested format in which the key material shall be
* returned
*
* @return the underlying key specification (key material) in the
* requested format
*
* @exception InvalidKeySpecException if the requested key specification is
* inappropriate for the given key (e.g., the algorithms associated with
* <code>key</code> and <code>keySpec</code> do not match, or
* <code>key</code> references a key on a cryptographic hardware device
* whereas <code>keySpec</code> is the specification of a software-based
* key), or the given key cannot be dealt with
* (e.g., the given key has an algorithm or format not supported by this
* secret-key factory).
*/
public final KeySpec getKeySpec(SecretKey key, Class keySpec)
throws InvalidKeySpecException {
if (serviceIterator == null) {
return spi.engineGetKeySpec(key, keySpec);
}
Exception failure = null;
SecretKeyFactorySpi mySpi = spi;
do {
try {
return mySpi.engineGetKeySpec(key, keySpec);
} catch (Exception e) {
if (failure == null) {
failure = e;
}
mySpi = nextSpi(mySpi);
}
} while (mySpi != null);
if (failure instanceof InvalidKeySpecException) {
throw (InvalidKeySpecException)failure;
}
throw new InvalidKeySpecException
("Could not get key spec", failure);
}
/** {@collect.stats}
* Translates a key object, whose provider may be unknown or potentially
* untrusted, into a corresponding key object of this secret-key factory.
*
* @param key the key whose provider is unknown or untrusted
*
* @return the translated key
*
* @exception InvalidKeyException if the given key cannot be processed
* by this secret-key factory.
*/
public final SecretKey translateKey(SecretKey key)
throws InvalidKeyException {
if (serviceIterator == null) {
return spi.engineTranslateKey(key);
}
Exception failure = null;
SecretKeyFactorySpi mySpi = spi;
do {
try {
return mySpi.engineTranslateKey(key);
} catch (Exception e) {
if (failure == null) {
failure = e;
}
mySpi = nextSpi(mySpi);
}
} while (mySpi != null);
if (failure instanceof InvalidKeyException) {
throw (InvalidKeyException)failure;
}
throw new InvalidKeyException
("Could not translate key", failure);
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.io.*;
/** {@collect.stats}
* A CipherInputStream is composed of an InputStream and a Cipher so
* that read() methods return data that are read in from the
* underlying InputStream but have been additionally processed by the
* Cipher. The Cipher must be fully initialized before being used by
* a CipherInputStream.
*
* <p> For example, if the Cipher is initialized for decryption, the
* CipherInputStream will attempt to read in data and decrypt them,
* before returning the decrypted data.
*
* <p> This class adheres strictly to the semantics, especially the
* failure semantics, of its ancestor classes
* java.io.FilterInputStream and java.io.InputStream. This class has
* exactly those methods specified in its ancestor classes, and
* overrides them all. Moreover, this class catches all exceptions
* that are not thrown by its ancestor classes. In particular, the
* <code>skip</code> method skips, and the <code>available</code>
* method counts only data that have been processed by the encapsulated Cipher.
*
* <p> It is crucial for a programmer using this class not to use
* methods that are not defined or overriden in this class (such as a
* new method or constructor that is later added to one of the super
* classes), because the design and implementation of those methods
* are unlikely to have considered security impact with regard to
* CipherInputStream.
*
* @author Li Gong
* @see java.io.InputStream
* @see java.io.FilterInputStream
* @see javax.crypto.Cipher
* @see javax.crypto.CipherOutputStream
*
* @since 1.4
*/
public class CipherInputStream extends FilterInputStream {
// the cipher engine to use to process stream data
private Cipher cipher;
// the underlying input stream
private InputStream input;
/* the buffer holding data that have been read in from the
underlying stream, but have not been processed by the cipher
engine. the size 512 bytes is somewhat randomly chosen */
private byte[] ibuffer = new byte[512];
// having reached the end of the underlying input stream
private boolean done = false;
/* the buffer holding data that have been processed by the cipher
engine, but have not been read out */
private byte[] obuffer;
// the offset pointing to the next "new" byte
private int ostart = 0;
// the offset pointing to the last "new" byte
private int ofinish = 0;
/** {@collect.stats}
* private convenience function.
*
* Entry condition: ostart = ofinish
*
* Exit condition: ostart <= ofinish
*
* return (ofinish-ostart) (we have this many bytes for you)
* return 0 (no data now, but could have more later)
* return -1 (absolutely no more data)
*/
private int getMoreData() throws IOException {
if (done) return -1;
int readin = input.read(ibuffer);
if (readin == -1) {
done = true;
try {
obuffer = cipher.doFinal();
}
catch (IllegalBlockSizeException e) {obuffer = null;}
catch (BadPaddingException e) {obuffer = null;}
if (obuffer == null)
return -1;
else {
ostart = 0;
ofinish = obuffer.length;
return ofinish;
}
}
try {
obuffer = cipher.update(ibuffer, 0, readin);
} catch (IllegalStateException e) {obuffer = null;};
ostart = 0;
if (obuffer == null)
ofinish = 0;
else ofinish = obuffer.length;
return ofinish;
}
/** {@collect.stats}
* Constructs a CipherInputStream from an InputStream and a
* Cipher.
* <br>Note: if the specified input stream or cipher is
* null, a NullPointerException may be thrown later when
* they are used.
* @param is the to-be-processed input stream
* @param c an initialized Cipher object
*/
public CipherInputStream(InputStream is, Cipher c) {
super(is);
input = is;
cipher = c;
}
/** {@collect.stats}
* Constructs a CipherInputStream from an InputStream without
* specifying a Cipher. This has the effect of constructing a
* CipherInputStream using a NullCipher.
* <br>Note: if the specified input stream is null, a
* NullPointerException may be thrown later when it is used.
* @param is the to-be-processed input stream
*/
protected CipherInputStream(InputStream is) {
super(is);
input = is;
cipher = new NullCipher();
}
/** {@collect.stats}
* Reads the next byte of data from this input stream. The value
* byte is returned as an <code>int</code> in the range
* <code>0</code> to <code>255</code>. If no byte is available
* because the end of the stream has been reached, the value
* <code>-1</code> is returned. This method blocks until input data
* is available, the end of the stream is detected, or an exception
* is thrown.
* <p>
*
* @return the next byte of data, or <code>-1</code> if the end of the
* stream is reached.
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public int read() throws IOException {
if (ostart >= ofinish) {
// we loop for new data as the spec says we are blocking
int i = 0;
while (i == 0) i = getMoreData();
if (i == -1) return -1;
}
return ((int) obuffer[ostart++] & 0xff);
};
/** {@collect.stats}
* Reads up to <code>b.length</code> bytes of data from this input
* stream into an array of bytes.
* <p>
* The <code>read</code> method of <code>InputStream</code> calls
* the <code>read</code> method of three arguments with the arguments
* <code>b</code>, <code>0</code>, and <code>b.length</code>.
*
* @param b the buffer into which the data is read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> is there is no more data because the end of
* the stream has been reached.
* @exception IOException if an I/O error occurs.
* @see java.io.InputStream#read(byte[], int, int)
* @since JCE1.2
*/
public int read(byte b[]) throws IOException {
return read(b, 0, b.length);
}
/** {@collect.stats}
* Reads up to <code>len</code> bytes of data from this input stream
* into an array of bytes. This method blocks until some input is
* available. If the first argument is <code>null,</code> up to
* <code>len</code> bytes are read and discarded.
*
* @param b the buffer into which the data is read.
* @param off the start offset in the destination array
* <code>buf</code>
* @param len the maximum number of bytes read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the stream has been reached.
* @exception IOException if an I/O error occurs.
* @see java.io.InputStream#read()
* @since JCE1.2
*/
public int read(byte b[], int off, int len) throws IOException {
if (ostart >= ofinish) {
// we loop for new data as the spec says we are blocking
int i = 0;
while (i == 0) i = getMoreData();
if (i == -1) return -1;
}
if (len <= 0) {
return 0;
}
int available = ofinish - ostart;
if (len < available) available = len;
if (b != null) {
System.arraycopy(obuffer, ostart, b, off, available);
}
ostart = ostart + available;
return available;
}
/** {@collect.stats}
* Skips <code>n</code> bytes of input from the bytes that can be read
* from this input stream without blocking.
*
* <p>Fewer bytes than requested might be skipped.
* The actual number of bytes skipped is equal to <code>n</code> or
* the result of a call to
* {@link #available() <code>available</code>},
* whichever is smaller.
* If <code>n</code> is less than zero, no bytes are skipped.
*
* <p>The actual number of bytes skipped is returned.
*
* @param n the number of bytes to be skipped.
* @return the actual number of bytes skipped.
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public long skip(long n) throws IOException {
int available = ofinish - ostart;
if (n > available) {
n = available;
}
if (n < 0) {
return 0;
}
ostart += n;
return n;
}
/** {@collect.stats}
* Returns the number of bytes that can be read from this input
* stream without blocking. The <code>available</code> method of
* <code>InputStream</code> returns <code>0</code>. This method
* <B>should</B> be overridden by subclasses.
*
* @return the number of bytes that can be read from this input stream
* without blocking.
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public int available() throws IOException {
return (ofinish - ostart);
}
/** {@collect.stats}
* Closes this input stream and releases any system resources
* associated with the stream.
* <p>
* The <code>close</code> method of <code>CipherInputStream</code>
* calls the <code>close</code> method of its underlying input
* stream.
*
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public void close() throws IOException {
input.close();
try {
// throw away the unprocessed data
cipher.doFinal();
}
catch (BadPaddingException ex) {
}
catch (IllegalBlockSizeException ex) {
}
ostart = 0;
ofinish = 0;
}
/** {@collect.stats}
* Tests if this input stream supports the <code>mark</code>
* and <code>reset</code> methods, which it does not.
*
* @return <code>false</code>, since this class does not support the
* <code>mark</code> and <code>reset</code> methods.
* @see java.io.InputStream#mark(int)
* @see java.io.InputStream#reset()
* @since JCE1.2
*/
public boolean markSupported() {
return false;
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.util.*;
import java.security.*;
import java.security.Provider.Service;
import java.security.spec.*;
import sun.security.util.Debug;
import sun.security.jca.*;
import sun.security.jca.GetInstance.Instance;
/** {@collect.stats}
* This class provides the functionality of a key agreement (or key
* exchange) protocol.
* <p>
* The keys involved in establishing a shared secret are created by one of the
* key generators (<code>KeyPairGenerator</code> or
* <code>KeyGenerator</code>), a <code>KeyFactory</code>, or as a result from
* an intermediate phase of the key agreement protocol.
*
* <p> For each of the correspondents in the key exchange, <code>doPhase</code>
* needs to be called. For example, if this key exchange is with one other
* party, <code>doPhase</code> needs to be called once, with the
* <code>lastPhase</code> flag set to <code>true</code>.
* If this key exchange is
* with two other parties, <code>doPhase</code> needs to be called twice,
* the first time setting the <code>lastPhase</code> flag to
* <code>false</code>, and the second time setting it to <code>true</code>.
* There may be any number of parties involved in a key exchange.
*
* @author Jan Luehe
*
* @see KeyGenerator
* @see SecretKey
* @since 1.4
*/
public class KeyAgreement {
private static final Debug debug =
Debug.getInstance("jca", "KeyAgreement");
// The provider
private Provider provider;
// The provider implementation (delegate)
private KeyAgreementSpi spi;
// The name of the key agreement algorithm.
private final String algorithm;
// next service to try in provider selection
// null once provider is selected
private Service firstService;
// remaining services to try in provider selection
// null once provider is selected
private Iterator serviceIterator;
private final Object lock;
/** {@collect.stats}
* Creates a KeyAgreement object.
*
* @param keyAgreeSpi the delegate
* @param provider the provider
* @param algorithm the algorithm
*/
protected KeyAgreement(KeyAgreementSpi keyAgreeSpi, Provider provider,
String algorithm) {
this.spi = keyAgreeSpi;
this.provider = provider;
this.algorithm = algorithm;
lock = null;
}
private KeyAgreement(Service s, Iterator t, String algorithm) {
firstService = s;
serviceIterator = t;
this.algorithm = algorithm;
lock = new Object();
}
/** {@collect.stats}
* Returns the algorithm name of this <code>KeyAgreement</code> object.
*
* <p>This is the same name that was specified in one of the
* <code>getInstance</code> calls that created this
* <code>KeyAgreement</code> object.
*
* @return the algorithm name of this <code>KeyAgreement</code> object.
*/
public final String getAlgorithm() {
return this.algorithm;
}
/** {@collect.stats}
* Returns a <code>KeyAgreement</code> object that implements the
* specified key agreement algorithm.
*
* <p> This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new KeyAgreement object encapsulating the
* KeyAgreementSpi implementation from the first
* Provider that supports the specified algorithm is returned.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the standard name of the requested key agreement
* algorithm.
* See Appendix A in the
* <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard algorithm names.
*
* @return the new <code>KeyAgreement</code> object.
*
* @exception NullPointerException if the specified algorithm
* is null.
*
* @exception NoSuchAlgorithmException if no Provider supports a
* KeyAgreementSpi implementation for the
* specified algorithm.
*
* @see java.security.Provider
*/
public static final KeyAgreement getInstance(String algorithm)
throws NoSuchAlgorithmException {
List services = GetInstance.getServices("KeyAgreement", algorithm);
// make sure there is at least one service from a signed provider
Iterator t = services.iterator();
while (t.hasNext()) {
Service s = (Service)t.next();
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
return new KeyAgreement(s, t, algorithm);
}
throw new NoSuchAlgorithmException
("Algorithm " + algorithm + " not available");
}
/** {@collect.stats}
* Returns a <code>KeyAgreement</code> object that implements the
* specified key agreement algorithm.
*
* <p> A new KeyAgreement object encapsulating the
* KeyAgreementSpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the standard name of the requested key agreement
* algorithm.
* See Appendix A in the
* <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard algorithm names.
*
* @param provider the name of the provider.
*
* @return the new <code>KeyAgreement</code> object.
*
* @exception NullPointerException if the specified algorithm
* is null.
*
* @exception NoSuchAlgorithmException if a KeyAgreementSpi
* implementation for the specified algorithm is not
* available from the specified provider.
*
* @exception NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception IllegalArgumentException if the <code>provider</code>
* is null or empty.
*
* @see java.security.Provider
*/
public static final KeyAgreement getInstance(String algorithm,
String provider) throws NoSuchAlgorithmException,
NoSuchProviderException {
Instance instance = JceSecurity.getInstance
("KeyAgreement", KeyAgreementSpi.class, algorithm, provider);
return new KeyAgreement((KeyAgreementSpi)instance.impl,
instance.provider, algorithm);
}
/** {@collect.stats}
* Returns a <code>KeyAgreement</code> object that implements the
* specified key agreement algorithm.
*
* <p> A new KeyAgreement object encapsulating the
* KeyAgreementSpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param algorithm the standard name of the requested key agreement
* algorithm.
* See Appendix A in the
* <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard algorithm names.
*
* @param provider the provider.
*
* @return the new <code>KeyAgreement</code> object.
*
* @exception NullPointerException if the specified algorithm
* is null.
*
* @exception NoSuchAlgorithmException if a KeyAgreementSpi
* implementation for the specified algorithm is not available
* from the specified Provider object.
*
* @exception IllegalArgumentException if the <code>provider</code>
* is null.
*
* @see java.security.Provider
*/
public static final KeyAgreement getInstance(String algorithm,
Provider provider) throws NoSuchAlgorithmException {
Instance instance = JceSecurity.getInstance
("KeyAgreement", KeyAgreementSpi.class, algorithm, provider);
return new KeyAgreement((KeyAgreementSpi)instance.impl,
instance.provider, algorithm);
}
// max number of debug warnings to print from chooseFirstProvider()
private static int warnCount = 10;
/** {@collect.stats}
* Choose the Spi from the first provider available. Used if
* delayed provider selection is not possible because init()
* is not the first method called.
*/
void chooseFirstProvider() {
if (spi != null) {
return;
}
synchronized (lock) {
if (spi != null) {
return;
}
if (debug != null) {
int w = --warnCount;
if (w >= 0) {
debug.println("KeyAgreement.init() not first method "
+ "called, disabling delayed provider selection");
if (w == 0) {
debug.println("Further warnings of this type will "
+ "be suppressed");
}
new Exception("Call trace").printStackTrace();
}
}
Exception lastException = null;
while ((firstService != null) || serviceIterator.hasNext()) {
Service s;
if (firstService != null) {
s = firstService;
firstService = null;
} else {
s = (Service)serviceIterator.next();
}
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
try {
Object obj = s.newInstance(null);
if (obj instanceof KeyAgreementSpi == false) {
continue;
}
spi = (KeyAgreementSpi)obj;
provider = s.getProvider();
// not needed any more
firstService = null;
serviceIterator = null;
return;
} catch (Exception e) {
lastException = e;
}
}
ProviderException e = new ProviderException
("Could not construct KeyAgreementSpi instance");
if (lastException != null) {
e.initCause(lastException);
}
throw e;
}
}
private final static int I_NO_PARAMS = 1;
private final static int I_PARAMS = 2;
private void implInit(KeyAgreementSpi spi, int type, Key key,
AlgorithmParameterSpec params, SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
if (type == I_NO_PARAMS) {
spi.engineInit(key, random);
} else { // I_PARAMS
spi.engineInit(key, params, random);
}
}
private void chooseProvider(int initType, Key key,
AlgorithmParameterSpec params, SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
synchronized (lock) {
if (spi != null) {
implInit(spi, initType, key, params, random);
return;
}
Exception lastException = null;
while ((firstService != null) || serviceIterator.hasNext()) {
Service s;
if (firstService != null) {
s = firstService;
firstService = null;
} else {
s = (Service)serviceIterator.next();
}
// if provider says it does not support this key, ignore it
if (s.supportsParameter(key) == false) {
continue;
}
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
try {
KeyAgreementSpi spi = (KeyAgreementSpi)s.newInstance(null);
implInit(spi, initType, key, params, random);
provider = s.getProvider();
this.spi = spi;
firstService = null;
serviceIterator = null;
return;
} catch (Exception e) {
// NoSuchAlgorithmException from newInstance()
// InvalidKeyException from init()
// RuntimeException (ProviderException) from init()
if (lastException == null) {
lastException = e;
}
}
}
// no working provider found, fail
if (lastException instanceof InvalidKeyException) {
throw (InvalidKeyException)lastException;
}
if (lastException instanceof InvalidAlgorithmParameterException) {
throw (InvalidAlgorithmParameterException)lastException;
}
if (lastException instanceof RuntimeException) {
throw (RuntimeException)lastException;
}
String kName = (key != null) ? key.getClass().getName() : "(null)";
throw new InvalidKeyException
("No installed provider supports this key: "
+ kName, lastException);
}
}
/** {@collect.stats}
* Returns the provider of this <code>KeyAgreement</code> object.
*
* @return the provider of this <code>KeyAgreement</code> object
*/
public final Provider getProvider() {
chooseFirstProvider();
return this.provider;
}
/** {@collect.stats}
* Initializes this key agreement with the given key, which is required to
* contain all the algorithm parameters required for this key agreement.
*
* <p> If this key agreement requires any random bytes, it will get
* them using the
* {@link SecureRandom <code>SecureRandom</code>}
* implementation of the highest-priority
* installed provider as the source of randomness.
* (If none of the installed providers supply an implementation of
* SecureRandom, a system-provided source of randomness will be used.)
*
* @param key the party's private information. For example, in the case
* of the Diffie-Hellman key agreement, this would be the party's own
* Diffie-Hellman private key.
*
* @exception InvalidKeyException if the given key is
* inappropriate for this key agreement, e.g., is of the wrong type or
* has an incompatible algorithm type.
*/
public final void init(Key key) throws InvalidKeyException {
init(key, JceSecurity.RANDOM);
}
/** {@collect.stats}
* Initializes this key agreement with the given key and source of
* randomness. The given key is required to contain all the algorithm
* parameters required for this key agreement.
*
* <p> If the key agreement algorithm requires random bytes, it gets them
* from the given source of randomness, <code>random</code>.
* However, if the underlying
* algorithm implementation does not require any random bytes,
* <code>random</code> is ignored.
*
* @param key the party's private information. For example, in the case
* of the Diffie-Hellman key agreement, this would be the party's own
* Diffie-Hellman private key.
* @param random the source of randomness
*
* @exception InvalidKeyException if the given key is
* inappropriate for this key agreement, e.g., is of the wrong type or
* has an incompatible algorithm type.
*/
public final void init(Key key, SecureRandom random)
throws InvalidKeyException {
if (spi != null) {
spi.engineInit(key, random);
} else {
try {
chooseProvider(I_NO_PARAMS, key, null, random);
} catch (InvalidAlgorithmParameterException e) {
// should never occur
throw new InvalidKeyException(e);
}
}
}
/** {@collect.stats}
* Initializes this key agreement with the given key and set of
* algorithm parameters.
*
* <p> If this key agreement requires any random bytes, it will get
* them using the
* {@link SecureRandom <code>SecureRandom</code>}
* implementation of the highest-priority
* installed provider as the source of randomness.
* (If none of the installed providers supply an implementation of
* SecureRandom, a system-provided source of randomness will be used.)
*
* @param key the party's private information. For example, in the case
* of the Diffie-Hellman key agreement, this would be the party's own
* Diffie-Hellman private key.
* @param params the key agreement parameters
*
* @exception InvalidKeyException if the given key is
* inappropriate for this key agreement, e.g., is of the wrong type or
* has an incompatible algorithm type.
* @exception InvalidAlgorithmParameterException if the given parameters
* are inappropriate for this key agreement.
*/
public final void init(Key key, AlgorithmParameterSpec params)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
init(key, params, JceSecurity.RANDOM);
}
/** {@collect.stats}
* Initializes this key agreement with the given key, set of
* algorithm parameters, and source of randomness.
*
* @param key the party's private information. For example, in the case
* of the Diffie-Hellman key agreement, this would be the party's own
* Diffie-Hellman private key.
* @param params the key agreement parameters
* @param random the source of randomness
*
* @exception InvalidKeyException if the given key is
* inappropriate for this key agreement, e.g., is of the wrong type or
* has an incompatible algorithm type.
* @exception InvalidAlgorithmParameterException if the given parameters
* are inappropriate for this key agreement.
*/
public final void init(Key key, AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
if (spi != null) {
spi.engineInit(key, params, random);
} else {
chooseProvider(I_PARAMS, key, params, random);
}
}
/** {@collect.stats}
* Executes the next phase of this key agreement with the given
* key that was received from one of the other parties involved in this key
* agreement.
*
* @param key the key for this phase. For example, in the case of
* Diffie-Hellman between 2 parties, this would be the other party's
* Diffie-Hellman public key.
* @param lastPhase flag which indicates whether or not this is the last
* phase of this key agreement.
*
* @return the (intermediate) key resulting from this phase, or null
* if this phase does not yield a key
*
* @exception InvalidKeyException if the given key is inappropriate for
* this phase.
* @exception IllegalStateException if this key agreement has not been
* initialized.
*/
public final Key doPhase(Key key, boolean lastPhase)
throws InvalidKeyException, IllegalStateException
{
chooseFirstProvider();
return spi.engineDoPhase(key, lastPhase);
}
/** {@collect.stats}
* Generates the shared secret and returns it in a new buffer.
*
* <p>This method resets this <code>KeyAgreement</code> object, so that it
* can be reused for further key agreements. Unless this key agreement is
* reinitialized with one of the <code>init</code> methods, the same
* private information and algorithm parameters will be used for
* subsequent key agreements.
*
* @return the new buffer with the shared secret
*
* @exception IllegalStateException if this key agreement has not been
* completed yet
*/
public final byte[] generateSecret() throws IllegalStateException {
chooseFirstProvider();
return spi.engineGenerateSecret();
}
/** {@collect.stats}
* Generates the shared secret, and places it into the buffer
* <code>sharedSecret</code>, beginning at <code>offset</code> inclusive.
*
* <p>If the <code>sharedSecret</code> buffer is too small to hold the
* result, a <code>ShortBufferException</code> is thrown.
* In this case, this call should be repeated with a larger output buffer.
*
* <p>This method resets this <code>KeyAgreement</code> object, so that it
* can be reused for further key agreements. Unless this key agreement is
* reinitialized with one of the <code>init</code> methods, the same
* private information and algorithm parameters will be used for
* subsequent key agreements.
*
* @param sharedSecret the buffer for the shared secret
* @param offset the offset in <code>sharedSecret</code> where the
* shared secret will be stored
*
* @return the number of bytes placed into <code>sharedSecret</code>
*
* @exception IllegalStateException if this key agreement has not been
* completed yet
* @exception ShortBufferException if the given output buffer is too small
* to hold the secret
*/
public final int generateSecret(byte[] sharedSecret, int offset)
throws IllegalStateException, ShortBufferException
{
chooseFirstProvider();
return spi.engineGenerateSecret(sharedSecret, offset);
}
/** {@collect.stats}
* Creates the shared secret and returns it as a <code>SecretKey</code>
* object of the specified algorithm.
*
* <p>This method resets this <code>KeyAgreement</code> object, so that it
* can be reused for further key agreements. Unless this key agreement is
* reinitialized with one of the <code>init</code> methods, the same
* private information and algorithm parameters will be used for
* subsequent key agreements.
*
* @param algorithm the requested secret-key algorithm
*
* @return the shared secret key
*
* @exception IllegalStateException if this key agreement has not been
* completed yet
* @exception NoSuchAlgorithmException if the specified secret-key
* algorithm is not available
* @exception InvalidKeyException if the shared secret-key material cannot
* be used to generate a secret key of the specified algorithm (e.g.,
* the key material is too short)
*/
public final SecretKey generateSecret(String algorithm)
throws IllegalStateException, NoSuchAlgorithmException,
InvalidKeyException
{
chooseFirstProvider();
return spi.engineGenerateSecret(algorithm);
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.security.*;
import java.security.spec.*;
/** {@collect.stats}
* This class defines the <i>Service Provider Interface</i> (<b>SPI</b>)
* for the <code>KeyAgreement</code> class.
* All the abstract methods in this class must be implemented by each
* cryptographic service provider who wishes to supply the implementation
* of a particular key agreement algorithm.
*
* <p> The keys involved in establishing a shared secret are created by one
* of the
* key generators (<code>KeyPairGenerator</code> or
* <code>KeyGenerator</code>), a <code>KeyFactory</code>, or as a result from
* an intermediate phase of the key agreement protocol
* ({@link #engineDoPhase(java.security.Key, boolean) engineDoPhase}).
*
* <p> For each of the correspondents in the key exchange,
* <code>engineDoPhase</code>
* needs to be called. For example, if the key exchange is with one other
* party, <code>engineDoPhase</code> needs to be called once, with the
* <code>lastPhase</code> flag set to <code>true</code>.
* If the key exchange is
* with two other parties, <code>engineDoPhase</code> needs to be called twice,
* the first time setting the <code>lastPhase</code> flag to
* <code>false</code>, and the second time setting it to <code>true</code>.
* There may be any number of parties involved in a key exchange.
*
* @author Jan Luehe
*
* @see KeyGenerator
* @see SecretKey
* @since 1.4
*/
public abstract class KeyAgreementSpi {
/** {@collect.stats}
* Initializes this key agreement with the given key and source of
* randomness. The given key is required to contain all the algorithm
* parameters required for this key agreement.
*
* <p> If the key agreement algorithm requires random bytes, it gets them
* from the given source of randomness, <code>random</code>.
* However, if the underlying
* algorithm implementation does not require any random bytes,
* <code>random</code> is ignored.
*
* @param key the party's private information. For example, in the case
* of the Diffie-Hellman key agreement, this would be the party's own
* Diffie-Hellman private key.
* @param random the source of randomness
*
* @exception InvalidKeyException if the given key is
* inappropriate for this key agreement, e.g., is of the wrong type or
* has an incompatible algorithm type.
*/
protected abstract void engineInit(Key key, SecureRandom random)
throws InvalidKeyException;
/** {@collect.stats}
* Initializes this key agreement with the given key, set of
* algorithm parameters, and source of randomness.
*
* @param key the party's private information. For example, in the case
* of the Diffie-Hellman key agreement, this would be the party's own
* Diffie-Hellman private key.
* @param params the key agreement parameters
* @param random the source of randomness
*
* @exception InvalidKeyException if the given key is
* inappropriate for this key agreement, e.g., is of the wrong type or
* has an incompatible algorithm type.
* @exception InvalidAlgorithmParameterException if the given parameters
* are inappropriate for this key agreement.
*/
protected abstract void engineInit(Key key, AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException;
/** {@collect.stats}
* Executes the next phase of this key agreement with the given
* key that was received from one of the other parties involved in this key
* agreement.
*
* @param key the key for this phase. For example, in the case of
* Diffie-Hellman between 2 parties, this would be the other party's
* Diffie-Hellman public key.
* @param lastPhase flag which indicates whether or not this is the last
* phase of this key agreement.
*
* @return the (intermediate) key resulting from this phase, or null if
* this phase does not yield a key
*
* @exception InvalidKeyException if the given key is inappropriate for
* this phase.
* @exception IllegalStateException if this key agreement has not been
* initialized.
*/
protected abstract Key engineDoPhase(Key key, boolean lastPhase)
throws InvalidKeyException, IllegalStateException;
/** {@collect.stats}
* Generates the shared secret and returns it in a new buffer.
*
* <p>This method resets this <code>KeyAgreementSpi</code> object,
* so that it
* can be reused for further key agreements. Unless this key agreement is
* reinitialized with one of the <code>engineInit</code> methods, the same
* private information and algorithm parameters will be used for
* subsequent key agreements.
*
* @return the new buffer with the shared secret
*
* @exception IllegalStateException if this key agreement has not been
* completed yet
*/
protected abstract byte[] engineGenerateSecret()
throws IllegalStateException;
/** {@collect.stats}
* Generates the shared secret, and places it into the buffer
* <code>sharedSecret</code>, beginning at <code>offset</code> inclusive.
*
* <p>If the <code>sharedSecret</code> buffer is too small to hold the
* result, a <code>ShortBufferException</code> is thrown.
* In this case, this call should be repeated with a larger output buffer.
*
* <p>This method resets this <code>KeyAgreementSpi</code> object,
* so that it
* can be reused for further key agreements. Unless this key agreement is
* reinitialized with one of the <code>engineInit</code> methods, the same
* private information and algorithm parameters will be used for
* subsequent key agreements.
*
* @param sharedSecret the buffer for the shared secret
* @param offset the offset in <code>sharedSecret</code> where the
* shared secret will be stored
*
* @return the number of bytes placed into <code>sharedSecret</code>
*
* @exception IllegalStateException if this key agreement has not been
* completed yet
* @exception ShortBufferException if the given output buffer is too small
* to hold the secret
*/
protected abstract int engineGenerateSecret(byte[] sharedSecret,
int offset)
throws IllegalStateException, ShortBufferException;
/** {@collect.stats}
* Creates the shared secret and returns it as a secret key object
* of the requested algorithm type.
*
* <p>This method resets this <code>KeyAgreementSpi</code> object,
* so that it
* can be reused for further key agreements. Unless this key agreement is
* reinitialized with one of the <code>engineInit</code> methods, the same
* private information and algorithm parameters will be used for
* subsequent key agreements.
*
* @param algorithm the requested secret key algorithm
*
* @return the shared secret key
*
* @exception IllegalStateException if this key agreement has not been
* completed yet
* @exception NoSuchAlgorithmException if the requested secret key
* algorithm is not available
* @exception InvalidKeyException if the shared secret key material cannot
* be used to generate a secret key of the requested algorithm type (e.g.,
* the key material is too short)
*/
protected abstract SecretKey engineGenerateSecret(String algorithm)
throws IllegalStateException, NoSuchAlgorithmException,
InvalidKeyException;
}
| Java |
/*
* Copyright (c) 1998, 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 javax.crypto.spec;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.spec.KeySpec;
import javax.crypto.SecretKey;
/** {@collect.stats}
* This class specifies a secret key in a provider-independent fashion.
*
* <p>It can be used to construct a <code>SecretKey</code> from a byte array,
* without having to go through a (provider-based)
* <code>SecretKeyFactory</code>.
*
* <p>This class is only useful for raw secret keys that can be represented as
* a byte array and have no key parameters associated with them, e.g., DES or
* Triple DES keys.
*
* @author Jan Luehe
*
* @see javax.crypto.SecretKey
* @see javax.crypto.SecretKeyFactory
* @since 1.4
*/
public class SecretKeySpec implements KeySpec, SecretKey {
private static final long serialVersionUID = 6577238317307289933L;
/** {@collect.stats}
* The secret key.
*
* @serial
*/
private byte[] key;
/** {@collect.stats}
* The name of the algorithm associated with this key.
*
* @serial
*/
private String algorithm;
/** {@collect.stats}
* Constructs a secret key from the given byte array.
*
* <p>This constructor does not check if the given bytes indeed specify a
* secret key of the specified algorithm. For example, if the algorithm is
* DES, this constructor does not check if <code>key</code> is 8 bytes
* long, and also does not check for weak or semi-weak keys.
* In order for those checks to be performed, an algorithm-specific
* <i>key specification</i> class (in this case:
* {@link DESKeySpec DESKeySpec})
* should be used.
*
* @param key the key material of the secret key. The contents of
* the array are copied to protect against subsequent modification.
* @param algorithm the name of the secret-key algorithm to be associated
* with the given key material.
* See Appendix A in the <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard algorithm names.
* @exception IllegalArgumentException if <code>algorithm</code>
* is null or <code>key</code> is null or empty.
*/
public SecretKeySpec(byte[] key, String algorithm) {
if (key == null || algorithm == null) {
throw new IllegalArgumentException("Missing argument");
}
if (key.length == 0) {
throw new IllegalArgumentException("Empty key");
}
this.key = (byte[])key.clone();
this.algorithm = algorithm;
}
/** {@collect.stats}
* Constructs a secret key from the given byte array, using the first
* <code>len</code> bytes of <code>key</code>, starting at
* <code>offset</code> inclusive.
*
* <p> The bytes that constitute the secret key are
* those between <code>key[offset]</code> and
* <code>key[offset+len-1]</code> inclusive.
*
* <p>This constructor does not check if the given bytes indeed specify a
* secret key of the specified algorithm. For example, if the algorithm is
* DES, this constructor does not check if <code>key</code> is 8 bytes
* long, and also does not check for weak or semi-weak keys.
* In order for those checks to be performed, an algorithm-specific key
* specification class (in this case:
* {@link DESKeySpec DESKeySpec})
* must be used.
*
* @param key the key material of the secret key. The first
* <code>len</code> bytes of the array beginning at
* <code>offset</code> inclusive are copied to protect
* against subsequent modification.
* @param offset the offset in <code>key</code> where the key material
* starts.
* @param len the length of the key material.
* @param algorithm the name of the secret-key algorithm to be associated
* with the given key material.
* See Appendix A in the <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard algorithm names.
* @exception IllegalArgumentException if <code>algorithm</code>
* is null or <code>key</code> is null, empty, or too short,
* i.e. <code>key.length-offset<len</code>.
* @exception ArrayIndexOutOfBoundsException is thrown if
* <code>offset</code> or <code>len</code> index bytes outside the
* <code>key</code>.
*/
public SecretKeySpec(byte[] key, int offset, int len, String algorithm) {
if (key == null || algorithm == null) {
throw new IllegalArgumentException("Missing argument");
}
if (key.length == 0) {
throw new IllegalArgumentException("Empty key");
}
if (key.length-offset < len) {
throw new IllegalArgumentException
("Invalid offset/length combination");
}
if (len < 0) {
throw new ArrayIndexOutOfBoundsException("len is negative");
}
this.key = new byte[len];
System.arraycopy(key, offset, this.key, 0, len);
this.algorithm = algorithm;
}
/** {@collect.stats}
* Returns the name of the algorithm associated with this secret key.
*
* @return the secret key algorithm.
*/
public String getAlgorithm() {
return this.algorithm;
}
/** {@collect.stats}
* Returns the name of the encoding format for this secret key.
*
* @return the string "RAW".
*/
public String getFormat() {
return "RAW";
}
/** {@collect.stats}
* Returns the key material of this secret key.
*
* @return the key material. Returns a new array
* each time this method is called.
*/
public byte[] getEncoded() {
return (byte[])this.key.clone();
}
/** {@collect.stats}
* Calculates a hash code value for the object.
* Objects that are equal will also have the same hashcode.
*/
public int hashCode() {
int retval = 0;
for (int i = 1; i < this.key.length; i++) {
retval += this.key[i] * i;
}
if (this.algorithm.equalsIgnoreCase("TripleDES"))
return (retval ^= "desede".hashCode());
else
return (retval ^= this.algorithm.toLowerCase().hashCode());
}
/** {@collect.stats}
* Tests for equality between the specified object and this
* object. Two SecretKeySpec objects are considered equal if
* they are both SecretKey instances which have the
* same case-insensitive algorithm name and key encoding.
*
* @param obj the object to test for equality with this object.
*
* @return true if the objects are considered equal, false if
* <code>obj</code> is null or otherwise.
*/
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof SecretKey))
return false;
String thatAlg = ((SecretKey)obj).getAlgorithm();
if (!(thatAlg.equalsIgnoreCase(this.algorithm))) {
if ((!(thatAlg.equalsIgnoreCase("DESede"))
|| !(this.algorithm.equalsIgnoreCase("TripleDES")))
&& (!(thatAlg.equalsIgnoreCase("TripleDES"))
|| !(this.algorithm.equalsIgnoreCase("DESede"))))
return false;
}
byte[] thatKey = ((SecretKey)obj).getEncoded();
return java.util.Arrays.equals(this.key, thatKey);
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto.spec;
import java.math.BigInteger;
import java.security.spec.AlgorithmParameterSpec;
/** {@collect.stats}
* This class specifies the set of parameters used for generating
* Diffie-Hellman (system) parameters for use in Diffie-Hellman key
* agreement. This is typically done by a central
* authority.
*
* <p> The central authority, after computing the parameters, must send this
* information to the parties looking to agree on a secret key.
*
* @author Jan Luehe
*
* @see DHParameterSpec
* @since 1.4
*/
public class DHGenParameterSpec implements AlgorithmParameterSpec {
// The size in bits of the prime modulus
private int primeSize;
// The size in bits of the random exponent (private value)
private int exponentSize;
/** {@collect.stats}
* Constructs a parameter set for the generation of Diffie-Hellman
* (system) parameters. The constructed parameter set can be used to
* initialize an
* {@link java.security.AlgorithmParameterGenerator AlgorithmParameterGenerator}
* object for the generation of Diffie-Hellman parameters.
*
* @param primeSize the size (in bits) of the prime modulus.
* @param exponentSize the size (in bits) of the random exponent.
*/
public DHGenParameterSpec(int primeSize, int exponentSize) {
this.primeSize = primeSize;
this.exponentSize = exponentSize;
}
/** {@collect.stats}
* Returns the size in bits of the prime modulus.
*
* @return the size in bits of the prime modulus
*/
public int getPrimeSize() {
return this.primeSize;
}
/** {@collect.stats}
* Returns the size in bits of the random exponent (private value).
*
* @return the size in bits of the random exponent (private value)
*/
public int getExponentSize() {
return this.exponentSize;
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto.spec;
import java.math.BigInteger;
/** {@collect.stats}
* This class specifies a Diffie-Hellman public key with its associated
* parameters.
*
* <p>Note that this class does not perform any validation on specified
* parameters. Thus, the specified values are returned directly even
* if they are null.
*
* @author Jan Luehe
*
* @see DHPrivateKeySpec
* @since 1.4
*/
public class DHPublicKeySpec implements java.security.spec.KeySpec {
// The public value
private BigInteger y;
// The prime modulus
private BigInteger p;
// The base generator
private BigInteger g;
/** {@collect.stats}
* Constructor that takes a public value <code>y</code>, a prime
* modulus <code>p</code>, and a base generator <code>g</code>.
* @param y public value y
* @param p prime modulus p
* @param g base generator g
*/
public DHPublicKeySpec(BigInteger y, BigInteger p, BigInteger g) {
this.y = y;
this.p = p;
this.g = g;
}
/** {@collect.stats}
* Returns the public value <code>y</code>.
*
* @return the public value <code>y</code>
*/
public BigInteger getY() {
return this.y;
}
/** {@collect.stats}
* Returns the prime modulus <code>p</code>.
*
* @return the prime modulus <code>p</code>
*/
public BigInteger getP() {
return this.p;
}
/** {@collect.stats}
* Returns the base generator <code>g</code>.
*
* @return the base generator <code>g</code>
*/
public BigInteger getG() {
return this.g;
}
}
| Java |
/*
* Copyright (c) 1998, 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 javax.crypto.spec;
import java.security.spec.AlgorithmParameterSpec;
/** {@collect.stats}
* This class specifies the parameters used with the
* <a href="http://www.ietf.org/rfc/rfc2040.txt"><i>RC5</i></a>
* algorithm.
*
* <p> The parameters consist of a version number, a rounds count, a word
* size, and optionally an initialization vector (IV) (only in feedback mode).
*
* <p> This class can be used to initialize a <code>Cipher</code> object that
* implements the <i>RC5</i> algorithm as supplied by
* <a href="http://www.rsasecurity.com">RSA Security Inc.</a>,
* or any parties authorized by RSA Security.
*
* @author Jan Luehe
*
* @since 1.4
*/
public class RC5ParameterSpec implements AlgorithmParameterSpec {
private byte[] iv = null;
private int version;
private int rounds;
private int wordSize; // the word size in bits
/** {@collect.stats}
* Constructs a parameter set for RC5 from the given version, number of
* rounds and word size (in bits).
*
* @param version the version.
* @param rounds the number of rounds.
* @param wordSize the word size in bits.
*/
public RC5ParameterSpec(int version, int rounds, int wordSize) {
this.version = version;
this.rounds = rounds;
this.wordSize = wordSize;
}
/** {@collect.stats}
* Constructs a parameter set for RC5 from the given version, number of
* rounds, word size (in bits), and IV.
*
* <p> Note that the size of the IV (block size) must be twice the word
* size. The bytes that constitute the IV are those between
* <code>iv[0]</code> and <code>iv[2*(wordSize/8)-1]</code> inclusive.
*
* @param version the version.
* @param rounds the number of rounds.
* @param wordSize the word size in bits.
* @param iv the buffer with the IV. The first <code>2*(wordSize/8)
* </code> bytes of the buffer are copied to protect against subsequent
* modification.
* @exception IllegalArgumentException if <code>iv</code> is
* <code>null</code> or <code>(iv.length < 2 * (wordSize / 8))</code>
*/
public RC5ParameterSpec(int version, int rounds, int wordSize, byte[] iv) {
this(version, rounds, wordSize, iv, 0);
}
/** {@collect.stats}
* Constructs a parameter set for RC5 from the given version, number of
* rounds, word size (in bits), and IV.
*
* <p> The IV is taken from <code>iv</code>, starting at
* <code>offset</code> inclusive.
* Note that the size of the IV (block size), starting at
* <code>offset</code> inclusive, must be twice the word size.
* The bytes that constitute the IV are those between
* <code>iv[offset]</code> and <code>iv[offset+2*(wordSize/8)-1]</code>
* inclusive.
*
* @param version the version.
* @param rounds the number of rounds.
* @param wordSize the word size in bits.
* @param iv the buffer with the IV. The first <code>2*(wordSize/8)
* </code> bytes of the buffer beginning at <code>offset</code>
* inclusive are copied to protect against subsequent modification.
* @param offset the offset in <code>iv</code> where the IV starts.
* @exception IllegalArgumentException if <code>iv</code> is
* <code>null</code> or
* <code>(iv.length - offset < 2 * (wordSize / 8))</code>
*/
public RC5ParameterSpec(int version, int rounds, int wordSize,
byte[] iv, int offset) {
this.version = version;
this.rounds = rounds;
this.wordSize = wordSize;
if (iv == null) throw new IllegalArgumentException("IV missing");
int blockSize = (wordSize / 8) * 2;
if (iv.length - offset < blockSize) {
throw new IllegalArgumentException("IV too short");
}
this.iv = new byte[blockSize];
System.arraycopy(iv, offset, this.iv, 0, blockSize);
}
/** {@collect.stats}
* Returns the version.
*
* @return the version.
*/
public int getVersion() {
return this.version;
}
/** {@collect.stats}
* Returns the number of rounds.
*
* @return the number of rounds.
*/
public int getRounds() {
return this.rounds;
}
/** {@collect.stats}
* Returns the word size in bits.
*
* @return the word size in bits.
*/
public int getWordSize() {
return this.wordSize;
}
/** {@collect.stats}
* Returns the IV or null if this parameter set does not contain an IV.
*
* @return the IV or null if this parameter set does not contain an IV.
* Returns a new array each time this method is called.
*/
public byte[] getIV() {
return (iv == null? null:(byte[])iv.clone());
}
/** {@collect.stats}
* Tests for equality between the specified object and this
* object. Two RC5ParameterSpec objects are considered equal if their
* version numbers, number of rounds, word sizes, and IVs are equal.
* (Two IV references are considered equal if both are <tt>null</tt>.)
*
* @param obj the object to test for equality with this object.
*
* @return true if the objects are considered equal, false if
* <code>obj</code> is null or otherwise.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof RC5ParameterSpec)) {
return false;
}
RC5ParameterSpec other = (RC5ParameterSpec) obj;
return ((version == other.version) &&
(rounds == other.rounds) &&
(wordSize == other.wordSize) &&
java.util.Arrays.equals(iv, other.iv));
}
/** {@collect.stats}
* Calculates a hash code value for the object.
* Objects that are equal will also have the same hashcode.
*/
public int hashCode() {
int retval = 0;
if (iv != null) {
for (int i = 1; i < iv.length; i++) {
retval += iv[i] * i;
}
}
retval += (version + rounds + wordSize);
return retval;
}
}
| Java |
/*
* Copyright (c) 2003, 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 javax.crypto.spec;
import java.math.BigInteger;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.MGF1ParameterSpec;
/** {@collect.stats}
* This class specifies the set of parameters used with OAEP Padding,
* as defined in the
* <a href="http://www.ietf.org/rfc/rfc3447.txt">PKCS #1</a>
* standard.
*
* Its ASN.1 definition in PKCS#1 standard is described below:
* <pre>
* RSAES-OAEP-params ::= SEQUENCE {
* hashAlgorithm [0] OAEP-PSSDigestAlgorithms DEFAULT sha1,
* maskGenAlgorithm [1] PKCS1MGFAlgorithms DEFAULT mgf1SHA1,
* pSourceAlgorithm [2] PKCS1PSourceAlgorithms DEFAULT pSpecifiedEmpty
* }
* </pre>
* where
* <pre>
* OAEP-PSSDigestAlgorithms ALGORITHM-IDENTIFIER ::= {
* { OID id-sha1 PARAMETERS NULL }|
* { OID id-sha256 PARAMETERS NULL }|
* { OID id-sha384 PARAMETERS NULL }|
* { OID id-sha512 PARAMETERS NULL },
* ... -- Allows for future expansion --
* }
* PKCS1MGFAlgorithms ALGORITHM-IDENTIFIER ::= {
* { OID id-mgf1 PARAMETERS OAEP-PSSDigestAlgorithms },
* ... -- Allows for future expansion --
* }
* PKCS1PSourceAlgorithms ALGORITHM-IDENTIFIER ::= {
* { OID id-pSpecified PARAMETERS OCTET STRING },
* ... -- Allows for future expansion --
* }
* </pre>
* <p>Note: the OAEPParameterSpec.DEFAULT uses the following:
* message digest -- "SHA-1"
* mask generation function (mgf) -- "MGF1"
* parameters for mgf -- MGF1ParameterSpec.SHA1
* source of encoding input -- PSource.PSpecified.DEFAULT
*
* @see java.security.spec.MGF1ParameterSpec
* @see PSource
*
* @author Valerie Peng
*
* @since 1.5
*/
public class OAEPParameterSpec implements AlgorithmParameterSpec {
private String mdName = "SHA-1";
private String mgfName = "MGF1";
private AlgorithmParameterSpec mgfSpec = MGF1ParameterSpec.SHA1;
private PSource pSrc = PSource.PSpecified.DEFAULT;
/** {@collect.stats}
* The OAEP parameter set with all default values.
*/
public static final OAEPParameterSpec DEFAULT = new OAEPParameterSpec();
/** {@collect.stats}
* Constructs a parameter set for OAEP padding as defined in
* the PKCS #1 standard using the default values.
*/
private OAEPParameterSpec() {
}
/** {@collect.stats}
* Constructs a parameter set for OAEP padding as defined in
* the PKCS #1 standard using the specified message digest
* algorithm <code>mdName</code>, mask generation function
* algorithm <code>mgfName</code>, parameters for the mask
* generation function <code>mgfSpec</code>, and source of
* the encoding input P <code>pSrc</code>.
*
* @param mdName the algorithm name for the message digest.
* @param mgfName the algorithm name for the mask generation
* function.
* @param mgfSpec the parameters for the mask generation function.
* If null is specified, null will be returned by getMGFParameters().
* @param pSrc the source of the encoding input P.
* @exception NullPointerException if <code>mdName</code>,
* <code>mgfName</code>, or <code>pSrc</code> is null.
*/
public OAEPParameterSpec(String mdName, String mgfName,
AlgorithmParameterSpec mgfSpec,
PSource pSrc) {
if (mdName == null) {
throw new NullPointerException("digest algorithm is null");
}
if (mgfName == null) {
throw new NullPointerException("mask generation function " +
"algorithm is null");
}
if (pSrc == null) {
throw new NullPointerException("source of the encoding input " +
"is null");
}
this.mdName = mdName;
this.mgfName = mgfName;
this.mgfSpec = mgfSpec;
this.pSrc = pSrc;
}
/** {@collect.stats}
* Returns the message digest algorithm name.
*
* @return the message digest algorithm name.
*/
public String getDigestAlgorithm() {
return mdName;
}
/** {@collect.stats}
* Returns the mask generation function algorithm name.
*
* @return the mask generation function algorithm name.
*/
public String getMGFAlgorithm() {
return mgfName;
}
/** {@collect.stats}
* Returns the parameters for the mask generation function.
*
* @return the parameters for the mask generation function.
*/
public AlgorithmParameterSpec getMGFParameters() {
return mgfSpec;
}
/** {@collect.stats}
* Returns the source of encoding input P.
*
* @return the source of encoding input P.
*/
public PSource getPSource() {
return pSrc;
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto.spec;
import java.math.BigInteger;
import java.security.spec.AlgorithmParameterSpec;
/** {@collect.stats}
* This class specifies the set of parameters used with password-based
* encryption (PBE), as defined in the
* <a href="http://www.ietf.org/rfc/rfc2898.txt">PKCS #5</a>
* standard.
*
* @author Jan Luehe
*
* @since 1.4
*/
public class PBEParameterSpec implements AlgorithmParameterSpec {
private byte[] salt;
private int iterationCount;
/** {@collect.stats}
* Constructs a parameter set for password-based encryption as defined in
* the PKCS #5 standard.
*
* @param salt the salt. The contents of <code>salt</code> are copied
* to protect against subsequent modification.
* @param iterationCount the iteration count.
* @exception NullPointerException if <code>salt</code> is null.
*/
public PBEParameterSpec(byte[] salt, int iterationCount) {
this.salt = (byte[])salt.clone();
this.iterationCount = iterationCount;
}
/** {@collect.stats}
* Returns the salt.
*
* @return the salt. Returns a new array
* each time this method is called.
*/
public byte[] getSalt() {
return (byte[])this.salt.clone();
}
/** {@collect.stats}
* Returns the iteration count.
*
* @return the iteration count
*/
public int getIterationCount() {
return this.iterationCount;
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto.spec;
import java.math.BigInteger;
import java.security.spec.AlgorithmParameterSpec;
/** {@collect.stats}
* This class specifies the set of parameters used with the Diffie-Hellman
* algorithm, as specified in PKCS #3: <i>Diffie-Hellman Key-Agreement
* Standard</i>.
*
* <p>A central authority generates parameters and gives them to the two
* entities seeking to generate a secret key. The parameters are a prime
* <code>p</code>, a base <code>g</code>, and optionally the length
* in bits of the private value, <code>l</code>.
*
* <p>It is possible that more than one instance of parameters may be
* generated by a given central authority, and that there may be more than
* one central authority. Indeed, each individual may be its own central
* authority, with different entities having different parameters.
*
* <p>Note that this class does not perform any validation on specified
* parameters. Thus, the specified values are returned directly even
* if they are null.
*
* @author Jan Luehe
*
* @see javax.crypto.KeyAgreement
* @since 1.4
*/
public class DHParameterSpec implements AlgorithmParameterSpec {
// The prime modulus
private BigInteger p;
// The base generator
private BigInteger g;
// The size in bits of the random exponent (private value) (optional)
private int l;
/** {@collect.stats}
* Constructs a parameter set for Diffie-Hellman, using a prime modulus
* <code>p</code> and a base generator <code>g</code>.
*
* @param p the prime modulus
* @param g the base generator
*/
public DHParameterSpec(BigInteger p, BigInteger g) {
this.p = p;
this.g = g;
this.l = 0;
}
/** {@collect.stats}
* Constructs a parameter set for Diffie-Hellman, using a prime modulus
* <code>p</code>, a base generator <code>g</code>,
* and the size in bits, <code>l</code>, of the random exponent
* (private value).
*
* @param p the prime modulus
* @param g the base generator
* @param l the size in bits of the random exponent (private value)
*/
public DHParameterSpec(BigInteger p, BigInteger g, int l) {
this.p = p;
this.g = g;
this.l = l;
}
/** {@collect.stats}
* Returns the prime modulus <code>p</code>.
*
* @return the prime modulus <code>p</code>
*/
public BigInteger getP() {
return this.p;
}
/** {@collect.stats}
* Returns the base generator <code>g</code>.
*
* @return the base generator <code>g</code>
*/
public BigInteger getG() {
return this.g;
}
/** {@collect.stats}
* Returns the size in bits, <code>l</code>, of the random exponent
* (private value).
*
* @return the size in bits, <code>l</code>, of the random exponent
* (private value), or 0 if this size has not been set
*/
public int getL() {
return this.l;
}
}
| Java |
/*
* Copyright (c) 2003, 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 javax.crypto.spec;
import java.math.BigInteger;
import java.security.spec.AlgorithmParameterSpec;
/** {@collect.stats}
* This class specifies the source for encoding input P in OAEP Padding,
* as defined in the
* <a href="http://www.ietf.org/rfc/rfc3447.txt">PKCS #1</a>
* standard.
* <pre>
* PKCS1PSourceAlgorithms ALGORITHM-IDENTIFIER ::= {
* { OID id-pSpecified PARAMETERS OCTET STRING },
* ... -- Allows for future expansion --
* }
* </pre>
* @author Valerie Peng
*
* @since 1.5
*/
public class PSource {
private String pSrcName;
/** {@collect.stats}
* Constructs a source of the encoding input P for OAEP
* padding as defined in the PKCS #1 standard using the
* specified PSource algorithm.
* @param pSrcName the algorithm for the source of the
* encoding input P.
* @exception NullPointerException if <code>pSrcName</code>
* is null.
*/
protected PSource(String pSrcName) {
if (pSrcName == null) {
throw new NullPointerException("pSource algorithm is null");
}
this.pSrcName = pSrcName;
}
/** {@collect.stats}
* Returns the PSource algorithm name.
*
* @return the PSource algorithm name.
*/
public String getAlgorithm() {
return pSrcName;
}
/** {@collect.stats}
* This class is used to explicitly specify the value for
* encoding input P in OAEP Padding.
*
* @since 1.5
*/
public static final class PSpecified extends PSource {
private byte[] p = new byte[0];
/** {@collect.stats}
* The encoding input P whose value equals byte[0].
*/
public static final PSpecified DEFAULT = new PSpecified(new byte[0]);
/** {@collect.stats}
* Constructs the source explicitly with the specified
* value <code>p</code> as the encoding input P.
* Note:
* @param p the value of the encoding input. The contents
* of the array are copied to protect against subsequent
* modification.
* @exception NullPointerException if <code>p</code> is null.
*/
public PSpecified(byte[] p) {
super("PSpecified");
this.p = (byte[]) p.clone();
}
/** {@collect.stats}
* Returns the value of encoding input P.
* @return the value of encoding input P. A new array is
* returned each time this method is called.
*/
public byte[] getValue() {
return (p.length==0? p: (byte[])p.clone());
}
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto.spec;
import java.math.BigInteger;
/** {@collect.stats}
* This class specifies a Diffie-Hellman private key with its associated
* parameters.
*
* <p>Note that this class does not perform any validation on specified
* parameters. Thus, the specified values are returned directly even
* if they are null.
*
* @author Jan Luehe
*
* @see DHPublicKeySpec
* @since 1.4
*/
public class DHPrivateKeySpec implements java.security.spec.KeySpec {
// The private value
private BigInteger x;
// The prime modulus
private BigInteger p;
// The base generator
private BigInteger g;
/** {@collect.stats}
* Constructor that takes a private value <code>x</code>, a prime
* modulus <code>p</code>, and a base generator <code>g</code>.
* @param x private value x
* @param p prime modulus p
* @param g base generator g
*/
public DHPrivateKeySpec(BigInteger x, BigInteger p, BigInteger g) {
this.x = x;
this.p = p;
this.g = g;
}
/** {@collect.stats}
* Returns the private value <code>x</code>.
*
* @return the private value <code>x</code>
*/
public BigInteger getX() {
return this.x;
}
/** {@collect.stats}
* Returns the prime modulus <code>p</code>.
*
* @return the prime modulus <code>p</code>
*/
public BigInteger getP() {
return this.p;
}
/** {@collect.stats}
* Returns the base generator <code>g</code>.
*
* @return the base generator <code>g</code>
*/
public BigInteger getG() {
return this.g;
}
}
| Java |
/*
* Copyright (c) 1998, 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 javax.crypto.spec;
import java.security.spec.AlgorithmParameterSpec;
/** {@collect.stats}
* This class specifies the parameters used with the
* <a href="http://www.ietf.org/rfc/rfc2268.txt"><i>RC2</i></a>
* algorithm.
*
* <p> The parameters consist of an effective key size and optionally
* an 8-byte initialization vector (IV) (only in feedback mode).
*
* <p> This class can be used to initialize a <code>Cipher</code> object that
* implements the <i>RC2</i> algorithm.
*
* @author Jan Luehe
*
* @since 1.4
*/
public class RC2ParameterSpec implements AlgorithmParameterSpec {
private byte[] iv = null;
private int effectiveKeyBits;
/** {@collect.stats}
* Constructs a parameter set for RC2 from the given effective key size
* (in bits).
*
* @param effectiveKeyBits the effective key size in bits.
*/
public RC2ParameterSpec(int effectiveKeyBits) {
this.effectiveKeyBits = effectiveKeyBits;
}
/** {@collect.stats}
* Constructs a parameter set for RC2 from the given effective key size
* (in bits) and an 8-byte IV.
*
* <p> The bytes that constitute the IV are those between
* <code>iv[0]</code> and <code>iv[7]</code> inclusive.
*
* @param effectiveKeyBits the effective key size in bits.
* @param iv the buffer with the 8-byte IV. The first 8 bytes of
* the buffer are copied to protect against subsequent modification.
* @exception IllegalArgumentException if <code>iv</code> is null.
*/
public RC2ParameterSpec(int effectiveKeyBits, byte[] iv) {
this(effectiveKeyBits, iv, 0);
}
/** {@collect.stats}
* Constructs a parameter set for RC2 from the given effective key size
* (in bits) and IV.
*
* <p> The IV is taken from <code>iv</code>, starting at
* <code>offset</code> inclusive.
* The bytes that constitute the IV are those between
* <code>iv[offset]</code> and <code>iv[offset+7]</code> inclusive.
*
* @param effectiveKeyBits the effective key size in bits.
* @param iv the buffer with the IV. The first 8 bytes
* of the buffer beginning at <code>offset</code> inclusive
* are copied to protect against subsequent modification.
* @param offset the offset in <code>iv</code> where the 8-byte IV
* starts.
* @exception IllegalArgumentException if <code>iv</code> is null.
*/
public RC2ParameterSpec(int effectiveKeyBits, byte[] iv, int offset) {
this.effectiveKeyBits = effectiveKeyBits;
if (iv == null) throw new IllegalArgumentException("IV missing");
int blockSize = 8;
if (iv.length - offset < blockSize) {
throw new IllegalArgumentException("IV too short");
}
this.iv = new byte[blockSize];
System.arraycopy(iv, offset, this.iv, 0, blockSize);
}
/** {@collect.stats}
* Returns the effective key size in bits.
*
* @return the effective key size in bits.
*/
public int getEffectiveKeyBits() {
return this.effectiveKeyBits;
}
/** {@collect.stats}
* Returns the IV or null if this parameter set does not contain an IV.
*
* @return the IV or null if this parameter set does not contain an IV.
* Returns a new array each time this method is called.
*/
public byte[] getIV() {
return (iv == null? null:(byte[])iv.clone());
}
/** {@collect.stats}
* Tests for equality between the specified object and this
* object. Two RC2ParameterSpec objects are considered equal if their
* effective key sizes and IVs are equal.
* (Two IV references are considered equal if both are <tt>null</tt>.)
*
* @param obj the object to test for equality with this object.
*
* @return true if the objects are considered equal, false if
* <code>obj</code> is null or otherwise.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof RC2ParameterSpec)) {
return false;
}
RC2ParameterSpec other = (RC2ParameterSpec) obj;
return ((effectiveKeyBits == other.effectiveKeyBits) &&
java.util.Arrays.equals(iv, other.iv));
}
/** {@collect.stats}
* Calculates a hash code value for the object.
* Objects that are equal will also have the same hashcode.
*/
public int hashCode() {
int retval = 0;
if (iv != null) {
for (int i = 1; i < iv.length; i++) {
retval += iv[i] * i;
}
}
return (retval += effectiveKeyBits);
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto.spec;
import java.security.InvalidKeyException;
/** {@collect.stats}
* This class specifies a DES key.
*
* @author Jan Luehe
*
* @since 1.4
*/
public class DESKeySpec implements java.security.spec.KeySpec {
/** {@collect.stats}
* The constant which defines the length of a DES key in bytes.
*/
public static final int DES_KEY_LEN = 8;
private byte[] key;
/*
* Weak/semi-weak keys copied from FIPS 74.
*
* "...The first 6 keys have duals different than themselves, hence
* each is both a key and a dual giving 12 keys with duals. The last
* four keys equal their duals, and are called self-dual keys..."
*
* 1. E001E001F101F101 01E001E001F101F1
* 2. FE1FFE1FFEOEFEOE 1FFE1FFEOEFEOEFE
* 3. E01FE01FF10EF10E 1FE01FEOOEF10EF1
* 4. 01FE01FE01FE01FE FE01FE01FE01FE01
* 5. 011F011F010E010E 1F011F010E010E01
* 6. E0FEE0FEF1FEF1FE FEE0FEE0FEF1FEF1
* 7. 0101010101010101 0101010101010101
* 8. FEFEFEFEFEFEFEFE FEFEFEFEFEFEFEFE
* 9. E0E0E0E0F1F1F1F1 E0E0E0E0F1F1F1F1
* 10. 1F1F1F1F0E0E0E0E 1F1F1F1F0E0E0E0E
*/
private static final byte[][] WEAK_KEYS = {
{ (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x01,
(byte)0x01, (byte)0x01, (byte)0x01 },
{ (byte)0xFE, (byte)0xFE, (byte)0xFE, (byte)0xFE, (byte)0xFE,
(byte)0xFE, (byte)0xFE, (byte)0xFE },
{ (byte)0x1F, (byte)0x1F, (byte)0x1F, (byte)0x1F, (byte)0x0E,
(byte)0x0E, (byte)0x0E, (byte)0x0E },
{ (byte)0xE0, (byte)0xE0, (byte)0xE0, (byte)0xE0, (byte)0xF1,
(byte)0xF1, (byte)0xF1, (byte)0xF1 },
{ (byte)0x01, (byte)0xFE, (byte)0x01, (byte)0xFE, (byte)0x01,
(byte)0xFE, (byte)0x01, (byte)0xFE },
{ (byte)0x1F, (byte)0xE0, (byte)0x1F, (byte)0xE0, (byte)0x0E,
(byte)0xF1, (byte)0x0E, (byte)0xF1 },
{ (byte)0x01, (byte)0xE0, (byte)0x01, (byte)0xE0, (byte)0x01,
(byte)0xF1, (byte)0x01, (byte)0xF1 },
{ (byte)0x1F, (byte)0xFE, (byte)0x1F, (byte)0xFE, (byte)0x0E,
(byte)0xFE, (byte)0x0E, (byte)0xFE },
{ (byte)0x01, (byte)0x1F, (byte)0x01, (byte)0x1F, (byte)0x01,
(byte)0x0E, (byte)0x01, (byte)0x0E },
{ (byte)0xE0, (byte)0xFE, (byte)0xE0, (byte)0xFE, (byte)0xF1,
(byte)0xFE, (byte)0xF1, (byte)0xFE },
{ (byte)0xFE, (byte)0x01, (byte)0xFE, (byte)0x01, (byte)0xFE,
(byte)0x01, (byte)0xFE, (byte)0x01 },
{ (byte)0xE0, (byte)0x1F, (byte)0xE0, (byte)0x1F, (byte)0xF1,
(byte)0x0E, (byte)0xF1, (byte)0x0E },
{ (byte)0xE0, (byte)0x01, (byte)0xE0, (byte)0x01, (byte)0xF1,
(byte)0x01, (byte)0xF1, (byte)0x01 },
{ (byte)0xFE, (byte)0x1F, (byte)0xFE, (byte)0x1F, (byte)0xFE,
(byte)0x0E, (byte)0xFE, (byte)0x0E },
{ (byte)0x1F, (byte)0x01, (byte)0x1F, (byte)0x01, (byte)0x0E,
(byte)0x01, (byte)0x0E, (byte)0x01 },
{ (byte)0xFE, (byte)0xE0, (byte)0xFE, (byte)0xE0, (byte)0xFE,
(byte)0xF1, (byte)0xFE, (byte)0xF1 }
};
/** {@collect.stats}
* Creates a DESKeySpec object using the first 8 bytes in
* <code>key</code> as the key material for the DES key.
*
* <p> The bytes that constitute the DES key are those between
* <code>key[0]</code> and <code>key[7]</code> inclusive.
*
* @param key the buffer with the DES key material. The first 8 bytes
* of the buffer are copied to protect against subsequent modification.
*
* @exception NullPointerException if the given key material is
* <code>null</code>
* @exception InvalidKeyException if the given key material is shorter
* than 8 bytes.
*/
public DESKeySpec(byte[] key) throws InvalidKeyException {
this(key, 0);
}
/** {@collect.stats}
* Creates a DESKeySpec object using the first 8 bytes in
* <code>key</code>, beginning at <code>offset</code> inclusive,
* as the key material for the DES key.
*
* <p> The bytes that constitute the DES key are those between
* <code>key[offset]</code> and <code>key[offset+7]</code> inclusive.
*
* @param key the buffer with the DES key material. The first 8 bytes
* of the buffer beginning at <code>offset</code> inclusive are copied
* to protect against subsequent modification.
* @param offset the offset in <code>key</code>, where the DES key
* material starts.
*
* @exception NullPointerException if the given key material is
* <code>null</code>
* @exception InvalidKeyException if the given key material, starting at
* <code>offset</code> inclusive, is shorter than 8 bytes.
*/
public DESKeySpec(byte[] key, int offset) throws InvalidKeyException {
if (key.length - offset < DES_KEY_LEN) {
throw new InvalidKeyException("Wrong key size");
}
this.key = new byte[DES_KEY_LEN];
System.arraycopy(key, offset, this.key, 0, DES_KEY_LEN);
}
/** {@collect.stats}
* Returns the DES key material.
*
* @return the DES key material. Returns a new array
* each time this method is called.
*/
public byte[] getKey() {
return (byte[])this.key.clone();
}
/** {@collect.stats}
* Checks if the given DES key material, starting at <code>offset</code>
* inclusive, is parity-adjusted.
*
* @param key the buffer with the DES key material.
* @param offset the offset in <code>key</code>, where the DES key
* material starts.
*
* @return true if the given DES key material is parity-adjusted, false
* otherwise.
*
* @exception InvalidKeyException if the given key material is
* <code>null</code>, or starting at <code>offset</code> inclusive, is
* shorter than 8 bytes.
*/
public static boolean isParityAdjusted(byte[] key, int offset)
throws InvalidKeyException {
if (key == null) {
throw new InvalidKeyException("null key");
}
if (key.length - offset < DES_KEY_LEN) {
throw new InvalidKeyException("Wrong key size");
}
for (int i = 0; i < DES_KEY_LEN; i++) {
int k = Integer.bitCount(key[offset++] & 0xff);
if ((k & 1) == 0) {
return false;
}
}
return true;
}
/** {@collect.stats}
* Checks if the given DES key material is weak or semi-weak.
*
* @param key the buffer with the DES key material.
* @param offset the offset in <code>key</code>, where the DES key
* material starts.
*
* @return true if the given DES key material is weak or semi-weak, false
* otherwise.
*
* @exception InvalidKeyException if the given key material is
* <code>null</code>, or starting at <code>offset</code> inclusive, is
* shorter than 8 bytes.
*/
public static boolean isWeak(byte[] key, int offset)
throws InvalidKeyException {
if (key == null) {
throw new InvalidKeyException("null key");
}
if (key.length - offset < DES_KEY_LEN) {
throw new InvalidKeyException("Wrong key size");
}
for (int i = 0; i < WEAK_KEYS.length; i++) {
boolean found = true;
for (int j = 0; j < DES_KEY_LEN && found == true; j++) {
if (WEAK_KEYS[i][j] != key[j+offset]) {
found = false;
}
}
if (found == true) {
return found;
}
}
return false;
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto.spec;
import java.security.spec.AlgorithmParameterSpec;
/** {@collect.stats}
* This class specifies an <i>initialization vector</i> (IV).
* Examples which use IVs are ciphers in feedback mode,
* e.g., DES in CBC mode and RSA ciphers with OAEP encoding
* operation.
*
* @author Jan Luehe
*
* @since 1.4
*/
public class IvParameterSpec implements AlgorithmParameterSpec {
private byte[] iv;
/** {@collect.stats}
* Creates an IvParameterSpec object using the bytes in <code>iv</code>
* as the IV.
*
* @param iv the buffer with the IV. The contents of the
* buffer are copied to protect against subsequent modification.
* @throws NullPointerException if <code>iv</code> is <code>null</code>
*/
public IvParameterSpec(byte[] iv) {
this(iv, 0, iv.length);
}
/** {@collect.stats}
* Creates an IvParameterSpec object using the first <code>len</code>
* bytes in <code>iv</code>, beginning at <code>offset</code>
* inclusive, as the IV.
*
* <p> The bytes that constitute the IV are those between
* <code>iv[offset]</code> and <code>iv[offset+len-1]</code> inclusive.
*
* @param iv the buffer with the IV. The first <code>len</code>
* bytes of the buffer beginning at <code>offset</code> inclusive
* are copied to protect against subsequent modification.
* @param offset the offset in <code>iv</code> where the IV
* starts.
* @param len the number of IV bytes.
* @throws IllegalArgumentException if <code>iv</code> is <code>null</code>
* or <code>(iv.length - offset < len)</code>
* @throws ArrayIndexOutOfBoundsException is thrown if <code>offset</code>
* or <code>len</code> index bytes outside the <code>iv</code>.
*/
public IvParameterSpec(byte[] iv, int offset, int len) {
if (iv == null) {
throw new IllegalArgumentException("IV missing");
}
if (iv.length - offset < len) {
throw new IllegalArgumentException
("IV buffer too short for given offset/length combination");
}
if (len < 0) {
throw new ArrayIndexOutOfBoundsException("len is negative");
}
this.iv = new byte[len];
System.arraycopy(iv, offset, this.iv, 0, len);
}
/** {@collect.stats}
* Returns the initialization vector (IV).
*
* @return the initialization vector (IV). Returns a new array
* each time this method is called.
*/
public byte[] getIV() {
return (byte[])this.iv.clone();
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto.spec;
import java.security.InvalidKeyException;
/** {@collect.stats}
* This class specifies a DES-EDE ("triple-DES") key.
*
* @author Jan Luehe
*
* @since 1.4
*/
public class DESedeKeySpec implements java.security.spec.KeySpec {
/** {@collect.stats}
* The constant which defines the length of a DESede key in bytes.
*/
public static final int DES_EDE_KEY_LEN = 24;
private byte[] key;
/** {@collect.stats}
* Creates a DESedeKeySpec object using the first 24 bytes in
* <code>key</code> as the key material for the DES-EDE key.
*
* <p> The bytes that constitute the DES-EDE key are those between
* <code>key[0]</code> and <code>key[23]</code> inclusive
*
* @param key the buffer with the DES-EDE key material. The first
* 24 bytes of the buffer are copied to protect against subsequent
* modification.
*
* @exception NullPointerException if <code>key</code> is null.
* @exception InvalidKeyException if the given key material is shorter
* than 24 bytes.
*/
public DESedeKeySpec(byte[] key) throws InvalidKeyException {
this(key, 0);
}
/** {@collect.stats}
* Creates a DESedeKeySpec object using the first 24 bytes in
* <code>key</code>, beginning at <code>offset</code> inclusive,
* as the key material for the DES-EDE key.
*
* <p> The bytes that constitute the DES-EDE key are those between
* <code>key[offset]</code> and <code>key[offset+23]</code> inclusive.
*
* @param key the buffer with the DES-EDE key material. The first
* 24 bytes of the buffer beginning at <code>offset</code> inclusive
* are copied to protect against subsequent modification.
* @param offset the offset in <code>key</code>, where the DES-EDE key
* material starts.
*
* @exception NullPointerException if <code>key</code> is null.
* @exception InvalidKeyException if the given key material, starting at
* <code>offset</code> inclusive, is shorter than 24 bytes
*/
public DESedeKeySpec(byte[] key, int offset) throws InvalidKeyException {
if (key.length - offset < 24) {
throw new InvalidKeyException("Wrong key size");
}
this.key = new byte[24];
System.arraycopy(key, offset, this.key, 0, 24);
}
/** {@collect.stats}
* Returns the DES-EDE key.
*
* @return the DES-EDE key. Returns a new array
* each time this method is called.
*/
public byte[] getKey() {
return (byte[])this.key.clone();
}
/** {@collect.stats}
* Checks if the given DES-EDE key, starting at <code>offset</code>
* inclusive, is parity-adjusted.
*
* @param key a byte array which holds the key value
* @param offset the offset into the byte array
* @return true if the given DES-EDE key is parity-adjusted, false
* otherwise
*
* @exception NullPointerException if <code>key</code> is null.
* @exception InvalidKeyException if the given key material, starting at
* <code>offset</code> inclusive, is shorter than 24 bytes
*/
public static boolean isParityAdjusted(byte[] key, int offset)
throws InvalidKeyException {
if (key.length - offset < 24) {
throw new InvalidKeyException("Wrong key size");
}
if (DESKeySpec.isParityAdjusted(key, offset) == false
|| DESKeySpec.isParityAdjusted(key, offset + 8) == false
|| DESKeySpec.isParityAdjusted(key, offset + 16) == false) {
return false;
}
return true;
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto.spec;
import java.security.spec.KeySpec;
/** {@collect.stats}
* A user-chosen password that can be used with password-based encryption
* (<i>PBE</i>).
*
* <p>The password can be viewed as some kind of raw key material, from which
* the encryption mechanism that uses it derives a cryptographic key.
*
* <p>Different PBE mechanisms may consume different bits of each password
* character. For example, the PBE mechanism defined in
* <a href="http://www.ietf.org/rfc/rfc2898.txt">
* PKCS #5</a> looks at only the low order 8 bits of each character, whereas
* PKCS #12 looks at all 16 bits of each character.
*
* <p>You convert the password characters to a PBE key by creating an
* instance of the appropriate secret-key factory. For example, a secret-key
* factory for PKCS #5 will construct a PBE key from only the low order 8 bits
* of each password character, whereas a secret-key factory for PKCS #12 will
* take all 16 bits of each character.
*
* <p>Also note that this class stores passwords as char arrays instead of
* <code>String</code> objects (which would seem more logical), because the
* String class is immutable and there is no way to overwrite its
* internal value when the password stored in it is no longer needed. Hence,
* this class requests the password as a char array, so it can be overwritten
* when done.
*
* @author Jan Luehe
* @author Valerie Peng
*
* @see javax.crypto.SecretKeyFactory
* @see PBEParameterSpec
* @since 1.4
*/
public class PBEKeySpec implements KeySpec {
private char[] password;
private byte[] salt = null;
private int iterationCount = 0;
private int keyLength = 0;
/** {@collect.stats}
* Constructor that takes a password. An empty char[] is used if
* null is specified.
*
* <p> Note: <code>password</code> is cloned before it is stored in
* the new <code>PBEKeySpec</code> object.
*
* @param password the password.
*/
public PBEKeySpec(char[] password) {
if ((password == null) || (password.length == 0)) {
this.password = new char[0];
} else {
this.password = (char[])password.clone();
}
}
/** {@collect.stats}
* Constructor that takes a password, salt, iteration count, and
* to-be-derived key length for generating PBEKey of variable-key-size
* PBE ciphers. An empty char[] is used if null is specified for
* <code>password</code>.
*
* <p> Note: the <code>password</code> and <code>salt</code>
* are cloned before they are stored in
* the new <code>PBEKeySpec</code> object.
*
* @param password the password.
* @param salt the salt.
* @param iterationCount the iteration count.
* @param keyLength the to-be-derived key length.
* @exception NullPointerException if <code>salt</code> is null.
* @exception IllegalArgumentException if <code>salt</code> is empty,
* i.e. 0-length, <code>iterationCount</code> or
* <code>keyLength</code> is not positive.
*/
public PBEKeySpec(char[] password, byte[] salt, int iterationCount,
int keyLength) {
if ((password == null) || (password.length == 0)) {
this.password = new char[0];
} else {
this.password = (char[])password.clone();
}
if (salt == null) {
throw new NullPointerException("the salt parameter " +
"must be non-null");
} else if (salt.length == 0) {
throw new IllegalArgumentException("the salt parameter " +
"must not be empty");
} else {
this.salt = (byte[]) salt.clone();
}
if (iterationCount<=0) {
throw new IllegalArgumentException("invalid iterationCount value");
}
if (keyLength<=0) {
throw new IllegalArgumentException("invalid keyLength value");
}
this.iterationCount = iterationCount;
this.keyLength = keyLength;
}
/** {@collect.stats}
* Constructor that takes a password, salt, iteration count for
* generating PBEKey of fixed-key-size PBE ciphers. An empty
* char[] is used if null is specified for <code>password</code>.
*
* <p> Note: the <code>password</code> and <code>salt</code>
* are cloned before they are stored in the new
* <code>PBEKeySpec</code> object.
*
* @param password the password.
* @param salt the salt.
* @param iterationCount the iteration count.
* @exception NullPointerException if <code>salt</code> is null.
* @exception IllegalArgumentException if <code>salt</code> is empty,
* i.e. 0-length, or <code>iterationCount</code> is not positive.
*/
public PBEKeySpec(char[] password, byte[] salt, int iterationCount) {
if ((password == null) || (password.length == 0)) {
this.password = new char[0];
} else {
this.password = (char[])password.clone();
}
if (salt == null) {
throw new NullPointerException("the salt parameter " +
"must be non-null");
} else if (salt.length == 0) {
throw new IllegalArgumentException("the salt parameter " +
"must not be empty");
} else {
this.salt = (byte[]) salt.clone();
}
if (iterationCount<=0) {
throw new IllegalArgumentException("invalid iterationCount value");
}
this.iterationCount = iterationCount;
}
/** {@collect.stats}
* Clears the internal copy of the password.
*
*/
public final void clearPassword() {
if (password != null) {
for (int i = 0; i < password.length; i++) {
password[i] = ' ';
}
password = null;
}
}
/** {@collect.stats}
* Returns a copy of the password.
*
* <p> Note: this method returns a copy of the password. It is
* the caller's responsibility to zero out the password information after
* it is no longer needed.
*
* @exception IllegalStateException if password has been cleared by
* calling <code>clearPassword</code> method.
* @return the password.
*/
public final char[] getPassword() {
if (password == null) {
throw new IllegalStateException("password has been cleared");
}
return (char[]) password.clone();
}
/** {@collect.stats}
* Returns a copy of the salt or null if not specified.
*
* <p> Note: this method should return a copy of the salt. It is
* the caller's responsibility to zero out the salt information after
* it is no longer needed.
*
* @return the salt.
*/
public final byte[] getSalt() {
if (salt != null) {
return (byte[]) salt.clone();
} else {
return null;
}
}
/** {@collect.stats}
* Returns the iteration count or 0 if not specified.
*
* @return the iteration count.
*/
public final int getIterationCount() {
return iterationCount;
}
/** {@collect.stats}
* Returns the to-be-derived key length or 0 if not specified.
*
* <p> Note: this is used to indicate the preference on key length
* for variable-key-size ciphers. The actual key size depends on
* each provider's implementation.
*
* @return the to-be-derived key length.
*/
public final int getKeyLength() {
return keyLength;
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
/** {@collect.stats}
* This exception is thrown when the length of data provided to a block
* cipher is incorrect, i.e., does not match the block size of the cipher.
*
* @author Jan Luehe
*
* @since 1.4
*/
public class IllegalBlockSizeException
extends java.security.GeneralSecurityException {
private static final long serialVersionUID = -1965144811953540392L;
/** {@collect.stats}
* Constructs an IllegalBlockSizeException with no detail message.
* A detail message is a String that describes this particular
* exception.
*/
public IllegalBlockSizeException() {
super();
}
/** {@collect.stats}
* Constructs an IllegalBlockSizeException with the specified
* detail message.
*
* @param msg the detail message.
*/
public IllegalBlockSizeException(String msg) {
super(msg);
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.lang.ref.*;
import java.util.*;
import java.util.jar.*;
import java.io.*;
import java.net.URL;
import java.security.*;
import java.security.Provider.Service;
import sun.security.jca.*;
import sun.security.jca.GetInstance.Instance;
/** {@collect.stats}
* This class instantiates implementations of JCE engine classes from
* providers registered with the java.security.Security object.
*
* @author Jan Luehe
* @author Sharon Liu
* @since 1.4
*/
final class JceSecurity {
static final SecureRandom RANDOM = new SecureRandom();
// The defaultPolicy and exemptPolicy will be set up
// in the static initializer.
private static CryptoPermissions defaultPolicy = null;
private static CryptoPermissions exemptPolicy = null;
// Map<Provider,?> of the providers we already have verified
// value == PROVIDER_VERIFIED is successfully verified
// value is failure cause Exception in error case
private final static Map verificationResults = new IdentityHashMap();
// Map<Provider,?> of the providers currently being verified
private final static Map verifyingProviders = new IdentityHashMap();
// Set the default value. May be changed in the static initializer.
private static boolean isRestricted = true;
/*
* Don't let anyone instantiate this.
*/
private JceSecurity() {
}
static {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws Exception {
setupJurisdictionPolicies();
return null;
}
});
isRestricted = defaultPolicy.implies(
CryptoAllPermission.INSTANCE) ? false : true;
} catch (Exception e) {
SecurityException se =
new SecurityException(
"Can not initialize cryptographic mechanism");
se.initCause(e);
throw se;
}
}
static Instance getInstance(String type, Class clazz, String algorithm,
String provider) throws NoSuchAlgorithmException,
NoSuchProviderException {
Service s = GetInstance.getService(type, algorithm, provider);
Exception ve = getVerificationResult(s.getProvider());
if (ve != null) {
String msg = "JCE cannot authenticate the provider " + provider;
throw (NoSuchProviderException)
new NoSuchProviderException(msg).initCause(ve);
}
return GetInstance.getInstance(s, clazz);
}
static Instance getInstance(String type, Class clazz, String algorithm,
Provider provider) throws NoSuchAlgorithmException {
Service s = GetInstance.getService(type, algorithm, provider);
Exception ve = JceSecurity.getVerificationResult(provider);
if (ve != null) {
String msg = "JCE cannot authenticate the provider "
+ provider.getName();
throw new SecurityException(msg, ve);
}
return GetInstance.getInstance(s, clazz);
}
static Instance getInstance(String type, Class clazz, String algorithm)
throws NoSuchAlgorithmException {
List services = GetInstance.getServices(type, algorithm);
NoSuchAlgorithmException failure = null;
for (Iterator t = services.iterator(); t.hasNext(); ) {
Service s = (Service)t.next();
if (canUseProvider(s.getProvider()) == false) {
// allow only signed providers
continue;
}
try {
Instance instance = GetInstance.getInstance(s, clazz);
return instance;
} catch (NoSuchAlgorithmException e) {
failure = e;
}
}
throw new NoSuchAlgorithmException("Algorithm " + algorithm
+ " not available", failure);
}
/** {@collect.stats}
* Verify if the JAR at URL codeBase is a signed exempt application
* JAR file and returns the permissions bundled with the JAR.
*
* @throws Exception on error
*/
static CryptoPermissions verifyExemptJar(URL codeBase) throws Exception {
JarVerifier jv = new JarVerifier(codeBase, true);
jv.verify();
return jv.getPermissions();
}
/** {@collect.stats}
* Verify if the JAR at URL codeBase is a signed provider JAR file.
*
* @throws Exception on error
*/
static void verifyProviderJar(URL codeBase) throws Exception {
// Verify the provider JAR file and all
// supporting JAR files if there are any.
JarVerifier jv = new JarVerifier(codeBase, false);
jv.verify();
}
private final static Object PROVIDER_VERIFIED = Boolean.TRUE;
/*
* Verify that the provider JAR files are signed properly, which
* means the signer's certificate can be traced back to a
* JCE trusted CA.
* Return null if ok, failure Exception if verification failed.
*/
static synchronized Exception getVerificationResult(Provider p) {
Object o = verificationResults.get(p);
if (o == PROVIDER_VERIFIED) {
return null;
} else if (o != null) {
return (Exception)o;
}
if (verifyingProviders.get(p) != null) {
// this method is static synchronized, must be recursion
// return failure now but do not save the result
return new NoSuchProviderException("Recursion during verification");
}
try {
verifyingProviders.put(p, Boolean.FALSE);
URL providerURL = getCodeBase(p.getClass());
verifyProviderJar(providerURL);
// Verified ok, cache result
verificationResults.put(p, PROVIDER_VERIFIED);
return null;
} catch (Exception e) {
verificationResults.put(p, e);
return e;
} finally {
verifyingProviders.remove(p);
}
}
// return whether this provider is properly signed and can be used by JCE
static boolean canUseProvider(Provider p) {
return getVerificationResult(p) == null;
}
// dummy object to represent null
private static final URL NULL_URL;
static {
try {
NULL_URL = new URL("http://null.sun.com/");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// reference to a Map we use as a cache for codebases
private static final Map codeBaseCacheRef = new WeakHashMap();
/*
* Retuns the CodeBase for the given class.
*/
static URL getCodeBase(final Class clazz) {
URL url = (URL)codeBaseCacheRef.get(clazz);
if (url == null) {
url = (URL)AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ProtectionDomain pd = clazz.getProtectionDomain();
if (pd != null) {
CodeSource cs = pd.getCodeSource();
if (cs != null) {
return cs.getLocation();
}
}
return NULL_URL;
}
});
codeBaseCacheRef.put(clazz, url);
}
return (url == NULL_URL) ? null : url;
}
private static void setupJurisdictionPolicies() throws Exception {
String javaHomeDir = System.getProperty("java.home");
String sep = File.separator;
String pathToPolicyJar = javaHomeDir + sep + "lib" + sep +
"security" + sep;
File exportJar = new File(pathToPolicyJar, "US_export_policy.jar");
File importJar = new File(pathToPolicyJar, "local_policy.jar");
URL jceCipherURL = ClassLoader.getSystemResource
("javax/crypto/Cipher.class");
if ((jceCipherURL == null) ||
!exportJar.exists() || !importJar.exists()) {
throw new SecurityException
("Cannot locate policy or framework files!");
}
// Enforce the signer restraint, i.e. signer of JCE framework
// jar should also be the signer of the two jurisdiction policy
// jar files.
JarVerifier.verifyFrameworkSigned(jceCipherURL);
// Read jurisdiction policies.
CryptoPermissions defaultExport = new CryptoPermissions();
CryptoPermissions exemptExport = new CryptoPermissions();
loadPolicies(exportJar, defaultExport, exemptExport);
CryptoPermissions defaultImport = new CryptoPermissions();
CryptoPermissions exemptImport = new CryptoPermissions();
loadPolicies(importJar, defaultImport, exemptImport);
// Merge the export and import policies for default applications.
if (defaultExport.isEmpty() || defaultImport.isEmpty()) {
throw new SecurityException("Missing mandatory jurisdiction " +
"policy files");
}
defaultPolicy = defaultExport.getMinimum(defaultImport);
// Merge the export and import policies for exempt applications.
if (exemptExport.isEmpty()) {
exemptPolicy = exemptImport.isEmpty() ? null : exemptImport;
} else {
exemptPolicy = exemptExport.getMinimum(exemptImport);
}
}
/** {@collect.stats}
* Load the policies from the specified file. Also checks that the
* policies are correctly signed.
*/
private static void loadPolicies(File jarPathName,
CryptoPermissions defaultPolicy,
CryptoPermissions exemptPolicy)
throws Exception {
JarFile jf = new JarFile(jarPathName);
Enumeration entries = jf.entries();
while (entries.hasMoreElements()) {
JarEntry je = (JarEntry)entries.nextElement();
InputStream is = null;
try {
if (je.getName().startsWith("default_")) {
is = jf.getInputStream(je);
defaultPolicy.load(is);
} else if (je.getName().startsWith("exempt_")) {
is = jf.getInputStream(je);
exemptPolicy.load(is);
} else {
continue;
}
} finally {
if (is != null) {
is.close();
}
}
// Enforce the signer restraint, i.e. signer of JCE framework
// jar should also be the signer of the two jurisdiction policy
// jar files.
JarVerifier.verifyPolicySigned(je.getCertificates());
}
// Close and nullify the JarFile reference to help GC.
jf.close();
jf = null;
}
static CryptoPermissions getDefaultPolicy() {
return defaultPolicy;
}
static CryptoPermissions getExemptPolicy() {
return exemptPolicy;
}
static boolean isRestricted() {
return isRestricted;
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.util.*;
import java.security.*;
import java.security.Provider.Service;
import java.security.spec.*;
import sun.security.jca.*;
import sun.security.jca.GetInstance.Instance;
/** {@collect.stats}
* This class provides the functionality of a secret (symmetric) key generator.
*
* <p>Key generators are constructed using one of the <code>getInstance</code>
* class methods of this class.
*
* <p>KeyGenerator objects are reusable, i.e., after a key has been
* generated, the same KeyGenerator object can be re-used to generate further
* keys.
*
* <p>There are two ways to generate a key: in an algorithm-independent
* manner, and in an algorithm-specific manner.
* The only difference between the two is the initialization of the object:
*
* <ul>
* <li><b>Algorithm-Independent Initialization</b>
* <p>All key generators share the concepts of a <i>keysize</i> and a
* <i>source of randomness</i>.
* There is an
* {@link #init(int, java.security.SecureRandom) init}
* method in this KeyGenerator class that takes these two universally
* shared types of arguments. There is also one that takes just a
* <code>keysize</code> argument, and uses the SecureRandom implementation
* of the highest-priority installed provider as the source of randomness
* (or a system-provided source of randomness if none of the installed
* providers supply a SecureRandom implementation), and one that takes just a
* source of randomness.
*
* <p>Since no other parameters are specified when you call the above
* algorithm-independent <code>init</code> methods, it is up to the
* provider what to do about the algorithm-specific parameters (if any) to be
* associated with each of the keys.
* <p>
*
* <li><b>Algorithm-Specific Initialization</b>
* <p>For situations where a set of algorithm-specific parameters already
* exists, there are two
* {@link #init(java.security.spec.AlgorithmParameterSpec) init}
* methods that have an <code>AlgorithmParameterSpec</code>
* argument. One also has a <code>SecureRandom</code> argument, while the
* other uses the SecureRandom implementation
* of the highest-priority installed provider as the source of randomness
* (or a system-provided source of randomness if none of the installed
* providers supply a SecureRandom implementation).
* </ul>
*
* <p>In case the client does not explicitly initialize the KeyGenerator
* (via a call to an <code>init</code> method), each provider must
* supply (and document) a default initialization.
*
* @author Jan Luehe
*
* @see SecretKey
* @since 1.4
*/
public class KeyGenerator {
// see java.security.KeyPairGenerator for failover notes
private final static int I_NONE = 1;
private final static int I_RANDOM = 2;
private final static int I_PARAMS = 3;
private final static int I_SIZE = 4;
// The provider
private Provider provider;
// The provider implementation (delegate)
private volatile KeyGeneratorSpi spi;
// The algorithm
private final String algorithm;
private final Object lock = new Object();
private Iterator serviceIterator;
private int initType;
private int initKeySize;
private AlgorithmParameterSpec initParams;
private SecureRandom initRandom;
/** {@collect.stats}
* Creates a KeyGenerator object.
*
* @param keyGenSpi the delegate
* @param provider the provider
* @param algorithm the algorithm
*/
protected KeyGenerator(KeyGeneratorSpi keyGenSpi, Provider provider,
String algorithm) {
this.spi = keyGenSpi;
this.provider = provider;
this.algorithm = algorithm;
}
private KeyGenerator(String algorithm) throws NoSuchAlgorithmException {
this.algorithm = algorithm;
List list = GetInstance.getServices("KeyGenerator", algorithm);
serviceIterator = list.iterator();
initType = I_NONE;
// fetch and instantiate initial spi
if (nextSpi(null, false) == null) {
throw new NoSuchAlgorithmException
(algorithm + " KeyGenerator not available");
}
}
/** {@collect.stats}
* Returns the algorithm name of this <code>KeyGenerator</code> object.
*
* <p>This is the same name that was specified in one of the
* <code>getInstance</code> calls that created this
* <code>KeyGenerator</code> object.
*
* @return the algorithm name of this <code>KeyGenerator</code> object.
*/
public final String getAlgorithm() {
return this.algorithm;
}
/** {@collect.stats}
* Returns a <code>KeyGenerator</code> object that generates secret keys
* for the specified algorithm.
*
* <p> This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new KeyGenerator object encapsulating the
* KeyGeneratorSpi implementation from the first
* Provider that supports the specified algorithm is returned.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the standard name of the requested key algorithm.
* See Appendix A in the
* <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard algorithm names.
*
* @return the new <code>KeyGenerator</code> object.
*
* @exception NullPointerException if the specified algorithm is null.
*
* @exception NoSuchAlgorithmException if no Provider supports a
* KeyGeneratorSpi implementation for the
* specified algorithm.
*
* @see java.security.Provider
*/
public static final KeyGenerator getInstance(String algorithm)
throws NoSuchAlgorithmException {
return new KeyGenerator(algorithm);
}
/** {@collect.stats}
* Returns a <code>KeyGenerator</code> object that generates secret keys
* for the specified algorithm.
*
* <p> A new KeyGenerator object encapsulating the
* KeyGeneratorSpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the standard name of the requested key algorithm.
* See Appendix A in the
* <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard algorithm names.
*
* @param provider the name of the provider.
*
* @return the new <code>KeyGenerator</code> object.
*
* @exception NullPointerException if the specified algorithm is null.
*
* @exception NoSuchAlgorithmException if a KeyGeneratorSpi
* implementation for the specified algorithm is not
* available from the specified provider.
*
* @exception NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception IllegalArgumentException if the <code>provider</code>
* is null or empty.
*
* @see java.security.Provider
*/
public static final KeyGenerator getInstance(String algorithm,
String provider) throws NoSuchAlgorithmException,
NoSuchProviderException {
Instance instance = JceSecurity.getInstance("KeyGenerator",
KeyGeneratorSpi.class, algorithm, provider);
return new KeyGenerator((KeyGeneratorSpi)instance.impl,
instance.provider, algorithm);
}
/** {@collect.stats}
* Returns a <code>KeyGenerator</code> object that generates secret keys
* for the specified algorithm.
*
* <p> A new KeyGenerator object encapsulating the
* KeyGeneratorSpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param algorithm the standard name of the requested key algorithm.
* See Appendix A in the
* <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard algorithm names.
*
* @param provider the provider.
*
* @return the new <code>KeyGenerator</code> object.
*
* @exception NullPointerException if the specified algorithm is null.
*
* @exception NoSuchAlgorithmException if a KeyGeneratorSpi
* implementation for the specified algorithm is not available
* from the specified Provider object.
*
* @exception IllegalArgumentException if the <code>provider</code>
* is null.
*
* @see java.security.Provider
*/
public static final KeyGenerator getInstance(String algorithm,
Provider provider) throws NoSuchAlgorithmException {
Instance instance = JceSecurity.getInstance("KeyGenerator",
KeyGeneratorSpi.class, algorithm, provider);
return new KeyGenerator((KeyGeneratorSpi)instance.impl,
instance.provider, algorithm);
}
/** {@collect.stats}
* Returns the provider of this <code>KeyGenerator</code> object.
*
* @return the provider of this <code>KeyGenerator</code> object
*/
public final Provider getProvider() {
synchronized (lock) {
disableFailover();
return provider;
}
}
/** {@collect.stats}
* Update the active spi of this class and return the next
* implementation for failover. If no more implemenations are
* available, this method returns null. However, the active spi of
* this class is never set to null.
*/
private KeyGeneratorSpi nextSpi(KeyGeneratorSpi oldSpi,
boolean reinit) {
synchronized (lock) {
// somebody else did a failover concurrently
// try that spi now
if ((oldSpi != null) && (oldSpi != spi)) {
return spi;
}
if (serviceIterator == null) {
return null;
}
while (serviceIterator.hasNext()) {
Service s = (Service)serviceIterator.next();
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
try {
Object inst = s.newInstance(null);
// ignore non-spis
if (inst instanceof KeyGeneratorSpi == false) {
continue;
}
KeyGeneratorSpi spi = (KeyGeneratorSpi)inst;
if (reinit) {
if (initType == I_SIZE) {
spi.engineInit(initKeySize, initRandom);
} else if (initType == I_PARAMS) {
spi.engineInit(initParams, initRandom);
} else if (initType == I_RANDOM) {
spi.engineInit(initRandom);
} else if (initType != I_NONE) {
throw new AssertionError
("KeyGenerator initType: " + initType);
}
}
provider = s.getProvider();
this.spi = spi;
return spi;
} catch (Exception e) {
// ignore
}
}
disableFailover();
return null;
}
}
void disableFailover() {
serviceIterator = null;
initType = 0;
initParams = null;
initRandom = null;
}
/** {@collect.stats}
* Initializes this key generator.
*
* @param random the source of randomness for this generator
*/
public final void init(SecureRandom random) {
if (serviceIterator == null) {
spi.engineInit(random);
return;
}
RuntimeException failure = null;
KeyGeneratorSpi mySpi = spi;
do {
try {
mySpi.engineInit(random);
initType = I_RANDOM;
initKeySize = 0;
initParams = null;
initRandom = random;
return;
} catch (RuntimeException e) {
if (failure == null) {
failure = e;
}
mySpi = nextSpi(mySpi, false);
}
} while (mySpi != null);
throw failure;
}
/** {@collect.stats}
* Initializes this key generator with the specified parameter set.
*
* <p> If this key generator requires any random bytes, it will get them
* using the
* {@link SecureRandom <code>SecureRandom</code>}
* implementation of the highest-priority installed
* provider as the source of randomness.
* (If none of the installed providers supply an implementation of
* SecureRandom, a system-provided source of randomness will be used.)
*
* @param params the key generation parameters
*
* @exception InvalidAlgorithmParameterException if the given parameters
* are inappropriate for this key generator
*/
public final void init(AlgorithmParameterSpec params)
throws InvalidAlgorithmParameterException
{
init(params, JceSecurity.RANDOM);
}
/** {@collect.stats}
* Initializes this key generator with the specified parameter
* set and a user-provided source of randomness.
*
* @param params the key generation parameters
* @param random the source of randomness for this key generator
*
* @exception InvalidAlgorithmParameterException if <code>params</code> is
* inappropriate for this key generator
*/
public final void init(AlgorithmParameterSpec params, SecureRandom random)
throws InvalidAlgorithmParameterException
{
if (serviceIterator == null) {
spi.engineInit(params, random);
return;
}
Exception failure = null;
KeyGeneratorSpi mySpi = spi;
do {
try {
mySpi.engineInit(params, random);
initType = I_PARAMS;
initKeySize = 0;
initParams = params;
initRandom = random;
return;
} catch (Exception e) {
if (failure == null) {
failure = e;
}
mySpi = nextSpi(mySpi, false);
}
} while (mySpi != null);
if (failure instanceof InvalidAlgorithmParameterException) {
throw (InvalidAlgorithmParameterException)failure;
}
if (failure instanceof RuntimeException) {
throw (RuntimeException)failure;
}
throw new InvalidAlgorithmParameterException("init() failed", failure);
}
/** {@collect.stats}
* Initializes this key generator for a certain keysize.
*
* <p> If this key generator requires any random bytes, it will get them
* using the
* {@link SecureRandom <code>SecureRandom</code>}
* implementation of the highest-priority installed
* provider as the source of randomness.
* (If none of the installed providers supply an implementation of
* SecureRandom, a system-provided source of randomness will be used.)
*
* @param keysize the keysize. This is an algorithm-specific metric,
* specified in number of bits.
*
* @exception InvalidParameterException if the keysize is wrong or not
* supported.
*/
public final void init(int keysize) {
init(keysize, JceSecurity.RANDOM);
}
/** {@collect.stats}
* Initializes this key generator for a certain keysize, using a
* user-provided source of randomness.
*
* @param keysize the keysize. This is an algorithm-specific metric,
* specified in number of bits.
* @param random the source of randomness for this key generator
*
* @exception InvalidParameterException if the keysize is wrong or not
* supported.
*/
public final void init(int keysize, SecureRandom random) {
if (serviceIterator == null) {
spi.engineInit(keysize, random);
return;
}
RuntimeException failure = null;
KeyGeneratorSpi mySpi = spi;
do {
try {
mySpi.engineInit(keysize, random);
initType = I_SIZE;
initKeySize = keysize;
initParams = null;
initRandom = random;
return;
} catch (RuntimeException e) {
if (failure == null) {
failure = e;
}
mySpi = nextSpi(mySpi, false);
}
} while (mySpi != null);
throw failure;
}
/** {@collect.stats}
* Generates a secret key.
*
* @return the new key
*/
public final SecretKey generateKey() {
if (serviceIterator == null) {
return spi.engineGenerateKey();
}
RuntimeException failure = null;
KeyGeneratorSpi mySpi = spi;
do {
try {
return mySpi.engineGenerateKey();
} catch (RuntimeException e) {
if (failure == null) {
failure = e;
}
mySpi = nextSpi(mySpi, true);
}
} while (mySpi != null);
throw failure;
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.security.*;
import java.security.spec.*;
/** {@collect.stats}
* This class defines the <i>Service Provider Interface</i> (<b>SPI</b>)
* for the <code>SecretKeyFactory</code> class.
* All the abstract methods in this class must be implemented by each
* cryptographic service provider who wishes to supply the implementation
* of a secret-key factory for a particular algorithm.
*
* <P> A provider should document all the key specifications supported by its
* secret key factory.
* For example, the DES secret-key factory supplied by the "SunJCE" provider
* supports <code>DESKeySpec</code> as a transparent representation of DES
* keys, and that provider's secret-key factory for Triple DES keys supports
* <code>DESedeKeySpec</code> as a transparent representation of Triple DES
* keys.
*
* @author Jan Luehe
*
* @see SecretKey
* @see javax.crypto.spec.DESKeySpec
* @see javax.crypto.spec.DESedeKeySpec
* @since 1.4
*/
public abstract class SecretKeyFactorySpi {
/** {@collect.stats}
* Generates a <code>SecretKey</code> object from the
* provided key specification (key material).
*
* @param keySpec the specification (key material) of the secret key
*
* @return the secret key
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this secret-key factory to produce a secret key.
*/
protected abstract SecretKey engineGenerateSecret(KeySpec keySpec)
throws InvalidKeySpecException;
/** {@collect.stats}
* Returns a specification (key material) of the given key
* object in the requested format.
*
* @param key the key
*
* @param keySpec the requested format in which the key material shall be
* returned
*
* @return the underlying key specification (key material) in the
* requested format
*
* @exception InvalidKeySpecException if the requested key specification is
* inappropriate for the given key (e.g., the algorithms associated with
* <code>key</code> and <code>keySpec</code> do not match, or
* <code>key</code> references a key on a cryptographic hardware device
* whereas <code>keySpec</code> is the specification of a software-based
* key), or the given key cannot be dealt with
* (e.g., the given key has an algorithm or format not supported by this
* secret-key factory).
*/
protected abstract KeySpec engineGetKeySpec(SecretKey key, Class keySpec)
throws InvalidKeySpecException;
/** {@collect.stats}
* Translates a key object, whose provider may be unknown or
* potentially untrusted, into a corresponding key object of this
* secret-key factory.
*
* @param key the key whose provider is unknown or untrusted
*
* @return the translated key
*
* @exception InvalidKeyException if the given key cannot be processed
* by this secret-key factory.
*/
protected abstract SecretKey engineTranslateKey(SecretKey key)
throws InvalidKeyException;
}
| 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 javax.crypto;
import java.io.*;
import java.net.*;
import java.security.*;
import java.util.*;
import java.util.jar.*;
import javax.crypto.CryptoPolicyParser.ParsingException;
/** {@collect.stats}
* This class verifies JAR files (and any supporting JAR files), and
* determines whether they may be used in this implementation.
*
* The JCE in OpenJDK has an open cryptographic interface, meaning it
* does not restrict which providers can be used. Compliance with
* United States export controls and with local law governing the
* import/export of products incorporating the JCE in the OpenJDK is
* the responsibility of the licensee.
*
* @since 1.7
*/
final class JarVerifier {
// The URL for the JAR file we want to verify.
private URL jarURL;
private boolean savePerms;
private CryptoPermissions appPerms = null;
/** {@collect.stats}
* Creates a JarVerifier object to verify the given URL.
*
* @param jarURL the JAR file to be verified.
* @param savePerms if true, save the permissions allowed by the
* exemption mechanism
*/
JarVerifier(URL jarURL, boolean savePerms) {
this.jarURL = jarURL;
this.savePerms = savePerms;
}
/** {@collect.stats}
* Verify the JAR file is signed by an entity which has a certificate
* issued by a trusted CA.
*
* In OpenJDK, we just need to examine the "cryptoperms" file to see
* if any permissions were bundled together with this jar file.
*/
void verify() throws JarException, IOException {
// Short-circuit. If we weren't asked to save any, we're done.
if (!savePerms) {
return;
}
// If the protocol of jarURL isn't "jar", we should
// construct a JAR URL so we can open a JarURLConnection
// for verifying this provider.
final URL url = jarURL.getProtocol().equalsIgnoreCase("jar")?
jarURL : new URL("jar:" + jarURL.toString() + "!/");
JarFile jf = null;
try {
// Get a link to the Jarfile to search.
try {
jf = (JarFile)
AccessController.doPrivileged(
new PrivilegedExceptionAction() {
public Object run() throws Exception {
JarURLConnection conn =
(JarURLConnection) url.openConnection();
// You could do some caching here as
// an optimization.
conn.setUseCaches(false);
return conn.getJarFile();
}
});
} catch (java.security.PrivilegedActionException pae) {
SecurityException se = new SecurityException(
"Cannot load " + url.toString());
se.initCause(pae);
throw se;
}
if (jf != null) {
JarEntry je = jf.getJarEntry("cryptoPerms");
if (je == null) {
throw new JarException(
"Can not find cryptoPerms");
}
try {
appPerms = new CryptoPermissions();
appPerms.load(jf.getInputStream(je));
} catch (Exception ex) {
JarException jex =
new JarException("Cannot load/parse" +
jarURL.toString());
jex.initCause(ex);
throw jex;
}
}
} finally {
// Only call close() when caching is not enabled.
// Otherwise, exceptions will be thrown for all
// subsequent accesses of this cached jar.
if (jf != null) {
jf.close();
}
}
}
/** {@collect.stats}
* Verify that the provided JarEntry was indeed signed by the
* framework signing certificate.
*
* @param je the URL of the jar entry to be checked.
* @throws Exception if the jar entry was not signed by
* the proper certificate
*/
static void verifyFrameworkSigned(URL je) throws Exception {
}
/** {@collect.stats}
* Verify that the provided certs include the
* framework signing certificate.
*
* @param certs the list of certs to be checked.
* @throws Exception if the list of certs did not contain
* the framework signing certificate
*/
static void verifyPolicySigned(java.security.cert.Certificate[] certs)
throws Exception {
}
/** {@collect.stats}
* Returns the permissions which are bundled with the JAR file,
* aka the "cryptoperms" file.
*
* NOTE: if this JarVerifier instance is constructed with "savePerms"
* equal to false, then this method would always return null.
*/
CryptoPermissions getPermissions() {
return appPerms;
}
}
| Java |
/*
* Copyright (c) 1999, 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 javax.crypto;
import java.security.AlgorithmParameters;
import java.security.Provider;
import java.security.Key;
import java.security.Security;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.InvalidKeyException;
import java.security.InvalidAlgorithmParameterException;
import java.security.spec.AlgorithmParameterSpec;
import sun.security.jca.GetInstance.Instance;
/** {@collect.stats}
* This class provides the functionality of an exemption mechanism, examples
* of which are <i>key recovery</i>, <i>key weakening</i>, and
* <i>key escrow</i>.
*
* <p>Applications or applets that use an exemption mechanism may be granted
* stronger encryption capabilities than those which don't.
*
* @since 1.4
*/
public class ExemptionMechanism {
// The provider
private Provider provider;
// The provider implementation (delegate)
private ExemptionMechanismSpi exmechSpi;
// The name of the exemption mechanism.
private String mechanism;
// Flag which indicates whether this ExemptionMechanism
// result is generated successfully.
private boolean done = false;
// State information
private boolean initialized = false;
// Store away the key at init() time for later comparison.
private Key keyStored = null;
/** {@collect.stats}
* Creates a ExemptionMechanism object.
*
* @param exmechSpi the delegate
* @param provider the provider
* @param mechanism the exemption mechanism
*/
protected ExemptionMechanism(ExemptionMechanismSpi exmechSpi,
Provider provider,
String mechanism) {
this.exmechSpi = exmechSpi;
this.provider = provider;
this.mechanism = mechanism;
}
/** {@collect.stats}
* Returns the exemption mechanism name of this
* <code>ExemptionMechanism</code> object.
*
* <p>This is the same name that was specified in one of the
* <code>getInstance</code> calls that created this
* <code>ExemptionMechanism</code> object.
*
* @return the exemption mechanism name of this
* <code>ExemptionMechanism</code> object.
*/
public final String getName() {
return this.mechanism;
}
/** {@collect.stats}
* Returns an <code>ExemptionMechanism</code> object that implements the
* specified exemption mechanism algorithm.
*
* <p> This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new ExemptionMechanism object encapsulating the
* ExemptionMechanismSpi implementation from the first
* Provider that supports the specified algorithm is returned.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the standard name of the requested exemption
* mechanism.
* See Appendix A in the
* <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard exemption mechanism names.
*
* @return the new <code>ExemptionMechanism</code> object.
*
* @exception NullPointerException if <code>algorithm</code>
* is null.
*
* @exception NoSuchAlgorithmException if no Provider supports an
* ExemptionMechanismSpi implementation for the
* specified algorithm.
*
* @see java.security.Provider
*/
public static final ExemptionMechanism getInstance(String algorithm)
throws NoSuchAlgorithmException {
Instance instance = JceSecurity.getInstance("ExemptionMechanism",
ExemptionMechanismSpi.class, algorithm);
return new ExemptionMechanism((ExemptionMechanismSpi)instance.impl,
instance.provider, algorithm);
}
/** {@collect.stats}
* Returns an <code>ExemptionMechanism</code> object that implements the
* specified exemption mechanism algorithm.
*
* <p> A new ExemptionMechanism object encapsulating the
* ExemptionMechanismSpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
* @param algorithm the standard name of the requested exemption mechanism.
* See Appendix A in the
* <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard exemption mechanism names.
*
* @param provider the name of the provider.
*
* @return the new <code>ExemptionMechanism</code> object.
*
* @exception NullPointerException if <code>algorithm</code>
* is null.
*
* @exception NoSuchAlgorithmException if an ExemptionMechanismSpi
* implementation for the specified algorithm is not
* available from the specified provider.
*
* @exception NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception IllegalArgumentException if the <code>provider</code>
* is null or empty.
*
* @see java.security.Provider
*/
public static final ExemptionMechanism getInstance(String algorithm,
String provider) throws NoSuchAlgorithmException,
NoSuchProviderException {
Instance instance = JceSecurity.getInstance("ExemptionMechanism",
ExemptionMechanismSpi.class, algorithm, provider);
return new ExemptionMechanism((ExemptionMechanismSpi)instance.impl,
instance.provider, algorithm);
}
/** {@collect.stats}
* Returns an <code>ExemptionMechanism</code> object that implements the
* specified exemption mechanism algorithm.
*
* <p> A new ExemptionMechanism object encapsulating the
* ExemptionMechanismSpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param algorithm the standard name of the requested exemption mechanism.
* See Appendix A in the
* <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard exemption mechanism names.
*
* @param provider the provider.
*
* @return the new <code>ExemptionMechanism</code> object.
*
* @exception NullPointerException if <code>algorithm</code>
* is null.
*
* @exception NoSuchAlgorithmException if an ExemptionMechanismSpi
* implementation for the specified algorithm is not available
* from the specified Provider object.
*
* @exception IllegalArgumentException if the <code>provider</code>
* is null.
*
* @see java.security.Provider
*/
public static final ExemptionMechanism getInstance(String algorithm,
Provider provider) throws NoSuchAlgorithmException {
Instance instance = JceSecurity.getInstance("ExemptionMechanism",
ExemptionMechanismSpi.class, algorithm, provider);
return new ExemptionMechanism((ExemptionMechanismSpi)instance.impl,
instance.provider, algorithm);
}
/** {@collect.stats}
* Returns the provider of this <code>ExemptionMechanism</code> object.
*
* @return the provider of this <code>ExemptionMechanism</code> object.
*/
public final Provider getProvider() {
return this.provider;
}
/** {@collect.stats}
* Returns whether the result blob has been generated successfully by this
* exemption mechanism.
*
* <p>The method also makes sure that the key passed in is the same as
* the one this exemption mechanism used in initializing and generating
* phases.
*
* @param key the key the crypto is going to use.
*
* @return whether the result blob of the same key has been generated
* successfully by this exemption mechanism; false if <code>key</code>
* is null.
*
* @exception ExemptionMechanismException if problem(s) encountered
* while determining whether the result blob has been generated successfully
* by this exemption mechanism object.
*/
public final boolean isCryptoAllowed(Key key)
throws ExemptionMechanismException {
boolean ret = false;
if (done && (key != null)) {
// Check if the key passed in is the same as the one
// this exemption mechanism used.
ret = keyStored.equals(key);
}
return ret;
}
/** {@collect.stats}
* Returns the length in bytes that an output buffer would need to be in
* order to hold the result of the next
* {@link #genExemptionBlob(byte[]) genExemptionBlob}
* operation, given the input length <code>inputLen</code> (in bytes).
*
* <p>The actual output length of the next
* {@link #genExemptionBlob(byte[]) genExemptionBlob}
* call may be smaller than the length returned by this method.
*
* @param inputLen the input length (in bytes)
*
* @return the required output buffer size (in bytes)
*
* @exception IllegalStateException if this exemption mechanism is in a
* wrong state (e.g., has not yet been initialized)
*/
public final int getOutputSize(int inputLen) throws IllegalStateException {
if (!initialized) {
throw new IllegalStateException(
"ExemptionMechanism not initialized");
}
if (inputLen < 0) {
throw new IllegalArgumentException(
"Input size must be equal to " + "or greater than zero");
}
return exmechSpi.engineGetOutputSize(inputLen);
}
/** {@collect.stats}
* Initializes this exemption mechanism with a key.
*
* <p>If this exemption mechanism requires any algorithm parameters
* that cannot be derived from the given <code>key</code>, the
* underlying exemption mechanism implementation is supposed to
* generate the required parameters itself (using provider-specific
* default values); in the case that algorithm parameters must be
* specified by the caller, an <code>InvalidKeyException</code> is raised.
*
* @param key the key for this exemption mechanism
*
* @exception InvalidKeyException if the given key is inappropriate for
* this exemption mechanism.
* @exception ExemptionMechanismException if problem(s) encountered in the
* process of initializing.
*/
public final void init(Key key)
throws InvalidKeyException, ExemptionMechanismException {
done = false;
initialized = false;
keyStored = key;
exmechSpi.engineInit(key);
initialized = true;
}
/** {@collect.stats}
* Initializes this exemption mechanism with a key and a set of algorithm
* parameters.
*
* <p>If this exemption mechanism requires any algorithm parameters
* and <code>params</code> is null, the underlying exemption
* mechanism implementation is supposed to generate the required
* parameters itself (using provider-specific default values); in the case
* that algorithm parameters must be specified by the caller, an
* <code>InvalidAlgorithmParameterException</code> is raised.
*
* @param key the key for this exemption mechanism
* @param params the algorithm parameters
*
* @exception InvalidKeyException if the given key is inappropriate for
* this exemption mechanism.
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this exemption mechanism.
* @exception ExemptionMechanismException if problem(s) encountered in the
* process of initializing.
*/
public final void init(Key key, AlgorithmParameterSpec params)
throws InvalidKeyException, InvalidAlgorithmParameterException,
ExemptionMechanismException {
done = false;
initialized = false;
keyStored = key;
exmechSpi.engineInit(key, params);
initialized = true;
}
/** {@collect.stats}
* Initializes this exemption mechanism with a key and a set of algorithm
* parameters.
*
* <p>If this exemption mechanism requires any algorithm parameters
* and <code>params</code> is null, the underlying exemption mechanism
* implementation is supposed to generate the required parameters itself
* (using provider-specific default values); in the case that algorithm
* parameters must be specified by the caller, an
* <code>InvalidAlgorithmParameterException</code> is raised.
*
* @param key the key for this exemption mechanism
* @param params the algorithm parameters
*
* @exception InvalidKeyException if the given key is inappropriate for
* this exemption mechanism.
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this exemption mechanism.
* @exception ExemptionMechanismException if problem(s) encountered in the
* process of initializing.
*/
public final void init(Key key, AlgorithmParameters params)
throws InvalidKeyException, InvalidAlgorithmParameterException,
ExemptionMechanismException {
done = false;
initialized = false;
keyStored = key;
exmechSpi.engineInit(key, params);
initialized = true;
}
/** {@collect.stats}
* Generates the exemption mechanism key blob.
*
* @return the new buffer with the result key blob.
*
* @exception IllegalStateException if this exemption mechanism is in
* a wrong state (e.g., has not been initialized).
* @exception ExemptionMechanismException if problem(s) encountered in the
* process of generating.
*/
public final byte[] genExemptionBlob() throws IllegalStateException,
ExemptionMechanismException {
if (!initialized) {
throw new IllegalStateException(
"ExemptionMechanism not initialized");
}
byte[] blob = exmechSpi.engineGenExemptionBlob();
done = true;
return blob;
}
/** {@collect.stats}
* Generates the exemption mechanism key blob, and stores the result in
* the <code>output</code> buffer.
*
* <p>If the <code>output</code> buffer is too small to hold the result,
* a <code>ShortBufferException</code> is thrown. In this case, repeat this
* call with a larger output buffer. Use
* {@link #getOutputSize(int) getOutputSize} to determine how big
* the output buffer should be.
*
* @param output the buffer for the result
*
* @return the number of bytes stored in <code>output</code>
*
* @exception IllegalStateException if this exemption mechanism is in
* a wrong state (e.g., has not been initialized).
* @exception ShortBufferException if the given output buffer is too small
* to hold the result.
* @exception ExemptionMechanismException if problem(s) encountered in the
* process of generating.
*/
public final int genExemptionBlob(byte[] output)
throws IllegalStateException, ShortBufferException,
ExemptionMechanismException {
if (!initialized) {
throw new IllegalStateException
("ExemptionMechanism not initialized");
}
int n = exmechSpi.engineGenExemptionBlob(output, 0);
done = true;
return n;
}
/** {@collect.stats}
* Generates the exemption mechanism key blob, and stores the result in
* the <code>output</code> buffer, starting at <code>outputOffset</code>
* inclusive.
*
* <p>If the <code>output</code> buffer is too small to hold the result,
* a <code>ShortBufferException</code> is thrown. In this case, repeat this
* call with a larger output buffer. Use
* {@link #getOutputSize(int) getOutputSize} to determine how big
* the output buffer should be.
*
* @param output the buffer for the result
* @param outputOffset the offset in <code>output</code> where the result
* is stored
*
* @return the number of bytes stored in <code>output</code>
*
* @exception IllegalStateException if this exemption mechanism is in
* a wrong state (e.g., has not been initialized).
* @exception ShortBufferException if the given output buffer is too small
* to hold the result.
* @exception ExemptionMechanismException if problem(s) encountered in the
* process of generating.
*/
public final int genExemptionBlob(byte[] output, int outputOffset)
throws IllegalStateException, ShortBufferException,
ExemptionMechanismException {
if (!initialized) {
throw new IllegalStateException
("ExemptionMechanism not initialized");
}
int n = exmechSpi.engineGenExemptionBlob(output, outputOffset);
done = true;
return n;
}
/** {@collect.stats}
* Ensures that the key stored away by this ExemptionMechanism
* object will be wiped out when there are no more references to it.
*/
protected void finalize() {
keyStored = null;
// Are there anything else we could do?
}
}
| Java |
/*
* Copyright (c) 1999, 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 javax.crypto;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import java.util.StringTokenizer;
import static java.util.Locale.ENGLISH;
import java.security.GeneralSecurityException;
import java.security.spec.AlgorithmParameterSpec;
import java.lang.reflect.*;
/** {@collect.stats}
* JCE has two pairs of jurisdiction policy files: one represents U.S. export
* laws, and the other represents the local laws of the country where the
* JCE will be used.
*
* The jurisdiction policy file has the same syntax as JDK policy files except
* that JCE has new permission classes called javax.crypto.CryptoPermission
* and javax.crypto.CryptoAllPermission.
*
* The format of a permission entry in the jurisdiction policy file is:
*
* permission <crypto permission class name>[, <algorithm name>
* [[, <exemption mechanism name>][, <maxKeySize>
* [, <AlgrithomParameterSpec class name>, <parameters
* for constructing an AlgrithomParameterSpec object>]]]];
*
* @author Sharon Liu
*
* @see java.security.Permissions
* @see java.security.spec.AlgrithomParameterSpec
* @see javax.crypto.CryptoPermission
* @see javax.crypto.CryptoAllPermission
* @see javax.crypto.CryptoPermissions
* @since 1.4
*/
final class CryptoPolicyParser {
private Vector grantEntries;
// Convenience variables for parsing
private StreamTokenizer st;
private int lookahead;
/** {@collect.stats}
* Creates a CryptoPolicyParser object.
*/
CryptoPolicyParser() {
grantEntries = new Vector();
}
/** {@collect.stats}
* Reads a policy configuration using a Reader object. <p>
*
* @param policy the policy Reader object.
*
* @exception ParsingException if the policy configuration
* contains a syntax error.
*
* @exception IOException if an error occurs while reading
* the policy configuration.
*/
void read(Reader policy)
throws ParsingException, IOException
{
if (!(policy instanceof BufferedReader)) {
policy = new BufferedReader(policy);
}
/*
* Configure the stream tokenizer:
* Recognize strings between "..."
* Don't convert words to lowercase
* Recognize both C-style and C++-style comments
* Treat end-of-line as white space, not as a token
*/
st = new StreamTokenizer(policy);
st.resetSyntax();
st.wordChars('a', 'z');
st.wordChars('A', 'Z');
st.wordChars('.', '.');
st.wordChars('0', '9');
st.wordChars('_', '_');
st.wordChars('$', '$');
st.wordChars(128 + 32, 255);
st.whitespaceChars(0, ' ');
st.commentChar('/');
st.quoteChar('\'');
st.quoteChar('"');
st.lowerCaseMode(false);
st.ordinaryChar('/');
st.slashSlashComments(true);
st.slashStarComments(true);
st.parseNumbers();
/*
* The crypto jurisdiction policy must be consistent. The
* following hashtable is used for checking consistency.
*/
Hashtable processedPermissions = null;
/*
* The main parsing loop. The loop is executed once for each entry
* in the policy file. The entries are delimited by semicolons. Once
* we've read in the information for an entry, go ahead and try to
* add it to the grantEntries.
*/
lookahead = st.nextToken();
while (lookahead != StreamTokenizer.TT_EOF) {
if (peek("grant")) {
GrantEntry ge = parseGrantEntry(processedPermissions);
if (ge != null)
grantEntries.addElement(ge);
} else {
throw new ParsingException(st.lineno(), "expected grant " +
"statement");
}
match(";");
}
}
/** {@collect.stats}
* parse a Grant entry
*/
private GrantEntry parseGrantEntry(Hashtable processedPermissions)
throws ParsingException, IOException
{
GrantEntry e = new GrantEntry();
match("grant");
match("{");
while(!peek("}")) {
if (peek("Permission")) {
CryptoPermissionEntry pe =
parsePermissionEntry(processedPermissions);
e.add(pe);
match(";");
} else {
throw new
ParsingException(st.lineno(), "expected permission entry");
}
}
match("}");
return e;
}
/** {@collect.stats}
* parse a CryptoPermission entry
*/
private CryptoPermissionEntry parsePermissionEntry(
Hashtable processedPermissions)
throws ParsingException, IOException
{
CryptoPermissionEntry e = new CryptoPermissionEntry();
match("Permission");
e.cryptoPermission = match("permission type");
if (e.cryptoPermission.equals("javax.crypto.CryptoAllPermission")) {
// Done with the CryptoAllPermission entry.
e.alg = CryptoAllPermission.ALG_NAME;
e.maxKeySize = Integer.MAX_VALUE;
return e;
}
// Should see the algorithm name.
if (peek("\"")) {
// Algorithm name - always convert to upper case after parsing.
e.alg = match("quoted string").toUpperCase(ENGLISH);
} else {
// The algorithm name can be a wildcard.
if (peek("*")) {
match("*");
e.alg = CryptoPermission.ALG_NAME_WILDCARD;
} else {
throw new ParsingException(st.lineno(),
"Missing the algorithm name");
}
}
peekAndMatch(",");
// May see the exemption mechanism name.
if (peek("\"")) {
// Exemption mechanism name - convert to upper case too.
e.exemptionMechanism = match("quoted string").toUpperCase(ENGLISH);
}
peekAndMatch(",");
// Check whether this entry is consistent with other permission entries
// that have been read.
if (!isConsistent(e.alg, e.exemptionMechanism, processedPermissions)) {
throw new ParsingException(st.lineno(), "Inconsistent policy");
}
// Should see the maxKeySize if not at the end of this entry yet.
if (peek("number")) {
e.maxKeySize = match();
} else {
if (peek("*")) {
match("*");
e.maxKeySize = Integer.MAX_VALUE;
} else {
if (!peek(";")) {
throw new ParsingException(st.lineno(),
"Missing the maximum " +
"allowable key size");
} else {
// At the end of this permission entry
e.maxKeySize = Integer.MAX_VALUE;
}
}
}
peekAndMatch(",");
// May see an AlgorithmParameterSpec class name.
if (peek("\"")) {
// AlgorithmParameterSpec class name.
String algParamSpecClassName = match("quoted string");
Vector paramsV = new Vector(1);
while (peek(",")) {
match(",");
if (peek("number")) {
paramsV.addElement(new Integer(match()));
} else {
if (peek("*")) {
match("*");
paramsV.addElement(new Integer(Integer.MAX_VALUE));
} else {
throw new ParsingException(st.lineno(),
"Expecting an integer");
}
}
}
Integer[] params = new Integer[paramsV.size()];
paramsV.copyInto(params);
e.checkParam = true;
e.algParamSpec = getInstance(algParamSpecClassName, params);
}
return e;
}
private static final AlgorithmParameterSpec getInstance(String type,
Integer[] params)
throws ParsingException
{
AlgorithmParameterSpec ret = null;
try {
Class apsClass = Class.forName(type);
Class[] paramClasses = new Class[params.length];
for (int i = 0; i < params.length; i++) {
paramClasses[i] = int.class;
}
Constructor c = apsClass.getConstructor(paramClasses);
ret = (AlgorithmParameterSpec) c.newInstance((Object[]) params);
} catch (Exception e) {
throw new ParsingException("Cannot call the constructor of " +
type + e);
}
return ret;
}
private boolean peekAndMatch(String expect)
throws ParsingException, IOException
{
if (peek(expect)) {
match(expect);
return true;
}
return false;
}
private boolean peek(String expect) {
boolean found = false;
switch (lookahead) {
case StreamTokenizer.TT_WORD:
if (expect.equalsIgnoreCase(st.sval))
found = true;
break;
case StreamTokenizer.TT_NUMBER:
if (expect.equalsIgnoreCase("number")) {
found = true;
}
break;
case ',':
if (expect.equals(","))
found = true;
break;
case '{':
if (expect.equals("{"))
found = true;
break;
case '}':
if (expect.equals("}"))
found = true;
break;
case '"':
if (expect.equals("\""))
found = true;
break;
case '*':
if (expect.equals("*"))
found = true;
break;
case ';':
if (expect.equals(";"))
found = true;
break;
default:
break;
}
return found;
}
/** {@collect.stats}
* Excepts to match a non-negative number.
*/
private int match()
throws ParsingException, IOException
{
int value = -1;
int lineno = st.lineno();
String sValue = null;
switch (lookahead) {
case StreamTokenizer.TT_NUMBER:
value = (int)st.nval;
if (value < 0) {
sValue = String.valueOf(st.nval);
}
lookahead = st.nextToken();
break;
default:
sValue = st.sval;
break;
}
if (value <= 0) {
throw new ParsingException(lineno, "a non-negative number",
sValue);
}
return value;
}
private String match(String expect)
throws ParsingException, IOException
{
String value = null;
switch (lookahead) {
case StreamTokenizer.TT_NUMBER:
throw new ParsingException(st.lineno(), expect,
"number "+String.valueOf(st.nval));
case StreamTokenizer.TT_EOF:
throw new ParsingException("expected "+expect+", read end of file");
case StreamTokenizer.TT_WORD:
if (expect.equalsIgnoreCase(st.sval)) {
lookahead = st.nextToken();
}
else if (expect.equalsIgnoreCase("permission type")) {
value = st.sval;
lookahead = st.nextToken();
}
else
throw new ParsingException(st.lineno(), expect, st.sval);
break;
case '"':
if (expect.equalsIgnoreCase("quoted string")) {
value = st.sval;
lookahead = st.nextToken();
} else if (expect.equalsIgnoreCase("permission type")) {
value = st.sval;
lookahead = st.nextToken();
}
else
throw new ParsingException(st.lineno(), expect, st.sval);
break;
case ',':
if (expect.equals(","))
lookahead = st.nextToken();
else
throw new ParsingException(st.lineno(), expect, ",");
break;
case '{':
if (expect.equals("{"))
lookahead = st.nextToken();
else
throw new ParsingException(st.lineno(), expect, "{");
break;
case '}':
if (expect.equals("}"))
lookahead = st.nextToken();
else
throw new ParsingException(st.lineno(), expect, "}");
break;
case ';':
if (expect.equals(";"))
lookahead = st.nextToken();
else
throw new ParsingException(st.lineno(), expect, ";");
break;
case '*':
if (expect.equals("*"))
lookahead = st.nextToken();
else
throw new ParsingException(st.lineno(), expect, "*");
break;
default:
throw new ParsingException(st.lineno(), expect,
new String(new char[] {(char)lookahead}));
}
return value;
}
CryptoPermission[] getPermissions() {
Vector result = new Vector();
Enumeration grantEnum = grantEntries.elements();
while (grantEnum.hasMoreElements()) {
GrantEntry ge = (GrantEntry)grantEnum.nextElement();
Enumeration permEnum = ge.permissionElements();
while (permEnum.hasMoreElements()) {
CryptoPermissionEntry pe =
(CryptoPermissionEntry)permEnum.nextElement();
if (pe.cryptoPermission.equals(
"javax.crypto.CryptoAllPermission")) {
result.addElement(CryptoAllPermission.INSTANCE);
} else {
if (pe.checkParam) {
result.addElement(new CryptoPermission(
pe.alg,
pe.maxKeySize,
pe.algParamSpec,
pe.exemptionMechanism));
} else {
result.addElement(new CryptoPermission(
pe.alg,
pe.maxKeySize,
pe.exemptionMechanism));
}
}
}
}
CryptoPermission[] ret = new CryptoPermission[result.size()];
result.copyInto(ret);
return ret;
}
private boolean isConsistent(String alg,
String exemptionMechanism,
Hashtable processedPermissions) {
String thisExemptionMechanism =
exemptionMechanism == null ? "none" : exemptionMechanism;
if (processedPermissions == null) {
processedPermissions = new Hashtable();
Vector exemptionMechanisms = new Vector(1);
exemptionMechanisms.addElement(thisExemptionMechanism);
processedPermissions.put(alg, exemptionMechanisms);
return true;
}
if (processedPermissions.containsKey(CryptoAllPermission.ALG_NAME)) {
return false;
}
Vector exemptionMechanisms;
if (processedPermissions.containsKey(alg)) {
exemptionMechanisms = (Vector)processedPermissions.get(alg);
if (exemptionMechanisms.contains(thisExemptionMechanism)) {
return false;
}
} else {
exemptionMechanisms = new Vector(1);
}
exemptionMechanisms.addElement(thisExemptionMechanism);
processedPermissions.put(alg, exemptionMechanisms);
return true;
}
/** {@collect.stats}
* Each grant entry in the policy configuration file is represented by a
* GrantEntry object. <p>
*
* <p>
* For example, the entry
* <pre>
* grant {
* permission javax.crypto.CryptoPermission "DES", 56;
* };
*
* </pre>
* is represented internally
* <pre>
*
* pe = new CryptoPermissionEntry("javax.crypto.CryptoPermission",
* "DES", 56);
*
* ge = new GrantEntry();
*
* ge.add(pe);
*
* </pre>
*
* @see java.security.Permission
* @see javax.crypto.CryptoPermission
* @see javax.crypto.CryptoPermissions
*/
private static class GrantEntry {
private Vector permissionEntries;
GrantEntry() {
permissionEntries = new Vector();
}
void add(CryptoPermissionEntry pe)
{
permissionEntries.addElement(pe);
}
boolean remove(CryptoPermissionEntry pe)
{
return permissionEntries.removeElement(pe);
}
boolean contains(CryptoPermissionEntry pe)
{
return permissionEntries.contains(pe);
}
/** {@collect.stats}
* Enumerate all the permission entries in this GrantEntry.
*/
Enumeration permissionElements(){
return permissionEntries.elements();
}
}
/** {@collect.stats}
* Each crypto permission entry in the policy configuration file is
* represented by a CryptoPermissionEntry object. <p>
*
* <p>
* For example, the entry
* <pre>
* permission javax.crypto.CryptoPermission "DES", 56;
* </pre>
* is represented internally
* <pre>
*
* pe = new CryptoPermissionEntry("javax.crypto.cryptoPermission",
* "DES", 56);
* </pre>
*
* @see java.security.Permissions
* @see javax.crypto.CryptoPermission
* @see javax.crypto.CryptoAllPermission
*/
private static class CryptoPermissionEntry {
String cryptoPermission;
String alg;
String exemptionMechanism;
int maxKeySize;
boolean checkParam;
AlgorithmParameterSpec algParamSpec;
CryptoPermissionEntry() {
// Set default values.
maxKeySize = 0;
alg = null;
exemptionMechanism = null;
checkParam = false;
algParamSpec = null;
}
/** {@collect.stats}
* Calculates a hash code value for the object. Objects
* which are equal will also have the same hashcode.
*/
public int hashCode() {
int retval = cryptoPermission.hashCode();
if (alg != null) retval ^= alg.hashCode();
if (exemptionMechanism != null) {
retval ^= exemptionMechanism.hashCode();
}
retval ^= maxKeySize;
if (checkParam) retval ^= 100;
if (algParamSpec != null) {
retval ^= algParamSpec.hashCode();
}
return retval;
}
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof CryptoPermissionEntry))
return false;
CryptoPermissionEntry that = (CryptoPermissionEntry) obj;
if (this.cryptoPermission == null) {
if (that.cryptoPermission != null) return false;
} else {
if (!this.cryptoPermission.equals(
that.cryptoPermission))
return false;
}
if (this.alg == null) {
if (that.alg != null) return false;
} else {
if (!this.alg.equalsIgnoreCase(that.alg))
return false;
}
if (!(this.maxKeySize == that.maxKeySize)) return false;
if (this.checkParam != that.checkParam) return false;
if (this.algParamSpec == null) {
if (that.algParamSpec != null) return false;
} else {
if (!this.algParamSpec.equals(that.algParamSpec))
return false;
}
// everything matched -- the 2 objects are equal
return true;
}
}
static final class ParsingException extends GeneralSecurityException {
private static final long serialVersionUID = 7147241245566588374L;
/** {@collect.stats}
* Constructs a ParsingException with the specified
* detail message.
* @param msg the detail message.
*/
ParsingException(String msg) {
super(msg);
}
ParsingException(int line, String msg) {
super("line " + line + ": " + msg);
}
ParsingException(int line, String expect, String actual) {
super("line "+line+": expected '"+expect+"', found '"+actual+"'");
}
}
}
| Java |
/*
* Copyright (c) 1998, 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 javax.crypto;
import java.util.*;
import java.security.*;
import java.security.Provider.Service;
import java.security.spec.AlgorithmParameterSpec;
import java.nio.ByteBuffer;
import sun.security.util.Debug;
import sun.security.jca.*;
import sun.security.jca.GetInstance.Instance;
/** {@collect.stats}
* This class provides the functionality of a "Message Authentication Code"
* (MAC) algorithm.
*
* <p> A MAC provides a way to check
* the integrity of information transmitted over or stored in an unreliable
* medium, based on a secret key. Typically, message
* authentication codes are used between two parties that share a secret
* key in order to validate information transmitted between these
* parties.
*
* <p> A MAC mechanism that is based on cryptographic hash functions is
* referred to as HMAC. HMAC can be used with any cryptographic hash function,
* e.g., MD5 or SHA-1, in combination with a secret shared key. HMAC is
* specified in RFC 2104.
*
* @author Jan Luehe
*
* @since 1.4
*/
public class Mac implements Cloneable {
private static final Debug debug =
Debug.getInstance("jca", "Mac");
// The provider
private Provider provider;
// The provider implementation (delegate)
private MacSpi spi;
// The name of the MAC algorithm.
private final String algorithm;
// Has this object been initialized?
private boolean initialized = false;
// next service to try in provider selection
// null once provider is selected
private Service firstService;
// remaining services to try in provider selection
// null once provider is selected
private Iterator serviceIterator;
private final Object lock;
/** {@collect.stats}
* Creates a MAC object.
*
* @param macSpi the delegate
* @param provider the provider
* @param algorithm the algorithm
*/
protected Mac(MacSpi macSpi, Provider provider, String algorithm) {
this.spi = macSpi;
this.provider = provider;
this.algorithm = algorithm;
serviceIterator = null;
lock = null;
}
private Mac(Service s, Iterator t, String algorithm) {
firstService = s;
serviceIterator = t;
this.algorithm = algorithm;
lock = new Object();
}
/** {@collect.stats}
* Returns the algorithm name of this <code>Mac</code> object.
*
* <p>This is the same name that was specified in one of the
* <code>getInstance</code> calls that created this
* <code>Mac</code> object.
*
* @return the algorithm name of this <code>Mac</code> object.
*/
public final String getAlgorithm() {
return this.algorithm;
}
/** {@collect.stats}
* Returns a <code>Mac</code> object that implements the
* specified MAC algorithm.
*
* <p> This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new Mac object encapsulating the
* MacSpi implementation from the first
* Provider that supports the specified algorithm is returned.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the standard name of the requested MAC algorithm.
* See Appendix A in the <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard algorithm names.
*
* @return the new <code>Mac</code> object.
*
* @exception NoSuchAlgorithmException if no Provider supports a
* MacSpi implementation for the
* specified algorithm.
*
* @see java.security.Provider
*/
public static final Mac getInstance(String algorithm)
throws NoSuchAlgorithmException {
List services = GetInstance.getServices("Mac", algorithm);
// make sure there is at least one service from a signed provider
Iterator t = services.iterator();
while (t.hasNext()) {
Service s = (Service)t.next();
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
return new Mac(s, t, algorithm);
}
throw new NoSuchAlgorithmException
("Algorithm " + algorithm + " not available");
}
/** {@collect.stats}
* Returns a <code>Mac</code> object that implements the
* specified MAC algorithm.
*
* <p> A new Mac object encapsulating the
* MacSpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the standard name of the requested MAC algorithm.
* See Appendix A in the <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard algorithm names.
*
* @param provider the name of the provider.
*
* @return the new <code>Mac</code> object.
*
* @exception NoSuchAlgorithmException if a MacSpi
* implementation for the specified algorithm is not
* available from the specified provider.
*
* @exception NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception IllegalArgumentException if the <code>provider</code>
* is null or empty.
*
* @see java.security.Provider
*/
public static final Mac getInstance(String algorithm, String provider)
throws NoSuchAlgorithmException, NoSuchProviderException {
Instance instance = JceSecurity.getInstance
("Mac", MacSpi.class, algorithm, provider);
return new Mac((MacSpi)instance.impl, instance.provider, algorithm);
}
/** {@collect.stats}
* Returns a <code>Mac</code> object that implements the
* specified MAC algorithm.
*
* <p> A new Mac object encapsulating the
* MacSpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param algorithm the standard name of the requested MAC algorithm.
* See Appendix A in the <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard algorithm names.
*
* @param provider the provider.
*
* @return the new <code>Mac</code> object.
*
* @exception NoSuchAlgorithmException if a MacSpi
* implementation for the specified algorithm is not available
* from the specified Provider object.
*
* @exception IllegalArgumentException if the <code>provider</code>
* is null.
*
* @see java.security.Provider
*/
public static final Mac getInstance(String algorithm, Provider provider)
throws NoSuchAlgorithmException {
Instance instance = JceSecurity.getInstance
("Mac", MacSpi.class, algorithm, provider);
return new Mac((MacSpi)instance.impl, instance.provider, algorithm);
}
// max number of debug warnings to print from chooseFirstProvider()
private static int warnCount = 10;
/** {@collect.stats}
* Choose the Spi from the first provider available. Used if
* delayed provider selection is not possible because init()
* is not the first method called.
*/
void chooseFirstProvider() {
if ((spi != null) || (serviceIterator == null)) {
return;
}
synchronized (lock) {
if (spi != null) {
return;
}
if (debug != null) {
int w = --warnCount;
if (w >= 0) {
debug.println("Mac.init() not first method "
+ "called, disabling delayed provider selection");
if (w == 0) {
debug.println("Further warnings of this type will "
+ "be suppressed");
}
new Exception("Call trace").printStackTrace();
}
}
Exception lastException = null;
while ((firstService != null) || serviceIterator.hasNext()) {
Service s;
if (firstService != null) {
s = firstService;
firstService = null;
} else {
s = (Service)serviceIterator.next();
}
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
try {
Object obj = s.newInstance(null);
if (obj instanceof MacSpi == false) {
continue;
}
spi = (MacSpi)obj;
provider = s.getProvider();
// not needed any more
firstService = null;
serviceIterator = null;
return;
} catch (NoSuchAlgorithmException e) {
lastException = e;
}
}
ProviderException e = new ProviderException
("Could not construct MacSpi instance");
if (lastException != null) {
e.initCause(lastException);
}
throw e;
}
}
private void chooseProvider(Key key, AlgorithmParameterSpec params)
throws InvalidKeyException, InvalidAlgorithmParameterException {
synchronized (lock) {
if (spi != null) {
spi.engineInit(key, params);
return;
}
Exception lastException = null;
while ((firstService != null) || serviceIterator.hasNext()) {
Service s;
if (firstService != null) {
s = firstService;
firstService = null;
} else {
s = (Service)serviceIterator.next();
}
// if provider says it does not support this key, ignore it
if (s.supportsParameter(key) == false) {
continue;
}
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
try {
MacSpi spi = (MacSpi)s.newInstance(null);
spi.engineInit(key, params);
provider = s.getProvider();
this.spi = spi;
firstService = null;
serviceIterator = null;
return;
} catch (Exception e) {
// NoSuchAlgorithmException from newInstance()
// InvalidKeyException from init()
// RuntimeException (ProviderException) from init()
if (lastException == null) {
lastException = e;
}
}
}
// no working provider found, fail
if (lastException instanceof InvalidKeyException) {
throw (InvalidKeyException)lastException;
}
if (lastException instanceof InvalidAlgorithmParameterException) {
throw (InvalidAlgorithmParameterException)lastException;
}
if (lastException instanceof RuntimeException) {
throw (RuntimeException)lastException;
}
String kName = (key != null) ? key.getClass().getName() : "(null)";
throw new InvalidKeyException
("No installed provider supports this key: "
+ kName, lastException);
}
}
/** {@collect.stats}
* Returns the provider of this <code>Mac</code> object.
*
* @return the provider of this <code>Mac</code> object.
*/
public final Provider getProvider() {
chooseFirstProvider();
return this.provider;
}
/** {@collect.stats}
* Returns the length of the MAC in bytes.
*
* @return the MAC length in bytes.
*/
public final int getMacLength() {
chooseFirstProvider();
return spi.engineGetMacLength();
}
/** {@collect.stats}
* Initializes this <code>Mac</code> object with the given key.
*
* @param key the key.
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this MAC.
*/
public final void init(Key key) throws InvalidKeyException {
try {
if (spi != null) {
spi.engineInit(key, null);
} else {
chooseProvider(key, null);
}
} catch (InvalidAlgorithmParameterException e) {
throw new InvalidKeyException("init() failed", e);
}
initialized = true;
}
/** {@collect.stats}
* Initializes this <code>Mac</code> object with the given key and
* algorithm parameters.
*
* @param key the key.
* @param params the algorithm parameters.
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this MAC.
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this MAC.
*/
public final void init(Key key, AlgorithmParameterSpec params)
throws InvalidKeyException, InvalidAlgorithmParameterException {
if (spi != null) {
spi.engineInit(key, params);
} else {
chooseProvider(key, params);
}
initialized = true;
}
/** {@collect.stats}
* Processes the given byte.
*
* @param input the input byte to be processed.
*
* @exception IllegalStateException if this <code>Mac</code> has not been
* initialized.
*/
public final void update(byte input) throws IllegalStateException {
chooseFirstProvider();
if (initialized == false) {
throw new IllegalStateException("MAC not initialized");
}
spi.engineUpdate(input);
}
/** {@collect.stats}
* Processes the given array of bytes.
*
* @param input the array of bytes to be processed.
*
* @exception IllegalStateException if this <code>Mac</code> has not been
* initialized.
*/
public final void update(byte[] input) throws IllegalStateException {
chooseFirstProvider();
if (initialized == false) {
throw new IllegalStateException("MAC not initialized");
}
if (input != null) {
spi.engineUpdate(input, 0, input.length);
}
}
/** {@collect.stats}
* Processes the first <code>len</code> bytes in <code>input</code>,
* starting at <code>offset</code> inclusive.
*
* @param input the input buffer.
* @param offset the offset in <code>input</code> where the input starts.
* @param len the number of bytes to process.
*
* @exception IllegalStateException if this <code>Mac</code> has not been
* initialized.
*/
public final void update(byte[] input, int offset, int len)
throws IllegalStateException {
chooseFirstProvider();
if (initialized == false) {
throw new IllegalStateException("MAC not initialized");
}
if (input != null) {
if ((offset < 0) || (len > (input.length - offset)) || (len < 0))
throw new IllegalArgumentException("Bad arguments");
spi.engineUpdate(input, offset, len);
}
}
/** {@collect.stats}
* Processes <code>input.remaining()</code> bytes in the ByteBuffer
* <code>input</code>, starting at <code>input.position()</code>.
* Upon return, the buffer's position will be equal to its limit;
* its limit will not have changed.
*
* @param input the ByteBuffer
*
* @exception IllegalStateException if this <code>Mac</code> has not been
* initialized.
* @since 1.5
*/
public final void update(ByteBuffer input) {
chooseFirstProvider();
if (initialized == false) {
throw new IllegalStateException("MAC not initialized");
}
if (input == null) {
throw new IllegalArgumentException("Buffer must not be null");
}
spi.engineUpdate(input);
}
/** {@collect.stats}
* Finishes the MAC operation.
*
* <p>A call to this method resets this <code>Mac</code> object to the
* state it was in when previously initialized via a call to
* <code>init(Key)</code> or
* <code>init(Key, AlgorithmParameterSpec)</code>.
* That is, the object is reset and available to generate another MAC from
* the same key, if desired, via new calls to <code>update</code> and
* <code>doFinal</code>.
* (In order to reuse this <code>Mac</code> object with a different key,
* it must be reinitialized via a call to <code>init(Key)</code> or
* <code>init(Key, AlgorithmParameterSpec)</code>.
*
* @return the MAC result.
*
* @exception IllegalStateException if this <code>Mac</code> has not been
* initialized.
*/
public final byte[] doFinal() throws IllegalStateException {
chooseFirstProvider();
if (initialized == false) {
throw new IllegalStateException("MAC not initialized");
}
byte[] mac = spi.engineDoFinal();
spi.engineReset();
return mac;
}
/** {@collect.stats}
* Finishes the MAC operation.
*
* <p>A call to this method resets this <code>Mac</code> object to the
* state it was in when previously initialized via a call to
* <code>init(Key)</code> or
* <code>init(Key, AlgorithmParameterSpec)</code>.
* That is, the object is reset and available to generate another MAC from
* the same key, if desired, via new calls to <code>update</code> and
* <code>doFinal</code>.
* (In order to reuse this <code>Mac</code> object with a different key,
* it must be reinitialized via a call to <code>init(Key)</code> or
* <code>init(Key, AlgorithmParameterSpec)</code>.
*
* <p>The MAC result is stored in <code>output</code>, starting at
* <code>outOffset</code> inclusive.
*
* @param output the buffer where the MAC result is stored
* @param outOffset the offset in <code>output</code> where the MAC is
* stored
*
* @exception ShortBufferException if the given output buffer is too small
* to hold the result
* @exception IllegalStateException if this <code>Mac</code> has not been
* initialized.
*/
public final void doFinal(byte[] output, int outOffset)
throws ShortBufferException, IllegalStateException
{
chooseFirstProvider();
if (initialized == false) {
throw new IllegalStateException("MAC not initialized");
}
int macLen = getMacLength();
if (output == null || output.length-outOffset < macLen) {
throw new ShortBufferException
("Cannot store MAC in output buffer");
}
byte[] mac = doFinal();
System.arraycopy(mac, 0, output, outOffset, macLen);
return;
}
/** {@collect.stats}
* Processes the given array of bytes and finishes the MAC operation.
*
* <p>A call to this method resets this <code>Mac</code> object to the
* state it was in when previously initialized via a call to
* <code>init(Key)</code> or
* <code>init(Key, AlgorithmParameterSpec)</code>.
* That is, the object is reset and available to generate another MAC from
* the same key, if desired, via new calls to <code>update</code> and
* <code>doFinal</code>.
* (In order to reuse this <code>Mac</code> object with a different key,
* it must be reinitialized via a call to <code>init(Key)</code> or
* <code>init(Key, AlgorithmParameterSpec)</code>.
*
* @param input data in bytes
* @return the MAC result.
*
* @exception IllegalStateException if this <code>Mac</code> has not been
* initialized.
*/
public final byte[] doFinal(byte[] input) throws IllegalStateException
{
chooseFirstProvider();
if (initialized == false) {
throw new IllegalStateException("MAC not initialized");
}
update(input);
return doFinal();
}
/** {@collect.stats}
* Resets this <code>Mac</code> object.
*
* <p>A call to this method resets this <code>Mac</code> object to the
* state it was in when previously initialized via a call to
* <code>init(Key)</code> or
* <code>init(Key, AlgorithmParameterSpec)</code>.
* That is, the object is reset and available to generate another MAC from
* the same key, if desired, via new calls to <code>update</code> and
* <code>doFinal</code>.
* (In order to reuse this <code>Mac</code> object with a different key,
* it must be reinitialized via a call to <code>init(Key)</code> or
* <code>init(Key, AlgorithmParameterSpec)</code>.
*/
public final void reset() {
chooseFirstProvider();
spi.engineReset();
}
/** {@collect.stats}
* Returns a clone if the provider implementation is cloneable.
*
* @return a clone if the provider implementation is cloneable.
*
* @exception CloneNotSupportedException if this is called on a
* delegate that does not support <code>Cloneable</code>.
*/
public final Object clone() throws CloneNotSupportedException {
chooseFirstProvider();
Mac that = (Mac)super.clone();
that.spi = (MacSpi)this.spi.clone();
return that;
}
}
| Java |
/*
* Copyright (c) 1999, 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 javax.crypto;
import java.security.*;
import java.util.Enumeration;
import java.util.Vector;
/** {@collect.stats}
* The CryptoAllPermission is a permission that implies
* any other crypto permissions.
* <p>
*
* @see java.security.Permission
* @see java.security.AllPermission
*
* @author Sharon Liu
* @since 1.4
*/
final class CryptoAllPermission extends CryptoPermission {
private static final long serialVersionUID = -5066513634293192112L;
// This class is similar to java.security.AllPermission.
static final String ALG_NAME = "CryptoAllPermission";
static final CryptoAllPermission INSTANCE =
new CryptoAllPermission();
private CryptoAllPermission() {
super(ALG_NAME);
}
/** {@collect.stats}
* Checks if the specified permission is implied by
* this object.
*
* @param p the permission to check against.
*
* @return true if the specified permission is an
* instance of CryptoPermission.
*/
public boolean implies(Permission p) {
return (p instanceof CryptoPermission);
}
/** {@collect.stats}
* Checks two CryptoAllPermission objects for equality.
* Two CryptoAllPermission objects are always equal.
*
* @param obj the object to test for equality with this object.
*
* @return true if <i>obj</i> is a CryptoAllPermission object.
*/
public boolean equals(Object obj) {
return (obj == INSTANCE);
}
/** {@collect.stats}
*
* Returns the hash code value for this object.
*
* @return a hash code value for this object.
*/
public int hashCode() {
return 1;
}
/** {@collect.stats}
* Returns a new PermissionCollection object for storing
* CryptoAllPermission objects.
* <p>
*
* @return a new PermissionCollection object suitable for
* storing CryptoAllPermissions.
*/
public PermissionCollection newPermissionCollection() {
return new CryptoAllPermissionCollection();
}
}
/** {@collect.stats}
* A CryptoAllPermissionCollection stores a collection
* of CryptoAllPermission permissions.
*
* @see java.security.Permission
* @see java.security.Permissions
* @see javax.crypto.CryptoPermission
*
* @author Sharon Liu
*/
final class CryptoAllPermissionCollection extends PermissionCollection
implements java.io.Serializable
{
private static final long serialVersionUID = 7450076868380144072L;
// true if a CryptoAllPermission has been added
private boolean all_allowed;
/** {@collect.stats}
* Create an empty CryptoAllPermissions object.
*/
CryptoAllPermissionCollection() {
all_allowed = false;
}
/** {@collect.stats}
* Adds a permission to the CryptoAllPermissions.
*
* @param permission the Permission object to add.
*
* @exception SecurityException - if this CryptoAllPermissionCollection
* object has been marked readonly
*/
public void add(Permission permission)
{
if (isReadOnly())
throw new SecurityException("attempt to add a Permission to " +
"a readonly PermissionCollection");
if (permission != CryptoAllPermission.INSTANCE)
return;
all_allowed = true;
}
/** {@collect.stats}
* Check and see if this set of permissions implies the permissions
* expressed in "permission".
*
* @param p the Permission object to compare
*
* @return true if the given permission is implied by this
* CryptoAllPermissionCollection.
*/
public boolean implies(Permission permission)
{
if (!(permission instanceof CryptoPermission)) {
return false;
}
return all_allowed;
}
/** {@collect.stats}
* Returns an enumeration of all the CryptoAllPermission
* objects in the container.
*
* @return an enumeration of all the CryptoAllPermission objects.
*/
public Enumeration elements() {
Vector v = new Vector(1);
if (all_allowed) v.add(CryptoAllPermission.INSTANCE);
return v.elements();
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
/** {@collect.stats}
* A secret (symmetric) key.
*
* <p>This interface contains no methods or constants.
* Its only purpose is to group (and provide type safety for) secret keys.
*
* <p>Provider implementations of this interface must overwrite the
* <code>equals</code> and <code>hashCode</code> methods inherited from
* <code>java.lang.Object</code>, so that secret keys are compared based on
* their underlying key material and not based on reference.
*
* <p>Keys that implement this interface return the string <code>RAW</code>
* as their encoding format (see <code>getFormat</code>), and return the
* raw key bytes as the result of a <code>getEncoded</code> method call. (The
* <code>getFormat</code> and <code>getEncoded</code> methods are inherited
* from the <code>java.security.Key</code> parent interface.)
*
* @author Jan Luehe
*
* @see SecretKeyFactory
* @see Cipher
* @since 1.4
*/
public interface SecretKey extends java.security.Key {
/** {@collect.stats}
* The class fingerprint that is set to indicate serialization
* compatibility since J2SE 1.4.
*/
static final long serialVersionUID = -4795878709595146952L;
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.security.*;
import java.security.spec.*;
/** {@collect.stats}
* This class defines the <i>Service Provider Interface</i> (<b>SPI</b>)
* for the <code>KeyGenerator</code> class.
* All the abstract methods in this class must be implemented by each
* cryptographic service provider who wishes to supply the implementation
* of a key generator for a particular algorithm.
*
* @author Jan Luehe
*
* @see SecretKey
* @since 1.4
*/
public abstract class KeyGeneratorSpi {
/** {@collect.stats}
* Initializes the key generator.
*
* @param random the source of randomness for this generator
*/
protected abstract void engineInit(SecureRandom random);
/** {@collect.stats}
* Initializes the key generator with the specified parameter
* set and a user-provided source of randomness.
*
* @param params the key generation parameters
* @param random the source of randomness for this key generator
*
* @exception InvalidAlgorithmParameterException if <code>params</code> is
* inappropriate for this key generator
*/
protected abstract void engineInit(AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidAlgorithmParameterException;
/** {@collect.stats}
* Initializes this key generator for a certain keysize, using the given
* source of randomness.
*
* @param keysize the keysize. This is an algorithm-specific metric,
* specified in number of bits.
* @param random the source of randomness for this key generator
*
* @exception InvalidParameterException if the keysize is wrong or not
* supported.
*/
protected abstract void engineInit(int keysize, SecureRandom random);
/** {@collect.stats}
* Generates a secret key.
*
* @return the new key
*/
protected abstract SecretKey engineGenerateKey();
}
| Java |
/*
* Copyright (c) 2001, 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 javax.crypto;
import java.io.*;
import java.security.*;
import java.security.spec.*;
import sun.security.x509.AlgorithmId;
import sun.security.util.DerValue;
import sun.security.util.DerInputStream;
import sun.security.util.DerOutputStream;
/** {@collect.stats}
* This class implements the <code>EncryptedPrivateKeyInfo</code> type
* as defined in PKCS #8.
* <p>Its ASN.1 definition is as follows:
*
* <pre>
* EncryptedPrivateKeyInfo ::= SEQUENCE {
* encryptionAlgorithm AlgorithmIdentifier,
* encryptedData OCTET STRING }
*
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL }
* </pre>
*
* @author Valerie Peng
*
* @see java.security.spec.PKCS8EncodedKeySpec
*
* @since 1.4
*/
public class EncryptedPrivateKeyInfo {
// the "encryptionAlgorithm" field
private AlgorithmId algid;
// the "encryptedData" field
private byte[] encryptedData;
// the ASN.1 encoded contents of this class
private byte[] encoded = null;
/** {@collect.stats}
* Constructs (i.e., parses) an <code>EncryptedPrivateKeyInfo</code> from
* its ASN.1 encoding.
* @param encoded the ASN.1 encoding of this object. The contents of
* the array are copied to protect against subsequent modification.
* @exception NullPointerException if the <code>encoded</code> is null.
* @exception IOException if error occurs when parsing the ASN.1 encoding.
*/
public EncryptedPrivateKeyInfo(byte[] encoded)
throws IOException {
if (encoded == null) {
throw new NullPointerException("the encoded parameter " +
"must be non-null");
}
this.encoded = (byte[])encoded.clone();
DerValue val = new DerValue(this.encoded);
DerValue[] seq = new DerValue[2];
seq[0] = val.data.getDerValue();
seq[1] = val.data.getDerValue();
if (val.data.available() != 0) {
throw new IOException("overrun, bytes = " + val.data.available());
}
this.algid = AlgorithmId.parse(seq[0]);
if (seq[0].data.available() != 0) {
throw new IOException("encryptionAlgorithm field overrun");
}
this.encryptedData = seq[1].getOctetString();
if (seq[1].data.available() != 0) {
throw new IOException("encryptedData field overrun");
}
}
/** {@collect.stats}
* Constructs an <code>EncryptedPrivateKeyInfo</code> from the
* encryption algorithm name and the encrypted data.
*
* <p>Note: This constructor will use null as the value of the
* algorithm parameters. If the encryption algorithm has
* parameters whose value is not null, a different constructor,
* e.g. EncryptedPrivateKeyInfo(AlgorithmParameters, byte[]),
* should be used.
*
* @param algName encryption algorithm name. See Appendix A in the
* <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard Cipher algorithm names.
* @param encryptedData encrypted data. The contents of
* <code>encrypedData</code> are copied to protect against subsequent
* modification when constructing this object.
* @exception NullPointerException if <code>algName</code> or
* <code>encryptedData</code> is null.
* @exception IllegalArgumentException if <code>encryptedData</code>
* is empty, i.e. 0-length.
* @exception NoSuchAlgorithmException if the specified algName is
* not supported.
*/
public EncryptedPrivateKeyInfo(String algName, byte[] encryptedData)
throws NoSuchAlgorithmException {
if (algName == null)
throw new NullPointerException("the algName parameter " +
"must be non-null");
this.algid = AlgorithmId.get(algName);
if (encryptedData == null) {
throw new NullPointerException("the encryptedData " +
"parameter must be non-null");
} else if (encryptedData.length == 0) {
throw new IllegalArgumentException("the encryptedData " +
"parameter must not be empty");
} else {
this.encryptedData = (byte[])encryptedData.clone();
}
// delay the generation of ASN.1 encoding until
// getEncoded() is called
this.encoded = null;
}
/** {@collect.stats}
* Constructs an <code>EncryptedPrivateKeyInfo</code> from the
* encryption algorithm parameters and the encrypted data.
*
* @param algParams the algorithm parameters for the encryption
* algorithm. <code>algParams.getEncoded()</code> should return
* the ASN.1 encoded bytes of the <code>parameters</code> field
* of the <code>AlgorithmIdentifer</code> component of the
* <code>EncryptedPrivateKeyInfo</code> type.
* @param encryptedData encrypted data. The contents of
* <code>encrypedData</code> are copied to protect against
* subsequent modification when constructing this object.
* @exception NullPointerException if <code>algParams</code> or
* <code>encryptedData</code> is null.
* @exception IllegalArgumentException if <code>encryptedData</code>
* is empty, i.e. 0-length.
* @exception NoSuchAlgorithmException if the specified algName of
* the specified <code>algParams</code> parameter is not supported.
*/
public EncryptedPrivateKeyInfo(AlgorithmParameters algParams,
byte[] encryptedData) throws NoSuchAlgorithmException {
if (algParams == null) {
throw new NullPointerException("algParams must be non-null");
}
this.algid = AlgorithmId.get(algParams);
if (encryptedData == null) {
throw new NullPointerException("encryptedData must be non-null");
} else if (encryptedData.length == 0) {
throw new IllegalArgumentException("the encryptedData " +
"parameter must not be empty");
} else {
this.encryptedData = (byte[])encryptedData.clone();
}
// delay the generation of ASN.1 encoding until
// getEncoded() is called
this.encoded = null;
}
/** {@collect.stats}
* Returns the encryption algorithm.
* <p>Note: Standard name is returned instead of the specified one
* in the constructor when such mapping is available.
* See Appendix A in the
* <a href=
* "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture Reference Guide</a>
* for information about standard Cipher algorithm names.
*
* @return the encryption algorithm name.
*/
public String getAlgName() {
return this.algid.getName();
}
/** {@collect.stats}
* Returns the algorithm parameters used by the encryption algorithm.
* @return the algorithm parameters.
*/
public AlgorithmParameters getAlgParameters() {
return this.algid.getParameters();
}
/** {@collect.stats}
* Returns the encrypted data.
* @return the encrypted data. Returns a new array
* each time this method is called.
*/
public byte[] getEncryptedData() {
return (byte[])this.encryptedData.clone();
}
/** {@collect.stats}
* Extract the enclosed PKCS8EncodedKeySpec object from the
* encrypted data and return it.
* <br>Note: In order to successfully retrieve the enclosed
* PKCS8EncodedKeySpec object, <code>cipher</code> needs
* to be initialized to either Cipher.DECRYPT_MODE or
* Cipher.UNWRAP_MODE, with the same key and parameters used
* for generating the encrypted data.
*
* @param cipher the initialized cipher object which will be
* used for decrypting the encrypted data.
* @return the PKCS8EncodedKeySpec object.
* @exception NullPointerException if <code>cipher</code>
* is null.
* @exception InvalidKeySpecException if the given cipher is
* inappropriate for the encrypted data or the encrypted
* data is corrupted and cannot be decrypted.
*/
public PKCS8EncodedKeySpec getKeySpec(Cipher cipher)
throws InvalidKeySpecException {
byte[] encoded = null;
try {
encoded = cipher.doFinal((byte[])encryptedData);
checkPKCS8Encoding(encoded);
} catch (GeneralSecurityException gse) {
InvalidKeySpecException ikse = new
InvalidKeySpecException(
"Cannot retrieve the PKCS8EncodedKeySpec");
ikse.initCause(gse);
throw ikse;
} catch (IOException ioe) {
InvalidKeySpecException ikse = new
InvalidKeySpecException(
"Cannot retrieve the PKCS8EncodedKeySpec");
ikse.initCause(ioe);
throw ikse;
} catch (IllegalStateException ise) {
InvalidKeySpecException ikse = new
InvalidKeySpecException(
"Cannot retrieve the PKCS8EncodedKeySpec");
ikse.initCause(ise);
throw ikse;
}
return new PKCS8EncodedKeySpec(encoded);
}
private PKCS8EncodedKeySpec getKeySpecImpl(Key decryptKey,
Provider provider) throws NoSuchAlgorithmException,
InvalidKeyException {
byte[] encoded = null;
Cipher c;
try {
if (provider == null) {
// use the most preferred one
c = Cipher.getInstance(algid.getName());
} else {
c = Cipher.getInstance(algid.getName(), provider);
}
c.init(Cipher.DECRYPT_MODE, decryptKey, algid.getParameters());
encoded = c.doFinal(encryptedData);
checkPKCS8Encoding(encoded);
} catch (NoSuchAlgorithmException nsae) {
// rethrow
throw nsae;
} catch (GeneralSecurityException gse) {
InvalidKeyException ike = new InvalidKeyException
("Cannot retrieve the PKCS8EncodedKeySpec");
ike.initCause(gse);
throw ike;
} catch (IOException ioe) {
InvalidKeyException ike = new InvalidKeyException
("Cannot retrieve the PKCS8EncodedKeySpec");
ike.initCause(ioe);
throw ike;
}
return new PKCS8EncodedKeySpec(encoded);
}
/** {@collect.stats}
* Extract the enclosed PKCS8EncodedKeySpec object from the
* encrypted data and return it.
* @param decryptKey key used for decrypting the encrypted data.
* @return the PKCS8EncodedKeySpec object.
* @exception NullPointerException if <code>decryptKey</code>
* is null.
* @exception NoSuchAlgorithmException if cannot find appropriate
* cipher to decrypt the encrypted data.
* @exception InvalidKeyException if <code>decryptKey</code>
* cannot be used to decrypt the encrypted data or the decryption
* result is not a valid PKCS8KeySpec.
*
* @since 1.5
*/
public PKCS8EncodedKeySpec getKeySpec(Key decryptKey)
throws NoSuchAlgorithmException, InvalidKeyException {
if (decryptKey == null) {
throw new NullPointerException("decryptKey is null");
}
return getKeySpecImpl(decryptKey, null);
}
/** {@collect.stats}
* Extract the enclosed PKCS8EncodedKeySpec object from the
* encrypted data and return it.
* @param decryptKey key used for decrypting the encrypted data.
* @param providerName the name of provider whose Cipher
* implementation will be used.
* @return the PKCS8EncodedKeySpec object.
* @exception NullPointerException if <code>decryptKey</code>
* or <code>providerName</code> is null.
* @exception NoSuchProviderException if no provider
* <code>providerName</code> is registered.
* @exception NoSuchAlgorithmException if cannot find appropriate
* cipher to decrypt the encrypted data.
* @exception InvalidKeyException if <code>decryptKey</code>
* cannot be used to decrypt the encrypted data or the decryption
* result is not a valid PKCS8KeySpec.
*
* @since 1.5
*/
public PKCS8EncodedKeySpec getKeySpec(Key decryptKey,
String providerName) throws NoSuchProviderException,
NoSuchAlgorithmException, InvalidKeyException {
if (decryptKey == null) {
throw new NullPointerException("decryptKey is null");
}
if (providerName == null) {
throw new NullPointerException("provider is null");
}
Provider provider = Security.getProvider(providerName);
if (provider == null) {
throw new NoSuchProviderException("provider " +
providerName + " not found");
}
return getKeySpecImpl(decryptKey, provider);
}
/** {@collect.stats}
* Extract the enclosed PKCS8EncodedKeySpec object from the
* encrypted data and return it.
* @param decryptKey key used for decrypting the encrypted data.
* @param provider the name of provider whose Cipher implementation
* will be used.
* @return the PKCS8EncodedKeySpec object.
* @exception NullPointerException if <code>decryptKey</code>
* or <code>provider</code> is null.
* @exception NoSuchAlgorithmException if cannot find appropriate
* cipher to decrypt the encrypted data in <code>provider</code>.
* @exception InvalidKeyException if <code>decryptKey</code>
* cannot be used to decrypt the encrypted data or the decryption
* result is not a valid PKCS8KeySpec.
*
* @since 1.5
*/
public PKCS8EncodedKeySpec getKeySpec(Key decryptKey,
Provider provider) throws NoSuchAlgorithmException,
InvalidKeyException {
if (decryptKey == null) {
throw new NullPointerException("decryptKey is null");
}
if (provider == null) {
throw new NullPointerException("provider is null");
}
return getKeySpecImpl(decryptKey, provider);
}
/** {@collect.stats}
* Returns the ASN.1 encoding of this object.
* @return the ASN.1 encoding. Returns a new array
* each time this method is called.
* @exception IOException if error occurs when constructing its
* ASN.1 encoding.
*/
public byte[] getEncoded() throws IOException {
if (this.encoded == null) {
DerOutputStream out = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
// encode encryption algorithm
algid.encode(tmp);
// encode encrypted data
tmp.putOctetString(encryptedData);
// wrap everything into a SEQUENCE
out.write(DerValue.tag_Sequence, tmp);
this.encoded = out.toByteArray();
}
return (byte[])this.encoded.clone();
}
private static void checkTag(DerValue val, byte tag, String valName)
throws IOException {
if (val.getTag() != tag) {
throw new IOException("invalid key encoding - wrong tag for " +
valName);
}
}
private static void checkPKCS8Encoding(byte[] encodedKey)
throws IOException {
DerInputStream in = new DerInputStream(encodedKey);
DerValue[] values = in.getSequence(3);
switch (values.length) {
case 4:
checkTag(values[3], DerValue.TAG_CONTEXT, "attributes");
case 3:
checkTag(values[0], DerValue.tag_Integer, "version");
DerInputStream algid = values[1].toDerInputStream();
algid.getOID();
if (algid.available() != 0) {
algid.getDerValue();
}
checkTag(values[2], DerValue.tag_OctetString, "privateKey");
break;
default:
throw new IOException("invalid key encoding");
}
}
}
| Java |
/*
* Copyright (c) 1998, 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 javax.crypto;
import java.security.*;
import java.security.spec.*;
import java.nio.ByteBuffer;
/** {@collect.stats}
* This class defines the <i>Service Provider Interface</i> (<b>SPI</b>)
* for the <code>Mac</code> class.
* All the abstract methods in this class must be implemented by each
* cryptographic service provider who wishes to supply the implementation
* of a particular MAC algorithm.
*
* <p> Implementations are free to implement the Cloneable interface.
*
* @author Jan Luehe
*
* @since 1.4
*/
public abstract class MacSpi {
/** {@collect.stats}
* Returns the length of the MAC in bytes.
*
* @return the MAC length in bytes.
*/
protected abstract int engineGetMacLength();
/** {@collect.stats}
* Initializes the MAC with the given (secret) key and algorithm
* parameters.
*
* @param key the (secret) key.
* @param params the algorithm parameters.
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this MAC.
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this MAC.
*/
protected abstract void engineInit(Key key,
AlgorithmParameterSpec params)
throws InvalidKeyException, InvalidAlgorithmParameterException ;
/** {@collect.stats}
* Processes the given byte.
*
* @param input the input byte to be processed.
*/
protected abstract void engineUpdate(byte input);
/** {@collect.stats}
* Processes the first <code>len</code> bytes in <code>input</code>,
* starting at <code>offset</code> inclusive.
*
* @param input the input buffer.
* @param offset the offset in <code>input</code> where the input starts.
* @param len the number of bytes to process.
*/
protected abstract void engineUpdate(byte[] input, int offset, int len);
/** {@collect.stats}
* Processes <code>input.remaining()</code> bytes in the ByteBuffer
* <code>input</code>, starting at <code>input.position()</code>.
* Upon return, the buffer's position will be equal to its limit;
* its limit will not have changed.
*
* <p>Subclasses should consider overriding this method if they can
* process ByteBuffers more efficiently than byte arrays.
*
* @param input the ByteBuffer
* @since 1.5
*/
protected void engineUpdate(ByteBuffer input) {
if (input.hasRemaining() == false) {
return;
}
if (input.hasArray()) {
byte[] b = input.array();
int ofs = input.arrayOffset();
int pos = input.position();
int lim = input.limit();
engineUpdate(b, ofs + pos, lim - pos);
input.position(lim);
} else {
int len = input.remaining();
byte[] b = new byte[CipherSpi.getTempArraySize(len)];
while (len > 0) {
int chunk = Math.min(len, b.length);
input.get(b, 0, chunk);
engineUpdate(b, 0, chunk);
len -= chunk;
}
}
}
/** {@collect.stats}
* Completes the MAC computation and resets the MAC for further use,
* maintaining the secret key that the MAC was initialized with.
*
* @return the MAC result.
*/
protected abstract byte[] engineDoFinal();
/** {@collect.stats}
* Resets the MAC for further use, maintaining the secret key that the
* MAC was initialized with.
*/
protected abstract void engineReset();
/** {@collect.stats}
* Returns a clone if the implementation is cloneable.
*
* @return a clone if the implementation is cloneable.
*
* @exception CloneNotSupportedException if this is called
* on an implementation that does not support <code>Cloneable</code>.
*/
public Object clone() throws CloneNotSupportedException {
if (this instanceof Cloneable) {
return super.clone();
} else {
throw new CloneNotSupportedException();
}
}
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.security.*;
import java.security.spec.*;
/** {@collect.stats}
* This class provides a delegate for the identity cipher - one that does not
* tranform the plaintext.
*
* @author Li Gong
* @see Nullcipher
*
* @since 1.4
*/
final class NullCipherSpi extends CipherSpi {
/*
* Do not let anybody instantiate this directly (protected).
*/
protected NullCipherSpi() {}
public void engineSetMode(String mode) {}
public void engineSetPadding(String padding) {}
protected int engineGetBlockSize() {
return 1;
}
protected int engineGetOutputSize(int inputLen) {
return inputLen;
}
protected byte[] engineGetIV() {
byte[] x = new byte[8];
return x;
}
protected AlgorithmParameters engineGetParameters() {
return null;
}
protected void engineInit(int mode, Key key, SecureRandom random) {}
protected void engineInit(int mode, Key key,
AlgorithmParameterSpec params,
SecureRandom random) {}
protected void engineInit(int mode, Key key,
AlgorithmParameters params,
SecureRandom random) {}
protected byte[] engineUpdate(byte[] input, int inputOffset,
int inputLen) {
if (input == null) return null;
byte[] x = new byte[inputLen];
System.arraycopy(input, inputOffset, x, 0, inputLen);
return x;
}
protected int engineUpdate(byte[] input, int inputOffset,
int inputLen, byte[] output,
int outputOffset) {
if (input == null) return 0;
System.arraycopy(input, inputOffset, output, outputOffset, inputLen);
return inputLen;
}
protected byte[] engineDoFinal(byte[] input, int inputOffset,
int inputLen)
{
return engineUpdate(input, inputOffset, inputLen);
}
protected int engineDoFinal(byte[] input, int inputOffset,
int inputLen, byte[] output,
int outputOffset)
{
return engineUpdate(input, inputOffset, inputLen,
output, outputOffset);
}
protected int engineGetKeySize(Key key)
{
return 0;
}
}
| Java |
/*
* Copyright (c) 1999, 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 javax.crypto;
import java.security.Key;
import java.security.AlgorithmParameters;
import java.security.InvalidKeyException;
import java.security.InvalidAlgorithmParameterException;
import java.security.spec.AlgorithmParameterSpec;
/** {@collect.stats}
* This class defines the <i>Service Provider Interface</i> (<b>SPI</b>)
* for the <code>ExemptionMechanism</code> class.
* All the abstract methods in this class must be implemented by each
* cryptographic service provider who wishes to supply the implementation
* of a particular exemption mechanism.
*
* @author Sharon Liu
*
* @since 1.4
*/
public abstract class ExemptionMechanismSpi {
/** {@collect.stats}
* Returns the length in bytes that an output buffer would need to be in
* order to hold the result of the next
* {@link #engineGenExemptionBlob(byte[], int) engineGenExemptionBlob}
* operation, given the input length <code>inputLen</code> (in bytes).
*
* <p>The actual output length of the next
* {@link #engineGenExemptionBlob(byte[], int) engineGenExemptionBlob}
* call may be smaller than the length returned by this method.
*
* @param inputLen the input length (in bytes)
*
* @return the required output buffer size (in bytes)
*/
protected abstract int engineGetOutputSize(int inputLen);
/** {@collect.stats}
* Initializes this exemption mechanism with a key.
*
* <p>If this exemption mechanism requires any algorithm parameters
* that cannot be derived from the given <code>key</code>, the underlying
* exemption mechanism implementation is supposed to generate the required
* parameters itself (using provider-specific default values); in the case
* that algorithm parameters must be specified by the caller, an
* <code>InvalidKeyException</code> is raised.
*
* @param key the key for this exemption mechanism
*
* @exception InvalidKeyException if the given key is inappropriate for
* this exemption mechanism.
* @exception ExemptionMechanismException if problem(s) encountered in the
* process of initializing.
*/
protected abstract void engineInit(Key key)
throws InvalidKeyException, ExemptionMechanismException;
/** {@collect.stats}
* Initializes this exemption mechanism with a key and a set of algorithm
* parameters.
*
* <p>If this exemption mechanism requires any algorithm parameters and
* <code>params</code> is null, the underlying exemption mechanism
* implementation is supposed to generate the required parameters
* itself (using provider-specific default values); in the case that
* algorithm parameters must be specified by the caller, an
* <code>InvalidAlgorithmParameterException</code> is raised.
*
* @param key the key for this exemption mechanism
* @param params the algorithm parameters
*
* @exception InvalidKeyException if the given key is inappropriate for
* this exemption mechanism.
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this exemption mechanism.
* @exception ExemptionMechanismException if problem(s) encountered in the
* process of initializing.
*/
protected abstract void engineInit(Key key, AlgorithmParameterSpec params)
throws InvalidKeyException, InvalidAlgorithmParameterException,
ExemptionMechanismException;
/** {@collect.stats}
* Initializes this exemption mechanism with a key and a set of algorithm
* parameters.
*
* <p>If this exemption mechanism requires any algorithm parameters
* and <code>params</code> is null, the underlying exemption mechanism
* implementation is supposed to generate the required parameters
* itself (using provider-specific default values); in the case that
* algorithm parameters must be specified by the caller, an
* <code>InvalidAlgorithmParameterException</code> is raised.
*
* @param key the key for this exemption mechanism
* @param params the algorithm parameters
*
* @exception InvalidKeyException if the given key is inappropriate for
* this exemption mechanism.
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this exemption mechanism.
* @exception ExemptionMechanismException if problem(s) encountered in the
* process of initializing.
*/
protected abstract void engineInit(Key key, AlgorithmParameters params)
throws InvalidKeyException, InvalidAlgorithmParameterException,
ExemptionMechanismException;
/** {@collect.stats}
* Generates the exemption mechanism key blob.
*
* @return the new buffer with the result key blob.
*
* @exception ExemptionMechanismException if problem(s) encountered in the
* process of generating.
*/
protected abstract byte[] engineGenExemptionBlob()
throws ExemptionMechanismException;
/** {@collect.stats}
* Generates the exemption mechanism key blob, and stores the result in
* the <code>output</code> buffer, starting at <code>outputOffset</code>
* inclusive.
*
* <p>If the <code>output</code> buffer is too small to hold the result,
* a <code>ShortBufferException</code> is thrown. In this case, repeat this
* call with a larger output buffer. Use
* {@link #engineGetOutputSize(int) engineGetOutputSize} to determine
* how big the output buffer should be.
*
* @param output the buffer for the result
* @param outputOffset the offset in <code>output</code> where the result
* is stored
*
* @return the number of bytes stored in <code>output</code>
*
* @exception ShortBufferException if the given output buffer is too small
* to hold the result.
* @exception ExemptionMechanismException if problem(s) encountered in the
* process of generating.
*/
protected abstract int engineGenExemptionBlob
(byte[] output, int outputOffset)
throws ShortBufferException, ExemptionMechanismException;
}
| Java |
/*
* Copyright (c) 1997, 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 javax.crypto;
import java.io.*;
/** {@collect.stats}
* A CipherOutputStream is composed of an OutputStream and a Cipher so
* that write() methods first process the data before writing them out
* to the underlying OutputStream. The cipher must be fully
* initialized before being used by a CipherOutputStream.
*
* <p> For example, if the cipher is initialized for encryption, the
* CipherOutputStream will attempt to encrypt data before writing out the
* encrypted data.
*
* <p> This class adheres strictly to the semantics, especially the
* failure semantics, of its ancestor classes
* java.io.OutputStream and java.io.FilterOutputStream. This class
* has exactly those methods specified in its ancestor classes, and
* overrides them all. Moreover, this class catches all exceptions
* that are not thrown by its ancestor classes.
*
* <p> It is crucial for a programmer using this class not to use
* methods that are not defined or overriden in this class (such as a
* new method or constructor that is later added to one of the super
* classes), because the design and implementation of those methods
* are unlikely to have considered security impact with regard to
* CipherOutputStream.
*
* @author Li Gong
* @see java.io.OutputStream
* @see java.io.FilterOutputStream
* @see javax.crypto.Cipher
* @see javax.crypto.CipherInputStream
*
* @since 1.4
*/
public class CipherOutputStream extends FilterOutputStream {
// the cipher engine to use to process stream data
private Cipher cipher;
// the underlying output stream
private OutputStream output;
/* the buffer holding one byte of incoming data */
private byte[] ibuffer = new byte[1];
// the buffer holding data ready to be written out
private byte[] obuffer;
/** {@collect.stats}
*
* Constructs a CipherOutputStream from an OutputStream and a
* Cipher.
* <br>Note: if the specified output stream or cipher is
* null, a NullPointerException may be thrown later when
* they are used.
*
* @param os the OutputStream object
* @param c an initialized Cipher object
*/
public CipherOutputStream(OutputStream os, Cipher c) {
super(os);
output = os;
cipher = c;
};
/** {@collect.stats}
* Constructs a CipherOutputStream from an OutputStream without
* specifying a Cipher. This has the effect of constructing a
* CipherOutputStream using a NullCipher.
* <br>Note: if the specified output stream is null, a
* NullPointerException may be thrown later when it is used.
*
* @param os the OutputStream object
*/
protected CipherOutputStream(OutputStream os) {
super(os);
output = os;
cipher = new NullCipher();
}
/** {@collect.stats}
* Writes the specified byte to this output stream.
*
* @param b the <code>byte</code>.
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public void write(int b) throws IOException {
ibuffer[0] = (byte) b;
obuffer = cipher.update(ibuffer, 0, 1);
if (obuffer != null) {
output.write(obuffer);
obuffer = null;
}
};
/** {@collect.stats}
* Writes <code>b.length</code> bytes from the specified byte array
* to this output stream.
* <p>
* The <code>write</code> method of
* <code>CipherOutputStream</code> calls the <code>write</code>
* method of three arguments with the three arguments
* <code>b</code>, <code>0</code>, and <code>b.length</code>.
*
* @param b the data.
* @exception NullPointerException if <code>b</code> is null.
* @exception IOException if an I/O error occurs.
* @see javax.crypto.CipherOutputStream#write(byte[], int, int)
* @since JCE1.2
*/
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
/** {@collect.stats}
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this output stream.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public void write(byte b[], int off, int len) throws IOException {
obuffer = cipher.update(b, off, len);
if (obuffer != null) {
output.write(obuffer);
obuffer = null;
}
}
/** {@collect.stats}
* Flushes this output stream by forcing any buffered output bytes
* that have already been processed by the encapsulated cipher object
* to be written out.
*
* <p>Any bytes buffered by the encapsulated cipher
* and waiting to be processed by it will not be written out. For example,
* if the encapsulated cipher is a block cipher, and the total number of
* bytes written using one of the <code>write</code> methods is less than
* the cipher's block size, no bytes will be written out.
*
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public void flush() throws IOException {
if (obuffer != null) {
output.write(obuffer);
obuffer = null;
}
output.flush();
}
/** {@collect.stats}
* Closes this output stream and releases any system resources
* associated with this stream.
* <p>
* This method invokes the <code>doFinal</code> method of the encapsulated
* cipher object, which causes any bytes buffered by the encapsulated
* cipher to be processed. The result is written out by calling the
* <code>flush</code> method of this output stream.
* <p>
* This method resets the encapsulated cipher object to its initial state
* and calls the <code>close</code> method of the underlying output
* stream.
*
* @exception IOException if an I/O error occurs.
* @since JCE1.2
*/
public void close() throws IOException {
try {
obuffer = cipher.doFinal();
} catch (IllegalBlockSizeException e) {
obuffer = null;
} catch (BadPaddingException e) {
obuffer = null;
}
try {
flush();
} catch (IOException ignored) {}
out.close();
}
}
| Java |
/*
* Copyright (c) 1999, 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 javax.crypto;
import java.security.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import java.util.NoSuchElementException;
import java.io.Serializable;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
/** {@collect.stats}
* This class contains CryptoPermission objects, organized into
* PermissionCollections according to algorithm names.
*
* <p>When the <code>add</code> method is called to add a
* CryptoPermission, the CryptoPermission is stored in the
* appropriate PermissionCollection. If no such
* collection exists yet, the algorithm name associated with
* the CryptoPermission object is
* determined and the <code>newPermissionCollection</code> method
* is called on the CryptoPermission or CryptoAllPermission class to
* create the PermissionCollection and add it to the Permissions object.
*
* @see javax.crypto.CryptoPermission
* @see java.security.PermissionCollection
* @see java.security.Permissions
*
* @author Sharon Liu
* @since 1.4
*/
final class CryptoPermissions extends PermissionCollection
implements Serializable {
private static final long serialVersionUID = 4946547168093391015L;
// This class is similar to java.security.Permissions
private Hashtable perms;
/** {@collect.stats}
* Creates a new CryptoPermissions object containing
* no CryptoPermissionCollections.
*/
CryptoPermissions() {
perms = new Hashtable(7);
}
/** {@collect.stats}
* Populates the crypto policy from the specified
* InputStream into this CryptoPermissions object.
*
* @param in the InputStream to load from.
*
* @exception SecurityException if cannot load
* successfully.
*/
void load(InputStream in)
throws IOException, CryptoPolicyParser.ParsingException {
CryptoPolicyParser parser = new CryptoPolicyParser();
parser.read(new BufferedReader(new InputStreamReader(in, "UTF-8")));
CryptoPermission[] parsingResult = parser.getPermissions();
for (int i = 0; i < parsingResult.length; i++) {
this.add(parsingResult[i]);
}
}
/** {@collect.stats}
* Returns true if this CryptoPermissions object doesn't
* contain any CryptoPermission objects; otherwise, returns
* false.
*/
boolean isEmpty() {
return perms.isEmpty();
}
/** {@collect.stats}
* Adds a permission object to the PermissionCollection for the
* algorithm returned by
* <code>(CryptoPermission)permission.getAlgorithm()</code>.
*
* This method creates
* a new PermissionCollection object (and adds the permission to it)
* if an appropriate collection does not yet exist. <p>
*
* @param permission the Permission object to add.
*
* @exception SecurityException if this CryptoPermissions object is
* marked as readonly.
*
* @see isReadOnly
*/
public void add(Permission permission) {
if (isReadOnly())
throw new SecurityException("Attempt to add a Permission " +
"to a readonly CryptoPermissions " +
"object");
if (!(permission instanceof CryptoPermission))
return;
CryptoPermission cryptoPerm = (CryptoPermission)permission;
PermissionCollection pc =
getPermissionCollection(cryptoPerm);
pc.add(cryptoPerm);
String alg = cryptoPerm.getAlgorithm();
if (!perms.containsKey(alg)) {
perms.put(alg, pc);
}
}
/** {@collect.stats}
* Checks if this object's PermissionCollection for permissons
* of the specified permission's algorithm implies the specified
* permission. Returns true if the checking succeeded.
*
* @param permission the Permission object to check.
*
* @return true if "permission" is implied by the permissions
* in the PermissionCollection it belongs to, false if not.
*
*/
public boolean implies(Permission permission) {
if (!(permission instanceof CryptoPermission)) {
return false;
}
CryptoPermission cryptoPerm = (CryptoPermission)permission;
PermissionCollection pc =
getPermissionCollection(cryptoPerm.getAlgorithm());
return pc.implies(cryptoPerm);
}
/** {@collect.stats}
* Returns an enumeration of all the Permission objects in all the
* PermissionCollections in this CryptoPermissions object.
*
* @return an enumeration of all the Permissions.
*/
public Enumeration elements() {
// go through each Permissions in the hash table
// and call their elements() function.
return new PermissionsEnumerator(perms.elements());
}
/** {@collect.stats}
* Returns a CryptoPermissions object which
* represents the minimum of the specified
* CryptoPermissions object and this
* CryptoPermissions object.
*
* @param other the CryptoPermission
* object to compare with this object.
*/
CryptoPermissions getMinimum(CryptoPermissions other) {
if (other == null) {
return null;
}
if (this.perms.containsKey(CryptoAllPermission.ALG_NAME)) {
return other;
}
if (other.perms.containsKey(CryptoAllPermission.ALG_NAME)) {
return this;
}
CryptoPermissions ret = new CryptoPermissions();
PermissionCollection thatWildcard =
(PermissionCollection)other.perms.get(
CryptoPermission.ALG_NAME_WILDCARD);
int maxKeySize = 0;
if (thatWildcard != null) {
maxKeySize = ((CryptoPermission)
thatWildcard.elements().nextElement()).getMaxKeySize();
}
// For each algorithm in this CryptoPermissions,
// find out if there is anything we should add into
// ret.
Enumeration thisKeys = this.perms.keys();
while (thisKeys.hasMoreElements()) {
String alg = (String)thisKeys.nextElement();
PermissionCollection thisPc =
(PermissionCollection)this.perms.get(alg);
PermissionCollection thatPc =
(PermissionCollection)other.perms.get(alg);
CryptoPermission[] partialResult;
if (thatPc == null) {
if (thatWildcard == null) {
// The other CryptoPermissions
// doesn't allow this given
// algorithm at all. Just skip this
// algorithm.
continue;
}
partialResult = getMinimum(maxKeySize, thisPc);
} else {
partialResult = getMinimum(thisPc, thatPc);
}
for (int i = 0; i < partialResult.length; i++) {
ret.add(partialResult[i]);
}
}
PermissionCollection thisWildcard =
(PermissionCollection)this.perms.get(
CryptoPermission.ALG_NAME_WILDCARD);
// If this CryptoPermissions doesn't
// have a wildcard, we are done.
if (thisWildcard == null) {
return ret;
}
// Deal with the algorithms only appear
// in the other CryptoPermissions.
maxKeySize =
((CryptoPermission)
thisWildcard.elements().nextElement()).getMaxKeySize();
Enumeration thatKeys = other.perms.keys();
while (thatKeys.hasMoreElements()) {
String alg = (String)thatKeys.nextElement();
if (this.perms.containsKey(alg)) {
continue;
}
PermissionCollection thatPc =
(PermissionCollection)other.perms.get(alg);
CryptoPermission[] partialResult;
partialResult = getMinimum(maxKeySize, thatPc);
for (int i = 0; i < partialResult.length; i++) {
ret.add(partialResult[i]);
}
}
return ret;
}
/** {@collect.stats}
* Get the minimum of the two given PermissionCollection
* <code>thisPc</code> and <code>thatPc</code>.
*
* @param thisPc the first given PermissionColloection
* object.
*
* @param thatPc the second given PermissionCollection
* object.
*/
private CryptoPermission[] getMinimum(PermissionCollection thisPc,
PermissionCollection thatPc) {
Vector permVector = new Vector(2);
Enumeration thisPcPermissions = thisPc.elements();
// For each CryptoPermission in
// thisPc object, do the following:
// 1) if this CryptoPermission is implied
// by thatPc, this CryptoPermission
// should be returned, and we can
// move on to check the next
// CryptoPermission in thisPc.
// 2) otherwise, we should return
// all CryptoPermissions in thatPc
// which
// are implied by this CryptoPermission.
// Then we can move on to the
// next CryptoPermission in thisPc.
while (thisPcPermissions.hasMoreElements()) {
CryptoPermission thisCp =
(CryptoPermission)thisPcPermissions.nextElement();
Enumeration thatPcPermissions = thatPc.elements();
while (thatPcPermissions.hasMoreElements()) {
CryptoPermission thatCp =
(CryptoPermission)thatPcPermissions.nextElement();
if (thatCp.implies(thisCp)) {
permVector.addElement(thisCp);
break;
}
if (thisCp.implies(thatCp)) {
permVector.addElement(thatCp);
}
}
}
CryptoPermission[] ret = new CryptoPermission[permVector.size()];
permVector.copyInto(ret);
return ret;
}
/** {@collect.stats}
* Returns all the CryptoPermission objects in the given
* PermissionCollection object
* whose maximum keysize no greater than <code>maxKeySize</code>.
* For all CryptoPermission objects with a maximum keysize greater
* than <code>maxKeySize</code>, this method constructs a
* corresponding CryptoPermission object whose maximum keysize is
* set to <code>maxKeySize</code>, and includes that in the result.
*
* @param maxKeySize the given maximum key size.
*
* @param pc the given PermissionCollection object.
*/
private CryptoPermission[] getMinimum(int maxKeySize,
PermissionCollection pc) {
Vector permVector = new Vector(1);
Enumeration enum_ = pc.elements();
while (enum_.hasMoreElements()) {
CryptoPermission cp =
(CryptoPermission)enum_.nextElement();
if (cp.getMaxKeySize() <= maxKeySize) {
permVector.addElement(cp);
} else {
if (cp.getCheckParam()) {
permVector.addElement(
new CryptoPermission(cp.getAlgorithm(),
maxKeySize,
cp.getAlgorithmParameterSpec(),
cp.getExemptionMechanism()));
} else {
permVector.addElement(
new CryptoPermission(cp.getAlgorithm(),
maxKeySize,
cp.getExemptionMechanism()));
}
}
}
CryptoPermission[] ret = new CryptoPermission[permVector.size()];
permVector.copyInto(ret);
return ret;
}
/** {@collect.stats}
* Returns the PermissionCollection for the
* specified algorithm. Returns null if there
* isn't such a PermissionCollection.
*
* @param alg the algorithm name.
*/
PermissionCollection getPermissionCollection(String alg) {
// If this CryptoPermissions includes CryptoAllPermission,
// we should return CryptoAllPermission.
if (perms.containsKey(CryptoAllPermission.ALG_NAME)) {
return
(PermissionCollection)(perms.get(CryptoAllPermission.ALG_NAME));
}
PermissionCollection pc = (PermissionCollection)perms.get(alg);
// If there isn't a PermissionCollection for
// the given algorithm,we should return the
// PermissionCollection for the wildcard
// if there is one.
if (pc == null) {
pc = (PermissionCollection)perms.get(
CryptoPermission.ALG_NAME_WILDCARD);
}
return pc;
}
/** {@collect.stats}
* Returns the PermissionCollection for the algorithm
* associated with the specified CryptoPermission
* object. Creates such a PermissionCollection
* if such a PermissionCollection does not
* exist yet.
*
* @param cryptoPerm the CryptoPermission object.
*/
private PermissionCollection getPermissionCollection(
CryptoPermission cryptoPerm) {
String alg = cryptoPerm.getAlgorithm();
PermissionCollection pc = (PermissionCollection)perms.get(alg);
if (pc == null) {
pc = cryptoPerm.newPermissionCollection();
}
return pc;
}
}
final class PermissionsEnumerator implements Enumeration {
// all the perms
private Enumeration perms;
// the current set
private Enumeration permset;
PermissionsEnumerator(Enumeration e) {
perms = e;
permset = getNextEnumWithMore();
}
public synchronized boolean hasMoreElements() {
// if we enter with permissionimpl null, we know
// there are no more left.
if (permset == null)
return false;
// try to see if there are any left in the current one
if (permset.hasMoreElements())
return true;
// get the next one that has something in it...
permset = getNextEnumWithMore();
// if it is null, we are done!
return (permset != null);
}
public synchronized Object nextElement() {
// hasMoreElements will update permset to the next permset
// with something in it...
if (hasMoreElements()) {
return permset.nextElement();
} else {
throw new NoSuchElementException("PermissionsEnumerator");
}
}
private Enumeration getNextEnumWithMore() {
while (perms.hasMoreElements()) {
PermissionCollection pc =
(PermissionCollection) perms.nextElement();
Enumeration next = pc.elements();
if (next.hasMoreElements())
return next;
}
return null;
}
}
| Java |
/*
* Copyright (c) 2003, 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 javax.rmi.ssl;
import java.io.IOException;
import java.io.Serializable;
import java.net.Socket;
import java.rmi.server.RMIClientSocketFactory;
import java.util.StringTokenizer;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
/** {@collect.stats}
* <p>An <code>SslRMIClientSocketFactory</code> instance is used by the RMI
* runtime in order to obtain client sockets for RMI calls via SSL.</p>
*
* <p>This class implements <code>RMIClientSocketFactory</code> over
* the Secure Sockets Layer (SSL) or Transport Layer Security (TLS)
* protocols.</p>
*
* <p>This class creates SSL sockets using the default
* <code>SSLSocketFactory</code> (see {@link
* SSLSocketFactory#getDefault}). All instances of this class are
* functionally equivalent. In particular, they all share the same
* truststore, and the same keystore when client authentication is
* required by the server. This behavior can be modified in
* subclasses by overriding the {@link #createSocket(String,int)}
* method; in that case, {@link #equals(Object) equals} and {@link
* #hashCode() hashCode} may also need to be overridden.</p>
*
* <p>If the system property
* <code>javax.rmi.ssl.client.enabledCipherSuites</code> is specified,
* the {@link #createSocket(String,int)} method will call {@link
* SSLSocket#setEnabledCipherSuites(String[])} before returning the
* socket. The value of this system property is a string that is a
* comma-separated list of SSL/TLS cipher suites to enable.</p>
*
* <p>If the system property
* <code>javax.rmi.ssl.client.enabledProtocols</code> is specified,
* the {@link #createSocket(String,int)} method will call {@link
* SSLSocket#setEnabledProtocols(String[])} before returning the
* socket. The value of this system property is a string that is a
* comma-separated list of SSL/TLS protocol versions to enable.</p>
*
* @see javax.net.ssl.SSLSocketFactory
* @see javax.rmi.ssl.SslRMIServerSocketFactory
* @since 1.5
*/
public class SslRMIClientSocketFactory
implements RMIClientSocketFactory, Serializable {
/** {@collect.stats}
* <p>Creates a new <code>SslRMIClientSocketFactory</code>.</p>
*/
public SslRMIClientSocketFactory() {
// We don't force the initialization of the default SSLSocketFactory
// at construction time - because the RMI client socket factory is
// created on the server side, where that initialization is a priori
// meaningless, unless both server and client run in the same JVM.
// We could possibly override readObject() to force this initialization,
// but it might not be a good idea to actually mix this with possible
// deserialization problems.
// So contrarily to what we do for the server side, the initialization
// of the SSLSocketFactory will be delayed until the first time
// createSocket() is called - note that the default SSLSocketFactory
// might already have been initialized anyway if someone in the JVM
// already called SSLSocketFactory.getDefault().
//
}
/** {@collect.stats}
* <p>Creates an SSL socket.</p>
*
* <p>If the system property
* <code>javax.rmi.ssl.client.enabledCipherSuites</code> is
* specified, this method will call {@link
* SSLSocket#setEnabledCipherSuites(String[])} before returning
* the socket. The value of this system property is a string that
* is a comma-separated list of SSL/TLS cipher suites to
* enable.</p>
*
* <p>If the system property
* <code>javax.rmi.ssl.client.enabledProtocols</code> is
* specified, this method will call {@link
* SSLSocket#setEnabledProtocols(String[])} before returning the
* socket. The value of this system property is a string that is a
* comma-separated list of SSL/TLS protocol versions to
* enable.</p>
*/
public Socket createSocket(String host, int port) throws IOException {
// Retrieve the SSLSocketFactory
//
final SocketFactory sslSocketFactory = getDefaultClientSocketFactory();
// Create the SSLSocket
//
final SSLSocket sslSocket = (SSLSocket)
sslSocketFactory.createSocket(host, port);
// Set the SSLSocket Enabled Cipher Suites
//
final String enabledCipherSuites = (String)
System.getProperty("javax.rmi.ssl.client.enabledCipherSuites");
if (enabledCipherSuites != null) {
StringTokenizer st = new StringTokenizer(enabledCipherSuites, ",");
int tokens = st.countTokens();
String enabledCipherSuitesList[] = new String[tokens];
for (int i = 0 ; i < tokens; i++) {
enabledCipherSuitesList[i] = st.nextToken();
}
try {
sslSocket.setEnabledCipherSuites(enabledCipherSuitesList);
} catch (IllegalArgumentException e) {
throw (IOException)
new IOException(e.getMessage()).initCause(e);
}
}
// Set the SSLSocket Enabled Protocols
//
final String enabledProtocols = (String)
System.getProperty("javax.rmi.ssl.client.enabledProtocols");
if (enabledProtocols != null) {
StringTokenizer st = new StringTokenizer(enabledProtocols, ",");
int tokens = st.countTokens();
String enabledProtocolsList[] = new String[tokens];
for (int i = 0 ; i < tokens; i++) {
enabledProtocolsList[i] = st.nextToken();
}
try {
sslSocket.setEnabledProtocols(enabledProtocolsList);
} catch (IllegalArgumentException e) {
throw (IOException)
new IOException(e.getMessage()).initCause(e);
}
}
// Return the preconfigured SSLSocket
//
return sslSocket;
}
/** {@collect.stats}
* <p>Indicates whether some other object is "equal to" this one.</p>
*
* <p>Because all instances of this class are functionally equivalent
* (they all use the default
* <code>SSLSocketFactory</code>), this method simply returns
* <code>this.getClass().equals(obj.getClass())</code>.</p>
*
* <p>A subclass should override this method (as well
* as {@link #hashCode()}) if its instances are not all
* functionally equivalent.</p>
*/
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj == this) return true;
return this.getClass().equals(obj.getClass());
}
/** {@collect.stats}
* <p>Returns a hash code value for this
* <code>SslRMIClientSocketFactory</code>.</p>
*
* @return a hash code value for this
* <code>SslRMIClientSocketFactory</code>.
*/
public int hashCode() {
return this.getClass().hashCode();
}
// We use a static field because:
//
// SSLSocketFactory.getDefault() always returns the same object
// (at least on Sun's implementation), and we want to make sure
// that the Javadoc & the implementation stay in sync.
//
// If someone needs to have different SslRMIClientSocketFactory factories
// with different underlying SSLSocketFactory objects using different key
// and trust stores, he can always do so by subclassing this class and
// overriding createSocket(String host, int port).
//
private static SocketFactory defaultSocketFactory = null;
private static synchronized SocketFactory getDefaultClientSocketFactory() {
if (defaultSocketFactory == null)
defaultSocketFactory = SSLSocketFactory.getDefault();
return defaultSocketFactory;
}
private static final long serialVersionUID = -8310631444933958385L;
}
| Java |
/*
* Copyright (c) 2003, 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 javax.rmi.ssl;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.server.RMIServerSocketFactory;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
/** {@collect.stats}
* <p>An <code>SslRMIServerSocketFactory</code> instance is used by the RMI
* runtime in order to obtain server sockets for RMI calls via SSL.</p>
*
* <p>This class implements <code>RMIServerSocketFactory</code> over
* the Secure Sockets Layer (SSL) or Transport Layer Security (TLS)
* protocols.</p>
*
* <p>This class creates SSL sockets using the default
* <code>SSLSocketFactory</code> (see {@link
* SSLSocketFactory#getDefault}) or the default
* <code>SSLServerSocketFactory</code> (see {@link
* SSLServerSocketFactory#getDefault}). Therefore, all instances of
* this class share the same keystore, and the same truststore, when
* client authentication is required by the server. This behavior
* can be modified in subclasses by overriding the {@link
* #createServerSocket(int)} method; in that case, {@link
* #equals(Object) equals} and {@link #hashCode() hashCode} may also
* need to be overridden.</p>
*
* @see javax.net.ssl.SSLSocketFactory
* @see javax.net.ssl.SSLServerSocketFactory
* @see javax.rmi.ssl.SslRMIClientSocketFactory
* @since 1.5
*/
public class SslRMIServerSocketFactory implements RMIServerSocketFactory {
/** {@collect.stats}
* <p>Creates a new <code>SslRMIServerSocketFactory</code> with
* the default SSL socket configuration.</p>
*
* <p>SSL connections accepted by server sockets created by this
* factory have the default cipher suites and protocol versions
* enabled and do not require client authentication.</p>
*/
public SslRMIServerSocketFactory() {
this(null, null, false);
}
/** {@collect.stats}
* <p>Creates a new <code>SslRMIServerSocketFactory</code> with
* the specified SSL socket configuration.</p>
*
* @param enabledCipherSuites names of all the cipher suites to
* enable on SSL connections accepted by server sockets created by
* this factory, or <code>null</code> to use the cipher suites
* that are enabled by default
*
* @param enabledProtocols names of all the protocol versions to
* enable on SSL connections accepted by server sockets created by
* this factory, or <code>null</code> to use the protocol versions
* that are enabled by default
*
* @param needClientAuth <code>true</code> to require client
* authentication on SSL connections accepted by server sockets
* created by this factory; <code>false</code> to not require
* client authentication
*
* @exception IllegalArgumentException when one or more of the cipher
* suites named by the <code>enabledCipherSuites</code> parameter is
* not supported, when one or more of the protocols named by the
* <code>enabledProtocols</code> parameter is not supported or when
* a problem is encountered while trying to check if the supplied
* cipher suites and protocols to be enabled are supported.
*
* @see SSLSocket#setEnabledCipherSuites
* @see SSLSocket#setEnabledProtocols
* @see SSLSocket#setNeedClientAuth
*/
public SslRMIServerSocketFactory(String[] enabledCipherSuites,
String[] enabledProtocols,
boolean needClientAuth)
throws IllegalArgumentException {
// Initialize the configuration parameters.
//
this.enabledCipherSuites = enabledCipherSuites == null ?
null : (String[]) enabledCipherSuites.clone();
this.enabledProtocols = enabledProtocols == null ?
null : (String[]) enabledProtocols.clone();
this.needClientAuth = needClientAuth;
// Force the initialization of the default at construction time,
// rather than delaying it to the first time createServerSocket()
// is called.
//
final SSLSocketFactory sslSocketFactory = getDefaultSSLSocketFactory();
SSLSocket sslSocket = null;
if (this.enabledCipherSuites != null || this.enabledProtocols != null) {
try {
sslSocket = (SSLSocket) sslSocketFactory.createSocket();
} catch (Exception e) {
final String msg = "Unable to check if the cipher suites " +
"and protocols to enable are supported";
throw (IllegalArgumentException)
new IllegalArgumentException(msg).initCause(e);
}
}
// Check if all the cipher suites and protocol versions to enable
// are supported by the underlying SSL/TLS implementation and if
// true create lists from arrays.
//
if (this.enabledCipherSuites != null) {
sslSocket.setEnabledCipherSuites(this.enabledCipherSuites);
enabledCipherSuitesList =
Arrays.asList((String[]) this.enabledCipherSuites);
}
if (this.enabledProtocols != null) {
sslSocket.setEnabledProtocols(this.enabledProtocols);
enabledProtocolsList =
Arrays.asList((String[]) this.enabledProtocols);
}
}
/** {@collect.stats}
* <p>Returns the names of the cipher suites enabled on SSL
* connections accepted by server sockets created by this factory,
* or <code>null</code> if this factory uses the cipher suites
* that are enabled by default.</p>
*
* @return an array of cipher suites enabled, or <code>null</code>
*
* @see SSLSocket#setEnabledCipherSuites
*/
public final String[] getEnabledCipherSuites() {
return enabledCipherSuites == null ?
null : (String[]) enabledCipherSuites.clone();
}
/** {@collect.stats}
* <p>Returns the names of the protocol versions enabled on SSL
* connections accepted by server sockets created by this factory,
* or <code>null</code> if this factory uses the protocol versions
* that are enabled by default.</p>
*
* @return an array of protocol versions enabled, or
* <code>null</code>
*
* @see SSLSocket#setEnabledProtocols
*/
public final String[] getEnabledProtocols() {
return enabledProtocols == null ?
null : (String[]) enabledProtocols.clone();
}
/** {@collect.stats}
* <p>Returns <code>true</code> if client authentication is
* required on SSL connections accepted by server sockets created
* by this factory.</p>
*
* @return <code>true</code> if client authentication is required
*
* @see SSLSocket#setNeedClientAuth
*/
public final boolean getNeedClientAuth() {
return needClientAuth;
}
/** {@collect.stats}
* <p>Creates a server socket that accepts SSL connections
* configured according to this factory's SSL socket configuration
* parameters.</p>
*/
public ServerSocket createServerSocket(int port) throws IOException {
final SSLSocketFactory sslSocketFactory = getDefaultSSLSocketFactory();
return new ServerSocket(port) {
public Socket accept() throws IOException {
Socket socket = super.accept();
SSLSocket sslSocket = (SSLSocket)
sslSocketFactory.createSocket(
socket, socket.getInetAddress().getHostName(),
socket.getPort(), true);
sslSocket.setUseClientMode(false);
if (enabledCipherSuites != null) {
sslSocket.setEnabledCipherSuites(enabledCipherSuites);
}
if (enabledProtocols != null) {
sslSocket.setEnabledProtocols(enabledProtocols);
}
sslSocket.setNeedClientAuth(needClientAuth);
return sslSocket;
}
};
// If we do not instantiate the server socket class, but
// instead must layer on top of an arbitrary server socket,
// then this implementation would become uglier, like this
// (given "serverSocket" to layer on top of):
//
// return new ForwardingServerSocket(serverSocket) {
// public Socket accept() throws IOException {
// Socket socket = serverSocket.accept();
// SSLSocket sslSocket =
// (SSLSocket) sslSocketFactory.createSocket(
// socket,
// socket.getInetAddress().getHostName(),
// socket.getPort(),
// true);
// sslSocket.setUseClientMode(false);
// if (enabledProtocols != null) {
// sslSocket.setEnabledProtocols(enabledProtocols);
// }
// if (enabledCipherSuites != null) {
// sslSocket.setEnabledCipherSuites(enabledCipherSuites);
// }
// sslSocket.setNeedClientAuth(needClientAuth);
// return sslSocket;
// }
// public ServerSocketChannel getChannel() {
// return null;
// }
// public String toString() {
// return serverSocket.toString();
// }
// };
}
/** {@collect.stats}
* <p>Indicates whether some other object is "equal to" this one.</p>
*
* <p>Two <code>SslRMIServerSocketFactory</code> objects are equal
* if they have been constructed with the same SSL socket
* configuration parameters.</p>
*
* <p>A subclass should override this method (as well as
* {@link #hashCode()}) if it adds instance state that affects
* equality.</p>
*/
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj == this) return true;
if (!(obj instanceof SslRMIServerSocketFactory))
return false;
SslRMIServerSocketFactory that = (SslRMIServerSocketFactory) obj;
return (getClass().equals(that.getClass()) && checkParameters(that));
}
private boolean checkParameters(SslRMIServerSocketFactory that) {
// needClientAuth flag
//
if (needClientAuth != that.needClientAuth)
return false;
// enabledCipherSuites
//
if ((enabledCipherSuites == null && that.enabledCipherSuites != null) ||
(enabledCipherSuites != null && that.enabledCipherSuites == null))
return false;
if (enabledCipherSuites != null && that.enabledCipherSuites != null) {
List thatEnabledCipherSuitesList =
Arrays.asList((String[]) that.enabledCipherSuites);
if (!enabledCipherSuitesList.equals(thatEnabledCipherSuitesList))
return false;
}
// enabledProtocols
//
if ((enabledProtocols == null && that.enabledProtocols != null) ||
(enabledProtocols != null && that.enabledProtocols == null))
return false;
if (enabledProtocols != null && that.enabledProtocols != null) {
List thatEnabledProtocolsList =
Arrays.asList((String[]) that.enabledProtocols);
if (!enabledProtocolsList.equals(thatEnabledProtocolsList))
return false;
}
return true;
}
/** {@collect.stats}
* <p>Returns a hash code value for this
* <code>SslRMIServerSocketFactory</code>.</p>
*
* @return a hash code value for this
* <code>SslRMIServerSocketFactory</code>.
*/
public int hashCode() {
return getClass().hashCode() +
(needClientAuth ? Boolean.TRUE.hashCode() : Boolean.FALSE.hashCode()) +
(enabledCipherSuites == null ? 0 : enabledCipherSuitesList.hashCode()) +
(enabledProtocols == null ? 0 : enabledProtocolsList.hashCode());
}
// We use a static field because:
//
// SSLSocketFactory.getDefault() always returns the same object
// (at least on Sun's implementation), and we want to make sure that
// the Javadoc & the implementation stay in sync.
//
// If someone needs to have different SslRMIServerSocketFactory factories
// with different underlying SSLSocketFactory objects using different
// key and trust stores, he can always do so by subclassing this class and
// overriding createServerSocket(int port).
//
private static SSLSocketFactory defaultSSLSocketFactory = null;
private static synchronized SSLSocketFactory getDefaultSSLSocketFactory() {
if (defaultSSLSocketFactory == null)
defaultSSLSocketFactory =
(SSLSocketFactory) SSLSocketFactory.getDefault();
return defaultSSLSocketFactory;
}
private final String[] enabledCipherSuites;
private final String[] enabledProtocols;
private final boolean needClientAuth;
private List enabledCipherSuitesList;
private List enabledProtocolsList;
// private static class ForwardingServerSocket extends ServerSocket {
// private final ServerSocket ss;
// ForwardingServerSocket(ServerSocket ss) throws IOException {
// super();
// this.ss = ss;
// }
// public void bind(SocketAddress endpoint) throws IOException {
// ss.bind(endpoint);
// }
// public void bind(SocketAddress endpoint, int backlog)
// throws IOException
// {
// ss.bind(endpoint, backlog);
// }
// public InetAddress getInetAddress() {
// return ss.getInetAddress();
// }
// public int getLocalPort() {
// return ss.getLocalPort();
// }
// public SocketAddress getLocalSocketAddress() {
// return ss.getLocalSocketAddress();
// }
// public Socket accept() throws IOException {
// return ss.accept();
// }
// public void close() throws IOException {
// ss.close();
// }
// public ServerSocketChannel getChannel() {
// return ss.getChannel();
// }
// public boolean isBound() {
// return ss.isBound();
// }
// public boolean isClosed() {
// return ss.isClosed();
// }
// public void setSoTimeout(int timeout) throws SocketException {
// ss.setSoTimeout(timeout);
// }
// public int getSoTimeout() throws IOException {
// return ss.getSoTimeout();
// }
// public void setReuseAddress(boolean on) throws SocketException {
// ss.setReuseAddress(on);
// }
// public boolean getReuseAddress() throws SocketException {
// return ss.getReuseAddress();
// }
// public String toString() {
// return ss.toString();
// }
// public void setReceiveBufferSize(int size) throws SocketException {
// ss.setReceiveBufferSize(size);
// }
// public int getReceiveBufferSize() throws SocketException {
// return ss.getReceiveBufferSize();
// }
// }
}
| Java |
/*
* Copyright (c) 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 javax.script;
import java.util.Map;
/** {@collect.stats}
* Extended by classes that store results of compilations. State
* might be stored in the form of Java classes, Java class files or scripting
* language opcodes. The script may be executed repeatedly
* without reparsing.
* <br><br>
* Each <code>CompiledScript</code> is associated with a <code>ScriptEngine</code> -- A call to an <code>eval</code>
* method of the <code>CompiledScript</code> causes the execution of the script by the
* <code>ScriptEngine</code>. Changes in the state of the <code>ScriptEngine</code> caused by execution
* of tne <code>CompiledScript</code> may visible during subsequent executions of scripts by the engine.
*
* @author Mike Grogan
* @since 1.6
*/
public abstract class CompiledScript {
/** {@collect.stats}
* Executes the program stored in this <code>CompiledScript</code> object.
*
* @param context A <code>ScriptContext</code> that is used in the same way as
* the <code>ScriptContext</code> passed to the <code>eval</code> methods of
* <code>ScriptEngine</code>.
*
* @return The value returned by the script execution, if any. Should return <code>null</code>
* if no value is returned by the script execution.
*
* @throws ScriptException if an error occurs.
* @throws NullPointerException if context is null.
*/
public abstract Object eval(ScriptContext context) throws ScriptException;
/** {@collect.stats}
* Executes the program stored in the <code>CompiledScript</code> object using
* the supplied <code>Bindings</code> of attributes as the <code>ENGINE_SCOPE</code> of the
* associated <code>ScriptEngine</code> during script execution. If bindings is null,
* then the effect of calling this method is same as that of eval(getEngine().getContext()).
* <p>.
* The <code>GLOBAL_SCOPE</code> <code>Bindings</code>, <code>Reader</code> and <code>Writer</code>
* associated with the default <code>ScriptContext</code> of the associated <code>ScriptEngine</code> are used.
*
* @param bindings The bindings of attributes used for the <code>ENGINE_SCOPE</code>.
*
* @return The return value from the script execution
*
* @throws ScriptException if an error occurs.
*/
public Object eval(Bindings bindings) throws ScriptException {
ScriptContext ctxt = getEngine().getContext();
if (bindings != null) {
SimpleScriptContext tempctxt = new SimpleScriptContext();
tempctxt.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
tempctxt.setBindings(ctxt.getBindings(ScriptContext.GLOBAL_SCOPE),
ScriptContext.GLOBAL_SCOPE);
tempctxt.setWriter(ctxt.getWriter());
tempctxt.setReader(ctxt.getReader());
tempctxt.setErrorWriter(ctxt.getErrorWriter());
ctxt = tempctxt;
}
return eval(ctxt);
}
/** {@collect.stats}
* Executes the program stored in the <code>CompiledScript</code> object. The
* default <code>ScriptContext</code> of the associated <code>ScriptEngine</code> is used.
* The effect of calling this method is same as that of eval(getEngine().getContext()).
*
* @return The return value from the script execution
*
* @throws ScriptException if an error occurs.
*/
public Object eval() throws ScriptException {
return eval(getEngine().getContext());
}
/** {@collect.stats}
* Returns the <code>ScriptEngine</code> wbose <code>compile</code> method created this <code>CompiledScript</code>.
* The <code>CompiledScript</code> will execute in this engine.
*
* @return The <code>ScriptEngine</code> that created this <code>CompiledScript</code>
*/
public abstract ScriptEngine getEngine();
}
| 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 javax.script;
/** {@collect.stats}
* The optional interface implemented by ScriptEngines whose methods allow the invocation of
* procedures in scripts that have previously been executed.
*
* @author Mike Grogan
* @author A. Sundararajan
* @since 1.6
*/
public interface Invocable {
/** {@collect.stats}
* Calls a method on a script object compiled during a previous script execution,
* which is retained in the state of the <code>ScriptEngine</code>.
*
* @param name The name of the procedure to be called.
*
* @param thiz If the procedure is a member of a class
* defined in the script and thiz is an instance of that class
* returned by a previous execution or invocation, the named method is
* called through that instance.
*
* @param args Arguments to pass to the procedure. The rules for converting
* the arguments to scripting variables are implementation-specific.
*
* @return The value returned by the procedure. The rules for converting the scripting
* variable returned by the script method to a Java Object are implementation-specific.
*
* @throws ScriptException if an error occurrs during invocation of the method.
* @throws NoSuchMethodException if method with given name or matching argument types cannot be found.
* @throws NullPointerException if the method name is null.
* @throws IllegalArgumentException if the specified thiz is null or the specified Object is
* does not represent a scripting object.
*/
public Object invokeMethod(Object thiz, String name, Object... args)
throws ScriptException, NoSuchMethodException;
/** {@collect.stats}
* Used to call top-level procedures and functions defined in scripts.
*
* @param args Arguments to pass to the procedure or function
* @return The value returned by the procedure or function
*
* @throws ScriptException if an error occurrs during invocation of the method.
* @throws NoSuchMethodException if method with given name or matching argument types cannot be found.
* @throws NullPointerException if method name is null.
*/
public Object invokeFunction(String name, Object... args)
throws ScriptException, NoSuchMethodException;
/** {@collect.stats}
* Returns an implementation of an interface using functions compiled in
* the interpreter. The methods of the interface
* may be implemented using the <code>invokeFunction</code> method.
*
* @param clasz The <code>Class</code> object of the interface to return.
*
* @return An instance of requested interface - null if the requested interface is unavailable,
* i. e. if compiled functions in the <code>ScriptEngine</code> cannot be found matching
* the ones in the requested interface.
*
* @throws IllegalArgumentException if the specified <code>Class</code> object
* is null or is not an interface.
*/
public <T> T getInterface(Class<T> clasz);
/** {@collect.stats}
* Returns an implementation of an interface using member functions of
* a scripting object compiled in the interpreter. The methods of the
* interface may be implemented using the <code>invokeMethod</code> method.
*
* @param thiz The scripting object whose member functions are used to implement the methods of the interface.
* @param clasz The <code>Class</code> object of the interface to return.
*
* @return An instance of requested interface - null if the requested interface is unavailable,
* i. e. if compiled methods in the <code>ScriptEngine</code> cannot be found matching
* the ones in the requested interface.
*
* @throws IllegalArgumentException if the specified <code>Class</code> object
* is null or is not an interface, or if the specified Object is
* null or does not represent a scripting object.
*/
public <T> T getInterface(Object thiz, Class<T> clasz);
}
| Java |
/*
* Copyright (c) 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 javax.script;
import java.util.List;
import java.io.Writer;
import java.io.Reader;
/** {@collect.stats}
* The interface whose implementing classes are used to connect Script Engines
* with objects, such as scoped Bindings, in hosting applications. Each scope is a set
* of named attributes whose values can be set and retrieved using the
* <code>ScriptContext</code> methods. ScriptContexts also expose Readers and Writers
* that can be used by the ScriptEngines for input and output.
*
* @author Mike Grogan
* @since 1.6
*/
public interface ScriptContext {
/** {@collect.stats}
* EngineScope attributes are visible during the lifetime of a single
* <code>ScriptEngine</code> and a set of attributes is maintained for each
* engine.
*/
public static final int ENGINE_SCOPE = 100;
/** {@collect.stats}
* GlobalScope attributes are visible to all engines created by same ScriptEngineFactory.
*/
public static final int GLOBAL_SCOPE = 200;
/** {@collect.stats}
* Associates a <code>Bindings</code> instance with a particular scope in this
* <code>ScriptContext</code>. Calls to the <code>getAttribute</code> and
* <code>setAttribute</code> methods must map to the <code>get</code> and
* <code>put</code> methods of the <code>Bindings</code> for the specified scope.
*
* @param bindings The <code>Bindings</code> to associate with the given scope
* @param scope The scope
*
* @throws IllegalArgumentException If no <code>Bindings</code> is defined for the
* specified scope value in ScriptContexts of this type.
* @throws NullPointerException if value of scope is <code>ENGINE_SCOPE</code> and
* the specified <code>Bindings</code> is null.
*
*/
public void setBindings(Bindings bindings, int scope);
/** {@collect.stats}
* Gets the <code>Bindings</code> associated with the given scope in this
* <code>ScriptContext</code>.
*
* @return The associated <code>Bindings</code>. Returns <code>null</code> if it has not
* been set.
*
* @throws IllegalArgumentException If no <code>Bindings</code> is defined for the
* specified scope value in <code>ScriptContext</code> of this type.
*/
public Bindings getBindings(int scope);
/** {@collect.stats}
* Sets the value of an attribute in a given scope.
*
* @param name The name of the attribute to set
* @param value The value of the attribute
* @param scope The scope in which to set the attribute
*
* @throws IllegalArgumentException
* if the name is empty or if the scope is invalid.
* @throws NullPointerException if the name is null.
*/
public void setAttribute(String name, Object value, int scope);
/** {@collect.stats}
* Gets the value of an attribute in a given scope.
*
* @param name The name of the attribute to retrieve.
* @param scope The scope in which to retrieve the attribute.
* @return The value of the attribute. Returns <code>null</code> is the name
* does not exist in the given scope.
*
* @throws IllegalArgumentException
* if the name is empty or if the value of scope is invalid.
* @throws NullPointerException if the name is null.
*/
public Object getAttribute(String name, int scope);
/** {@collect.stats}
* Remove an attribute in a given scope.
*
* @param name The name of the attribute to remove
* @param scope The scope in which to remove the attribute
*
* @return The removed value.
* @throws IllegalArgumentException
* if the name is empty or if the scope is invalid.
* @throws NullPointerException if the name is null.
*/
public Object removeAttribute(String name, int scope);
/** {@collect.stats}
* Retrieves the value of the attribute with the given name in
* the scope occurring earliest in the search order. The order
* is determined by the numeric value of the scope parameter (lowest
* scope values first.)
*
* @param name The name of the the attribute to retrieve.
* @return The value of the attribute in the lowest scope for
* which an attribute with the given name is defined. Returns
* null if no attribute with the name exists in any scope.
* @throws NullPointerException if the name is null.
* @throws IllegalArgumentException if the name is empty.
*/
public Object getAttribute(String name);
/** {@collect.stats}
* Get the lowest scope in which an attribute is defined.
* @param name Name of the attribute
* .
* @return The lowest scope. Returns -1 if no attribute with the given
* name is defined in any scope.
* @throws NullPointerException if name is null.
* @throws IllegalArgumentException if name is empty.
*/
public int getAttributesScope(String name);
/** {@collect.stats}
* Returns the <code>Writer</code> for scripts to use when displaying output.
*
* @return The <code>Writer</code>.
*/
public Writer getWriter();
/** {@collect.stats}
* Returns the <code>Writer</code> used to display error output.
*
* @return The <code>Writer</code>
*/
public Writer getErrorWriter();
/** {@collect.stats}
* Sets the <code>Writer</code> for scripts to use when displaying output.
*
* @param writer The new <code>Writer</code>.
*/
public void setWriter(Writer writer);
/** {@collect.stats}
* Sets the <code>Writer</code> used to display error output.
*
* @param writer The <code>Writer</code>.
*/
public void setErrorWriter(Writer writer);
/** {@collect.stats}
* Returns a <code>Reader</code> to be used by the script to read
* input.
*
* @return The <code>Reader</code>.
*/
public Reader getReader();
/** {@collect.stats}
* Sets the <code>Reader</code> for scripts to read input
* .
* @param reader The new <code>Reader</code>.
*/
public void setReader(Reader reader);
/** {@collect.stats}
* Returns immutable <code>List</code> of all the valid values for
* scope in the ScriptContext.
*
* @return list of scope values
*/
public List<Integer> getScopes();
}
| 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 javax.script;
import java.io.Reader;
import java.util.Map;
import java.util.Iterator;
/** {@collect.stats}
* Provides a standard implementation for several of the variants of the <code>eval</code>
* method.
* <br><br>
* <code><b>eval(Reader)</b></code><p><code><b>eval(String)</b></code><p>
* <code><b>eval(String, Bindings)</b></code><p><code><b>eval(Reader, Bindings)</b></code>
* <br><br> are implemented using the abstract methods
* <br><br>
* <code><b>eval(Reader,ScriptContext)</b></code> or
* <code><b>eval(String, ScriptContext)</b></code>
* <br><br>
* with a <code>SimpleScriptContext</code>.
* <br><br>
* A <code>SimpleScriptContext</code> is used as the default <code>ScriptContext</code>
* of the <code>AbstractScriptEngine</code>..
*
* @author Mike Grogan
* @since 1.6
*/
public abstract class AbstractScriptEngine implements ScriptEngine {
/** {@collect.stats}
* The default <code>ScriptContext</code> of this <code>AbstractScriptEngine</code>.
*/
protected ScriptContext context;
/** {@collect.stats}
* Creates a new instance of AbstractScriptEngine using a <code>SimpleScriptContext</code>
* as its default <code>ScriptContext</code>.
*/
public AbstractScriptEngine() {
context = new SimpleScriptContext();
}
/** {@collect.stats}
* Creates a new instance using the specified <code>Bindings</code> as the
* <code>ENGINE_SCOPE</code> <code>Bindings</code> in the protected <code>context</code> field.
*
* @param n The specified <code>Bindings</code>.
* @throws NullPointerException if n is null.
*/
public AbstractScriptEngine(Bindings n) {
this();
if (n == null) {
throw new NullPointerException("n is null");
}
context.setBindings(n, ScriptContext.ENGINE_SCOPE);
}
/** {@collect.stats}
* Sets the value of the protected <code>context</code> field to the specified
* <code>ScriptContext</code>.
*
* @param ctxt The specified <code>ScriptContext</code>.
* @throws NullPointerException if ctxt is null.
*/
public void setContext(ScriptContext ctxt) {
if (ctxt == null) {
throw new NullPointerException("null context");
}
context = ctxt;
}
/** {@collect.stats}
* Returns the value of the protected <code>context</code> field.
*
* @return The value of the protected <code>context</code> field.
*/
public ScriptContext getContext() {
return context;
}
/** {@collect.stats}
* Returns the <code>Bindings</code> with the specified scope value in
* the protected <code>context</code> field.
*
* @param scope The specified scope
*
* @return The corresponding <code>Bindings</code>.
*
* @throws IllegalArgumentException if the value of scope is
* invalid for the type the protected <code>context</code> field.
*/
public Bindings getBindings(int scope) {
if (scope == ScriptContext.GLOBAL_SCOPE) {
return context.getBindings(ScriptContext.GLOBAL_SCOPE);
} else if (scope == ScriptContext.ENGINE_SCOPE) {
return context.getBindings(ScriptContext.ENGINE_SCOPE);
} else {
throw new IllegalArgumentException("Invalid scope value.");
}
}
/** {@collect.stats}
* Sets the <code>Bindings</code> with the corresponding scope value in the
* <code>context</code> field.
*
* @param bindings The specified <code>Bindings</code>.
* @param scope The specified scope.
*
* @throws IllegalArgumentException if the value of scope is
* invalid for the type the <code>context</code> field.
* @throws NullPointerException if the bindings is null and the scope is
* <code>ScriptContext.ENGINE_SCOPE</code>
*/
public void setBindings(Bindings bindings, int scope) {
if (scope == ScriptContext.GLOBAL_SCOPE) {
context.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);;
} else if (scope == ScriptContext.ENGINE_SCOPE) {
context.setBindings(bindings, ScriptContext.ENGINE_SCOPE);;
} else {
throw new IllegalArgumentException("Invalid scope value.");
}
}
/** {@collect.stats}
* Sets the specified value with the specified key in the <code>ENGINE_SCOPE</code>
* <code>Bindings</code> of the protected <code>context</code> field.
*
* @param key The specified key.
* @param value The specified value.
*
* @throws NullPointerException if key is null.
* @throws IllegalArgumentException if key is empty.
*/
public void put(String key, Object value) {
Bindings nn = getBindings(ScriptContext.ENGINE_SCOPE);
if (nn != null) {
nn.put(key, value);
}
}
/** {@collect.stats}
* Gets the value for the specified key in the <code>ENGINE_SCOPE</code> of the
* protected <code>context</code> field.
*
* @return The value for the specified key.
*
* @throws NullPointerException if key is null.
* @throws IllegalArgumentException if key is empty.
*/
public Object get(String key) {
Bindings nn = getBindings(ScriptContext.ENGINE_SCOPE);
if (nn != null) {
return nn.get(key);
}
return null;
}
/** {@collect.stats}
* <code>eval(Reader, Bindings)</code> calls the abstract
* <code>eval(Reader, ScriptContext)</code> method, passing it a <code>ScriptContext</code>
* whose Reader, Writers and Bindings for scopes other that <code>ENGINE_SCOPE</code>
* are identical to those members of the protected <code>context</code> field. The specified
* <code>Bindings</code> is used instead of the <code>ENGINE_SCOPE</code>
*
* <code>Bindings</code> of the <code>context</code> field.
*
* @param reader A <code>Reader</code> containing the source of the script.
* @param bindings A <code>Bindings</code> to use for the <code>ENGINE_SCOPE</code>
* while the script executes.
*
* @return The return value from <code>eval(Reader, ScriptContext)</code>
* @throws ScriptException if an error occurs in script.
* @throws NullPointerException if any of the parameters is null.
*/
public Object eval(Reader reader, Bindings bindings ) throws ScriptException {
ScriptContext ctxt = getScriptContext(bindings);
return eval(reader, ctxt);
}
/** {@collect.stats}
* Same as <code>eval(Reader, Bindings)</code> except that the abstract
* <code>eval(String, ScriptContext)</code> is used.
*
* @param script A <code>String</code> containing the source of the script.
*
* @param bindings A <code>Bindings</code> to use as the <code>ENGINE_SCOPE</code>
* while the script executes.
*
* @return The return value from <code>eval(String, ScriptContext)</code>
* @throws ScriptException if an error occurs in script.
* @throws NullPointerException if any of the parameters is null.
*/
public Object eval(String script, Bindings bindings) throws ScriptException {
ScriptContext ctxt = getScriptContext(bindings);
return eval(script , ctxt);
}
/** {@collect.stats}
* <code>eval(Reader)</code> calls the abstract
* <code>eval(Reader, ScriptContext)</code> passing the value of the <code>context</code>
* field.
*
* @param reader A <code>Reader</code> containing the source of the script.
* @return The return value from <code>eval(Reader, ScriptContext)</code>
* @throws ScriptException if an error occurs in script.
* @throws NullPointerException if any of the parameters is null.
*/
public Object eval(Reader reader) throws ScriptException {
return eval(reader, context);
}
/** {@collect.stats}
* Same as <code>eval(Reader)</code> except that the abstract
* <code>eval(String, ScriptContext)</code> is used.
*
* @param script A <code>String</code> containing the source of the script.
* @return The return value from <code>eval(String, ScriptContext)</code>
* @throws ScriptException if an error occurrs in script.
* @throws NullPointerException if any of the parameters is null.
*/
public Object eval(String script) throws ScriptException {
return eval(script, context);
}
/** {@collect.stats}
* Returns a <code>SimpleScriptContext</code>. The <code>SimpleScriptContext</code>:
*<br><br>
* <ul>
* <li>Uses the specified <code>Bindings</code> for its <code>ENGINE_SCOPE</code>
* </li>
* <li>Uses the <code>Bindings</code> returned by the abstract <code>getGlobalScope</code>
* method as its <code>GLOBAL_SCOPE</code>
* </li>
* <li>Uses the Reader and Writer in the default <code>ScriptContext</code> of this
* <code>ScriptEngine</code>
* </li>
* </ul>
* <br><br>
* A <code>SimpleScriptContext</code> returned by this method is used to implement eval methods
* using the abstract <code>eval(Reader,Bindings)</code> and <code>eval(String,Bindings)</code>
* versions.
*
* @param nn Bindings to use for the <code>ENGINE_SCOPE</code>
* @return The <code>SimpleScriptContext</code>
*/
protected ScriptContext getScriptContext(Bindings nn) {
SimpleScriptContext ctxt = new SimpleScriptContext();
Bindings gs = getBindings(ScriptContext.GLOBAL_SCOPE);
if (gs != null) {
ctxt.setBindings(gs, ScriptContext.GLOBAL_SCOPE);
}
if (nn != null) {
ctxt.setBindings(nn,
ScriptContext.ENGINE_SCOPE);
} else {
throw new NullPointerException("Engine scope Bindings may not be null.");
}
ctxt.setReader(context.getReader());
ctxt.setWriter(context.getWriter());
ctxt.setErrorWriter(context.getErrorWriter());
return ctxt;
}
}
| 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 javax.script;
import java.util.*;
import java.net.URL;
import java.io.*;
import java.security.*;
import sun.misc.Service;
import sun.misc.ServiceConfigurationError;
import sun.reflect.Reflection;
import sun.security.util.SecurityConstants;
/** {@collect.stats}
* The <code>ScriptEngineManager</code> implements a discovery and instantiation
* mechanism for <code>ScriptEngine</code> classes and also maintains a
* collection of key/value pairs storing state shared by all engines created
* by the Manager. This class uses the <a href="../../../technotes/guides/jar/jar.html#Service%20Provider">service provider</a> mechanism to enumerate all the
* implementations of <code>ScriptEngineFactory</code>. <br><br>
* The <code>ScriptEngineManager</code> provides a method to return an array of all these factories
* as well as utility methods which look up factories on the basis of language name, file extension
* and mime type.
* <p>
* The <code>Bindings</code> of key/value pairs, referred to as the "Global Scope" maintained
* by the manager is available to all instances of <code>ScriptEngine</code> created
* by the <code>ScriptEngineManager</code>. The values in the <code>Bindings</code> are
* generally exposed in all scripts.
*
* @author Mike Grogan
* @author A. Sundararajan
* @since 1.6
*/
public class ScriptEngineManager {
private static final boolean DEBUG = false;
/** {@collect.stats}
* If the thread context ClassLoader can be accessed by the caller,
* then the effect of calling this constructor is the same as calling
* <code>ScriptEngineManager(Thread.currentThread().getContextClassLoader())</code>.
* Otherwise, the effect is the same as calling <code>ScriptEngineManager(null)</code>.
*
* @see java.lang.Thread#getContextClassLoader
*/
public ScriptEngineManager() {
ClassLoader ctxtLoader = Thread.currentThread().getContextClassLoader();
if (canCallerAccessLoader(ctxtLoader)) {
if (DEBUG) System.out.println("using " + ctxtLoader);
init(ctxtLoader);
} else {
if (DEBUG) System.out.println("using bootstrap loader");
init(null);
}
}
/** {@collect.stats}
* This constructor loads the implementations of
* <code>ScriptEngineFactory</code> visible to the given
* <code>ClassLoader</code> using the <a href="../../../technotes/guides/jar/jar.html#Service%20Provider">service provider</a> mechanism.<br><br>
* If loader is <code>null</code>, the script engine factories that are
* bundled with the platform and that are in the usual extension
* directories (installed extensions) are loaded. <br><br>
*
* @param loader ClassLoader used to discover script engine factories.
*/
public ScriptEngineManager(ClassLoader loader) {
init(loader);
}
private void init(final ClassLoader loader) {
globalScope = new SimpleBindings();
engineSpis = new HashSet<ScriptEngineFactory>();
nameAssociations = new HashMap<String, ScriptEngineFactory>();
extensionAssociations = new HashMap<String, ScriptEngineFactory>();
mimeTypeAssociations = new HashMap<String, ScriptEngineFactory>();
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
initEngines(loader);
return null;
}
});
}
private void initEngines(final ClassLoader loader) {
Iterator itr = null;
try {
if (loader != null) {
itr = Service.providers(ScriptEngineFactory.class, loader);
} else {
itr = Service.installedProviders(ScriptEngineFactory.class);
}
} catch (ServiceConfigurationError err) {
System.err.println("Can't find ScriptEngineFactory providers: " +
err.getMessage());
if (DEBUG) {
err.printStackTrace();
}
// do not throw any exception here. user may want to
// manage his/her own factories using this manager
// by explicit registratation (by registerXXX) methods.
return;
}
try {
while (itr.hasNext()) {
try {
ScriptEngineFactory fact = (ScriptEngineFactory) itr.next();
engineSpis.add(fact);
} catch (ServiceConfigurationError err) {
System.err.println("ScriptEngineManager providers.next(): "
+ err.getMessage());
if (DEBUG) {
err.printStackTrace();
}
// one factory failed, but check other factories...
continue;
}
}
} catch (ServiceConfigurationError err) {
System.err.println("ScriptEngineManager providers.hasNext(): "
+ err.getMessage());
if (DEBUG) {
err.printStackTrace();
}
// do not throw any exception here. user may want to
// manage his/her own factories using this manager
// by explicit registratation (by registerXXX) methods.
return;
}
}
/** {@collect.stats}
* <code>setBindings</code> stores the specified <code>Bindings</code>
* in the <code>globalScope</code> field. ScriptEngineManager sets this
* <code>Bindings</code> as global bindings for <code>ScriptEngine</code>
* objects created by it.
*
* @param bindings The specified <code>Bindings</code>
* @throws IllegalArgumentException if bindings is null.
*/
public void setBindings(Bindings bindings) {
if (bindings == null) {
throw new IllegalArgumentException("Global scope cannot be null.");
}
globalScope = bindings;
}
/** {@collect.stats}
* <code>getBindings</code> returns the value of the <code>globalScope</code> field.
* ScriptEngineManager sets this <code>Bindings</code> as global bindings for
* <code>ScriptEngine</code> objects created by it.
*
* @return The globalScope field.
*/
public Bindings getBindings() {
return globalScope;
}
/** {@collect.stats}
* Sets the specified key/value pair in the Global Scope.
* @param key Key to set
* @param value Value to set.
* @throws NullPointerException if key is null.
* @throws IllegalArgumentException if key is empty string.
*/
public void put(String key, Object value) {
globalScope.put(key, value);
}
/** {@collect.stats}
* Gets the value for the specified key in the Global Scope
* @param key The key whose value is to be returned.
* @return The value for the specified key.
*/
public Object get(String key) {
return globalScope.get(key);
}
/** {@collect.stats}
* Looks up and creates a <code>ScriptEngine</code> for a given name.
* The algorithm first searches for a <code>ScriptEngineFactory</code> that has been
* registered as a handler for the specified name using the <code>registerEngineName</code>
* method.
* <br><br> If one is not found, it searches the array of <code>ScriptEngineFactory</code> instances
* stored by the constructor for one with the specified name. If a <code>ScriptEngineFactory</code>
* is found by either method, it is used to create instance of <code>ScriptEngine</code>.
* @param shortName The short name of the <code>ScriptEngine</code> implementation.
* returned by the <code>getNames</code> method of its <code>ScriptEngineFactory</code>.
* @return A <code>ScriptEngine</code> created by the factory located in the search. Returns null
* if no such factory was found. The <code>ScriptEngineManager</code> sets its own <code>globalScope</code>
* <code>Bindings</code> as the <code>GLOBAL_SCOPE</code> <code>Bindings</code> of the newly
* created <code>ScriptEngine</code>.
* @throws NullPointerException if shortName is null.
*/
public ScriptEngine getEngineByName(String shortName) {
if (shortName == null) throw new NullPointerException();
//look for registered name first
Object obj;
if (null != (obj = nameAssociations.get(shortName))) {
ScriptEngineFactory spi = (ScriptEngineFactory)obj;
try {
ScriptEngine engine = spi.getScriptEngine();
engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);
return engine;
} catch (Exception exp) {
if (DEBUG) exp.printStackTrace();
}
}
for (ScriptEngineFactory spi : engineSpis) {
List<String> names = null;
try {
names = spi.getNames();
} catch (Exception exp) {
if (DEBUG) exp.printStackTrace();
}
if (names != null) {
for (String name : names) {
if (shortName.equals(name)) {
try {
ScriptEngine engine = spi.getScriptEngine();
engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);
return engine;
} catch (Exception exp) {
if (DEBUG) exp.printStackTrace();
}
}
}
}
}
return null;
}
/** {@collect.stats}
* Look up and create a <code>ScriptEngine</code> for a given extension. The algorithm
* used by <code>getEngineByName</code> is used except that the search starts
* by looking for a <code>ScriptEngineFactory</code> registered to handle the
* given extension using <code>registerEngineExtension</code>.
* @param extension The given extension
* @return The engine to handle scripts with this extension. Returns <code>null</code>
* if not found.
* @throws NullPointerException if extension is null.
*/
public ScriptEngine getEngineByExtension(String extension) {
if (extension == null) throw new NullPointerException();
//look for registered extension first
Object obj;
if (null != (obj = extensionAssociations.get(extension))) {
ScriptEngineFactory spi = (ScriptEngineFactory)obj;
try {
ScriptEngine engine = spi.getScriptEngine();
engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);
return engine;
} catch (Exception exp) {
if (DEBUG) exp.printStackTrace();
}
}
for (ScriptEngineFactory spi : engineSpis) {
List<String> exts = null;
try {
exts = spi.getExtensions();
} catch (Exception exp) {
if (DEBUG) exp.printStackTrace();
}
if (exts == null) continue;
for (String ext : exts) {
if (extension.equals(ext)) {
try {
ScriptEngine engine = spi.getScriptEngine();
engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);
return engine;
} catch (Exception exp) {
if (DEBUG) exp.printStackTrace();
}
}
}
}
return null;
}
/** {@collect.stats}
* Look up and create a <code>ScriptEngine</code> for a given mime type. The algorithm
* used by <code>getEngineByName</code> is used except that the search starts
* by looking for a <code>ScriptEngineFactory</code> registered to handle the
* given mime type using <code>registerEngineMimeType</code>.
* @param mimeType The given mime type
* @return The engine to handle scripts with this mime type. Returns <code>null</code>
* if not found.
* @throws NullPointerException if mimeType is null.
*/
public ScriptEngine getEngineByMimeType(String mimeType) {
if (mimeType == null) throw new NullPointerException();
//look for registered types first
Object obj;
if (null != (obj = mimeTypeAssociations.get(mimeType))) {
ScriptEngineFactory spi = (ScriptEngineFactory)obj;
try {
ScriptEngine engine = spi.getScriptEngine();
engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);
return engine;
} catch (Exception exp) {
if (DEBUG) exp.printStackTrace();
}
}
for (ScriptEngineFactory spi : engineSpis) {
List<String> types = null;
try {
types = spi.getMimeTypes();
} catch (Exception exp) {
if (DEBUG) exp.printStackTrace();
}
if (types == null) continue;
for (String type : types) {
if (mimeType.equals(type)) {
try {
ScriptEngine engine = spi.getScriptEngine();
engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);
return engine;
} catch (Exception exp) {
if (DEBUG) exp.printStackTrace();
}
}
}
}
return null;
}
/** {@collect.stats}
* Returns an array whose elements are instances of all the <code>ScriptEngineFactory</code> classes
* found by the discovery mechanism.
* @return List of all discovered <code>ScriptEngineFactory</code>s.
*/
public List<ScriptEngineFactory> getEngineFactories() {
List<ScriptEngineFactory> res = new ArrayList<ScriptEngineFactory>(engineSpis.size());
for (ScriptEngineFactory spi : engineSpis) {
res.add(spi);
}
return Collections.unmodifiableList(res);
}
/** {@collect.stats}
* Registers a <code>ScriptEngineFactory</code> to handle a language
* name. Overrides any such association found using the Discovery mechanism.
* @param name The name to be associated with the <code>ScriptEngineFactory</code>.
* @param factory The class to associate with the given name.
* @throws NullPointerException if any of the parameters is null.
*/
public void registerEngineName(String name, ScriptEngineFactory factory) {
if (name == null || factory == null) throw new NullPointerException();
nameAssociations.put(name, factory);
}
/** {@collect.stats}
* Registers a <code>ScriptEngineFactory</code> to handle a mime type.
* Overrides any such association found using the Discovery mechanism.
*
* @param type The mime type to be associated with the
* <code>ScriptEngineFactory</code>.
*
* @param factory The class to associate with the given mime type.
* @throws NullPointerException if any of the parameters is null.
*/
public void registerEngineMimeType(String type, ScriptEngineFactory factory) {
if (type == null || factory == null) throw new NullPointerException();
mimeTypeAssociations.put(type, factory);
}
/** {@collect.stats}
* Registers a <code>ScriptEngineFactory</code> to handle an extension.
* Overrides any such association found using the Discovery mechanism.
*
* @param extension The extension type to be associated with the
* <code>ScriptEngineFactory</code>.
* @param factory The class to associate with the given extension.
* @throws NullPointerException if any of the parameters is null.
*/
public void registerEngineExtension(String extension, ScriptEngineFactory factory) {
if (extension == null || factory == null) throw new NullPointerException();
extensionAssociations.put(extension, factory);
}
/** {@collect.stats} Set of script engine factories discovered. */
private HashSet<ScriptEngineFactory> engineSpis;
/** {@collect.stats} Map of engine name to script engine factory. */
private HashMap<String, ScriptEngineFactory> nameAssociations;
/** {@collect.stats} Map of script file extension to script engine factory. */
private HashMap<String, ScriptEngineFactory> extensionAssociations;
/** {@collect.stats} Map of script script MIME type to script engine factory. */
private HashMap<String, ScriptEngineFactory> mimeTypeAssociations;
/** {@collect.stats} Global bindings associated with script engines created by this manager. */
private Bindings globalScope;
private boolean canCallerAccessLoader(ClassLoader loader) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
ClassLoader callerLoader = getCallerClassLoader();
if (callerLoader != null) {
if (loader != callerLoader || !isAncestor(loader, callerLoader)) {
try {
sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
} catch (SecurityException exp) {
if (DEBUG) exp.printStackTrace();
return false;
}
} // else fallthru..
} // else fallthru..
} // else fallthru..
return true;
}
// Note that this code is same as ClassLoader.getCallerClassLoader().
// But, that method is package private and hence we can't call here.
private ClassLoader getCallerClassLoader() {
Class caller = Reflection.getCallerClass(3);
if (caller == null) {
return null;
}
return caller.getClassLoader();
}
// is cl1 ancestor of cl2?
private boolean isAncestor(ClassLoader cl1, ClassLoader cl2) {
do {
cl2 = cl2.getParent();
if (cl1 == cl2) return true;
} while (cl2 != null);
return false;
}
}
| Java |
/*
* Copyright (c) 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 javax.script;
import java.util.Map;
import java.io.Reader;
/** {@collect.stats}
* The optional interface implemented by ScriptEngines whose methods compile scripts
* to a form that can be executed repeatedly without recompilation.
*
* @author Mike Grogan
* @since 1.6
*/
public interface Compilable {
/** {@collect.stats}
* Compiles the script (source represented as a <code>String</code>) for
* later execution.
*
* @param script The source of the script, represented as a <code>String</code>.
*
* @return An subclass of <code>CompiledScript</code> to be executed later using one
* of the <code>eval</code> methods of <code>CompiledScript</code>.
*
* @throws ScriptException if compilation fails.
* @throws NullPointerException if the argument is null.
*
*/
public CompiledScript compile(String script) throws
ScriptException;
/** {@collect.stats}
* Compiles the script (source read from <code>Reader</code>) for
* later execution. Functionality is identical to
* <code>compile(String)</code> other than the way in which the source is
* passed.
*
* @param script The reader from which the script source is obtained.
*
* @return An implementation of <code>CompiledScript</code> to be executed
* later using one of its <code>eval</code> methods of <code>CompiledScript</code>.
*
* @throws ScriptException if compilation fails.
* @throws NullPointerException if argument is null.
*/
public CompiledScript compile(Reader script) throws
ScriptException;
}
| 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 javax.script;
import java.util.Map;
/** {@collect.stats}
* A mapping of key/value pairs, all of whose keys are
* <code>Strings</code>.
*
* @author Mike Grogan
* @since 1.6
*/
public interface Bindings extends Map<String, Object> {
/** {@collect.stats}
* Set a named value.
*
* @param name The name associated with the value.
* @param value The value associated with the name.
*
* @return The value previously associated with the given name.
* Returns null if no value was previously associated with the name.
*
* @throws NullPointerException if the name is null.
* @throws IllegalArgumentException if the name is empty String.
*/
public Object put(String name, Object value);
/** {@collect.stats}
* Adds all the mappings in a given <code>Map</code> to this <code>Bindings</code>.
* @param toMerge The <code>Map</code> to merge with this one.
*
* @throws NullPointerException
* if toMerge map is null or if some key in the map is null.
* @throws IllegalArgumentException
* if some key in the map is an empty String.
*/
public void putAll(Map<? extends String, ? extends Object> toMerge);
/** {@collect.stats}
* Returns <tt>true</tt> if this map contains a mapping for the specified
* key. More formally, returns <tt>true</tt> if and only if
* this map contains a mapping for a key <tt>k</tt> such that
* <tt>(key==null ? k==null : key.equals(k))</tt>. (There can be
* at most one such mapping.)
*
* @param key key whose presence in this map is to be tested.
* @return <tt>true</tt> if this map contains a mapping for the specified
* key.
*
* @throws NullPointerException if key is null
* @throws ClassCastException if key is not String
* @throws IllegalArgumentException if key is empty String
*/
public boolean containsKey(Object key);
/** {@collect.stats}
* Returns the value to which this map maps the specified key. Returns
* <tt>null</tt> if the map contains no mapping for this key. A return
* value of <tt>null</tt> does not <i>necessarily</i> indicate that the
* map contains no mapping for the key; it's also possible that the map
* explicitly maps the key to <tt>null</tt>. The <tt>containsKey</tt>
* operation may be used to distinguish these two cases.
*
* <p>More formally, if this map contains a mapping from a key
* <tt>k</tt> to a value <tt>v</tt> such that <tt>(key==null ? k==null :
* key.equals(k))</tt>, then this method returns <tt>v</tt>; otherwise
* it returns <tt>null</tt>. (There can be at most one such mapping.)
*
* @param key key whose associated value is to be returned.
* @return the value to which this map maps the specified key, or
* <tt>null</tt> if the map contains no mapping for this key.
*
* @throws NullPointerException if key is null
* @throws ClassCastException if key is not String
* @throws IllegalArgumentException if key is empty String
*/
public Object get(Object key);
/** {@collect.stats}
* Removes the mapping for this key from this map if it is present
* (optional operation). More formally, if this map contains a mapping
* from key <tt>k</tt> to value <tt>v</tt> such that
* <code>(key==null ? k==null : key.equals(k))</code>, that mapping
* is removed. (The map can contain at most one such mapping.)
*
* <p>Returns the value to which the map previously associated the key, or
* <tt>null</tt> if the map contained no mapping for this key. (A
* <tt>null</tt> return can also indicate that the map previously
* associated <tt>null</tt> with the specified key if the implementation
* supports <tt>null</tt> values.) The map will not contain a mapping for
* the specified key once the call returns.
*
* @param key key whose mapping is to be removed from the map.
* @return previous value associated with specified key, or <tt>null</tt>
* if there was no mapping for key.
*
* @throws NullPointerException if key is null
* @throws ClassCastException if key is not String
* @throws IllegalArgumentException if key is empty String
*/
public Object remove(Object key);
}
| 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 javax.script;
import java.util.*;
import java.io.*;
/** {@collect.stats}
* Simple implementation of ScriptContext.
*
* @author Mike Grogan
* @since 1.6
*/
public class SimpleScriptContext implements ScriptContext {
/** {@collect.stats}
* This is the writer to be used to output from scripts.
* By default, a <code>PrintWriter</code> based on <code>System.out</code>
* is used. Accessor methods getWriter, setWriter are used to manage
* this field.
* @see java.lang.System#out
* @see java.io.PrintWriter
*/
protected Writer writer;
/** {@collect.stats}
* This is the writer to be used to output errors from scripts.
* By default, a <code>PrintWriter</code> based on <code>System.err</code> is
* used. Accessor methods getErrorWriter, setErrorWriter are used to manage
* this field.
* @see java.lang.System#err
* @see java.io.PrintWriter
*/
protected Writer errorWriter;
/** {@collect.stats}
* This is the reader to be used for input from scripts.
* By default, a <code>InputStreamReader</code> based on <code>System.in</code>
* is used and default charset is used by this reader. Accessor methods
* getReader, setReader are used to manage this field.
* @see java.lang.System#in
* @see java.io.InputStreamReader
*/
protected Reader reader;
/** {@collect.stats}
* This is the engine scope bindings.
* By default, a <code>SimpleBindings</code> is used. Accessor
* methods setBindings, getBindings are used to manage this field.
* @see SimpleBindings
*/
protected Bindings engineScope;
/** {@collect.stats}
* This is the global scope bindings.
* By default, a null value (which means no global scope) is used. Accessor
* methods setBindings, getBindings are used to manage this field.
*/
protected Bindings globalScope;
public SimpleScriptContext() {
engineScope = new SimpleBindings();
globalScope = null;
reader = new InputStreamReader(System.in);
writer = new PrintWriter(System.out , true);
errorWriter = new PrintWriter(System.err, true);
}
/** {@collect.stats}
* Sets a <code>Bindings</code> of attributes for the given scope. If the value
* of scope is <code>ENGINE_SCOPE</code> the given <code>Bindings</code> replaces the
* <code>engineScope</code> field. If the value
* of scope is <code>GLOBAL_SCOPE</code> the given <code>Bindings</code> replaces the
* <code>globalScope</code> field.
*
* @param bindings The <code>Bindings</code> of attributes to set.
* @param scope The value of the scope in which the attributes are set.
*
* @throws IllegalArgumentException if scope is invalid.
* @throws NullPointerException if the value of scope is <code>ENGINE_SCOPE</code> and
* the specified <code>Bindings</code> is null.
*/
public void setBindings(Bindings bindings, int scope) {
switch (scope) {
case ENGINE_SCOPE:
if (bindings == null) {
throw new NullPointerException("Engine scope cannot be null.");
}
engineScope = bindings;
break;
case GLOBAL_SCOPE:
globalScope = bindings;
break;
default:
throw new IllegalArgumentException("Invalid scope value.");
}
}
/** {@collect.stats}
* Retrieves the value of the attribute with the given name in
* the scope occurring earliest in the search order. The order
* is determined by the numeric value of the scope parameter (lowest
* scope values first.)
*
* @param name The name of the the attribute to retrieve.
* @return The value of the attribute in the lowest scope for
* which an attribute with the given name is defined. Returns
* null if no attribute with the name exists in any scope.
* @throws NullPointerException if the name is null.
* @throws IllegalArgumentException if the name is empty.
*/
public Object getAttribute(String name) {
if (engineScope.containsKey(name)) {
return getAttribute(name, ENGINE_SCOPE);
} else if (globalScope != null && globalScope.containsKey(name)) {
return getAttribute(name, GLOBAL_SCOPE);
}
return null;
}
/** {@collect.stats}
* Gets the value of an attribute in a given scope.
*
* @param name The name of the attribute to retrieve.
* @param scope The scope in which to retrieve the attribute.
* @return The value of the attribute. Returns <code>null</code> is the name
* does not exist in the given scope.
*
* @throws IllegalArgumentException
* if the name is empty or if the value of scope is invalid.
* @throws NullPointerException if the name is null.
*/
public Object getAttribute(String name, int scope) {
switch (scope) {
case ENGINE_SCOPE:
return engineScope.get(name);
case GLOBAL_SCOPE:
if (globalScope != null) {
return globalScope.get(name);
}
return null;
default:
throw new IllegalArgumentException("Illegal scope value.");
}
}
/** {@collect.stats}
* Remove an attribute in a given scope.
*
* @param name The name of the attribute to remove
* @param scope The scope in which to remove the attribute
*
* @return The removed value.
* @throws IllegalArgumentException
* if the name is empty or if the scope is invalid.
* @throws NullPointerException if the name is null.
*/
public Object removeAttribute(String name, int scope) {
switch (scope) {
case ENGINE_SCOPE:
if (getBindings(ENGINE_SCOPE) != null) {
return getBindings(ENGINE_SCOPE).remove(name);
}
return null;
case GLOBAL_SCOPE:
if (getBindings(GLOBAL_SCOPE) != null) {
return getBindings(GLOBAL_SCOPE).remove(name);
}
return null;
default:
throw new IllegalArgumentException("Illegal scope value.");
}
}
/** {@collect.stats}
* Sets the value of an attribute in a given scope.
*
* @param name The name of the attribute to set
* @param value The value of the attribute
* @param scope The scope in which to set the attribute
*
* @throws IllegalArgumentException
* if the name is empty or if the scope is invalid.
* @throws NullPointerException if the name is null.
*/
public void setAttribute(String name, Object value, int scope) {
switch (scope) {
case ENGINE_SCOPE:
engineScope.put(name, value);
return;
case GLOBAL_SCOPE:
if (globalScope != null) {
globalScope.put(name, value);
}
return;
default:
throw new IllegalArgumentException("Illegal scope value.");
}
}
/** {@collect.stats} {@inheritDoc} */
public Writer getWriter() {
return writer;
}
/** {@collect.stats} {@inheritDoc} */
public Reader getReader() {
return reader;
}
/** {@collect.stats} {@inheritDoc} */
public void setReader(Reader reader) {
this.reader = reader;
}
/** {@collect.stats} {@inheritDoc} */
public void setWriter(Writer writer) {
this.writer = writer;
}
/** {@collect.stats} {@inheritDoc} */
public Writer getErrorWriter() {
return errorWriter;
}
/** {@collect.stats} {@inheritDoc} */
public void setErrorWriter(Writer writer) {
this.errorWriter = writer;
}
/** {@collect.stats}
* Get the lowest scope in which an attribute is defined.
* @param name Name of the attribute
* .
* @return The lowest scope. Returns -1 if no attribute with the given
* name is defined in any scope.
* @throws NullPointerException if name is null.
* @throws IllegalArgumentException if name is empty.
*/
public int getAttributesScope(String name) {
if (engineScope.containsKey(name)) {
return ENGINE_SCOPE;
} else if (globalScope != null && globalScope.containsKey(name)) {
return GLOBAL_SCOPE;
} else {
return -1;
}
}
/** {@collect.stats}
* Returns the value of the <code>engineScope</code> field if specified scope is
* <code>ENGINE_SCOPE</code>. Returns the value of the <code>globalScope</code> field if the specified scope is
* <code>GLOBAL_SCOPE</code>.
*
* @param scope The specified scope
* @return The value of either the <code>engineScope</code> or <code>globalScope</code> field.
* @throws IllegalArgumentException if the value of scope is invalid.
*/
public Bindings getBindings(int scope) {
if (scope == ENGINE_SCOPE) {
return engineScope;
} else if (scope == GLOBAL_SCOPE) {
return globalScope;
} else {
throw new IllegalArgumentException("Illegal scope value.");
}
}
/** {@collect.stats} {@inheritDoc} */
public List<Integer> getScopes() {
return scopes;
}
private static List<Integer> scopes;
static {
scopes = new ArrayList<Integer>(2);
scopes.add(ENGINE_SCOPE);
scopes.add(GLOBAL_SCOPE);
scopes = Collections.unmodifiableList(scopes);
}
}
| Java |
/*
* Copyright (c) 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 javax.script;
import java.util.List;
/** {@collect.stats}
* <code>ScriptEngineFactory</code> is used to describe and instantiate
* <code>ScriptEngines</code>.
* <br><br>
* Each class implementing <code>ScriptEngine</code> has a corresponding factory
* that exposes metadata describing the engine class.
* <br><br>The <code>ScriptEngineManager</code>
* uses the service provider mechanism described in the <i>Jar File Specification</i> to obtain
* instances of all <code>ScriptEngineFactories</code> available in
* the current ClassLoader.
*
* @since 1.6
*/
public interface ScriptEngineFactory {
/** {@collect.stats}
* Returns the full name of the <code>ScriptEngine</code>. For
* instance an implementation based on the Mozilla Rhino Javascript engine
* might return <i>Rhino Mozilla Javascript Engine</i>.
* @return The name of the engine implementation.
*/
public String getEngineName();
/** {@collect.stats}
* Returns the version of the <code>ScriptEngine</code>.
* @return The <code>ScriptEngine</code> implementation version.
*/
public String getEngineVersion();
/** {@collect.stats}
* Returns an immutable list of filename extensions, which generally identify scripts
* written in the language supported by this <code>ScriptEngine</code>.
* The array is used by the <code>ScriptEngineManager</code> to implement its
* <code>getEngineByExtension</code> method.
* @return The list of extensions.
*/
public List<String> getExtensions();
/** {@collect.stats}
* Returns an immutable list of mimetypes, associated with scripts that
* can be executed by the engine. The list is used by the
* <code>ScriptEngineManager</code> class to implement its
* <code>getEngineByMimetype</code> method.
* @return The list of mime types.
*/
public List<String> getMimeTypes();
/** {@collect.stats}
* Returns an immutable list of short names for the <code>ScriptEngine</code>, which may be used to
* identify the <code>ScriptEngine</code> by the <code>ScriptEngineManager</code>.
* For instance, an implementation based on the Mozilla Rhino Javascript engine might
* return list containing {"javascript", "rhino"}.
*/
public List<String> getNames();
/** {@collect.stats}
* Returns the name of the scripting langauge supported by this
* <code>ScriptEngine</code>.
* @return The name of the supported language.
*/
public String getLanguageName();
/** {@collect.stats}
* Returns the version of the scripting language supported by this
* <code>ScriptEngine</code>.
* @return The version of the supported language.
*/
public String getLanguageVersion();
/** {@collect.stats}
* Returns the value of an attribute whose meaning may be implementation-specific.
* Keys for which the value is defined in all implementations are:
* <ul>
* <li>ScriptEngine.ENGINE</li>
* <li>ScriptEngine.ENGINE_VERSION</li>
* <li>ScriptEngine.NAME</li>
* <li>ScriptEngine.LANGUAGE</li>
* <li>ScriptEngine.LANGUAGE_VERSION</li>
* </ul>
* <p>
* The values for these keys are the Strings returned by <code>getEngineName</code>,
* <code>getEngineVersion</code>, <code>getName</code>, <code>getLanguageName</code> and
* <code>getLanguageVersion</code> respectively.<br><br>
* A reserved key, <code><b>THREADING</b></code>, whose value describes the behavior of the engine
* with respect to concurrent execution of scripts and maintenance of state is also defined.
* These values for the <code><b>THREADING</b></code> key are:<br><br>
* <ul>
* <p><code>null</code> - The engine implementation is not thread safe, and cannot
* be used to execute scripts concurrently on multiple threads.
* <p><code>"MULTITHREADED"</code> - The engine implementation is internally
* thread-safe and scripts may execute concurrently although effects of script execution
* on one thread may be visible to scripts on other threads.
* <p><code>"THREAD-ISOLATED"</code> - The implementation satisfies the requirements
* of "MULTITHREADED", and also, the engine maintains independent values
* for symbols in scripts executing on different threads.
* <p><code>"STATELESS"</code> - The implementation satisfies the requirements of
* <code>"THREAD-ISOLATED"</code>. In addition, script executions do not alter the
* mappings in the <code>Bindings</code> which is the engine scope of the
* <code>ScriptEngine</code>. In particular, the keys in the <code>Bindings</code>
* and their associated values are the same before and after the execution of the script.
* </li>
* </ul>
* <br><br>
* Implementations may define implementation-specific keys.
*
* @param key The name of the parameter
* @return The value for the given parameter. Returns <code>null</code> if no
* value is assigned to the key.
*
*/
public Object getParameter(String key);
/** {@collect.stats}
* Returns a String which can be used to invoke a method of a Java object using the syntax
* of the supported scripting language. For instance, an implementaton for a Javascript
* engine might be;
* <p>
* <code><pre>
* public String getMethodCallSyntax(String obj,
* String m, String... args) {
* String ret = obj;
* ret += "." + m + "(";
* for (int i = 0; i < args.length; i++) {
* ret += args[i];
* if (i == args.length - 1) {
* ret += ")";
* } else {
* ret += ",";
* }
* }
* return ret;
* }
*</pre></code>
* <p>
*
* @param obj The name representing the object whose method is to be invoked. The
* name is the one used to create bindings using the <code>put</code> method of
* <code>ScriptEngine</code>, the <code>put</code> method of an <code>ENGINE_SCOPE</code>
* <code>Bindings</code>,or the <code>setAttribute</code> method
* of <code>ScriptContext</code>. The identifier used in scripts may be a decorated form of the
* specified one.
*
* @param m The name of the method to invoke.
* @param args names of the arguments in the method call.
*
* @return The String used to invoke the method in the syntax of the scripting language.
*/
public String getMethodCallSyntax(String obj, String m, String... args);
/** {@collect.stats}
* Returns a String that can be used as a statement to display the specified String using
* the syntax of the supported scripting language. For instance, the implementaton for a Perl
* engine might be;
* <p>
* <pre><code>
* public String getOutputStatement(String toDisplay) {
* return "print(" + toDisplay + ")";
* }
* </code></pre>
*
* @param toDisplay The String to be displayed by the returned statement.
* @return The string used to display the String in the syntax of the scripting language.
*
*
*/
public String getOutputStatement(String toDisplay);
/** {@collect.stats}
* Returns A valid scripting language executable progam with given statements.
* For instance an implementation for a PHP engine might be:
* <p>
* <pre><code>
* public String getProgram(String... statements) {
* $retval = "<?\n";
* int len = statements.length;
* for (int i = 0; i < len; i++) {
* $retval += statements[i] + ";\n";
* }
* $retval += "?>";
*
* }
* </code></pre>
*
* @param statements The statements to be executed. May be return values of
* calls to the <code>getMethodCallSyntax</code> and <code>getOutputStatement</code> methods.
* @return The Program
*/
public String getProgram(String... statements);
/** {@collect.stats}
* Returns an instance of the <code>ScriptEngine</code> associated with this
* <code>ScriptEngineFactory</code>. A new ScriptEngine is generally
* returned, but implementations may pool, share or reuse engines.
*
* @return A new <code>ScriptEngine</code> instance.
*/
public ScriptEngine getScriptEngine();
}
| 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 javax.script;
import java.io.Reader;
import java.util.Map;
import java.util.Set;
/** {@collect.stats}
* <code>ScriptEngine</code> is the fundamental interface whose methods must be
* fully functional in every implementation of this specification.
* <br><br>
* These methods provide basic scripting functionality. Applications written to this
* simple interface are expected to work with minimal modifications in every implementation.
* It includes methods that execute scripts, and ones that set and get values.
* <br><br>
* The values are key/value pairs of two types. The first type of pairs consists of
* those whose keys are reserved and defined in this specification or by individual
* implementations. The values in the pairs with reserved keys have specified meanings.
* <br><br>
* The other type of pairs consists of those that create Java language Bindings, the values are
* usually represented in scripts by the corresponding keys or by decorated forms of them.
*
* @author Mike Grogan
* @since 1.6
*/
public interface ScriptEngine {
/** {@collect.stats}
* Reserved key for a named value that passes
* an array of positional arguments to a script.
*/
public static final String ARGV="javax.script.argv";
/** {@collect.stats}
* Reserved key for a named value that is
* the name of the file being executed.
*/
public static final String FILENAME = "javax.script.filename";
/** {@collect.stats}
* Reserved key for a named value that is
* the name of the <code>ScriptEngine</code> implementation.
*/
public static final String ENGINE = "javax.script.engine";
/** {@collect.stats}
* Reserved key for a named value that identifies
* the version of the <code>ScriptEngine</code> implementation.
*/
public static final String ENGINE_VERSION = "javax.script.engine_version";
/** {@collect.stats}
* Reserved key for a named value that identifies
* the short name of the scripting language. The name is used by the
* <code>ScriptEngineManager</code> to locate a <code>ScriptEngine</code>
* with a given name in the <code>getEngineByName</code> method.
*/
public static final String NAME = "javax.script.name";
/** {@collect.stats}
* Reserved key for a named value that is
* the full name of Scripting Language supported by the implementation.
*/
public static final String LANGUAGE = "javax.script.language";
/** {@collect.stats}
* Reserved key for the named value that identifies
* the version of the scripting language supported by the implementation.
*/
public static final String LANGUAGE_VERSION ="javax.script.language_version";
/** {@collect.stats}
* Causes the immediate execution of the script whose source is the String
* passed as the first argument. The script may be reparsed or recompiled before
* execution. State left in the engine from previous executions, including
* variable values and compiled procedures may be visible during this execution.
*
* @param script The script to be executed by the script engine.
*
* @param context A <code>ScriptContext</code> exposing sets of attributes in
* different scopes. The meanings of the scopes <code>ScriptContext.GLOBAL_SCOPE</code>,
* and <code>ScriptContext.ENGINE_SCOPE</code> are defined in the specification.
* <br><br>
* The <code>ENGINE_SCOPE</code> <code>Bindings</code> of the <code>ScriptContext</code> contains the
* bindings of scripting variables to application objects to be used during this
* script execution.
*
*
* @return The value returned from the execution of the script.
*
* @throws ScriptException if an error occurrs in script. ScriptEngines should create and throw
* <code>ScriptException</code> wrappers for checked Exceptions thrown by underlying scripting
* implementations.
* @throws NullPointerException if either argument is null.
*/
public Object eval(String script, ScriptContext context) throws ScriptException;
/** {@collect.stats}
* Same as <code>eval(String, ScriptContext)</code> where the source of the script
* is read from a <code>Reader</code>.
*
* @param reader The source of the script to be executed by the script engine.
*
* @param context The <code>ScriptContext</code> passed to the script engine.
*
* @return The value returned from the execution of the script.
*
* @throws ScriptException if an error occurrs in script.
* @throws NullPointerException if either argument is null.
*/
public Object eval(Reader reader , ScriptContext context) throws ScriptException;
/** {@collect.stats}
* Executes the specified script. The default <code>ScriptContext</code> for the <code>ScriptEngine</code>
* is used.
*
* @param script The script language source to be executed.
*
* @return The value returned from the execution of the script.
*
* @throws ScriptException if error occurrs in script.
* @throws NullPointerException if the argument is null.
*/
public Object eval(String script) throws ScriptException;
/** {@collect.stats}
* Same as <code>eval(String)</code> except that the source of the script is
* provided as a <code>Reader</code>
*
* @param reader The source of the script.
*
* @return The value returned by the script.
*
* @throws ScriptException if an error occurrs in script.
* @throws NullPointerException if the argument is null.
*/
public Object eval(Reader reader) throws ScriptException;
/** {@collect.stats}
* Executes the script using the <code>Bindings</code> argument as the <code>ENGINE_SCOPE</code>
* <code>Bindings</code> of the <code>ScriptEngine</code> during the script execution. The
* <code>Reader</code>, <code>Writer</code> and non-<code>ENGINE_SCOPE</code> <code>Bindings</code> of the
* default <code>ScriptContext</code> are used. The <code>ENGINE_SCOPE</code>
* <code>Bindings</code> of the <code>ScriptEngine</code> is not changed, and its
* mappings are unaltered by the script execution.
*
* @param script The source for the script.
*
* @param n The <code>Bindings</code> of attributes to be used for script execution.
*
* @return The value returned by the script.
*
* @throws ScriptException if an error occurrs in script.
* @throws NullPointerException if either argument is null.
*/
public Object eval(String script, Bindings n) throws ScriptException;
/** {@collect.stats}
* Same as <code>eval(String, Bindings)</code> except that the source of the script
* is provided as a <code>Reader</code>.
*
* @param reader The source of the script.
* @param n The <code>Bindings</code> of attributes.
*
* @return The value returned by the script.
*
* @throws ScriptException if an error occurrs.
* @throws NullPointerException if either argument is null.
*/
public Object eval(Reader reader , Bindings n) throws ScriptException;
/** {@collect.stats}
* Sets a key/value pair in the state of the ScriptEngine that may either create
* a Java Language Binding to be used in the execution of scripts or be used in some
* other way, depending on whether the key is reserved. Must have the same effect as
* <code>getBindings(ScriptContext.ENGINE_SCOPE).put</code>.
*
* @param key The name of named value to add
* @param value The value of named value to add.
*
* @throws NullPointerException if key is null.
* @throws IllegalArgumentException if key is empty.
*/
public void put(String key, Object value);
/** {@collect.stats}
* Retrieves a value set in the state of this engine. The value might be one
* which was set using <code>setValue</code> or some other value in the state
* of the <code>ScriptEngine</code>, depending on the implementation. Must have the same effect
* as <code>getBindings(ScriptContext.ENGINE_SCOPE).get</code>
*
* @param key The key whose value is to be returned
* @return the value for the given key
*
* @throws NullPointerException if key is null.
* @throws IllegalArgumentException if key is empty.
*/
public Object get(String key);
/** {@collect.stats}
* Returns a scope of named values. The possible scopes are:
* <br><br>
* <ul>
* <li><code>ScriptContext.GLOBAL_SCOPE</code> - The set of named values representing global
* scope. If this <code>ScriptEngine</code> is created by a <code>ScriptEngineManager</code>,
* then the manager sets global scope bindings. This may be <code>null</code> if no global
* scope is associated with this <code>ScriptEngine</code></li>
* <li><code>ScriptContext.ENGINE_SCOPE</code> - The set of named values representing the state of
* this <code>ScriptEngine</code>. The values are generally visible in scripts using
* the associated keys as variable names.</li>
* <li>Any other value of scope defined in the default <code>ScriptContext</code> of the <code>ScriptEngine</code>.
* </li>
* </ul>
* <br><br>
* The <code>Bindings</code> instances that are returned must be identical to those returned by the
* <code>getBindings</code> method of <code>ScriptContext</code> called with corresponding arguments on
* the default <code>ScriptContext</code> of the <code>ScriptEngine</code>.
*
* @param scope Either <code>ScriptContext.ENGINE_SCOPE</code> or <code>ScriptContext.GLOBAL_SCOPE</code>
* which specifies the <code>Bindings</code> to return. Implementations of <code>ScriptContext</code>
* may define additional scopes. If the default <code>ScriptContext</code> of the <code>ScriptEngine</code>
* defines additional scopes, any of them can be passed to get the corresponding <code>Bindings</code>.
*
* @return The <code>Bindings</code> with the specified scope.
*
* @throws IllegalArgumentException if specified scope is invalid
*
*/
public Bindings getBindings(int scope);
/** {@collect.stats}
* Sets a scope of named values to be used by scripts. The possible scopes are:
*<br><br>
* <ul>
* <li><code>ScriptContext.ENGINE_SCOPE</code> - The specified <code>Bindings</code> replaces the
* engine scope of the <code>ScriptEngine</code>.
* </li>
* <li><code>ScriptContext.GLOBAL_SCOPE</code> - The specified <code>Bindings</code> must be visible
* as the <code>GLOBAL_SCOPE</code>.
* </li>
* <li>Any other value of scope defined in the default <code>ScriptContext</code> of the <code>ScriptEngine</code>.
*</li>
* </ul>
* <br><br>
* The method must have the same effect as calling the <code>setBindings</code> method of
* <code>ScriptContext</code> with the corresponding value of <code>scope</code> on the default
* <code>ScriptContext</code> of the <code>ScriptEngine</code>.
*
* @param bindings The <code>Bindings</code> for the specified scope.
* @param scope The specified scope. Either <code>ScriptContext.ENGINE_SCOPE</code>,
* <code>ScriptContext.GLOBAL_SCOPE</code>, or any other valid value of scope.
*
* @throws IllegalArgumentException if the scope is invalid
* @throws NullPointerException if the bindings is null and the scope is
* <code>ScriptContext.ENGINE_SCOPE</code>
*/
public void setBindings(Bindings bindings, int scope);
/** {@collect.stats}
* Returns an uninitialized <code>Bindings</code>.
*
* @return A <code>Bindings</code> that can be used to replace the state of this <code>ScriptEngine</code>.
**/
public Bindings createBindings();
/** {@collect.stats}
* Returns the default <code>ScriptContext</code> of the <code>ScriptEngine</code> whose Bindings, Reader
* and Writers are used for script executions when no <code>ScriptContext</code> is specified.
*
* @return The default <code>ScriptContext</code> of the <code>ScriptEngine</code>.
*/
public ScriptContext getContext();
/** {@collect.stats}
* Sets the default <code>ScriptContext</code> of the <code>ScriptEngine</code> whose Bindings, Reader
* and Writers are used for script executions when no <code>ScriptContext</code> is specified.
*
* @param context A <code>ScriptContext</code> that will replace the default <code>ScriptContext</code> in
* the <code>ScriptEngine</code>.
* @throws NullPointerException if context is null.
*/
public void setContext(ScriptContext context);
/** {@collect.stats}
* Returns a <code>ScriptEngineFactory</code> for the class to which this <code>ScriptEngine</code> belongs.
*
* @return The <code>ScriptEngineFactory</code>
*/
public ScriptEngineFactory getFactory();
}
| Java |
/*
* Copyright (c) 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 javax.script;
/** {@collect.stats}
* The generic <code>Exception</code> class for the Scripting APIs. Checked
* exception types thrown by underlying scripting implementations must be wrapped in instances of
* <code>ScriptException</code>. The class has members to store line and column numbers and
* filenames if this information is available.
*
* @author Mike Grogan
* @since 1.6
*/
public class ScriptException extends Exception {
private String fileName;
private int lineNumber;
private int columnNumber;
/** {@collect.stats}
* Creates a <code>ScriptException</code> with a String to be used in its message.
* Filename, and line and column numbers are unspecified.
*
* @param s The String to use in the message.
*/
public ScriptException(String s) {
super(s);
fileName = null;
lineNumber = -1;
columnNumber = -1;
}
/** {@collect.stats}
* Creates a <code>ScriptException</code> wrapping an <code>Exception</code> thrown by an underlying
* interpreter. Line and column numbers and filename are unspecified.
*
* @param e The wrapped <code>Exception</code>.
*/
public ScriptException(Exception e) {
super(e);
fileName = null;
lineNumber = -1;
columnNumber = -1;
}
/** {@collect.stats}
* Creates a <code>ScriptException</code> with message, filename and linenumber to
* be used in error messages.
*
* @param message The string to use in the message
*
* @param fileName The file or resource name describing the location of a script error
* causing the <code>ScriptException</code> to be thrown.
*
* @param lineNumber A line number describing the location of a script error causing
* the <code>ScriptException</code> to be thrown.
*/
public ScriptException(String message, String fileName, int lineNumber) {
super(message);
this.fileName = fileName;
this.lineNumber = lineNumber;
this.columnNumber = -1;
}
/** {@collect.stats}
* <code>ScriptException</code> constructor specifying message, filename, line number
* and column number.
* @param message The message.
* @param fileName The filename
* @param lineNumber the line number.
* @param columnNumber the column number.
*/
public ScriptException(String message,
String fileName,
int lineNumber,
int columnNumber) {
super(message);
this.fileName = fileName;
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
}
/** {@collect.stats}
* Returns a message containing the String passed to a constructor as well as
* line and column numbers and filename if any of these are known.
* @return The error message.
*/
public String getMessage() {
String ret = super.getMessage();
if (fileName != null) {
ret += (" in " + fileName);
if (lineNumber != -1) {
ret += " at line number " + lineNumber;
}
if (columnNumber != -1) {
ret += " at column number " + columnNumber;
}
}
return ret;
}
/** {@collect.stats}
* Get the line number on which an error occurred.
* @return The line number. Returns -1 if a line number is unavailable.
*/
public int getLineNumber() {
return lineNumber;
}
/** {@collect.stats}
* Get the column number on which an error occurred.
* @return The column number. Returns -1 if a column number is unavailable.
*/
public int getColumnNumber() {
return columnNumber;
}
/** {@collect.stats}
* Get the source of the script causing the error.
* @return The file name of the script or some other string describing the script
* source. May return some implementation-defined string such as <i><unknown></i>
* if a description of the source is unavailable.
*/
public String getFileName() {
return fileName;
}
}
| Java |
/*
* Copyright (c) 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 javax.script;
import java.util.Map;
import java.util.HashMap;
import java.util.Collection;
import java.util.Set;
/** {@collect.stats}
* A simple implementation of Bindings backed by
* a <code>HashMap</code> or some other specified <code>Map</code>.
*
* @author Mike Grogan
* @since 1.6
*/
public class SimpleBindings implements Bindings {
/** {@collect.stats}
* The <code>Map</code> field stores the attributes.
*/
private Map<String,Object> map;
/** {@collect.stats}
* Constructor uses an existing <code>Map</code> to store the values.
* @param m The <code>Map</code> backing this <code>SimpleBindings</code>.
* @throws NullPointerException if m is null
*/
public SimpleBindings(Map<String,Object> m) {
if (m == null) {
throw new NullPointerException();
}
this.map = m;
}
/** {@collect.stats}
* Default constructor uses a <code>HashMap</code>.
*/
public SimpleBindings() {
this(new HashMap<String,Object>());
}
/** {@collect.stats}
* Sets the specified key/value in the underlying <code>map</code> field.
*
* @param name Name of value
* @param value Value to set.
*
* @return Previous value for the specified key. Returns null if key was previously
* unset.
*
* @throws NullPointerException if the name is null.
* @throws IllegalArgumentException if the name is empty.
*/
public Object put(String name, Object value) {
checkKey(name);
return map.put(name,value);
}
/** {@collect.stats}
* <code>putAll</code> is implemented using <code>Map.putAll</code>.
*
* @param toMerge The <code>Map</code> of values to add.
*
* @throws NullPointerException
* if toMerge map is null or if some key in the map is null.
* @throws IllegalArgumentException
* if some key in the map is an empty String.
*/
public void putAll(Map<? extends String, ? extends Object> toMerge) {
if (toMerge == null) {
throw new NullPointerException("toMerge map is null");
}
for (Map.Entry<? extends String, ? extends Object> entry : toMerge.entrySet()) {
String key = entry.getKey();
checkKey(key);
put(key, entry.getValue());
}
}
/** {@collect.stats} {@inheritDoc} */
public void clear() {
map.clear();
}
/** {@collect.stats}
* Returns <tt>true</tt> if this map contains a mapping for the specified
* key. More formally, returns <tt>true</tt> if and only if
* this map contains a mapping for a key <tt>k</tt> such that
* <tt>(key==null ? k==null : key.equals(k))</tt>. (There can be
* at most one such mapping.)
*
* @param key key whose presence in this map is to be tested.
* @return <tt>true</tt> if this map contains a mapping for the specified
* key.
*
* @throws NullPointerException if key is null
* @throws ClassCastException if key is not String
* @throws IllegalArgumentException if key is empty String
*/
public boolean containsKey(Object key) {
checkKey(key);
return map.containsKey(key);
}
/** {@collect.stats} {@inheritDoc} */
public boolean containsValue(Object value) {
return map.containsValue(value);
}
/** {@collect.stats} {@inheritDoc} */
public Set<Map.Entry<String, Object>> entrySet() {
return map.entrySet();
}
/** {@collect.stats}
* Returns the value to which this map maps the specified key. Returns
* <tt>null</tt> if the map contains no mapping for this key. A return
* value of <tt>null</tt> does not <i>necessarily</i> indicate that the
* map contains no mapping for the key; it's also possible that the map
* explicitly maps the key to <tt>null</tt>. The <tt>containsKey</tt>
* operation may be used to distinguish these two cases.
*
* <p>More formally, if this map contains a mapping from a key
* <tt>k</tt> to a value <tt>v</tt> such that <tt>(key==null ? k==null :
* key.equals(k))</tt>, then this method returns <tt>v</tt>; otherwise
* it returns <tt>null</tt>. (There can be at most one such mapping.)
*
* @param key key whose associated value is to be returned.
* @return the value to which this map maps the specified key, or
* <tt>null</tt> if the map contains no mapping for this key.
*
* @throws NullPointerException if key is null
* @throws ClassCastException if key is not String
* @throws IllegalArgumentException if key is empty String
*/
public Object get(Object key) {
checkKey(key);
return map.get(key);
}
/** {@collect.stats} {@inheritDoc} */
public boolean isEmpty() {
return map.isEmpty();
}
/** {@collect.stats} {@inheritDoc} */
public Set<String> keySet() {
return map.keySet();
}
/** {@collect.stats}
* Removes the mapping for this key from this map if it is present
* (optional operation). More formally, if this map contains a mapping
* from key <tt>k</tt> to value <tt>v</tt> such that
* <code>(key==null ? k==null : key.equals(k))</code>, that mapping
* is removed. (The map can contain at most one such mapping.)
*
* <p>Returns the value to which the map previously associated the key, or
* <tt>null</tt> if the map contained no mapping for this key. (A
* <tt>null</tt> return can also indicate that the map previously
* associated <tt>null</tt> with the specified key if the implementation
* supports <tt>null</tt> values.) The map will not contain a mapping for
* the specified key once the call returns.
*
* @param key key whose mapping is to be removed from the map.
* @return previous value associated with specified key, or <tt>null</tt>
* if there was no mapping for key.
*
* @throws NullPointerException if key is null
* @throws ClassCastException if key is not String
* @throws IllegalArgumentException if key is empty String
*/
public Object remove(Object key) {
checkKey(key);
return map.remove(key);
}
/** {@collect.stats} {@inheritDoc} */
public int size() {
return map.size();
}
/** {@collect.stats} {@inheritDoc} */
public Collection<Object> values() {
return map.values();
}
private void checkKey(Object key) {
if (key == null) {
throw new NullPointerException("key can not be null");
}
if (!(key instanceof String)) {
throw new ClassCastException("key should be a String");
}
if (key.equals("")) {
throw new IllegalArgumentException("key can not be empty");
}
}
}
| Java |
/*
* Copyright (c) 2000, 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 javax.print;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.print.attribute.AttributeSet;
import sun.awt.AppContext;
import java.util.ServiceLoader;
import java.util.ServiceConfigurationError;
/** {@collect.stats} Implementations of this class provide lookup services for
* print services (typically equivalent to printers) of a particular type.
* <p>
* Multiple implementations may be installed concurrently.
* All implementations must be able to describe the located printers
* as instances of a PrintService.
* Typically implementations of this service class are located
* automatically in JAR files (see the SPI JAR file specification).
* These classes must be instantiable using a default constructor.
* Alternatively applications may explicitly register instances
* at runtime.
* <p>
* Applications use only the static methods of this abstract class.
* The instance methods are implemented by a service provider in a subclass
* and the unification of the results from all installed lookup classes
* are reported by the static methods of this class when called by
* the application.
* <p>
* A PrintServiceLookup implementor is recommended to check for the
* SecurityManager.checkPrintJobAccess() to deny access to untrusted code.
* Following this recommended policy means that untrusted code may not
* be able to locate any print services. Downloaded applets are the most
* common example of untrusted code.
* <p>
* This check is made on a per lookup service basis to allow flexibility in
* the policy to reflect the needs of different lookup services.
* <p>
* Services which are registered by registerService(PrintService)
* will not be included in lookup results if a security manager is
* installed and its checkPrintJobAccess() method denies access.
*/
public abstract class PrintServiceLookup {
static class Services {
private ArrayList listOfLookupServices = null;
private ArrayList registeredServices = null;
}
private static Services getServicesForContext() {
Services services =
(Services)AppContext.getAppContext().get(Services.class);
if (services == null) {
services = new Services();
AppContext.getAppContext().put(Services.class, services);
}
return services;
}
private static ArrayList getListOfLookupServices() {
return getServicesForContext().listOfLookupServices;
}
private static ArrayList initListOfLookupServices() {
ArrayList listOfLookupServices = new ArrayList();
getServicesForContext().listOfLookupServices = listOfLookupServices;
return listOfLookupServices;
}
private static ArrayList getRegisteredServices() {
return getServicesForContext().registeredServices;
}
private static ArrayList initRegisteredServices() {
ArrayList registeredServices = new ArrayList();
getServicesForContext().registeredServices = registeredServices;
return registeredServices;
}
/** {@collect.stats}
* Locates print services capable of printing the specified
* {@link DocFlavor}.
*
* @param flavor the flavor to print. If null, this constraint is not
* used.
* @param attributes attributes that the print service must support.
* If null this constraint is not used.
*
* @return array of matching <code>PrintService</code> objects
* representing print services that support the specified flavor
* attributes. If no services match, the array is zero-length.
*/
public static final PrintService[]
lookupPrintServices(DocFlavor flavor,
AttributeSet attributes) {
ArrayList list = getServices(flavor, attributes);
return (PrintService[])(list.toArray(new PrintService[list.size()]));
}
/** {@collect.stats}
* Locates MultiDoc print Services capable of printing MultiDocs
* containing all the specified doc flavors.
* <P> This method is useful to help locate a service that can print
* a <code>MultiDoc</code> in which the elements may be different
* flavors. An application could perform this itself by multiple lookups
* on each <code>DocFlavor</code> in turn and collating the results,
* but the lookup service may be able to do this more efficiently.
*
* @param flavors the flavors to print. If null or empty this
* constraint is not used.
* Otherwise return only multidoc print services that can print all
* specified doc flavors.
* @param attributes attributes that the print service must
* support. If null this constraint is not used.
*
* @return array of matching {@link MultiDocPrintService} objects.
* If no services match, the array is zero-length.
*
*/
public static final MultiDocPrintService[]
lookupMultiDocPrintServices(DocFlavor[] flavors,
AttributeSet attributes) {
ArrayList list = getMultiDocServices(flavors, attributes);
return (MultiDocPrintService[])
list.toArray(new MultiDocPrintService[list.size()]);
}
/** {@collect.stats}
* Locates the default print service for this environment.
* This may return null.
* If multiple lookup services each specify a default, the
* chosen service is not precisely defined, but a
* platform native service, rather than an installed service,
* is usually returned as the default. If there is no clearly
* identifiable
* platform native default print service, the default is the first
* to be located in an implementation-dependent manner.
* <p>
* This may include making use of any preferences API that is available
* as part of the Java or native platform.
* This algorithm may be overridden by a user setting the property
* javax.print.defaultPrinter.
* A service specified must be discovered to be valid and currently
* available to be returned as the default.
*
* @return the default PrintService.
*/
public static final PrintService lookupDefaultPrintService() {
Iterator psIterator = getAllLookupServices().iterator();
while (psIterator.hasNext()) {
try {
PrintServiceLookup lus = (PrintServiceLookup)psIterator.next();
PrintService service = lus.getDefaultPrintService();
if (service != null) {
return service;
}
} catch (Exception e) {
}
}
return null;
}
/** {@collect.stats}
* Allows an application to explicitly register a class that
* implements lookup services. The registration will not persist
* across VM invocations.
* This is useful if an application needs to make a new service
* available that is not part of the installation.
* If the lookup service is already registered, or cannot be registered,
* the method returns false.
* <p>
*
* @param sp an implementation of a lookup service.
* @return <code>true</code> if the new lookup service is newly
* registered; <code>false</code> otherwise.
*/
public static boolean registerServiceProvider(PrintServiceLookup sp) {
synchronized (PrintServiceLookup.class) {
Iterator psIterator = getAllLookupServices().iterator();
while (psIterator.hasNext()) {
try {
Object lus = psIterator.next();
if (lus.getClass() == sp.getClass()) {
return false;
}
} catch (Exception e) {
}
}
getListOfLookupServices().add(sp);
return true;
}
}
/** {@collect.stats}
* Allows an application to directly register an instance of a
* class which implements a print service.
* The lookup operations for this service will be
* performed by the PrintServiceLookup class using the attribute
* values and classes reported by the service.
* This may be less efficient than a lookup
* service tuned for that service.
* Therefore registering a <code>PrintServiceLookup</code> instance
* instead is recommended.
* The method returns true if this service is not previously
* registered and is now successfully registered.
* This method should not be called with StreamPrintService instances.
* They will always fail to register and the method will return false.
* @param service an implementation of a print service.
* @return <code>true</code> if the service is newly
* registered; <code>false</code> otherwise.
*/
public static boolean registerService(PrintService service) {
synchronized (PrintServiceLookup.class) {
if (service instanceof StreamPrintService) {
return false;
}
ArrayList registeredServices = getRegisteredServices();
if (registeredServices == null) {
registeredServices = initRegisteredServices();
}
else {
if (registeredServices.contains(service)) {
return false;
}
}
registeredServices.add(service);
return true;
}
}
/** {@collect.stats}
* Locates services that can be positively confirmed to support
* the combination of attributes and DocFlavors specified.
* This method is not called directly by applications.
* <p>
* Implemented by a service provider, used by the static methods
* of this class.
* <p>
* The results should be the same as obtaining all the PrintServices
* and querying each one individually on its support for the
* specified attributes and flavors, but the process can be more
* efficient by taking advantage of the capabilities of lookup services
* for the print services.
*
* @param flavor of document required. If null it is ignored.
* @param attributes required to be supported. If null this
* constraint is not used.
* @return array of matching PrintServices. If no services match, the
* array is zero-length.
*/
public abstract PrintService[] getPrintServices(DocFlavor flavor,
AttributeSet attributes);
/** {@collect.stats}
* Not called directly by applications.
* Implemented by a service provider, used by the static methods
* of this class.
* @return array of all PrintServices known to this lookup service
* class. If none are found, the array is zero-length.
*/
public abstract PrintService[] getPrintServices() ;
/** {@collect.stats}
* Not called directly by applications.
* <p>
* Implemented by a service provider, used by the static methods
* of this class.
* <p>
* Locates MultiDoc print services which can be positively confirmed
* to support the combination of attributes and DocFlavors specified.
* <p>
*
* @param flavors of documents required. If null or empty it is ignored.
* @param attributes required to be supported. If null this
* constraint is not used.
* @return array of matching PrintServices. If no services match, the
* array is zero-length.
*/
public abstract MultiDocPrintService[]
getMultiDocPrintServices(DocFlavor[] flavors,
AttributeSet attributes);
/** {@collect.stats}
* Not called directly by applications.
* Implemented by a service provider, and called by the print lookup
* service
* @return the default PrintService for this lookup service.
* If there is no default, returns null.
*/
public abstract PrintService getDefaultPrintService();
private static ArrayList getAllLookupServices() {
synchronized (PrintServiceLookup.class) {
ArrayList listOfLookupServices = getListOfLookupServices();
if (listOfLookupServices != null) {
return listOfLookupServices;
} else {
listOfLookupServices = initListOfLookupServices();
}
try {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedExceptionAction() {
public Object run() {
Iterator<PrintServiceLookup> iterator =
ServiceLoader.load(PrintServiceLookup.class).
iterator();
ArrayList los = getListOfLookupServices();
while (iterator.hasNext()) {
try {
los.add(iterator.next());
} catch (ServiceConfigurationError err) {
/* In the applet case, we continue */
if (System.getSecurityManager() != null) {
err.printStackTrace();
} else {
throw err;
}
}
}
return null;
}
});
} catch (java.security.PrivilegedActionException e) {
}
return listOfLookupServices;
}
}
private static ArrayList getServices(DocFlavor flavor,
AttributeSet attributes) {
ArrayList listOfServices = new ArrayList();
Iterator psIterator = getAllLookupServices().iterator();
while (psIterator.hasNext()) {
try {
PrintServiceLookup lus = (PrintServiceLookup)psIterator.next();
PrintService[] services=null;
if (flavor == null && attributes == null) {
try {
services = lus.getPrintServices();
} catch (Throwable tr) {
}
} else {
services = lus.getPrintServices(flavor, attributes);
}
if (services == null) {
continue;
}
for (int i=0; i<services.length; i++) {
listOfServices.add(services[i]);
}
} catch (Exception e) {
}
}
/* add any directly registered services */
ArrayList registeredServices = null;
try {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPrintJobAccess();
}
registeredServices = getRegisteredServices();
} catch (SecurityException se) {
}
if (registeredServices != null) {
PrintService[] services = (PrintService[])
registeredServices.toArray(
new PrintService[registeredServices.size()]);
for (int i=0; i<services.length; i++) {
if (!listOfServices.contains(services[i])) {
if (flavor == null && attributes == null) {
listOfServices.add(services[i]);
} else if (((flavor != null &&
services[i].isDocFlavorSupported(flavor)) ||
flavor == null) &&
null == services[i].getUnsupportedAttributes(
flavor, attributes)) {
listOfServices.add(services[i]);
}
}
}
}
return listOfServices;
}
private static ArrayList getMultiDocServices(DocFlavor[] flavors,
AttributeSet attributes) {
ArrayList listOfServices = new ArrayList();
Iterator psIterator = getAllLookupServices().iterator();
while (psIterator.hasNext()) {
try {
PrintServiceLookup lus = (PrintServiceLookup)psIterator.next();
MultiDocPrintService[] services =
lus.getMultiDocPrintServices(flavors, attributes);
if (services == null) {
continue;
}
for (int i=0; i<services.length; i++) {
listOfServices.add(services[i]);
}
} catch (Exception e) {
}
}
/* add any directly registered services */
ArrayList registeredServices = null;
try {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPrintJobAccess();
}
registeredServices = getRegisteredServices();
} catch (Exception e) {
}
if (registeredServices != null) {
PrintService[] services = (PrintService[])
registeredServices.toArray(
new PrintService[registeredServices.size()]);
for (int i=0; i<services.length; i++) {
if (services[i] instanceof MultiDocPrintService &&
!listOfServices.contains(services[i])) {
if (flavors == null || flavors.length == 0) {
listOfServices.add(services[i]);
} else {
boolean supported = true;
for (int f=0; f<flavors.length; f++) {
if (services[i].isDocFlavorSupported(flavors[f])) {
if (services[i].getUnsupportedAttributes(
flavors[f], attributes) != null) {
supported = false;
break;
}
} else {
supported = false;
break;
}
}
if (supported) {
listOfServices.add(services[i]);
}
}
}
}
}
return listOfServices;
}
}
| Java |
/*
* Copyright (c) 2000, 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 javax.print;
import java.net.URI;
/** {@collect.stats}
* Interface URIException is a mixin interface which a subclass of {@link
* PrintException PrintException} can implement to report an error condition
* involving a URI address. The Print Service API does not define any print
* exception classes that implement interface URIException, that being left to
* the Print Service implementor's discretion.
*
*/
public interface URIException {
/** {@collect.stats}
* Indicates that the printer cannot access the URI address.
* For example, the printer might report this error if it goes to get
* the print data and cannot even establish a connection to the
* URI address.
*/
public static final int URIInaccessible = 1;
/** {@collect.stats}
* Indicates that the printer does not support the URI
* scheme ("http", "ftp", etc.) in the URI address.
*/
public static final int URISchemeNotSupported = 2;
/** {@collect.stats}
* Indicates any kind of problem not specifically identified
* by the other reasons.
*/
public static final int URIOtherProblem = -1;
/** {@collect.stats}
* Return the URI.
* @return the URI that is the cause of this exception.
*/
public URI getUnsupportedURI();
/** {@collect.stats}
* Return the reason for the event.
* @return one of the predefined reasons enumerated in this interface.
*/
public int getReason();
}
| Java |
/*
* Copyright (c) 2000, 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 javax.print.event;
import javax.print.DocPrintJob;
/** {@collect.stats}
*
* Class <code>PrintJobEvent</code> encapsulates common events a print job
* reports to let a listener know of progress in the processing of the
* {@link DocPrintJob}.
*
*/
public class PrintJobEvent extends PrintEvent {
private static final long serialVersionUID = -1711656903622072997L;
private int reason;
/** {@collect.stats}
* The job was canceled by the {@link javax.print.PrintService PrintService}.
*/
public static final int JOB_CANCELED = 101;
/** {@collect.stats}
* The document cis completely printed.
*/
public static final int JOB_COMPLETE = 102;
/** {@collect.stats}
* The print service reports that the job cannot be completed.
* The application must resubmit the job.
*/
public static final int JOB_FAILED = 103;
/** {@collect.stats}
* The print service indicates that a - possibly transient - problem
* may require external intervention before the print service can
* continue. One example of an event that can
* generate this message is when the printer runs out of paper.
*/
public static final int REQUIRES_ATTENTION = 104;
/** {@collect.stats}
* Not all print services may be capable of delivering interesting
* events, or even telling when a job is complete. This message indicates
* the print job has no further information or communication
* with the print service. This message should always be delivered
* if a terminal event (completed/failed/canceled) is not delivered.
* For example, if messages such as JOB_COMPLETE have NOT been received
* before receiving this message, the only inference that should be drawn
* is that the print service does not support delivering such an event.
*/
public static final int NO_MORE_EVENTS = 105;
/** {@collect.stats}
* The job is not necessarily printed yet, but the data has been transferred
* successfully from the client to the print service. The client may
* free data resources.
*/
public static final int DATA_TRANSFER_COMPLETE = 106;
/** {@collect.stats}
* Constructs a <code>PrintJobEvent</code> object.
*
* @param source a <code>DocPrintJob</code> object
* @param reason an int specifying the reason.
* @throws IllegalArgumentException if <code>source</code> is
* <code>null</code>.
*/
public PrintJobEvent( DocPrintJob source, int reason) {
super(source);
this.reason = reason;
}
/** {@collect.stats}
* Gets the reason for this event.
* @return reason int.
*/
public int getPrintEventType() {
return reason;
}
/** {@collect.stats}
* Determines the <code>DocPrintJob</code> to which this print job
* event pertains.
*
* @return the <code>DocPrintJob</code> object that represents the
* print job that reports the events encapsulated by this
* <code>PrintJobEvent</code>.
*
*/
public DocPrintJob getPrintJob() {
return (DocPrintJob) getSource();
}
}
| Java |
/*
* Copyright (c) 2000, 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 javax.print.event;
/** {@collect.stats}
* Implementations of this interface are attached to a
* {@link javax.print.DocPrintJob DocPrintJob} to monitor
* the status of attribute changes associated with the print job.
*
*/
public interface PrintJobAttributeListener {
/** {@collect.stats}
* Notifies the listener of a change in some print job attributes.
* One example of an occurrence triggering this event is if the
* {@link javax.print.attribute.standard.JobState JobState}
* attribute changed from
* <code>PROCESSING</code> to <code>PROCESSING_STOPPED</code>.
* @param pjae the event.
*/
public void attributeUpdate(PrintJobAttributeEvent pjae) ;
}
| Java |
/*
* Copyright (c) 2000, 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 javax.print.event;
/** {@collect.stats}
* Implementations of this listener interface should be attached to a
* {@link javax.print.DocPrintJob DocPrintJob} to monitor the status of
* the printer job.
* These callback methods may be invoked on the thread processing the
* print job, or a service created notification thread. In either case
* the client should not perform lengthy processing in these callbacks.
*/
public interface PrintJobListener {
/** {@collect.stats}
* Called to notify the client that data has been successfully
* transferred to the print service, and the client may free
* local resources allocated for that data. The client should
* not assume that the data has been completely printed after
* receiving this event.
* If this event is not received the client should wait for a terminal
* event (completed/canceled/failed) before freeing the resources.
* @param pje the job generating this event
*/
public void printDataTransferCompleted(PrintJobEvent pje) ;
/** {@collect.stats}
* Called to notify the client that the job completed successfully.
* @param pje the job generating this event
*/
public void printJobCompleted(PrintJobEvent pje) ;
/** {@collect.stats}
* Called to notify the client that the job failed to complete
* successfully and will have to be resubmitted.
* @param pje the job generating this event
*/
public void printJobFailed(PrintJobEvent pje) ;
/** {@collect.stats}
* Called to notify the client that the job was canceled
* by a user or a program.
* @param pje the job generating this event
*/
public void printJobCanceled(PrintJobEvent pje) ;
/** {@collect.stats}
* Called to notify the client that no more events will be delivered.
* One cause of this event being generated is if the job
* has successfully completed, but the printing system
* is limited in capability and cannot verify this.
* This event is required to be delivered if none of the other
* terminal events (completed/failed/canceled) are delivered.
* @param pje the job generating this event
*/
public void printJobNoMoreEvents(PrintJobEvent pje) ;
/** {@collect.stats}
* Called to notify the client that an error has occurred that the
* user might be able to fix. One example of an error that can
* generate this event is when the printer runs out of paper.
* @param pje the job generating this event
*/
public void printJobRequiresAttention(PrintJobEvent pje) ;
}
| Java |
/*
* Copyright (c) 2000, 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 javax.print.event;
/** {@collect.stats}
* Implementations of this listener interface are attached to a
* {@link javax.print.PrintService PrintService} to monitor
* the status of the print service.
* <p>
* To monitor a particular job see {@link PrintJobListener} and
* {@link PrintJobAttributeListener}.
*/
public interface PrintServiceAttributeListener {
/** {@collect.stats}
* Called to notify a listener of an event in the print service.
* The service will call this method on an event notification thread.
* The client should not perform lengthy processing in this callback
* or subsequent event notifications may be blocked.
* @param psae the event being notified
*/
public void attributeUpdate(PrintServiceAttributeEvent psae) ;
}
| Java |
/*
* Copyright (c) 2000, 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 javax.print.event;
import javax.print.DocPrintJob;
import javax.print.attribute.AttributeSetUtilities;
import javax.print.attribute.PrintJobAttributeSet;
/** {@collect.stats}
* Class PrintJobAttributeEvent encapsulates an event a PrintService
* reports to let the client know that one or more printing attributes for a
* PrintJob have changed.
*/
public class PrintJobAttributeEvent extends PrintEvent {
private static final long serialVersionUID = -6534469883874742101L;
private PrintJobAttributeSet attributes;
/** {@collect.stats}
* Constructs a PrintJobAttributeEvent object.
* @param source the print job generating this event
* @param attributes the attribute changes being reported
* @throws IllegalArgumentException if <code>source</code> is
* <code>null</code>.
*/
public PrintJobAttributeEvent (DocPrintJob source,
PrintJobAttributeSet attributes) {
super(source);
this.attributes = AttributeSetUtilities.unmodifiableView(attributes);
}
/** {@collect.stats}
* Determine the Print Job to which this print job event pertains.
*
* @return Print Job object.
*/
public DocPrintJob getPrintJob() {
return (DocPrintJob) getSource();
}
/** {@collect.stats}
* Determine the printing attributes that changed and their new values.
*
* @return Attributes containing the new values for the print job
* attributes that changed. The returned set may not be modifiable.
*/
public PrintJobAttributeSet getAttributes() {
return attributes;
}
}
| Java |
/*
* Copyright (c) 2000, 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 javax.print.event;
/** {@collect.stats}
*
* Class PrintEvent is the super class of all Print Service API events.
*/
public class PrintEvent extends java.util.EventObject {
private static final long serialVersionUID = 2286914924430763847L;
/** {@collect.stats}
* Constructs a PrintEvent object.
* @param source is the source of the event
* @throws IllegalArgumentException if <code>source</code> is
* <code>null</code>.
*/
public PrintEvent (Object source) {
super(source);
}
/** {@collect.stats}
* @return a message describing the event
*/
public String toString() {
return ("PrintEvent on " + getSource().toString());
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.