code
stringlengths 3
1.18M
| language
stringclasses 1
value |
|---|---|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown when resources are not available to complete
* the requested operation. This might due to a lack of resources on
* the server or on the client. There are no restrictions to resource types,
* as different services might make use of different resources. Such
* restrictions might be due to physical limits and/or adminstrative quotas.
* Examples of limited resources are internal buffers, memory, network bandwidth.
*<p>
* InsufficientResourcesException is different from LimitExceededException in that
* the latter is due to user/system specified limits. See LimitExceededException
* for details.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class InsufficientResourcesException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of InsufficientResourcesException using an
* explanation. All other fields default to null.
*
* @param explanation Possibly null additional detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public InsufficientResourcesException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of InsufficientResourcesException with
* all name resolution fields and explanation initialized to null.
*/
public InsufficientResourcesException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 6227672693037844532L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown when an authentication error occurs while
* accessing the naming or directory service.
* An authentication error can happen, for example, when the credentials
* supplied by the user program is invalid or otherwise fails to
* authenticate the user to the naming/directory service.
*<p>
* If the program wants to handle this exception in particular, it
* should catch AuthenticationException explicitly before attempting to
* catch NamingException. After catching AuthenticationException, the
* program could reattempt the authentication by updating
* the resolved context's environment properties with the appropriate
* appropriate credentials.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class AuthenticationException extends NamingSecurityException {
/** {@collect.stats}
* Constructs a new instance of AuthenticationException using the
* explanation supplied. All other fields default to null.
*
* @param explanation A possibly null string containing
* additional detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public AuthenticationException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of AuthenticationException.
* All fields are set to null.
*/
public AuthenticationException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 3678497619904568096L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown when a malformed link was encountered while
* resolving or constructing a link.
* <p>
* Synchronization and serialization issues that apply to LinkException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see LinkRef#getLinkName
* @see LinkRef
* @since 1.3
*/
public class MalformedLinkException extends LinkException {
/** {@collect.stats}
* Constructs a new instance of MalformedLinkException with an explanation
* All the other fields are initialized to null.
* @param explanation A possibly null string containing additional
* detail about this exception.
*/
public MalformedLinkException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of Malformed LinkException.
* All fields are initialized to null.
*/
public MalformedLinkException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -3066740437737830242L;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming;
/** {@collect.stats}
* This class represents the object name and class name pair of a binding
* found in a context.
*<p>
* A context consists of name-to-object bindings.
* The NameClassPair class represents the name and the
* class of the bound object. It consists
* of a name and a string representing the
* package-qualified class name.
*<p>
* Use subclassing for naming systems that generate contents of
* a name/class pair dynamically.
*<p>
* A NameClassPair instance is not synchronized against concurrent
* access by multiple threads. Threads that need to access a NameClassPair
* concurrently should synchronize amongst themselves and provide
* the necessary locking.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see Context#list
* @since 1.3
*/
/*
* <p>
* The serialized form of a NameClassPair object consists of the name (a
* String), class name (a String), and isRelative flag (a boolean).
*/
public class NameClassPair implements java.io.Serializable {
/** {@collect.stats}
* Contains the name of this NameClassPair.
* It is initialized by the constructor and can be updated using
* <tt>setName()</tt>.
* @serial
* @see #getName
* @see #setName
*/
private String name;
/** {@collect.stats}
*Contains the class name contained in this NameClassPair.
* It is initialized by the constructor and can be updated using
* <tt>setClassName()</tt>.
* @serial
* @see #getClassName
* @see #setClassName
*/
private String className;
/** {@collect.stats}
* Contains the full name of this NameClassPair within its
* own namespace.
* It is initialized using <tt>setNameInNamespace()</tt>
* @serial
* @see #getNameInNamespace
* @see #setNameInNamespace
*/
private String fullName = null;
/** {@collect.stats}
* Records whether the name of this <tt>NameClassPair</tt>
* is relative to the target context.
* It is initialized by the constructor and can be updated using
* <tt>setRelative()</tt>.
* @serial
* @see #isRelative
* @see #setRelative
* @see #getName
* @see #setName
*/
private boolean isRel = true;
/** {@collect.stats}
* Constructs an instance of a NameClassPair given its
* name and class name.
*
* @param name The non-null name of the object. It is relative
* to the <em>target context</em> (which is
* named by the first parameter of the <code>list()</code> method)
* @param className The possibly null class name of the object
* bound to name. It is null if the object bound is null.
* @see #getClassName
* @see #setClassName
* @see #getName
* @see #setName
*/
public NameClassPair(String name, String className) {
this.name = name;
this.className = className;
}
/** {@collect.stats}
* Constructs an instance of a NameClassPair given its
* name, class name, and whether it is relative to the listing context.
*
* @param name The non-null name of the object.
* @param className The possibly null class name of the object
* bound to name. It is null if the object bound is null.
* @param isRelative true if <code>name</code> is a name relative
* to the target context (which is named by the first parameter
* of the <code>list()</code> method); false if <code>name</code>
* is a URL string.
* @see #getClassName
* @see #setClassName
* @see #getName
* @see #setName
* @see #isRelative
* @see #setRelative
*/
public NameClassPair(String name, String className, boolean isRelative) {
this.name = name;
this.className = className;
this.isRel = isRelative;
}
/** {@collect.stats}
* Retrieves the class name of the object bound to the name of this binding.
* If a reference or some other indirect information is bound,
* retrieves the class name of the eventual object that
* will be returned by <tt>Binding.getObject()</tt>.
*
* @return The possibly null class name of object bound.
* It is null if the object bound is null.
* @see Binding#getObject
* @see Binding#getClassName
* @see #setClassName
*/
public String getClassName() {
return className;
}
/** {@collect.stats}
* Retrieves the name of this binding.
* If <tt>isRelative()</tt> is true, this name is relative to the
* target context (which is named by the first parameter of the
* <tt>list()</tt>).
* If <tt>isRelative()</tt> is false, this name is a URL string.
*
* @return The non-null name of this binding.
* @see #isRelative
* @see #setName
*/
public String getName() {
return name;
}
/** {@collect.stats}
* Sets the name of this binding.
*
* @param name the non-null string to use as the name.
* @see #getName
* @see #setRelative
*/
public void setName(String name) {
this.name = name;
}
/** {@collect.stats}
* Sets the class name of this binding.
*
* @param name the possibly null string to use as the class name.
* If null, <tt>Binding.getClassName()</tt> will return
* the actual class name of the object in the binding.
* The class name will be null if the object bound is null.
* @see #getClassName
* @see Binding#getClassName
*/
public void setClassName(String name) {
this.className = name;
}
/** {@collect.stats}
* Determines whether the name of this binding is
* relative to the target context (which is named by
* the first parameter of the <code>list()</code> method).
*
* @return true if the name of this binding is relative to the
* target context;
* false if the name of this binding is a URL string.
* @see #setRelative
* @see #getName
*/
public boolean isRelative() {
return isRel;
}
/** {@collect.stats}
* Sets whether the name of this binding is relative to the target
* context (which is named by the first parameter of the <code>list()</code>
* method).
*
* @param r If true, the name of binding is relative to the target context;
* if false, the name of binding is a URL string.
* @see #isRelative
* @see #setName
*/
public void setRelative(boolean r) {
isRel = r;
}
/** {@collect.stats}
* Retrieves the full name of this binding.
* The full name is the absolute name of this binding within
* its own namespace. See {@link Context#getNameInNamespace()}.
* <p>
*
* In naming systems for which the notion of full name does not
* apply to this binding an <tt>UnsupportedOperationException</tt>
* is thrown.
* This exception is also thrown when a service provider written before
* the introduction of the method is in use.
* <p>
* The string returned by this method is not a JNDI composite name and
* should not be passed directly to context methods.
*
* @return The full name of this binding.
* @throws UnsupportedOperationException if the notion of full name
* does not apply to this binding in the naming system.
* @since 1.5
* @see #setNameInNamespace
* @see #getName
*/
public String getNameInNamespace() {
if (fullName == null) {
throw new UnsupportedOperationException();
}
return fullName;
}
/** {@collect.stats}
* Sets the full name of this binding.
* This method must be called to set the full name whenever a
* <tt>NameClassPair</tt> is created and a full name is
* applicable to this binding.
* <p>
* Setting the full name to null, or not setting it at all, will
* cause <tt>getNameInNamespace()</tt> to throw an exception.
*
* @param fullName The full name to use.
* @since 1.5
* @see #getNameInNamespace
* @see #setName
*/
public void setNameInNamespace(String fullName) {
this.fullName = fullName;
}
/** {@collect.stats}
* Generates the string representation of this name/class pair.
* The string representation consists of the name and class name separated
* by a colon (':').
* The contents of this string is useful
* for debugging and is not meant to be interpreted programmatically.
*
* @return The string representation of this name/class pair.
*/
public String toString() {
return (isRelative() ? "" : "(not relative)") + getName() + ": " +
getClassName();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 5620776610160863339L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This interface is implemented by an object that can provide a
* Reference to itself.
*<p>
* A Reference represents a way of recording address information about
* objects which themselves are not directly bound to the naming system.
* Such objects can implement the Referenceable interface as a way
* for programs that use that object to determine what its Reference is.
* For example, when binding a object, if an object implements the
* Referenceable interface, getReference() can be invoked on the object to
* get its Reference to use for binding.
*
* @author Rosanna Lee
* @author Scott Seligman
* @author R. Vasudevan
*
* @see Context#bind
* @see javax.naming.spi.NamingManager#getObjectInstance
* @see Reference
* @since 1.3
*/
public interface Referenceable {
/** {@collect.stats}
* Retrieves the Reference of this object.
*
* @return The non-null Reference of this object.
* @exception NamingException If a naming exception was encountered
* while retrieving the reference.
*/
Reference getReference() throws NamingException;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown when a component of the name cannot be resolved
* because it is not bound.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class NameNotFoundException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of NameNotFoundException using the
* explanation supplied. All other fields default to null.
*
* @param explanation Possibly null additional detail about
* this exception.
* @see java.lang.Throwable#getMessage
*/
public NameNotFoundException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of NameNotFoundException.
* all name resolution fields and explanation initialized to null.
*/
public NameNotFoundException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -8007156725367842053L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This class represents the binary form of the address of
* a communications end-point.
*<p>
* A BinaryRefAddr consists of a type that describes the communication mechanism
* and an opaque buffer containing the address description
* specific to that communication mechanism. The format and interpretation of
* the address type and the contents of the opaque buffer are based on
* the agreement of three parties: the client that uses the address,
* the object/server that can be reached using the address,
* and the administrator or program that creates the address.
*<p>
* An example of a binary reference address is an BER X.500 presentation address.
* Another example of a binary reference address is a serialized form of
* a service's object handle.
*<p>
* A binary reference address is immutable in the sense that its fields
* once created, cannot be replaced. However, it is possible to access
* the byte array used to hold the opaque buffer. Programs are strongly
* recommended against changing this byte array. Changes to this
* byte array need to be explicitly synchronized.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see RefAddr
* @see StringRefAddr
* @since 1.3
*/
/*
* The serialized form of a BinaryRefAddr object consists of its type
* name String and a byte array containing its "contents".
*/
public class BinaryRefAddr extends RefAddr {
/** {@collect.stats}
* Contains the bytes of the address.
* This field is initialized by the constructor and returned
* using getAddressBytes() and getAddressContents().
* @serial
*/
private byte[] buf = null;
/** {@collect.stats}
* Constructs a new instance of BinaryRefAddr using its address type and a byte
* array for contents.
*
* @param addrType A non-null string describing the type of the address.
* @param src The non-null contents of the address as a byte array.
* The contents of src is copied into the new BinaryRefAddr.
*/
public BinaryRefAddr(String addrType, byte[] src) {
this(addrType, src, 0, src.length);
}
/** {@collect.stats}
* Constructs a new instance of BinaryRefAddr using its address type and
* a region of a byte array for contents.
*
* @param addrType A non-null string describing the type of the address.
* @param src The non-null contents of the address as a byte array.
* The contents of src is copied into the new BinaryRefAddr.
* @param offset The starting index in src to get the bytes.
* 0 <= offset <= src.length.
* @param count The number of bytes to extract from src.
* 0 <= count <= src.length-offset.
*/
public BinaryRefAddr(String addrType, byte[] src, int offset, int count) {
super(addrType);
buf = new byte[count];
System.arraycopy(src, offset, buf, 0, count);
}
/** {@collect.stats}
* Retrieves the contents of this address as an Object.
* The result is a byte array.
* Changes to this array will affect this BinaryRefAddr's contents.
* Programs are recommended against changing this array's contents
* and to lock the buffer if they need to change it.
*
* @return The non-null buffer containing this address's contents.
*/
public Object getContent() {
return buf;
}
/** {@collect.stats}
* Determines whether obj is equal to this address. It is equal if
* it contains the same address type and their contents are byte-wise
* equivalent.
* @param obj The possibly null object to check.
* @return true if the object is equal; false otherwise.
*/
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof BinaryRefAddr)) {
BinaryRefAddr target = (BinaryRefAddr)obj;
if (addrType.compareTo(target.addrType) == 0) {
if (buf == null && target.buf == null)
return true;
if (buf == null || target.buf == null ||
buf.length != target.buf.length)
return false;
for (int i = 0; i < buf.length; i++)
if (buf[i] != target.buf[i])
return false;
return true;
}
}
return false;
}
/** {@collect.stats}
* Computes the hash code of this address using its address type and contents.
* Two BinaryRefAddrs have the same hash code if they have
* the same address type and the same contents.
* It is also possible for different BinaryRefAddrs to have
* the same hash code.
*
* @return The hash code of this address as an int.
*/
public int hashCode() {
int hash = addrType.hashCode();
for (int i = 0; i < buf.length; i++) {
hash += buf[i]; // %%% improve later
}
return hash;
}
/** {@collect.stats}
* Generates the string representation of this address.
* The string consists of the address's type and contents with labels.
* The first 32 bytes of contents are displayed (in hexadecimal).
* If there are more than 32 bytes, "..." is used to indicate more.
* This string is meant to used for debugging purposes and not
* meant to be interpreted programmatically.
* @return The non-null string representation of this address.
*/
public String toString(){
StringBuffer str = new StringBuffer("Address Type: " + addrType + "\n");
str.append("AddressContents: ");
for (int i = 0; i<buf.length && i < 32; i++) {
str.append(Integer.toHexString(buf[i]) +" ");
}
if (buf.length >= 32)
str.append(" ...\n");
return (str.toString());
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -3415254970957330361L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
import javax.naming.Name;
/** {@collect.stats}
* This exception is thrown when a method
* terminates abnormally due to a user or system specified limit.
* This is different from a InsufficientResourceException in that
* LimitExceededException is due to a user/system specified limit.
* For example, running out of memory to complete the request would
* be an insufficient resource. The client asking for 10 answers and
* getting back 11 is a size limit exception.
*<p>
* Examples of these limits include client and server configuration
* limits such as size, time, number of hops, etc.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class LimitExceededException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of LimitExceededException with
* all name resolution fields and explanation initialized to null.
*/
public LimitExceededException() {
super();
}
/** {@collect.stats}
* Constructs a new instance of LimitExceededException using an
* explanation. All other fields default to null.
* @param explanation Possibly null detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public LimitExceededException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -776898738660207856L;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming;
import java.util.Hashtable;
/** {@collect.stats}
* This abstract class is used to represent a referral exception,
* which is generated in response to a <em>referral</em>
* such as that returned by LDAP v3 servers.
* <p>
* A service provider provides
* a subclass of <tt>ReferralException</tt> by providing implementations
* for <tt>getReferralInfo()</tt> and <tt>getReferralContext()</tt> (and appropriate
* constructors and/or corresponding "set" methods).
* <p>
* The following code sample shows how <tt>ReferralException</tt> can be used.
* <p><blockquote><pre>
* while (true) {
* try {
* bindings = ctx.listBindings(name);
* while (bindings.hasMore()) {
* b = bindings.next();
* ...
* }
* break;
* } catch (ReferralException e) {
* ctx = e.getReferralContext();
* }
* }
* </pre></blockquote></p>
*<p>
* <tt>ReferralException</tt> is an abstract class. Concrete implementations
* determine its synchronization and serialization properties.
*<p>
* An environment parameter passed to the <tt>getReferralContext()</tt>
* method is owned by the caller.
* The service provider will not modify the object or keep a reference to it,
* but may keep a reference to a clone of it.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @since 1.3
*
*/
public abstract class ReferralException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of ReferralException using the
* explanation supplied. All other fields are set to null.
*
* @param explanation Additional detail about this exception. Can be null.
* @see java.lang.Throwable#getMessage
*/
protected ReferralException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of ReferralException.
* All fields are set to null.
*/
protected ReferralException() {
super();
}
/** {@collect.stats}
* Retrieves information (such as URLs) related to this referral.
* The program may examine or display this information
* to the user to determine whether to continue with the referral,
* or to determine additional information needs to be supplied in order
* to continue with the referral.
*
* @return Non-null referral information related to this referral.
*/
public abstract Object getReferralInfo();
/** {@collect.stats}
* Retrieves the context at which to continue the method.
* Regardless of whether a referral is encountered directly during a
* context operation, or indirectly, for example, during a search
* enumeration, the referral exception should provide a context
* at which to continue the operation. The referral context is
* created using the environment properties of the context
* that threw the ReferralException.
*
*<p>
* To continue the operation, the client program should re-invoke
* the method using the same arguments as the original invocation.
*
* @return The non-null context at which to continue the method.
* @exception NamingException If a naming exception was encountered.
* Call either <tt>retryReferral()</tt> or <tt>skipReferral()</tt>
* to continue processing referrals.
*/
public abstract Context getReferralContext() throws NamingException;
/** {@collect.stats}
* Retrieves the context at which to continue the method using
* environment properties.
* Regardless of whether a referral is encountered directly during a
* context operation, or indirectly, for example, during a search
* enumeration, the referral exception should provide a context
* at which to continue the operation.
*<p>
* The referral context is created using <tt>env</tt> as its environment
* properties.
* This method should be used instead of the no-arg overloaded form
* when the caller needs to use different environment properties for
* the referral context. It might need to do this, for example, when
* it needs to supply different authentication information to the referred
* server in order to create the referral context.
*<p>
* To continue the operation, the client program should re-invoke
* the method using the same arguments as the original invocation.
*
* @param env The possibly null environment to use when retrieving the
* referral context. If null, no environment properties will be used.
*
* @return The non-null context at which to continue the method.
* @exception NamingException If a naming exception was encountered.
* Call either <tt>retryReferral()</tt> or <tt>skipReferral()</tt>
* to continue processing referrals.
*/
public abstract Context
getReferralContext(Hashtable<?,?> env)
throws NamingException;
/** {@collect.stats}
* Discards the referral about to be processed.
* A call to this method should be followed by a call to
* <code>getReferralContext</code> to allow the processing of
* other referrals to continue.
* The following code fragment shows a typical usage pattern.
* <p><blockquote><pre>
* } catch (ReferralException e) {
* if (!shallIFollow(e.getReferralInfo())) {
* if (!e.skipReferral()) {
* return;
* }
* }
* ctx = e.getReferralContext();
* }
* </pre></blockquote>
*
* @return true If more referral processing is pending; false otherwise.
*/
public abstract boolean skipReferral();
/** {@collect.stats}
* Retries the referral currently being processed.
* A call to this method should be followed by a call to
* <code>getReferralContext</code> to allow the current
* referral to be retried.
* The following code fragment shows a typical usage pattern.
* <p><blockquote><pre>
* } catch (ReferralException e) {
* while (true) {
* try {
* ctx = e.getReferralContext(env);
* break;
* } catch (NamingException ne) {
* if (! shallIRetry()) {
* return;
* }
* // modify environment properties (env), if necessary
* e.retryReferral();
* }
* }
* }
* </pre></blockquote>
*
*/
public abstract void retryReferral();
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -2881363844695698876L;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming;
/** {@collect.stats}
* This class represents a Reference whose contents is a name, called the link name,
* that is bound to an atomic name in a context.
*<p>
* The name is a URL, or a name to be resolved relative to the initial
* context, or if the first character of the name is ".", the name
* is relative to the context in which the link is bound.
*<p>
* Normal resolution of names in context operations always follow links.
* Resolution of the link name itself may cause resolution to pass through
* other links. This gives rise to the possibility of a cycle of links whose
* resolution could not terminate normally. As a simple means to avoid such
* non-terminating resolutions, service providers may define limits on the
* number of links that may be involved in any single operation invoked
* by the caller.
*<p>
* A LinkRef contains a single StringRefAddr, whose type is "LinkAddress",
* and whose contents is the link name. The class name field of the
* Reference is that of this (LinkRef) class.
*<p>
* LinkRef is bound to a name using the normal Context.bind()/rebind(), and
* DirContext.bind()/rebind(). Context.lookupLink() is used to retrieve the link
* itself if the terminal atomic name is bound to a link.
*<p>
* Many naming systems support a native notion of link that may be used
* within the naming system itself. JNDI does not specify whether
* there is any relationship between such native links and JNDI links.
*<p>
* A LinkRef instance is not synchronized against concurrent access by multiple
* threads. Threads that need to access a LinkRef instance concurrently should
* synchronize amongst themselves and provide the necessary locking.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see LinkException
* @see LinkLoopException
* @see MalformedLinkException
* @see Context#lookupLink
* @since 1.3
*/
/*<p>
* The serialized form of a LinkRef object consists of the serialized
* fields of its Reference superclass.
*/
public class LinkRef extends Reference {
/* code for link handling */
static final String linkClassName = LinkRef.class.getName();
static final String linkAddrType = "LinkAddress";
/** {@collect.stats}
* Constructs a LinkRef for a name.
* @param linkName The non-null name for which to create this link.
*/
public LinkRef(Name linkName) {
super(linkClassName, new StringRefAddr(linkAddrType, linkName.toString()));
}
/** {@collect.stats}
* Constructs a LinkRef for a string name.
* @param linkName The non-null name for which to create this link.
*/
public LinkRef(String linkName) {
super(linkClassName, new StringRefAddr(linkAddrType, linkName));
}
/** {@collect.stats}
* Retrieves the name of this link.
*
* @return The non-null name of this link.
* @exception MalformedLinkException If a link name could not be extracted
* @exception NamingException If a naming exception was encountered.
*/
public String getLinkName() throws NamingException {
if (className != null && className.equals(linkClassName)) {
RefAddr addr = get(linkAddrType);
if (addr != null && addr instanceof StringRefAddr) {
return (String)((StringRefAddr)addr).getContent();
}
}
throw new MalformedLinkException();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -5386290613498931298L;
}
|
Java
|
/*
* Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This class represents the address of a communications end-point.
* It consists of a type that describes the communication mechanism
* and an address contents determined by an RefAddr subclass.
*<p>
* For example, an address type could be "BSD Printer Address",
* which specifies that it is an address to be used with the BSD printing
* protocol. Its contents could be the machine name identifying the
* location of the printer server that understands this protocol.
*<p>
* A RefAddr is contained within a Reference.
*<p>
* RefAddr is an abstract class. Concrete implementations of it
* determine its synchronization properties.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see Reference
* @see LinkRef
* @see StringRefAddr
* @see BinaryRefAddr
* @since 1.3
*/
/*<p>
* The serialized form of a RefAddr object consists of only its type name
* String.
*/
public abstract class RefAddr implements java.io.Serializable {
/** {@collect.stats}
* Contains the type of this address.
* @serial
*/
protected String addrType;
/** {@collect.stats}
* Constructs a new instance of RefAddr using its address type.
*
* @param addrType A non-null string describing the type of the address.
*/
protected RefAddr(String addrType) {
this.addrType = addrType;
}
/** {@collect.stats}
* Retrieves the address type of this address.
*
* @return The non-null address type of this address.
*/
public String getType() {
return addrType;
}
/** {@collect.stats}
* Retrieves the contents of this address.
*
* @return The possibly null address contents.
*/
public abstract Object getContent();
/** {@collect.stats}
* Determines whether obj is equal to this RefAddr.
*<p>
* obj is equal to this RefAddr all of these conditions are true
*<ul> non-null
*<li> instance of RefAddr
*<li> obj has the same address type as this RefAddr (using String.compareTo())
*<li> both obj and this RefAddr's contents are null or they are equal
* (using the equals() test).
*</ul>
* @param obj possibly null obj to check.
* @return true if obj is equal to this refaddr; false otherwise.
* @see #getContent
* @see #getType
*/
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof RefAddr)) {
RefAddr target = (RefAddr)obj;
if (addrType.compareTo(target.addrType) == 0) {
Object thisobj = this.getContent();
Object thatobj = target.getContent();
if (thisobj == thatobj)
return true;
if (thisobj != null)
return thisobj.equals(thatobj);
}
}
return false;
}
/** {@collect.stats}
* Computes the hash code of this address using its address type and contents.
* The hash code is the sum of the hash code of the address type and
* the hash code of the address contents.
*
* @return The hash code of this address as an int.
* @see java.lang.Object#hashCode
*/
public int hashCode() {
return (getContent() == null)
? addrType.hashCode()
: addrType.hashCode() + getContent().hashCode();
}
/** {@collect.stats}
* Generates the string representation of this address.
* The string consists of the address's type and contents with labels.
* This representation is intended for display only and not to be parsed.
* @return The non-null string representation of this address.
*/
public String toString(){
StringBuffer str = new StringBuffer("Type: " + addrType + "\n");
str.append("Content: " + getContent() + "\n");
return (str.toString());
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -1468165120479154358L;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming;
import java.util.Vector;
import java.util.Enumeration;
import java.util.Properties;
import java.util.NoSuchElementException;
/** {@collect.stats}
* The implementation class for CompoundName and CompositeName.
* This class is package private.
*
* @author Rosanna Lee
* @author Scott Seligman
* @author Aravindan Ranganathan
* @since 1.3
*/
class NameImpl {
private static final byte LEFT_TO_RIGHT = 1;
private static final byte RIGHT_TO_LEFT = 2;
private static final byte FLAT = 0;
private Vector components;
private byte syntaxDirection = LEFT_TO_RIGHT;
private String syntaxSeparator = "/";
private String syntaxSeparator2 = null;
private boolean syntaxCaseInsensitive = false;
private boolean syntaxTrimBlanks = false;
private String syntaxEscape = "\\";
private String syntaxBeginQuote1 = "\"";
private String syntaxEndQuote1 = "\"";
private String syntaxBeginQuote2 = "'";
private String syntaxEndQuote2 = "'";
private String syntaxAvaSeparator = null;
private String syntaxTypevalSeparator = null;
// escapingStyle gives the method used at creation time for
// quoting or escaping characters in the name. It is set to the
// first style of quote or escape encountered if and when the name
// is parsed.
private static final int STYLE_NONE = 0;
private static final int STYLE_QUOTE1 = 1;
private static final int STYLE_QUOTE2 = 2;
private static final int STYLE_ESCAPE = 3;
private int escapingStyle = STYLE_NONE;
// Returns true if "match" is not null, and n contains "match" at
// position i.
private final boolean isA(String n, int i, String match) {
return (match != null && n.startsWith(match, i));
}
private final boolean isMeta(String n, int i) {
return (isA(n, i, syntaxEscape) ||
isA(n, i, syntaxBeginQuote1) ||
isA(n, i, syntaxBeginQuote2) ||
isSeparator(n, i));
}
private final boolean isSeparator(String n, int i) {
return (isA(n, i, syntaxSeparator) ||
isA(n, i, syntaxSeparator2));
}
private final int skipSeparator(String name, int i) {
if (isA(name, i, syntaxSeparator)) {
i += syntaxSeparator.length();
} else if (isA(name, i, syntaxSeparator2)) {
i += syntaxSeparator2.length();
}
return (i);
}
private final int extractComp(String name, int i, int len, Vector comps)
throws InvalidNameException {
String beginQuote;
String endQuote;
boolean start = true;
boolean one = false;
StringBuffer answer = new StringBuffer(len);
while (i < len) {
// handle quoted strings
if (start && ((one = isA(name, i, syntaxBeginQuote1)) ||
isA(name, i, syntaxBeginQuote2))) {
// record choice of quote chars being used
beginQuote = one ? syntaxBeginQuote1 : syntaxBeginQuote2;
endQuote = one ? syntaxEndQuote1 : syntaxEndQuote2;
if (escapingStyle == STYLE_NONE) {
escapingStyle = one ? STYLE_QUOTE1 : STYLE_QUOTE2;
}
// consume string until matching quote
for (i += beginQuote.length();
((i < len) && !name.startsWith(endQuote, i));
i++) {
// skip escape character if it is escaping ending quote
// otherwise leave as is.
if (isA(name, i, syntaxEscape) &&
isA(name, i + syntaxEscape.length(), endQuote)) {
i += syntaxEscape.length();
}
answer.append(name.charAt(i)); // copy char
}
// no ending quote found
if (i >= len)
throw
new InvalidNameException(name + ": no close quote");
// new Exception("no close quote");
i += endQuote.length();
// verify that end-quote occurs at separator or end of string
if (i == len || isSeparator(name, i)) {
break;
}
// throw (new Exception(
throw (new InvalidNameException(name +
": close quote appears before end of component"));
} else if (isSeparator(name, i)) {
break;
} else if (isA(name, i, syntaxEscape)) {
if (isMeta(name, i + syntaxEscape.length())) {
// if escape precedes meta, consume escape and let
// meta through
i += syntaxEscape.length();
if (escapingStyle == STYLE_NONE) {
escapingStyle = STYLE_ESCAPE;
}
} else if (i + syntaxEscape.length() >= len) {
throw (new InvalidNameException(name +
": unescaped " + syntaxEscape + " at end of component"));
}
} else if (isA(name, i, syntaxTypevalSeparator) &&
((one = isA(name, i+syntaxTypevalSeparator.length(), syntaxBeginQuote1)) ||
isA(name, i+syntaxTypevalSeparator.length(), syntaxBeginQuote2))) {
// Handle quote occurring after typeval separator
beginQuote = one ? syntaxBeginQuote1 : syntaxBeginQuote2;
endQuote = one ? syntaxEndQuote1 : syntaxEndQuote2;
i += syntaxTypevalSeparator.length();
answer.append(syntaxTypevalSeparator+beginQuote); // add back
// consume string until matching quote
for (i += beginQuote.length();
((i < len) && !name.startsWith(endQuote, i));
i++) {
// skip escape character if it is escaping ending quote
// otherwise leave as is.
if (isA(name, i, syntaxEscape) &&
isA(name, i + syntaxEscape.length(), endQuote)) {
i += syntaxEscape.length();
}
answer.append(name.charAt(i)); // copy char
}
// no ending quote found
if (i >= len)
throw
new InvalidNameException(name + ": typeval no close quote");
i += endQuote.length();
answer.append(endQuote); // add back
// verify that end-quote occurs at separator or end of string
if (i == len || isSeparator(name, i)) {
break;
}
throw (new InvalidNameException(name.substring(i) +
": typeval close quote appears before end of component"));
}
answer.append(name.charAt(i++));
start = false;
}
if (syntaxDirection == RIGHT_TO_LEFT)
comps.insertElementAt(answer.toString(), 0);
else
comps.addElement(answer.toString());
return i;
}
private static boolean getBoolean(Properties p, String name) {
return toBoolean(p.getProperty(name));
}
private static boolean toBoolean(String name) {
return ((name != null) && name.toLowerCase().equals("true"));
}
private final void recordNamingConvention(Properties p) {
String syntaxDirectionStr =
p.getProperty("jndi.syntax.direction", "flat");
if (syntaxDirectionStr.equals("left_to_right")) {
syntaxDirection = LEFT_TO_RIGHT;
} else if (syntaxDirectionStr.equals("right_to_left")) {
syntaxDirection = RIGHT_TO_LEFT;
} else if (syntaxDirectionStr.equals("flat")) {
syntaxDirection = FLAT;
} else {
throw new IllegalArgumentException(syntaxDirectionStr +
"is not a valid value for the jndi.syntax.direction property");
}
if (syntaxDirection != FLAT) {
syntaxSeparator = p.getProperty("jndi.syntax.separator");
syntaxSeparator2 = p.getProperty("jndi.syntax.separator2");
if (syntaxSeparator == null) {
throw new IllegalArgumentException(
"jndi.syntax.separator property required for non-flat syntax");
}
} else {
syntaxSeparator = null;
}
syntaxEscape = p.getProperty("jndi.syntax.escape");
syntaxCaseInsensitive = getBoolean(p, "jndi.syntax.ignorecase");
syntaxTrimBlanks = getBoolean(p, "jndi.syntax.trimblanks");
syntaxBeginQuote1 = p.getProperty("jndi.syntax.beginquote");
syntaxEndQuote1 = p.getProperty("jndi.syntax.endquote");
if (syntaxEndQuote1 == null && syntaxBeginQuote1 != null)
syntaxEndQuote1 = syntaxBeginQuote1;
else if (syntaxBeginQuote1 == null && syntaxEndQuote1 != null)
syntaxBeginQuote1 = syntaxEndQuote1;
syntaxBeginQuote2 = p.getProperty("jndi.syntax.beginquote2");
syntaxEndQuote2 = p.getProperty("jndi.syntax.endquote2");
if (syntaxEndQuote2 == null && syntaxBeginQuote2 != null)
syntaxEndQuote2 = syntaxBeginQuote2;
else if (syntaxBeginQuote2 == null && syntaxEndQuote2 != null)
syntaxBeginQuote2 = syntaxEndQuote2;
syntaxAvaSeparator = p.getProperty("jndi.syntax.separator.ava");
syntaxTypevalSeparator =
p.getProperty("jndi.syntax.separator.typeval");
}
NameImpl(Properties syntax) {
if (syntax != null) {
recordNamingConvention(syntax);
}
components = new Vector();
}
NameImpl(Properties syntax, String n) throws InvalidNameException {
this(syntax);
boolean rToL = (syntaxDirection == RIGHT_TO_LEFT);
boolean compsAllEmpty = true;
int len = n.length();
for (int i = 0; i < len; ) {
i = extractComp(n, i, len, components);
String comp = rToL
? (String)components.firstElement()
: (String)components.lastElement();
if (comp.length() >= 1) {
compsAllEmpty = false;
}
if (i < len) {
i = skipSeparator(n, i);
if ((i == len) && !compsAllEmpty) {
// Trailing separator found. Add an empty component.
if (rToL) {
components.insertElementAt("", 0);
} else {
components.addElement("");
}
}
}
}
}
NameImpl(Properties syntax, Enumeration comps) {
this(syntax);
// %% comps could shrink in the middle.
while (comps.hasMoreElements())
components.addElement(comps.nextElement());
}
/*
// Determines whether this component needs any escaping.
private final boolean escapingNeeded(String comp) {
int len = comp.length();
for (int i = 0; i < len; i++) {
if (i == 0) {
if (isA(comp, 0, syntaxBeginQuote1) ||
isA(comp, 0, syntaxBeginQuote2)) {
return (true);
}
}
if (isSeparator(comp, i)) {
return (true);
}
if (isA(comp, i, syntaxEscape)) {
i += syntaxEscape.length();
if (i >= len || isMeta(comp, i)) {
return (true);
}
}
}
return (false);
}
*/
private final String stringifyComp(String comp) {
int len = comp.length();
boolean escapeSeparator = false, escapeSeparator2 = false;
String beginQuote = null, endQuote = null;
StringBuffer strbuf = new StringBuffer(len);
// determine whether there are any separators; if so escape
// or quote them
if (syntaxSeparator != null &&
comp.indexOf(syntaxSeparator) >= 0) {
if (syntaxBeginQuote1 != null) {
beginQuote = syntaxBeginQuote1;
endQuote = syntaxEndQuote1;
} else if (syntaxBeginQuote2 != null) {
beginQuote = syntaxBeginQuote2;
endQuote = syntaxEndQuote2;
} else if (syntaxEscape != null)
escapeSeparator = true;
}
if (syntaxSeparator2 != null &&
comp.indexOf(syntaxSeparator2) >= 0) {
if (syntaxBeginQuote1 != null) {
if (beginQuote == null) {
beginQuote = syntaxBeginQuote1;
endQuote = syntaxEndQuote1;
}
} else if (syntaxBeginQuote2 != null) {
if (beginQuote == null) {
beginQuote = syntaxBeginQuote2;
endQuote = syntaxEndQuote2;
}
} else if (syntaxEscape != null)
escapeSeparator2 = true;
}
// if quoting component,
if (beginQuote != null) {
// start string off with opening quote
strbuf = strbuf.append(beginQuote);
// component is being quoted, so we only need to worry about
// escaping end quotes that occur in component
for (int i = 0; i < len; ) {
if (comp.startsWith(endQuote, i)) {
// end-quotes must be escaped when inside a quoted string
strbuf.append(syntaxEscape).append(endQuote);
i += endQuote.length();
} else {
// no special treatment required
strbuf.append(comp.charAt(i++));
}
}
// end with closing quote
strbuf.append(endQuote);
} else {
// When component is not quoted, add escape for:
// 1. leading quote
// 2. an escape preceding any meta char
// 3. an escape at the end of a component
// 4. separator
// go through characters in component and escape where necessary
boolean start = true;
for (int i = 0; i < len; ) {
// leading quote must be escaped
if (start && isA(comp, i, syntaxBeginQuote1)) {
strbuf.append(syntaxEscape).append(syntaxBeginQuote1);
i += syntaxBeginQuote1.length();
} else if (start && isA(comp, i, syntaxBeginQuote2)) {
strbuf.append(syntaxEscape).append(syntaxBeginQuote2);
i += syntaxBeginQuote2.length();
} else
// Escape an escape preceding meta characters, or at end.
// Other escapes pass through.
if (isA(comp, i, syntaxEscape)) {
if (i + syntaxEscape.length() >= len) {
// escape an ending escape
strbuf.append(syntaxEscape);
} else if (isMeta(comp, i + syntaxEscape.length())) {
// escape meta strings
strbuf.append(syntaxEscape);
}
strbuf.append(syntaxEscape);
i += syntaxEscape.length();
} else
// escape unescaped separator
if (escapeSeparator && comp.startsWith(syntaxSeparator, i)) {
// escape separator
strbuf.append(syntaxEscape).append(syntaxSeparator);
i += syntaxSeparator.length();
} else if (escapeSeparator2 &&
comp.startsWith(syntaxSeparator2, i)) {
// escape separator2
strbuf.append(syntaxEscape).append(syntaxSeparator2);
i += syntaxSeparator2.length();
} else {
// no special treatment required
strbuf.append(comp.charAt(i++));
}
start = false;
}
}
return (strbuf.toString());
}
public String toString() {
StringBuffer answer = new StringBuffer();
String comp;
boolean compsAllEmpty = true;
int size = components.size();
for (int i = 0; i < size; i++) {
if (syntaxDirection == RIGHT_TO_LEFT) {
comp =
stringifyComp((String) components.elementAt(size - 1 - i));
} else {
comp = stringifyComp((String) components.elementAt(i));
}
if ((i != 0) && (syntaxSeparator != null))
answer.append(syntaxSeparator);
if (comp.length() >= 1)
compsAllEmpty = false;
answer = answer.append(comp);
}
if (compsAllEmpty && (size >= 1) && (syntaxSeparator != null))
answer = answer.append(syntaxSeparator);
return (answer.toString());
}
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof NameImpl)) {
NameImpl target = (NameImpl)obj;
if (target.size() == this.size()) {
Enumeration mycomps = getAll();
Enumeration comps = target.getAll();
while (mycomps.hasMoreElements()) {
// %% comps could shrink in the middle.
String my = (String)mycomps.nextElement();
String his = (String)comps.nextElement();
if (syntaxTrimBlanks) {
my = my.trim();
his = his.trim();
}
if (syntaxCaseInsensitive) {
if (!(my.equalsIgnoreCase(his)))
return false;
} else {
if (!(my.equals(his)))
return false;
}
}
return true;
}
}
return false;
}
/** {@collect.stats}
* Compares obj to this NameImpl to determine ordering.
* Takes into account syntactic properties such as
* elimination of blanks, case-ignore, etc, if relevant.
*
* Note: using syntax of this NameImpl and ignoring
* that of comparison target.
*/
public int compareTo(NameImpl obj) {
if (this == obj) {
return 0;
}
int len1 = size();
int len2 = obj.size();
int n = Math.min(len1, len2);
int index1 = 0, index2 = 0;
while (n-- != 0) {
String comp1 = get(index1++);
String comp2 = obj.get(index2++);
// normalize according to syntax
if (syntaxTrimBlanks) {
comp1 = comp1.trim();
comp2 = comp2.trim();
}
if (syntaxCaseInsensitive) {
comp1 = comp1.toLowerCase();
comp2 = comp2.toLowerCase();
}
int local = comp1.compareTo(comp2);
if (local != 0) {
return local;
}
}
return len1 - len2;
}
public int size() {
return (components.size());
}
public Enumeration getAll() {
return components.elements();
}
public String get(int posn) {
return ((String) components.elementAt(posn));
}
public Enumeration getPrefix(int posn) {
if (posn < 0 || posn > size()) {
throw new ArrayIndexOutOfBoundsException(posn);
}
return new NameImplEnumerator(components, 0, posn);
}
public Enumeration getSuffix(int posn) {
int cnt = size();
if (posn < 0 || posn > cnt) {
throw new ArrayIndexOutOfBoundsException(posn);
}
return new NameImplEnumerator(components, posn, cnt);
}
public boolean isEmpty() {
return (components.isEmpty());
}
public boolean startsWith(int posn, Enumeration prefix) {
if (posn < 0 || posn > size()) {
return false;
}
try {
Enumeration mycomps = getPrefix(posn);
while (mycomps.hasMoreElements()) {
String my = (String)mycomps.nextElement();
String his = (String)prefix.nextElement();
if (syntaxTrimBlanks) {
my = my.trim();
his = his.trim();
}
if (syntaxCaseInsensitive) {
if (!(my.equalsIgnoreCase(his)))
return false;
} else {
if (!(my.equals(his)))
return false;
}
}
} catch (NoSuchElementException e) {
return false;
}
return true;
}
public boolean endsWith(int posn, Enumeration suffix) {
// posn is number of elements in suffix
// startIndex is the starting position in this name
// at which to start the comparison. It is calculated by
// subtracting 'posn' from size()
int startIndex = size() - posn;
if (startIndex < 0 || startIndex > size()) {
return false;
}
try {
Enumeration mycomps = getSuffix(startIndex);
while (mycomps.hasMoreElements()) {
String my = (String)mycomps.nextElement();
String his = (String)suffix.nextElement();
if (syntaxTrimBlanks) {
my = my.trim();
his = his.trim();
}
if (syntaxCaseInsensitive) {
if (!(my.equalsIgnoreCase(his)))
return false;
} else {
if (!(my.equals(his)))
return false;
}
}
} catch (NoSuchElementException e) {
return false;
}
return true;
}
public boolean addAll(Enumeration comps) throws InvalidNameException {
boolean added = false;
while (comps.hasMoreElements()) {
try {
Object comp = comps.nextElement();
if (size() > 0 && syntaxDirection == FLAT) {
throw new InvalidNameException(
"A flat name can only have a single component");
}
components.addElement(comp);
added = true;
} catch (NoSuchElementException e) {
break; // "comps" has shrunk.
}
}
return added;
}
public boolean addAll(int posn, Enumeration comps)
throws InvalidNameException {
boolean added = false;
for (int i = posn; comps.hasMoreElements(); i++) {
try {
Object comp = comps.nextElement();
if (size() > 0 && syntaxDirection == FLAT) {
throw new InvalidNameException(
"A flat name can only have a single component");
}
components.insertElementAt(comp, i);
added = true;
} catch (NoSuchElementException e) {
break; // "comps" has shrunk.
}
}
return added;
}
public void add(String comp) throws InvalidNameException {
if (size() > 0 && syntaxDirection == FLAT) {
throw new InvalidNameException(
"A flat name can only have a single component");
}
components.addElement(comp);
}
public void add(int posn, String comp) throws InvalidNameException {
if (size() > 0 && syntaxDirection == FLAT) {
throw new InvalidNameException(
"A flat name can only zero or one component");
}
components.insertElementAt(comp, posn);
}
public Object remove(int posn) {
Object r = components.elementAt(posn);
components.removeElementAt(posn);
return r;
}
public int hashCode() {
int hash = 0;
for (Enumeration e = getAll(); e.hasMoreElements();) {
String comp = (String)e.nextElement();
if (syntaxTrimBlanks) {
comp = comp.trim();
}
if (syntaxCaseInsensitive) {
comp = comp.toLowerCase();
}
hash += comp.hashCode();
}
return hash;
}
}
final
class NameImplEnumerator implements Enumeration {
Vector vector;
int count;
int limit;
NameImplEnumerator(Vector v, int start, int lim) {
vector = v;
count = start;
limit = lim;
}
public boolean hasMoreElements() {
return count < limit;
}
public Object nextElement() {
if (count < limit) {
return vector.elementAt(count++);
}
throw new NoSuchElementException("NameImplEnumerator");
}
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown when a naming operation proceeds to a point
* where a context is required to continue the operation, but the
* resolved object is not a context. For example, Context.destroy() requires
* that the named object be a context. If it is not, NotContextException
* is thrown. Another example is a non-context being encountered during
* the resolution phase of the Context methods.
*<p>
* It is also thrown when a particular subtype of context is required,
* such as a DirContext, and the resolved object is a context but not of
* the required subtype.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
* @see Context#destroySubcontext
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class NotContextException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of NotContextException using an
* explanation. All other fields default to null.
*
* @param explanation Possibly null additional detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public NotContextException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of NotContextException.
* All fields default to null.
*/
public NotContextException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 849752551644540417L;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming;
/** {@collect.stats}
* This is the superclass of all exceptions thrown by
* operations in the Context and DirContext interfaces.
* The nature of the failure is described by the name of the subclass.
* This exception captures the information pinpointing where the operation
* failed, such as where resolution last proceeded to.
* <ul>
* <li> Resolved Name. Portion of name that has been resolved.
* <li> Resolved Object. Object to which resolution of name proceeded.
* <li> Remaining Name. Portion of name that has not been resolved.
* <li> Explanation. Detail explaining why name resolution failed.
* <li> Root Exception. The exception that caused this naming exception
* to be thrown.
*</ul>
* null is an acceptable value for any of these fields. When null,
* it means that no such information has been recorded for that field.
*<p>
* A NamingException instance is not synchronized against concurrent
* multithreaded access. Multiple threads trying to access and modify
* a single NamingException instance should lock the object.
*<p>
* This exception has been retrofitted to conform to
* the general purpose exception-chaining mechanism. The
* <i>root exception</i> (or <i>root cause</i>) is the same object as the
* <i>cause</i> returned by the {@link Throwable#getCause()} method.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class NamingException extends Exception {
/** {@collect.stats}
* Contains the part of the name that has been successfully resolved.
* It is a composite name and can be null.
* This field is initialized by the constructors.
* You should access and manipulate this field
* through its get and set methods.
* @serial
* @see #getResolvedName
* @see #setResolvedName
*/
protected Name resolvedName;
/** {@collect.stats}
* Contains the object to which resolution of the part of the name was
* successful. Can be null.
* This field is initialized by the constructors.
* You should access and manipulate this field
* through its get and set methods.
* @serial
* @see #getResolvedObj
* @see #setResolvedObj
*/
protected Object resolvedObj;
/** {@collect.stats}
* Contains the remaining name that has not been resolved yet.
* It is a composite name and can be null.
* This field is initialized by the constructors.
* You should access and manipulate this field
* through its get, set, "append" methods.
* @serial
* @see #getRemainingName
* @see #setRemainingName
* @see #appendRemainingName
* @see #appendRemainingComponent
*/
protected Name remainingName;
/** {@collect.stats}
* Contains the original exception that caused this NamingException to
* be thrown. This field is set if there is additional
* information that could be obtained from the original
* exception, or if the original exception could not be
* mapped to a subclass of NamingException.
* Can be null.
*<p>
* This field predates the general-purpose exception chaining facility.
* The {@link #initCause(Throwable)} and {@link #getCause()} methods
* are now the preferred means of accessing this information.
*
* @serial
* @see #getRootCause
* @see #setRootCause(Throwable)
* @see #initCause(Throwable)
* @see #getCause
*/
protected Throwable rootException = null;
/** {@collect.stats}
* Constructs a new NamingException with an explanation.
* All unspecified fields are set to null.
*
* @param explanation A possibly null string containing
* additional detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public NamingException(String explanation) {
super(explanation);
resolvedName = remainingName = null;
resolvedObj = null;
}
/** {@collect.stats}
* Constructs a new NamingException.
* All fields are set to null.
*/
public NamingException() {
super();
resolvedName = remainingName = null;
resolvedObj = null;
}
/** {@collect.stats}
* Retrieves the leading portion of the name that was resolved
* successfully.
*
* @return The part of the name that was resolved successfully.
* It is a composite name. It can be null, which means
* the resolved name field has not been set.
* @see #getResolvedObj
* @see #setResolvedName
*/
public Name getResolvedName() {
return resolvedName;
}
/** {@collect.stats}
* Retrieves the remaining unresolved portion of the name.
* @return The part of the name that has not been resolved.
* It is a composite name. It can be null, which means
* the remaining name field has not been set.
* @see #setRemainingName
* @see #appendRemainingName
* @see #appendRemainingComponent
*/
public Name getRemainingName() {
return remainingName;
}
/** {@collect.stats}
* Retrieves the object to which resolution was successful.
* This is the object to which the resolved name is bound.
*
* @return The possibly null object that was resolved so far.
* null means that the resolved object field has not been set.
* @see #getResolvedName
* @see #setResolvedObj
*/
public Object getResolvedObj() {
return resolvedObj;
}
/** {@collect.stats}
* Retrieves the explanation associated with this exception.
*
* @return The possibly null detail string explaining more
* about this exception. If null, it means there is no
* detail message for this exception.
*
* @see java.lang.Throwable#getMessage
*/
public String getExplanation() {
return getMessage();
}
/** {@collect.stats}
* Sets the resolved name field of this exception.
*<p>
* <tt>name</tt> is a composite name. If the intent is to set
* this field using a compound name or string, you must
* "stringify" the compound name, and create a composite
* name with a single component using the string. You can then
* invoke this method using the resulting composite name.
*<p>
* A copy of <code>name</code> is made and stored.
* Subsequent changes to <code>name</code> does not
* affect the copy in this NamingException and vice versa.
*
* @param name The possibly null name to set resolved name to.
* If null, it sets the resolved name field to null.
* @see #getResolvedName
*/
public void setResolvedName(Name name) {
if (name != null)
resolvedName = (Name)(name.clone());
else
resolvedName = null;
}
/** {@collect.stats}
* Sets the remaining name field of this exception.
*<p>
* <tt>name</tt> is a composite name. If the intent is to set
* this field using a compound name or string, you must
* "stringify" the compound name, and create a composite
* name with a single component using the string. You can then
* invoke this method using the resulting composite name.
*<p>
* A copy of <code>name</code> is made and stored.
* Subsequent changes to <code>name</code> does not
* affect the copy in this NamingException and vice versa.
* @param name The possibly null name to set remaining name to.
* If null, it sets the remaining name field to null.
* @see #getRemainingName
* @see #appendRemainingName
* @see #appendRemainingComponent
*/
public void setRemainingName(Name name) {
if (name != null)
remainingName = (Name)(name.clone());
else
remainingName = null;
}
/** {@collect.stats}
* Sets the resolved object field of this exception.
* @param obj The possibly null object to set resolved object to.
* If null, the resolved object field is set to null.
* @see #getResolvedObj
*/
public void setResolvedObj(Object obj) {
resolvedObj = obj;
}
/** {@collect.stats}
* Add name as the last component in remaining name.
* @param name The component to add.
* If name is null, this method does not do anything.
* @see #setRemainingName
* @see #getRemainingName
* @see #appendRemainingName
*/
public void appendRemainingComponent(String name) {
if (name != null) {
try {
if (remainingName == null) {
remainingName = new CompositeName();
}
remainingName.add(name);
} catch (NamingException e) {
throw new IllegalArgumentException(e.toString());
}
}
}
/** {@collect.stats}
* Add components from 'name' as the last components in
* remaining name.
*<p>
* <tt>name</tt> is a composite name. If the intent is to append
* a compound name, you should "stringify" the compound name
* then invoke the overloaded form that accepts a String parameter.
*<p>
* Subsequent changes to <code>name</code> does not
* affect the remaining name field in this NamingException and vice versa.
* @param name The possibly null name containing ordered components to add.
* If name is null, this method does not do anything.
* @see #setRemainingName
* @see #getRemainingName
* @see #appendRemainingComponent
*/
public void appendRemainingName(Name name) {
if (name == null) {
return;
}
if (remainingName != null) {
try {
remainingName.addAll(name);
} catch (NamingException e) {
throw new IllegalArgumentException(e.toString());
}
} else {
remainingName = (Name)(name.clone());
}
}
/** {@collect.stats}
* Retrieves the root cause of this NamingException, if any.
* The root cause of a naming exception is used when the service provider
* wants to indicate to the caller a non-naming related exception
* but at the same time wants to use the NamingException structure
* to indicate how far the naming operation proceeded.
*<p>
* This method predates the general-purpose exception chaining facility.
* The {@link #getCause()} method is now the preferred means of obtaining
* this information.
*
* @return The possibly null exception that caused this naming
* exception. If null, it means no root cause has been
* set for this naming exception.
* @see #setRootCause
* @see #rootException
* @see #getCause
*/
public Throwable getRootCause() {
return rootException;
}
/** {@collect.stats}
* Records the root cause of this NamingException.
* If <tt>e</tt> is <tt>this</tt>, this method does not do anything.
*<p>
* This method predates the general-purpose exception chaining facility.
* The {@link #initCause(Throwable)} method is now the preferred means
* of recording this information.
*
* @param e The possibly null exception that caused the naming
* operation to fail. If null, it means this naming
* exception has no root cause.
* @see #getRootCause
* @see #rootException
* @see #initCause
*/
public void setRootCause(Throwable e) {
if (e != this) {
rootException = e;
}
}
/** {@collect.stats}
* Returns the cause of this exception. The cause is the
* throwable that caused this naming exception to be thrown.
* Returns <code>null</code> if the cause is nonexistent or
* unknown.
*
* @return the cause of this exception, or <code>null</code> if the
* cause is nonexistent or unknown.
* @see #initCause(Throwable)
* @since 1.4
*/
public Throwable getCause() {
return getRootCause();
}
/** {@collect.stats}
* Initializes the cause of this exception to the specified value.
* The cause is the throwable that caused this naming exception to be
* thrown.
*<p>
* This method may be called at most once.
*
* @param cause the cause, which is saved for later retrieval by
* the {@link #getCause()} method. A <tt>null</tt> value
* indicates that the cause is nonexistent or unknown.
* @return a reference to this <code>NamingException</code> instance.
* @throws IllegalArgumentException if <code>cause</code> is this
* exception. (A throwable cannot be its own cause.)
* @throws IllegalStateException if this method has already
* been called on this exception.
* @see #getCause
* @since 1.4
*/
public Throwable initCause(Throwable cause) {
super.initCause(cause);
setRootCause(cause);
return this;
}
/** {@collect.stats}
* Generates the string representation of this exception.
* The string representation consists of this exception's class name,
* its detailed message, and if it has a root cause, the string
* representation of the root cause exception, followed by
* the remaining name (if it is not null).
* This string is used for debugging and not meant to be interpreted
* programmatically.
*
* @return The non-null string containing the string representation
* of this exception.
*/
public String toString() {
String answer = super.toString();
if (rootException != null) {
answer += " [Root exception is " + rootException + "]";
}
if (remainingName != null) {
answer += "; remaining name '" + remainingName + "'";
}
return answer;
}
/** {@collect.stats}
* Generates the string representation in more detail.
* This string representation consists of the information returned
* by the toString() that takes no parameters, plus the string
* representation of the resolved object (if it is not null).
* This string is used for debugging and not meant to be interpreted
* programmatically.
*
* @param detail If true, include details about the resolved object
* in addition to the other information.
* @return The non-null string containing the string representation.
*/
public String toString(boolean detail) {
if (!detail || resolvedObj == null) {
return toString();
} else {
return (toString() + "; resolved object " + resolvedObj);
}
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -1299181962103167177L;
};
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown when
* the particular flavor of authentication requested is not supported.
* For example, if the program
* is attempting to use strong authentication but the directory/naming
* supports only simple authentication, this exception would be thrown.
* Identification of a particular flavor of authentication is
* provider- and server-specific. It may be specified using
* specific authentication schemes such
* those identified using SASL, or a generic authentication specifier
* (such as "simple" and "strong").
*<p>
* If the program wants to handle this exception in particular, it
* should catch AuthenticationNotSupportedException explicitly before
* attempting to catch NamingException. After catching
* <code>AuthenticationNotSupportedException</code>, the program could
* reattempt the authentication using a different authentication flavor
* by updating the resolved context's environment properties accordingly.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class AuthenticationNotSupportedException extends NamingSecurityException {
/** {@collect.stats}
* Constructs a new instance of AuthenticationNotSupportedException using
* an explanation. All other fields default to null.
*
* @param explanation A possibly null string containing additional
* detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public AuthenticationNotSupportedException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of AuthenticationNotSupportedException
* all name resolution fields and explanation initialized to null.
*/
public AuthenticationNotSupportedException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -7149033933259492300L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This class represents the string form of the address of
* a communications end-point.
* It consists of a type that describes the communication mechanism
* and a string contents specific to that communication mechanism.
* The format and interpretation of
* the address type and the contents of the address are based on
* the agreement of three parties: the client that uses the address,
* the object/server that can be reached using the address, and the
* administrator or program that creates the address.
*
* <p> An example of a string reference address is a host name.
* Another example of a string reference address is a URL.
*
* <p> A string reference address is immutable:
* once created, it cannot be changed. Multithreaded access to
* a single StringRefAddr need not be synchronized.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see RefAddr
* @see BinaryRefAddr
* @since 1.3
*/
public class StringRefAddr extends RefAddr {
/** {@collect.stats}
* Contains the contents of this address.
* Can be null.
* @serial
*/
private String contents;
/** {@collect.stats}
* Constructs a new instance of StringRefAddr using its address type
* and contents.
*
* @param addrType A non-null string describing the type of the address.
* @param addr The possibly null contents of the address in the form of a string.
*/
public StringRefAddr(String addrType, String addr) {
super(addrType);
contents = addr;
}
/** {@collect.stats}
* Retrieves the contents of this address. The result is a string.
*
* @return The possibly null address contents.
*/
public Object getContent() {
return contents;
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -8913762495138505527L;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming;
import java.util.Hashtable;
import javax.naming.spi.NamingManager;
import com.sun.naming.internal.ResourceManager;
/** {@collect.stats}
* This class is the starting context for performing naming operations.
*<p>
* All naming operations are relative to a context.
* The initial context implements the Context interface and
* provides the starting point for resolution of names.
*<p>
* <a name=ENVIRONMENT></a>
* When the initial context is constructed, its environment
* is initialized with properties defined in the environment parameter
* passed to the constructor, and in any
* <a href=Context.html#RESOURCEFILES>application resource files</a>.
* In addition, a small number of standard JNDI properties may
* be specified as system properties or as applet parameters
* (through the use of {@link Context#APPLET}).
* These special properties are listed in the field detail sections of the
* <a href=Context.html#field_detail><tt>Context</tt></a> and
* <a href=ldap/LdapContext.html#field_detail><tt>LdapContext</tt></a>
* interface documentation.
*<p>
* JNDI determines each property's value by merging
* the values from the following two sources, in order:
* <ol>
* <li>
* The first occurrence of the property from the constructor's
* environment parameter and (for appropriate properties) the applet
* parameters and system properties.
* <li>
* The application resource files (<tt>jndi.properties</tt>).
* </ol>
* For each property found in both of these two sources, or in
* more than one application resource file, the property's value
* is determined as follows. If the property is
* one of the standard JNDI properties that specify a list of JNDI
* factories (see <a href=Context.html#LISTPROPS><tt>Context</tt></a>),
* all of the values are
* concatenated into a single colon-separated list. For other
* properties, only the first value found is used.
*
*<p>
* The initial context implementation is determined at runtime.
* The default policy uses the environment property
* "{@link Context#INITIAL_CONTEXT_FACTORY java.naming.factory.initial}",
* which contains the class name of the initial context factory.
* An exception to this policy is made when resolving URL strings, as described
* below.
*<p>
* When a URL string (a <tt>String</tt> of the form
* <em>scheme_id:rest_of_name</em>) is passed as a name parameter to
* any method, a URL context factory for handling that scheme is
* located and used to resolve the URL. If no such factory is found,
* the initial context specified by
* <tt>"java.naming.factory.initial"</tt> is used. Similarly, when a
* <tt>CompositeName</tt> object whose first component is a URL string is
* passed as a name parameter to any method, a URL context factory is
* located and used to resolve the first name component.
* See {@link NamingManager#getURLContext
* <tt>NamingManager.getURLContext()</tt>} for a description of how URL
* context factories are located.
*<p>
* This default policy of locating the initial context and URL context
* factories may be overridden
* by calling
* <tt>NamingManager.setInitialContextFactoryBuilder()</tt>.
*<p>
* NoInitialContextException is thrown when an initial context cannot
* be instantiated. This exception can be thrown during any interaction
* with the InitialContext, not only when the InitialContext is constructed.
* For example, the implementation of the initial context might lazily
* retrieve the context only when actual methods are invoked on it.
* The application should not have any dependency on when the existence
* of an initial context is determined.
*<p>
* When the environment property "java.naming.factory.initial" is
* non-null, the InitialContext constructor will attempt to create the
* initial context specified therein. At that time, the initial context factory
* involved might throw an exception if a problem is encountered. However,
* it is provider implementation-dependent when it verifies and indicates
* to the users of the initial context any environment property- or
* connection- related problems. It can do so lazily--delaying until
* an operation is performed on the context, or eagerly, at the time
* the context is constructed.
*<p>
* An InitialContext instance is not synchronized against concurrent
* access by multiple threads. Multiple threads each manipulating a
* different InitialContext instance need not synchronize.
* Threads that need to access a single InitialContext instance
* concurrently should synchronize amongst themselves and provide the
* necessary locking.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see Context
* @see NamingManager#setInitialContextFactoryBuilder
* NamingManager.setInitialContextFactoryBuilder
* @since JNDI 1.1 / Java 2 Platform, Standard Edition, v 1.3
*/
public class InitialContext implements Context {
/** {@collect.stats}
* The environment associated with this InitialContext.
* It is initialized to null and is updated by the constructor
* that accepts an environment or by the <tt>init()</tt> method.
* @see #addToEnvironment
* @see #removeFromEnvironment
* @see #getEnvironment
*/
protected Hashtable<Object,Object> myProps = null;
/** {@collect.stats}
* Field holding the result of calling NamingManager.getInitialContext().
* It is set by getDefaultInitCtx() the first time getDefaultInitCtx()
* is called. Subsequent invocations of getDefaultInitCtx() return
* the value of defaultInitCtx.
* @see #getDefaultInitCtx
*/
protected Context defaultInitCtx = null;
/** {@collect.stats}
* Field indicating whether the initial context has been obtained
* by calling NamingManager.getInitialContext().
* If true, its result is in <code>defaultInitCtx</code>.
*/
protected boolean gotDefault = false;
/** {@collect.stats}
* Constructs an initial context with the option of not
* initializing it. This may be used by a constructor in
* a subclass when the value of the environment parameter
* is not yet known at the time the <tt>InitialContext</tt>
* constructor is called. The subclass's constructor will
* call this constructor, compute the value of the environment,
* and then call <tt>init()</tt> before returning.
*
* @param lazy
* true means do not initialize the initial context; false
* is equivalent to calling <tt>new InitialContext()</tt>
* @throws NamingException if a naming exception is encountered
*
* @see #init(Hashtable)
* @since 1.3
*/
protected InitialContext(boolean lazy) throws NamingException {
if (!lazy) {
init(null);
}
}
/** {@collect.stats}
* Constructs an initial context.
* No environment properties are supplied.
* Equivalent to <tt>new InitialContext(null)</tt>.
*
* @throws NamingException if a naming exception is encountered
*
* @see #InitialContext(Hashtable)
*/
public InitialContext() throws NamingException {
init(null);
}
/** {@collect.stats}
* Constructs an initial context using the supplied environment.
* Environment properties are discussed in the class description.
*
* <p> This constructor will not modify <tt>environment</tt>
* or save a reference to it, but may save a clone.
*
* @param environment
* environment used to create the initial context.
* Null indicates an empty environment.
*
* @throws NamingException if a naming exception is encountered
*/
public InitialContext(Hashtable<?,?> environment)
throws NamingException
{
if (environment != null) {
environment = (Hashtable)environment.clone();
}
init(environment);
}
/** {@collect.stats}
* Initializes the initial context using the supplied environment.
* Environment properties are discussed in the class description.
*
* <p> This method will modify <tt>environment</tt> and save
* a reference to it. The caller may no longer modify it.
*
* @param environment
* environment used to create the initial context.
* Null indicates an empty environment.
*
* @throws NamingException if a naming exception is encountered
*
* @see #InitialContext(boolean)
* @since 1.3
*/
protected void init(Hashtable<?,?> environment)
throws NamingException
{
myProps = ResourceManager.getInitialEnvironment(environment);
if (myProps.get(Context.INITIAL_CONTEXT_FACTORY) != null) {
// user has specified initial context factory; try to get it
getDefaultInitCtx();
}
}
/** {@collect.stats}
* A static method to retrieve the named object.
* This is a shortcut method equivalent to invoking:
* <p>
* <code>
* InitialContext ic = new InitialContext();
* Object obj = ic.lookup();
* </code>
* <p> If <tt>name</tt> is empty, returns a new instance of this context
* (which represents the same naming context as this context, but its
* environment may be modified independently and it may be accessed
* concurrently).
*
* @param name
* the name of the object to look up
* @return the object bound to <tt>name</tt>
* @throws NamingException if a naming exception is encountered
*
* @see #doLookup(String)
* @see #lookup(Name)
* @since 1.6
*/
public static <T> T doLookup(Name name)
throws NamingException {
return (T) (new InitialContext()).lookup(name);
}
/** {@collect.stats}
* A static method to retrieve the named object.
* See {@link #doLookup(Name)} for details.
* @param name
* the name of the object to look up
* @return the object bound to <tt>name</tt>
* @throws NamingException if a naming exception is encountered
* @since 1.6
*/
public static <T> T doLookup(String name)
throws NamingException {
return (T) (new InitialContext()).lookup(name);
}
private static String getURLScheme(String str) {
int colon_posn = str.indexOf(':');
int slash_posn = str.indexOf('/');
if (colon_posn > 0 && (slash_posn == -1 || colon_posn < slash_posn))
return str.substring(0, colon_posn);
return null;
}
/** {@collect.stats}
* Retrieves the initial context by calling
* <code>NamingManager.getInitialContext()</code>
* and cache it in defaultInitCtx.
* Set <code>gotDefault</code> so that we know we've tried this before.
* @return The non-null cached initial context.
* @exception NoInitialContextException If cannot find an initial context.
* @exception NamingException If a naming exception was encountered.
*/
protected Context getDefaultInitCtx() throws NamingException{
if (!gotDefault) {
defaultInitCtx = NamingManager.getInitialContext(myProps);
gotDefault = true;
}
if (defaultInitCtx == null)
throw new NoInitialContextException();
return defaultInitCtx;
}
/** {@collect.stats}
* Retrieves a context for resolving the string name <code>name</code>.
* If <code>name</code> name is a URL string, then attempt
* to find a URL context for it. If none is found, or if
* <code>name</code> is not a URL string, then return
* <code>getDefaultInitCtx()</code>.
*<p>
* See getURLOrDefaultInitCtx(Name) for description
* of how a subclass should use this method.
* @param name The non-null name for which to get the context.
* @return A URL context for <code>name</code> or the cached
* initial context. The result cannot be null.
* @exception NoInitialContextException If cannot find an initial context.
* @exception NamingException In a naming exception is encountered.
* @see javax.naming.spi.NamingManager#getURLContext
*/
protected Context getURLOrDefaultInitCtx(String name)
throws NamingException {
if (NamingManager.hasInitialContextFactoryBuilder()) {
return getDefaultInitCtx();
}
String scheme = getURLScheme(name);
if (scheme != null) {
Context ctx = NamingManager.getURLContext(scheme, myProps);
if (ctx != null) {
return ctx;
}
}
return getDefaultInitCtx();
}
/** {@collect.stats}
* Retrieves a context for resolving <code>name</code>.
* If the first component of <code>name</code> name is a URL string,
* then attempt to find a URL context for it. If none is found, or if
* the first component of <code>name</code> is not a URL string,
* then return <code>getDefaultInitCtx()</code>.
*<p>
* When creating a subclass of InitialContext, use this method as
* follows.
* Define a new method that uses this method to get an initial
* context of the desired subclass.
* <p><blockquote><pre>
* protected XXXContext getURLOrDefaultInitXXXCtx(Name name)
* throws NamingException {
* Context answer = getURLOrDefaultInitCtx(name);
* if (!(answer instanceof XXXContext)) {
* if (answer == null) {
* throw new NoInitialContextException();
* } else {
* throw new NotContextException("Not an XXXContext");
* }
* }
* return (XXXContext)answer;
* }
* </pre></blockquote>
* When providing implementations for the new methods in the subclass,
* use this newly defined method to get the initial context.
* <p><blockquote><pre>
* public Object XXXMethod1(Name name, ...) {
* throws NamingException {
* return getURLOrDefaultInitXXXCtx(name).XXXMethod1(name, ...);
* }
* </pre></blockquote>
*
* @param name The non-null name for which to get the context.
* @return A URL context for <code>name</code> or the cached
* initial context. The result cannot be null.
* @exception NoInitialContextException If cannot find an initial context.
* @exception NamingException In a naming exception is encountered.
*
* @see javax.naming.spi.NamingManager#getURLContext
*/
protected Context getURLOrDefaultInitCtx(Name name)
throws NamingException {
if (NamingManager.hasInitialContextFactoryBuilder()) {
return getDefaultInitCtx();
}
if (name.size() > 0) {
String first = name.get(0);
String scheme = getURLScheme(first);
if (scheme != null) {
Context ctx = NamingManager.getURLContext(scheme, myProps);
if (ctx != null) {
return ctx;
}
}
}
return getDefaultInitCtx();
}
// Context methods
// Most Javadoc is deferred to the Context interface.
public Object lookup(String name) throws NamingException {
return getURLOrDefaultInitCtx(name).lookup(name);
}
public Object lookup(Name name) throws NamingException {
return getURLOrDefaultInitCtx(name).lookup(name);
}
public void bind(String name, Object obj) throws NamingException {
getURLOrDefaultInitCtx(name).bind(name, obj);
}
public void bind(Name name, Object obj) throws NamingException {
getURLOrDefaultInitCtx(name).bind(name, obj);
}
public void rebind(String name, Object obj) throws NamingException {
getURLOrDefaultInitCtx(name).rebind(name, obj);
}
public void rebind(Name name, Object obj) throws NamingException {
getURLOrDefaultInitCtx(name).rebind(name, obj);
}
public void unbind(String name) throws NamingException {
getURLOrDefaultInitCtx(name).unbind(name);
}
public void unbind(Name name) throws NamingException {
getURLOrDefaultInitCtx(name).unbind(name);
}
public void rename(String oldName, String newName) throws NamingException {
getURLOrDefaultInitCtx(oldName).rename(oldName, newName);
}
public void rename(Name oldName, Name newName)
throws NamingException
{
getURLOrDefaultInitCtx(oldName).rename(oldName, newName);
}
public NamingEnumeration<NameClassPair> list(String name)
throws NamingException
{
return (getURLOrDefaultInitCtx(name).list(name));
}
public NamingEnumeration<NameClassPair> list(Name name)
throws NamingException
{
return (getURLOrDefaultInitCtx(name).list(name));
}
public NamingEnumeration<Binding> listBindings(String name)
throws NamingException {
return getURLOrDefaultInitCtx(name).listBindings(name);
}
public NamingEnumeration<Binding> listBindings(Name name)
throws NamingException {
return getURLOrDefaultInitCtx(name).listBindings(name);
}
public void destroySubcontext(String name) throws NamingException {
getURLOrDefaultInitCtx(name).destroySubcontext(name);
}
public void destroySubcontext(Name name) throws NamingException {
getURLOrDefaultInitCtx(name).destroySubcontext(name);
}
public Context createSubcontext(String name) throws NamingException {
return getURLOrDefaultInitCtx(name).createSubcontext(name);
}
public Context createSubcontext(Name name) throws NamingException {
return getURLOrDefaultInitCtx(name).createSubcontext(name);
}
public Object lookupLink(String name) throws NamingException {
return getURLOrDefaultInitCtx(name).lookupLink(name);
}
public Object lookupLink(Name name) throws NamingException {
return getURLOrDefaultInitCtx(name).lookupLink(name);
}
public NameParser getNameParser(String name) throws NamingException {
return getURLOrDefaultInitCtx(name).getNameParser(name);
}
public NameParser getNameParser(Name name) throws NamingException {
return getURLOrDefaultInitCtx(name).getNameParser(name);
}
/** {@collect.stats}
* Composes the name of this context with a name relative to
* this context.
* Since an initial context may never be named relative
* to any context other than itself, the value of the
* <tt>prefix</tt> parameter must be an empty name (<tt>""</tt>).
*/
public String composeName(String name, String prefix)
throws NamingException {
return name;
}
/** {@collect.stats}
* Composes the name of this context with a name relative to
* this context.
* Since an initial context may never be named relative
* to any context other than itself, the value of the
* <tt>prefix</tt> parameter must be an empty name.
*/
public Name composeName(Name name, Name prefix)
throws NamingException
{
return (Name)name.clone();
}
public Object addToEnvironment(String propName, Object propVal)
throws NamingException {
myProps.put(propName, propVal);
return getDefaultInitCtx().addToEnvironment(propName, propVal);
}
public Object removeFromEnvironment(String propName)
throws NamingException {
myProps.remove(propName);
return getDefaultInitCtx().removeFromEnvironment(propName);
}
public Hashtable<?,?> getEnvironment() throws NamingException {
return getDefaultInitCtx().getEnvironment();
}
public void close() throws NamingException {
myProps = null;
if (defaultInitCtx != null) {
defaultInitCtx.close();
defaultInitCtx = null;
}
gotDefault = false;
}
public String getNameInNamespace() throws NamingException {
return getDefaultInitCtx().getNameInNamespace();
}
};
|
Java
|
/*
* Copyright (c) 1999, 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.naming;
import java.util.Enumeration;
import java.util.Properties;
/** {@collect.stats}
* This class represents a composite name -- a sequence of
* component names spanning multiple namespaces.
* Each component is a string name from the namespace of a
* naming system. If the component comes from a hierarchical
* namespace, that component can be further parsed into
* its atomic parts by using the CompoundName class.
*<p>
* The components of a composite name are numbered. The indexes of a
* composite name with N components range from 0 up to, but not including, N.
* This range may be written as [0,N).
* The most significant component is at index 0.
* An empty composite name has no components.
*<p>
* <h4>JNDI Composite Name Syntax</h4>
* JNDI defines a standard string representation for composite names. This
* representation is the concatenation of the components of a composite name
* from left to right using the component separator (a forward
* slash character (/)) to separate each component.
* The JNDI syntax defines the following meta characters:
* <ul>
* <li>escape (backward slash \),
* <li>quote characters (single (') and double quotes (")), and
* <li>component separator (forward slash character (/)).
* </ul>
* Any occurrence of a leading quote, an escape preceding any meta character,
* an escape at the end of a component, or a component separator character
* in an unquoted component must be preceded by an escape character when
* that component is being composed into a composite name string.
* Alternatively, to avoid adding escape characters as described,
* the entire component can be quoted using matching single quotes
* or matching double quotes. A single quote occurring within a double-quoted
* component is not considered a meta character (and need not be escaped),
* and vice versa.
*<p>
* When two composite names are compared, the case of the characters
* is significant.
*<p>
* A leading component separator (the composite name string begins with
* a separator) denotes a leading empty component (a component consisting
* of an empty string).
* A trailing component separator (the composite name string ends with
* a separator) denotes a trailing empty component.
* Adjacent component separators denote an empty component.
*<p>
*<h4>Composite Name Examples</h4>
*This table shows examples of some composite names. Each row shows
*the string form of a composite name and its corresponding structural form
*(<tt>CompositeName</tt>).
*<p>
<table border="1" cellpadding=3 width="70%" summary="examples showing string form of composite name and its corresponding structural form (CompositeName)">
<tr>
<th>String Name</th>
<th>CompositeName</th>
</tr>
<tr>
<td>
""
</td>
<td>{} (the empty name == new CompositeName("") == new CompositeName())
</td>
</tr>
<tr>
<td>
"x"
</td>
<td>{"x"}
</td>
</tr>
<tr>
<td>
"x/y"
</td>
<td>{"x", "y"}</td>
</tr>
<tr>
<td>"x/"</td>
<td>{"x", ""}</td>
</tr>
<tr>
<td>"/x"</td>
<td>{"", "x"}</td>
</tr>
<tr>
<td>"/"</td>
<td>{""}</td>
</tr>
<tr>
<td>"//"</td>
<td>{"", ""}</td>
</tr>
<tr><td>"/x/"</td>
<td>{"", "x", ""}</td>
</tr>
<tr><td>"x//y"</td>
<td>{"x", "", "y"}</td>
</tr>
</table>
* <p>
*<h4>Composition Examples</h4>
* Here are some composition examples. The right column shows composing
* string composite names while the left column shows composing the
* corresponding <tt>CompositeName</tt>s. Notice that composing the
* string forms of two composite names simply involves concatenating
* their string forms together.
<p> <table border="1" cellpadding=3 width="70%" summary="composition examples showing string names and composite names">
<tr>
<th>String Names</th>
<th>CompositeNames</th>
</tr>
<tr>
<td>
"x/y" + "/" = x/y/
</td>
<td>
{"x", "y"} + {""} = {"x", "y", ""}
</td>
</tr>
<tr>
<td>
"" + "x" = "x"
</td>
<td>
{} + {"x"} = {"x"}
</td>
</tr>
<tr>
<td>
"/" + "x" = "/x"
</td>
<td>
{""} + {"x"} = {"", "x"}
</td>
</tr>
<tr>
<td>
"x" + "" + "" = "x"
</td>
<td>
{"x"} + {} + {} = {"x"}
</td>
</tr>
</table>
*<p>
*<h4>Multithreaded Access</h4>
* A <tt>CompositeName</tt> instance is not synchronized against concurrent
* multithreaded access. Multiple threads trying to access and modify a
* <tt>CompositeName</tt> should lock the object.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class CompositeName implements Name {
private transient NameImpl impl;
/** {@collect.stats}
* Constructs a new composite name instance using the components
* specified by 'comps'. This protected method is intended to be
* to be used by subclasses of CompositeName when they override
* methods such as clone(), getPrefix(), getSuffix().
*
* @param comps A non-null enumeration containing the components for the new
* composite name. Each element is of class String.
* The enumeration will be consumed to extract its
* elements.
*/
protected CompositeName(Enumeration<String> comps) {
impl = new NameImpl(null, comps); // null means use default syntax
}
/** {@collect.stats}
* Constructs a new composite name instance by parsing the string n
* using the composite name syntax (left-to-right, slash separated).
* The composite name syntax is described in detail in the class
* description.
*
* @param n The non-null string to parse.
* @exception InvalidNameException If n has invalid composite name syntax.
*/
public CompositeName(String n) throws InvalidNameException {
impl = new NameImpl(null, n); // null means use default syntax
}
/** {@collect.stats}
* Constructs a new empty composite name. Such a name returns true
* when <code>isEmpty()</code> is invoked on it.
*/
public CompositeName() {
impl = new NameImpl(null); // null means use default syntax
}
/** {@collect.stats}
* Generates the string representation of this composite name.
* The string representation consists of enumerating in order
* each component of the composite name and separating
* each component by a forward slash character. Quoting and
* escape characters are applied where necessary according to
* the JNDI syntax, which is described in the class description.
* An empty component is represented by an empty string.
*
* The string representation thus generated can be passed to
* the CompositeName constructor to create a new equivalent
* composite name.
*
* @return A non-null string representation of this composite name.
*/
public String toString() {
return impl.toString();
}
/** {@collect.stats}
* Determines whether two composite names are equal.
* If obj is null or not a composite name, false is returned.
* Two composite names are equal if each component in one is equal
* to the corresponding component in the other. This implies
* both have the same number of components, and each component's
* equals() test against the corresponding component in the other name
* returns true.
*
* @param obj The possibly null object to compare against.
* @return true if obj is equal to this composite name, false otherwise.
* @see #hashCode
*/
public boolean equals(Object obj) {
return (obj != null &&
obj instanceof CompositeName &&
impl.equals(((CompositeName)obj).impl));
}
/** {@collect.stats}
* Computes the hash code of this composite name.
* The hash code is the sum of the hash codes of individual components
* of this composite name.
*
* @return An int representing the hash code of this name.
* @see #equals
*/
public int hashCode() {
return impl.hashCode();
}
/** {@collect.stats}
* Compares this CompositeName with the specified Object for order.
* Returns a
* negative integer, zero, or a positive integer as this Name is less
* than, equal to, or greater than the given Object.
* <p>
* If obj is null or not an instance of CompositeName, ClassCastException
* is thrown.
* <p>
* See equals() for what it means for two composite names to be equal.
* If two composite names are equal, 0 is returned.
* <p>
* Ordering of composite names follows the lexicographical rules for
* string comparison, with the extension that this applies to all
* the components in the composite name. The effect is as if all the
* components were lined up in their specified ordered and the
* lexicographical rules applied over the two line-ups.
* If this composite name is "lexicographically" lesser than obj,
* a negative number is returned.
* If this composite name is "lexicographically" greater than obj,
* a positive number is returned.
* @param obj The non-null object to compare against.
*
* @return a negative integer, zero, or a positive integer as this Name
* is less than, equal to, or greater than the given Object.
* @exception ClassCastException if obj is not a CompositeName.
*/
public int compareTo(Object obj) {
if (!(obj instanceof CompositeName)) {
throw new ClassCastException("Not a CompositeName");
}
return impl.compareTo(((CompositeName)obj).impl);
}
/** {@collect.stats}
* Generates a copy of this composite name.
* Changes to the components of this composite name won't
* affect the new copy and vice versa.
*
* @return A non-null copy of this composite name.
*/
public Object clone() {
return (new CompositeName(getAll()));
}
/** {@collect.stats}
* Retrieves the number of components in this composite name.
*
* @return The nonnegative number of components in this composite name.
*/
public int size() {
return (impl.size());
}
/** {@collect.stats}
* Determines whether this composite name is empty. A composite name
* is empty if it has zero components.
*
* @return true if this composite name is empty, false otherwise.
*/
public boolean isEmpty() {
return (impl.isEmpty());
}
/** {@collect.stats}
* Retrieves the components of this composite name as an enumeration
* of strings.
* The effects of updates to this composite name on this enumeration
* is undefined.
*
* @return A non-null enumeration of the components of
* this composite name. Each element of the enumeration is of
* class String.
*/
public Enumeration<String> getAll() {
return (impl.getAll());
}
/** {@collect.stats}
* Retrieves a component of this composite name.
*
* @param posn The 0-based index of the component to retrieve.
* Must be in the range [0,size()).
* @return The non-null component at index posn.
* @exception ArrayIndexOutOfBoundsException if posn is outside the
* specified range.
*/
public String get(int posn) {
return (impl.get(posn));
}
/** {@collect.stats}
* Creates a composite name whose components consist of a prefix of the
* components in this composite name. Subsequent changes to
* this composite name does not affect the name that is returned.
*
* @param posn The 0-based index of the component at which to stop.
* Must be in the range [0,size()].
* @return A composite name consisting of the components at indexes in
* the range [0,posn).
* @exception ArrayIndexOutOfBoundsException
* If posn is outside the specified range.
*/
public Name getPrefix(int posn) {
Enumeration comps = impl.getPrefix(posn);
return (new CompositeName(comps));
}
/** {@collect.stats}
* Creates a composite name whose components consist of a suffix of the
* components in this composite name. Subsequent changes to
* this composite name does not affect the name that is returned.
*
* @param posn The 0-based index of the component at which to start.
* Must be in the range [0,size()].
* @return A composite name consisting of the components at indexes in
* the range [posn,size()). If posn is equal to
* size(), an empty composite name is returned.
* @exception ArrayIndexOutOfBoundsException
* If posn is outside the specified range.
*/
public Name getSuffix(int posn) {
Enumeration comps = impl.getSuffix(posn);
return (new CompositeName(comps));
}
/** {@collect.stats}
* Determines whether a composite name is a prefix of this composite name.
* A composite name 'n' is a prefix if it is equal to
* getPrefix(n.size())--in other words, this composite name
* starts with 'n'. If 'n' is null or not a composite name, false is returned.
*
* @param n The possibly null name to check.
* @return true if n is a CompositeName and
* is a prefix of this composite name, false otherwise.
*/
public boolean startsWith(Name n) {
if (n instanceof CompositeName) {
return (impl.startsWith(n.size(), n.getAll()));
} else {
return false;
}
}
/** {@collect.stats}
* Determines whether a composite name is a suffix of this composite name.
* A composite name 'n' is a suffix if it it is equal to
* getSuffix(size()-n.size())--in other words, this
* composite name ends with 'n'.
* If n is null or not a composite name, false is returned.
*
* @param n The possibly null name to check.
* @return true if n is a CompositeName and
* is a suffix of this composite name, false otherwise.
*/
public boolean endsWith(Name n) {
if (n instanceof CompositeName) {
return (impl.endsWith(n.size(), n.getAll()));
} else {
return false;
}
}
/** {@collect.stats}
* Adds the components of a composite name -- in order -- to the end of
* this composite name.
*
* @param suffix The non-null components to add.
* @return The updated CompositeName, not a new one. Cannot be null.
* @exception InvalidNameException If suffix is not a composite name.
*/
public Name addAll(Name suffix)
throws InvalidNameException
{
if (suffix instanceof CompositeName) {
impl.addAll(suffix.getAll());
return this;
} else {
throw new InvalidNameException("Not a composite name: " +
suffix.toString());
}
}
/** {@collect.stats}
* Adds the components of a composite name -- in order -- at a specified
* position within this composite name.
* Components of this composite name at or after the index of the first
* new component are shifted up (away from index 0)
* to accommodate the new components.
*
* @param n The non-null components to add.
* @param posn The index in this name at which to add the new
* components. Must be in the range [0,size()].
* @return The updated CompositeName, not a new one. Cannot be null.
* @exception InvalidNameException If n is not a composite name.
* @exception ArrayIndexOutOfBoundsException
* If posn is outside the specified range.
*/
public Name addAll(int posn, Name n)
throws InvalidNameException
{
if (n instanceof CompositeName) {
impl.addAll(posn, n.getAll());
return this;
} else {
throw new InvalidNameException("Not a composite name: " +
n.toString());
}
}
/** {@collect.stats}
* Adds a single component to the end of this composite name.
*
* @param comp The non-null component to add.
* @return The updated CompositeName, not a new one. Cannot be null.
* @exception InvalidNameException If adding comp at end of the name
* would violate the name's syntax.
*/
public Name add(String comp) throws InvalidNameException {
impl.add(comp);
return this;
}
/** {@collect.stats}
* Adds a single component at a specified position within this
* composite name.
* Components of this composite name at or after the index of the new
* component are shifted up by one (away from index 0) to accommodate
* the new component.
*
* @param comp The non-null component to add.
* @param posn The index at which to add the new component.
* Must be in the range [0,size()].
* @return The updated CompositeName, not a new one. Cannot be null.
* @exception ArrayIndexOutOfBoundsException
* If posn is outside the specified range.
* @exception InvalidNameException If adding comp at the specified position
* would violate the name's syntax.
*/
public Name add(int posn, String comp)
throws InvalidNameException
{
impl.add(posn, comp);
return this;
}
/** {@collect.stats}
* Deletes a component from this composite name.
* The component of this composite name at position 'posn' is removed,
* and components at indices greater than 'posn'
* are shifted down (towards index 0) by one.
*
* @param posn The index of the component to delete.
* Must be in the range [0,size()).
* @return The component removed (a String).
* @exception ArrayIndexOutOfBoundsException
* If posn is outside the specified range (includes case where
* composite name is empty).
* @exception InvalidNameException If deleting the component
* would violate the name's syntax.
*/
public Object remove(int posn) throws InvalidNameException{
return impl.remove(posn);
}
/** {@collect.stats}
* Overridden to avoid implementation dependency.
* @serialData The number of components (an <tt>int</tt>) followed by
* the individual components (each a <tt>String</tt>).
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
s.writeInt(size());
Enumeration comps = getAll();
while (comps.hasMoreElements()) {
s.writeObject(comps.nextElement());
}
}
/** {@collect.stats}
* Overridden to avoid implementation dependency.
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
impl = new NameImpl(null); // null means use default syntax
int n = s.readInt(); // number of components
try {
while (--n >= 0) {
add((String)s.readObject());
}
} catch (InvalidNameException e) {
throw (new java.io.StreamCorruptedException("Invalid name"));
}
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 1667768148915813118L;
/*
// %%% Test code for serialization.
public static void main(String[] args) throws Exception {
CompositeName c = new CompositeName("aaa/bbb");
java.io.FileOutputStream f1 = new java.io.FileOutputStream("/tmp/ser");
java.io.ObjectOutputStream s1 = new java.io.ObjectOutputStream(f1);
s1.writeObject(c);
s1.close();
java.io.FileInputStream f2 = new java.io.FileInputStream("/tmp/ser");
java.io.ObjectInputStream s2 = new java.io.ObjectInputStream(f2);
c = (CompositeName)s2.readObject();
System.out.println("Size: " + c.size());
System.out.println("Size: " + c.snit);
}
*/
/*
%%% Testing code
public static void main(String[] args) {
try {
for (int i = 0; i < args.length; i++) {
Name name;
Enumeration e;
System.out.println("Given name: " + args[i]);
name = new CompositeName(args[i]);
e = name.getComponents();
while (e.hasMoreElements()) {
System.out.println("Element: " + e.nextElement());
}
System.out.println("Constructed name: " + name.toString());
}
} catch (Exception ne) {
ne.printStackTrace();
}
}
*/
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown when no initial context implementation
* can be created. The policy of how an initial context implementation
* is selected is described in the documentation of the InitialContext class.
*<p>
* This exception can be thrown during any interaction with the
* InitialContext, not only when the InitialContext is constructed.
* For example, the implementation of the initial context might lazily
* retrieve the context only when actual methods are invoked on it.
* The application should not have any dependency on when the existence
* of an initial context is determined.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see InitialContext
* @see javax.naming.directory.InitialDirContext
* @see javax.naming.spi.NamingManager#getInitialContext
* @see javax.naming.spi.NamingManager#setInitialContextFactoryBuilder
* @since 1.3
*/
public class NoInitialContextException extends NamingException {
/** {@collect.stats}
* Constructs an instance of NoInitialContextException.
* All fields are initialized to null.
*/
public NoInitialContextException() {
super();
}
/** {@collect.stats}
* Constructs an instance of NoInitialContextException with an
* explanation. All other fields are initialized to null.
* @param explanation Possibly null additional detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public NoInitialContextException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -3413733186901258623L;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming;
import java.util.Enumeration;
/** {@collect.stats}
* The <tt>Name</tt> interface represents a generic name -- an ordered
* sequence of components. It can be a composite name (names that
* span multiple namespaces), or a compound name (names that are
* used within individual hierarchical naming systems).
*
* <p> There can be different implementations of <tt>Name</tt>; for example,
* composite names, URLs, or namespace-specific compound names.
*
* <p> The components of a name are numbered. The indexes of a name
* with N components range from 0 up to, but not including, N. This
* range may be written as [0,N).
* The most significant component is at index 0.
* An empty name has no components.
*
* <p> None of the methods in this interface accept null as a valid
* value for a parameter that is a name or a name component.
* Likewise, methods that return a name or name component never return null.
*
* <p> An instance of a <tt>Name</tt> may not be synchronized against
* concurrent multithreaded access if that access is not read-only.
*
* @author Rosanna Lee
* @author Scott Seligman
* @author R. Vasudevan
* @since 1.3
*/
public interface Name
extends Cloneable, java.io.Serializable, Comparable<Object>
{
/** {@collect.stats}
* The class fingerprint that is set to indicate
* serialization compatibility with a previous
* version of the class.
*/
static final long serialVersionUID = -3617482732056931635L;
/** {@collect.stats}
* Generates a new copy of this name.
* Subsequent changes to the components of this name will not
* affect the new copy, and vice versa.
*
* @return a copy of this name
*
* @see Object#clone()
*/
public Object clone();
/** {@collect.stats}
* Compares this name with another name for order.
* Returns a negative integer, zero, or a positive integer as this
* name is less than, equal to, or greater than the given name.
*
* <p> As with <tt>Object.equals()</tt>, the notion of ordering for names
* depends on the class that implements this interface.
* For example, the ordering may be
* based on lexicographical ordering of the name components.
* Specific attributes of the name, such as how it treats case,
* may affect the ordering. In general, two names of different
* classes may not be compared.
*
* @param obj the non-null object to compare against.
* @return a negative integer, zero, or a positive integer as this name
* is less than, equal to, or greater than the given name
* @throws ClassCastException if obj is not a <tt>Name</tt> of a
* type that may be compared with this name
*
* @see Comparable#compareTo(Object)
*/
public int compareTo(Object obj);
/** {@collect.stats}
* Returns the number of components in this name.
*
* @return the number of components in this name
*/
public int size();
/** {@collect.stats}
* Determines whether this name is empty.
* An empty name is one with zero components.
*
* @return true if this name is empty, false otherwise
*/
public boolean isEmpty();
/** {@collect.stats}
* Retrieves the components of this name as an enumeration
* of strings. The effect on the enumeration of updates to
* this name is undefined. If the name has zero components,
* an empty (non-null) enumeration is returned.
*
* @return an enumeration of the components of this name, each a string
*/
public Enumeration<String> getAll();
/** {@collect.stats}
* Retrieves a component of this name.
*
* @param posn
* the 0-based index of the component to retrieve.
* Must be in the range [0,size()).
* @return the component at index posn
* @throws ArrayIndexOutOfBoundsException
* if posn is outside the specified range
*/
public String get(int posn);
/** {@collect.stats}
* Creates a name whose components consist of a prefix of the
* components of this name. Subsequent changes to
* this name will not affect the name that is returned and vice versa.
*
* @param posn
* the 0-based index of the component at which to stop.
* Must be in the range [0,size()].
* @return a name consisting of the components at indexes in
* the range [0,posn).
* @throws ArrayIndexOutOfBoundsException
* if posn is outside the specified range
*/
public Name getPrefix(int posn);
/** {@collect.stats}
* Creates a name whose components consist of a suffix of the
* components in this name. Subsequent changes to
* this name do not affect the name that is returned and vice versa.
*
* @param posn
* the 0-based index of the component at which to start.
* Must be in the range [0,size()].
* @return a name consisting of the components at indexes in
* the range [posn,size()). If posn is equal to
* size(), an empty name is returned.
* @throws ArrayIndexOutOfBoundsException
* if posn is outside the specified range
*/
public Name getSuffix(int posn);
/** {@collect.stats}
* Determines whether this name starts with a specified prefix.
* A name <tt>n</tt> is a prefix if it is equal to
* <tt>getPrefix(n.size())</tt>.
*
* @param n
* the name to check
* @return true if <tt>n</tt> is a prefix of this name, false otherwise
*/
public boolean startsWith(Name n);
/** {@collect.stats}
* Determines whether this name ends with a specified suffix.
* A name <tt>n</tt> is a suffix if it is equal to
* <tt>getSuffix(size()-n.size())</tt>.
*
* @param n
* the name to check
* @return true if <tt>n</tt> is a suffix of this name, false otherwise
*/
public boolean endsWith(Name n);
/** {@collect.stats}
* Adds the components of a name -- in order -- to the end of this name.
*
* @param suffix
* the components to add
* @return the updated name (not a new one)
*
* @throws InvalidNameException if <tt>suffix</tt> is not a valid name,
* or if the addition of the components would violate the syntax
* rules of this name
*/
public Name addAll(Name suffix) throws InvalidNameException;
/** {@collect.stats}
* Adds the components of a name -- in order -- at a specified position
* within this name.
* Components of this name at or after the index of the first new
* component are shifted up (away from 0) to accommodate the new
* components.
*
* @param n
* the components to add
* @param posn
* the index in this name at which to add the new
* components. Must be in the range [0,size()].
* @return the updated name (not a new one)
*
* @throws ArrayIndexOutOfBoundsException
* if posn is outside the specified range
* @throws InvalidNameException if <tt>n</tt> is not a valid name,
* or if the addition of the components would violate the syntax
* rules of this name
*/
public Name addAll(int posn, Name n) throws InvalidNameException;
/** {@collect.stats}
* Adds a single component to the end of this name.
*
* @param comp
* the component to add
* @return the updated name (not a new one)
*
* @throws InvalidNameException if adding <tt>comp</tt> would violate
* the syntax rules of this name
*/
public Name add(String comp) throws InvalidNameException;
/** {@collect.stats}
* Adds a single component at a specified position within this name.
* Components of this name at or after the index of the new component
* are shifted up by one (away from index 0) to accommodate the new
* component.
*
* @param comp
* the component to add
* @param posn
* the index at which to add the new component.
* Must be in the range [0,size()].
* @return the updated name (not a new one)
*
* @throws ArrayIndexOutOfBoundsException
* if posn is outside the specified range
* @throws InvalidNameException if adding <tt>comp</tt> would violate
* the syntax rules of this name
*/
public Name add(int posn, String comp) throws InvalidNameException;
/** {@collect.stats}
* Removes a component from this name.
* The component of this name at the specified position is removed.
* Components with indexes greater than this position
* are shifted down (toward index 0) by one.
*
* @param posn
* the index of the component to remove.
* Must be in the range [0,size()).
* @return the component removed (a String)
*
* @throws ArrayIndexOutOfBoundsException
* if posn is outside the specified range
* @throws InvalidNameException if deleting the component
* would violate the syntax rules of the name
*/
public Object remove(int posn) throws InvalidNameException;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.spi;
import javax.naming.*;
import javax.naming.directory.Attributes;
import java.util.Hashtable;
/** {@collect.stats}
* This interface represents a factory for obtaining the state of an
* object and corresponding attributes for binding.
*<p>
* The JNDI framework allows for object implementations to
* be loaded in dynamically via <tt>object factories</tt>.
* <p>
* A <tt>DirStateFactory</tt> extends <tt>StateFactory</tt>
* by allowing an <tt>Attributes</tt> instance
* to be supplied to and be returned by the <tt>getStateToBind()</tt> method.
* <tt>DirStateFactory</tt> implementations are intended to be used by
* <tt>DirContext</tt> service providers.
* When a caller binds an object using <tt>DirContext.bind()</tt>,
* he might also specify a set of attributes to be bound with the object.
* The object and attributes to be bound are passed to
* the <tt>getStateToBind()</tt> method of a factory.
* If the factory processes the object and attributes, it returns
* a corresponding pair of object and attributes to be bound.
* If the factory does not process the object, it must return null.
*<p>
* For example, a caller might bind a printer object with some printer-related
* attributes.
*<blockquote><pre>
* ctx.rebind("inky", printer, printerAttrs);
*</pre></blockquote>
* An LDAP service provider for <tt>ctx</tt> uses a <tt>DirStateFactory</tt>
* (indirectly via <tt>DirectoryManager.getStateToBind()</tt>)
* and gives it <tt>printer</tt> and <tt>printerAttrs</tt>. A factory for
* an LDAP directory might turn <tt>printer</tt> into a set of attributes
* and merge that with <tt>printerAttrs</tt>. The service provider then
* uses the resulting attributes to create an LDAP entry and updates
* the directory.
*
* <p> Since <tt>DirStateFactory</tt> extends <tt>StateFactory</tt>, it
* has two <tt>getStateToBind()</tt> methods, where one
* differs from the other by the attributes
* argument. <tt>DirectoryManager.getStateToBind()</tt> will only use
* the form that accepts the attributes argument, while
* <tt>NamingManager.getStateToBind()</tt> will only use the form that
* does not accept the attributes argument.
*
* <p> Either form of the <tt>getStateToBind()</tt> method of a
* DirStateFactory may be invoked multiple times, possibly using different
* parameters. The implementation is thread-safe.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see DirectoryManager#getStateToBind
* @see DirObjectFactory
* @since 1.3
*/
public interface DirStateFactory extends StateFactory {
/** {@collect.stats}
* Retrieves the state of an object for binding given the object and attributes
* to be transformed.
*<p>
* <tt>DirectoryManager.getStateToBind()</tt>
* successively loads in state factories. If a factory implements
* <tt>DirStateFactory</tt>, <tt>DirectoryManager</tt> invokes this method;
* otherwise, it invokes <tt>StateFactory.getStateToBind()</tt>.
* It does this until a factory produces a non-null answer.
*<p>
* When an exception is thrown by a factory,
* the exception is passed on to the caller
* of <tt>DirectoryManager.getStateToBind()</tt>. The search for other factories
* that may produce a non-null answer is halted.
* A factory should only throw an exception if it is sure that
* it is the only intended factory and that no other factories
* should be tried.
* If this factory cannot create an object using the arguments supplied,
* it should return null.
* <p>
* The <code>name</code> and <code>nameCtx</code> parameters may
* optionally be used to specify the name of the object being created.
* See the description of "Name and Context Parameters" in
* {@link ObjectFactory#getObjectInstance ObjectFactory.getObjectInstance()}
* for details.
* If a factory uses <code>nameCtx</code> it should synchronize its use
* against concurrent access, since context implementations are not
* guaranteed to be thread-safe.
*<p>
* The <tt>name</tt>, <tt>inAttrs</tt>, and <tt>environment</tt> parameters
* are owned by the caller.
* The implementation will not modify these objects or keep references
* to them, although it may keep references to clones or copies.
* The object returned by this method is owned by the caller.
* The implementation will not subsequently modify it.
* It will contain either a new <tt>Attributes</tt> object that is
* likewise owned by the caller, or a reference to the original
* <tt>inAttrs</tt> parameter.
*
* @param obj A possibly null object whose state is to be retrieved.
* @param name The name of this object relative to <code>nameCtx</code>,
* or null if no name is specified.
* @param nameCtx The context relative to which the <code>name</code>
* parameter is specified, or null if <code>name</code> is
* relative to the default initial context.
* @param environment The possibly null environment to
* be used in the creation of the object's state.
* @param inAttrs The possibly null attributes to be bound with the object.
* The factory must not modify <tt>inAttrs</tt>.
* @return A <tt>Result</tt> containing the object's state for binding
* and the corresponding
* attributes to be bound; null if the object don't use this factory.
* @exception NamingException If this factory encountered an exception
* while attempting to get the object's state, and no other factories are
* to be tried.
*
* @see DirectoryManager#getStateToBind
*/
public Result getStateToBind(Object obj, Name name, Context nameCtx,
Hashtable<?,?> environment,
Attributes inAttrs)
throws NamingException;
/** {@collect.stats}
* An object/attributes pair for returning the result of
* DirStateFactory.getStateToBind().
*/
public static class Result {
/** {@collect.stats}
* The possibly null object to be bound.
*/
private Object obj;
/** {@collect.stats}
* The possibly null attributes to be bound.
*/
private Attributes attrs;
/** {@collect.stats}
* Constructs an instance of Result.
*
* @param obj The possibly null object to be bound.
* @param outAttrs The possibly null attributes to be bound.
*/
public Result(Object obj, Attributes outAttrs) {
this.obj = obj;
this.attrs = outAttrs;
}
/** {@collect.stats}
* Retrieves the object to be bound.
* @return The possibly null object to be bound.
*/
public Object getObject() { return obj; };
/** {@collect.stats}
* Retrieves the attributes to be bound.
* @return The possibly null attributes to be bound.
*/
public Attributes getAttributes() { return attrs; };
}
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.spi;
import java.util.Hashtable;
import javax.naming.*;
/** {@collect.stats}
* This class is for dealing with federations/continuations.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
class ContinuationContext implements Context, Resolver {
protected CannotProceedException cpe;
protected Hashtable env;
protected Context contCtx = null;
protected ContinuationContext(CannotProceedException cpe,
Hashtable env) {
this.cpe = cpe;
this.env = env;
}
protected Context getTargetContext() throws NamingException {
if (contCtx == null) {
if (cpe.getResolvedObj() == null)
throw (NamingException)cpe.fillInStackTrace();
contCtx = NamingManager.getContext(cpe.getResolvedObj(),
cpe.getAltName(),
cpe.getAltNameCtx(),
env);
if (contCtx == null)
throw (NamingException)cpe.fillInStackTrace();
}
return contCtx;
}
public Object lookup(Name name) throws NamingException {
Context ctx = getTargetContext();
return ctx.lookup(name);
}
public Object lookup(String name) throws NamingException {
Context ctx = getTargetContext();
return ctx.lookup(name);
}
public void bind(Name name, Object newObj) throws NamingException {
Context ctx = getTargetContext();
ctx.bind(name, newObj);
}
public void bind(String name, Object newObj) throws NamingException {
Context ctx = getTargetContext();
ctx.bind(name, newObj);
}
public void rebind(Name name, Object newObj) throws NamingException {
Context ctx = getTargetContext();
ctx.rebind(name, newObj);
}
public void rebind(String name, Object newObj) throws NamingException {
Context ctx = getTargetContext();
ctx.rebind(name, newObj);
}
public void unbind(Name name) throws NamingException {
Context ctx = getTargetContext();
ctx.unbind(name);
}
public void unbind(String name) throws NamingException {
Context ctx = getTargetContext();
ctx.unbind(name);
}
public void rename(Name name, Name newName) throws NamingException {
Context ctx = getTargetContext();
ctx.rename(name, newName);
}
public void rename(String name, String newName) throws NamingException {
Context ctx = getTargetContext();
ctx.rename(name, newName);
}
public NamingEnumeration list(Name name) throws NamingException {
Context ctx = getTargetContext();
return ctx.list(name);
}
public NamingEnumeration list(String name) throws NamingException {
Context ctx = getTargetContext();
return ctx.list(name);
}
public NamingEnumeration listBindings(Name name)
throws NamingException
{
Context ctx = getTargetContext();
return ctx.listBindings(name);
}
public NamingEnumeration listBindings(String name) throws NamingException {
Context ctx = getTargetContext();
return ctx.listBindings(name);
}
public void destroySubcontext(Name name) throws NamingException {
Context ctx = getTargetContext();
ctx.destroySubcontext(name);
}
public void destroySubcontext(String name) throws NamingException {
Context ctx = getTargetContext();
ctx.destroySubcontext(name);
}
public Context createSubcontext(Name name) throws NamingException {
Context ctx = getTargetContext();
return ctx.createSubcontext(name);
}
public Context createSubcontext(String name) throws NamingException {
Context ctx = getTargetContext();
return ctx.createSubcontext(name);
}
public Object lookupLink(Name name) throws NamingException {
Context ctx = getTargetContext();
return ctx.lookupLink(name);
}
public Object lookupLink(String name) throws NamingException {
Context ctx = getTargetContext();
return ctx.lookupLink(name);
}
public NameParser getNameParser(Name name) throws NamingException {
Context ctx = getTargetContext();
return ctx.getNameParser(name);
}
public NameParser getNameParser(String name) throws NamingException {
Context ctx = getTargetContext();
return ctx.getNameParser(name);
}
public Name composeName(Name name, Name prefix)
throws NamingException
{
Context ctx = getTargetContext();
return ctx.composeName(name, prefix);
}
public String composeName(String name, String prefix)
throws NamingException {
Context ctx = getTargetContext();
return ctx.composeName(name, prefix);
}
public Object addToEnvironment(String propName, Object value)
throws NamingException {
Context ctx = getTargetContext();
return ctx.addToEnvironment(propName, value);
}
public Object removeFromEnvironment(String propName)
throws NamingException {
Context ctx = getTargetContext();
return ctx.removeFromEnvironment(propName);
}
public Hashtable getEnvironment() throws NamingException {
Context ctx = getTargetContext();
return ctx.getEnvironment();
}
public String getNameInNamespace() throws NamingException {
Context ctx = getTargetContext();
return ctx.getNameInNamespace();
}
public ResolveResult
resolveToClass(Name name, Class<? extends Context> contextType)
throws NamingException
{
if (cpe.getResolvedObj() == null)
throw (NamingException)cpe.fillInStackTrace();
Resolver res = NamingManager.getResolver(cpe.getResolvedObj(),
cpe.getAltName(),
cpe.getAltNameCtx(),
env);
if (res == null)
throw (NamingException)cpe.fillInStackTrace();
return res.resolveToClass(name, contextType);
}
public ResolveResult
resolveToClass(String name, Class<? extends Context> contextType)
throws NamingException
{
if (cpe.getResolvedObj() == null)
throw (NamingException)cpe.fillInStackTrace();
Resolver res = NamingManager.getResolver(cpe.getResolvedObj(),
cpe.getAltName(),
cpe.getAltNameCtx(),
env);
if (res == null)
throw (NamingException)cpe.fillInStackTrace();
return res.resolveToClass(name, contextType);
}
public void close() throws NamingException {
cpe = null;
env = null;
if (contCtx != null) {
contCtx.close();
contCtx = null;
}
}
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.spi;
import java.util.Hashtable;
import javax.naming.*;
/** {@collect.stats}
* This interface represents a factory for creating an object.
*<p>
* The JNDI framework allows for object implementations to
* be loaded in dynamically via <em>object factories</em>.
* For example, when looking up a printer bound in the name space,
* if the print service binds printer names to References, the printer
* Reference could be used to create a printer object, so that
* the caller of lookup can directly operate on the printer object
* after the lookup.
* <p>An <tt>ObjectFactory</tt> is responsible
* for creating objects of a specific type. In the above example,
* you may have a PrinterObjectFactory for creating Printer objects.
*<p>
* An object factory must implement the <tt>ObjectFactory</tt> interface.
* In addition, the factory class must be public and must have a
* public constructor that accepts no parameters.
*<p>
* The <tt>getObjectInstance()</tt> method of an object factory may
* be invoked multiple times, possibly using different parameters.
* The implementation is thread-safe.
*<p>
* The mention of URL in the documentation for this class refers to
* a URL string as defined by RFC 1738 and its related RFCs. It is
* any string that conforms to the syntax described therein, and
* may not always have corresponding support in the java.net.URL
* class or Web browsers.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see NamingManager#getObjectInstance
* @see NamingManager#getURLContext
* @see ObjectFactoryBuilder
* @see StateFactory
* @since 1.3
*/
public interface ObjectFactory {
/** {@collect.stats}
* Creates an object using the location or reference information
* specified.
* <p>
* Special requirements of this object are supplied
* using <code>environment</code>.
* An example of such an environment property is user identity
* information.
*<p>
* <tt>NamingManager.getObjectInstance()</tt>
* successively loads in object factories and invokes this method
* on them until one produces a non-null answer. When an exception
* is thrown by an object factory, the exception is passed on to the caller
* of <tt>NamingManager.getObjectInstance()</tt>
* (and no search is made for other factories
* that may produce a non-null answer).
* An object factory should only throw an exception if it is sure that
* it is the only intended factory and that no other object factories
* should be tried.
* If this factory cannot create an object using the arguments supplied,
* it should return null.
*<p>
* A <em>URL context factory</em> is a special ObjectFactory that
* creates contexts for resolving URLs or objects whose locations
* are specified by URLs. The <tt>getObjectInstance()</tt> method
* of a URL context factory will obey the following rules.
* <ol>
* <li>If <code>obj</code> is null, create a context for resolving URLs of the
* scheme associated with this factory. The resulting context is not tied
* to a specific URL: it is able to handle arbitrary URLs with this factory's
* scheme id. For example, invoking <tt>getObjectInstance()</tt> with
* <code>obj</code> set to null on an LDAP URL context factory would return a
* context that can resolve LDAP URLs
* such as "ldap://ldap.wiz.com/o=wiz,c=us" and
* "ldap://ldap.umich.edu/o=umich,c=us".
* <li>
* If <code>obj</code> is a URL string, create an object (typically a context)
* identified by the URL. For example, suppose this is an LDAP URL context
* factory. If <code>obj</code> is "ldap://ldap.wiz.com/o=wiz,c=us",
* getObjectInstance() would return the context named by the distinguished
* name "o=wiz, c=us" at the LDAP server ldap.wiz.com. This context can
* then be used to resolve LDAP names (such as "cn=George")
* relative to that context.
* <li>
* If <code>obj</code> is an array of URL strings, the assumption is that the
* URLs are equivalent in terms of the context to which they refer.
* Verification of whether the URLs are, or need to be, equivalent is up
* to the context factory. The order of the URLs in the array is
* not significant.
* The object returned by getObjectInstance() is like that of the single
* URL case. It is the object named by the URLs.
* <li>
* If <code>obj</code> is of any other type, the behavior of
* <tt>getObjectInstance()</tt> is determined by the context factory
* implementation.
* </ol>
*
* <p>
* The <tt>name</tt> and <tt>environment</tt> parameters
* are owned by the caller.
* The implementation will not modify these objects or keep references
* to them, although it may keep references to clones or copies.
*
* <p>
* <b>Name and Context Parameters.</b>
* <a name=NAMECTX></a>
*
* The <code>name</code> and <code>nameCtx</code> parameters may
* optionally be used to specify the name of the object being created.
* <code>name</code> is the name of the object, relative to context
* <code>nameCtx</code>.
* If there are several possible contexts from which the object
* could be named -- as will often be the case -- it is up to
* the caller to select one. A good rule of thumb is to select the
* "deepest" context available.
* If <code>nameCtx</code> is null, <code>name</code> is relative
* to the default initial context. If no name is being specified, the
* <code>name</code> parameter should be null.
* If a factory uses <code>nameCtx</code> it should synchronize its use
* against concurrent access, since context implementations are not
* guaranteed to be thread-safe.
* <p>
*
* @param obj The possibly null object containing location or reference
* information that can be used in creating an object.
* @param name The name of this object relative to <code>nameCtx</code>,
* or null if no name is specified.
* @param nameCtx The context relative to which the <code>name</code>
* parameter is specified, or null if <code>name</code> is
* relative to the default initial context.
* @param environment The possibly null environment that is used in
* creating the object.
* @return The object created; null if an object cannot be created.
* @exception Exception if this object factory encountered an exception
* while attempting to create an object, and no other object factories are
* to be tried.
*
* @see NamingManager#getObjectInstance
* @see NamingManager#getURLContext
*/
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable<?,?> environment)
throws Exception;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.spi;
import java.util.Hashtable;
import javax.naming.*;
/** {@collect.stats}
* This interface represents a factory that creates an initial context.
*<p>
* The JNDI framework allows for different initial context implementations
* to be specified at runtime. The initial context is created using
* an <em>initial context factory</em>.
* An initial context factory must implement the InitialContextFactory
* interface, which provides a method for creating instances of initial
* context that implement the Context interface.
* In addition, the factory class must be public and must have a public
* constructor that accepts no arguments.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see InitialContextFactoryBuilder
* @see NamingManager#getInitialContext
* @see javax.naming.InitialContext
* @see javax.naming.directory.InitialDirContext
* @since 1.3
*/
public interface InitialContextFactory {
/** {@collect.stats}
* Creates an Initial Context for beginning name resolution.
* Special requirements of this context are supplied
* using <code>environment</code>.
*<p>
* The environment parameter is owned by the caller.
* The implementation will not modify the object or keep a reference
* to it, although it may keep a reference to a clone or copy.
*
* @param environment The possibly null environment
* specifying information to be used in the creation
* of the initial context.
* @return A non-null initial context object that implements the Context
* interface.
* @exception NamingException If cannot create an initial context.
*/
public Context getInitialContext(Hashtable<?,?> environment)
throws NamingException;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.spi;
import javax.naming.*;
import java.util.Hashtable;
/** {@collect.stats}
* This interface represents a factory for obtaining the state of an
* object for binding.
*<p>
* The JNDI framework allows for object implementations to
* be loaded in dynamically via <em>object factories</em>.
* For example, when looking up a printer bound in the name space,
* if the print service binds printer names to <tt>Reference</tt>s, the printer
* <tt>Reference</tt> could be used to create a printer object, so that
* the caller of lookup can directly operate on the printer object
* after the lookup.
* <p>An <tt>ObjectFactory</tt> is responsible
* for creating objects of a specific type. In the above example,
* you may have a <tt>PrinterObjectFactory</tt> for creating
* <tt>Printer</tt> objects.
* <p>
* For the reverse process, when an object is bound into the namespace,
* JNDI provides <em>state factories</em>.
* Continuing with the printer example, suppose the printer object is
* updated and rebound:
* <blockquote><pre>
* ctx.rebind("inky", printer);
* </pre></blockquote>
* The service provider for <tt>ctx</tt> uses a state factory
* to obtain the state of <tt>printer</tt> for binding into its namespace.
* A state factory for the <tt>Printer</tt> type object might return
* a more compact object for storage in the naming system.
*<p>
* A state factory must implement the <tt>StateFactory</tt> interface.
* In addition, the factory class must be public and must have a
* public constructor that accepts no parameters.
*<p>
* The <tt>getStateToBind()</tt> method of a state factory may
* be invoked multiple times, possibly using different parameters.
* The implementation is thread-safe.
*<p>
* <tt>StateFactory</tt> is intended for use with service providers
* that implement only the <tt>Context</tt> interface.
* <tt>DirStateFactory</tt> is intended for use with service providers
* that implement the <tt>DirContext</tt> interface.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see NamingManager#getStateToBind
* @see DirectoryManager#getStateToBind
* @see ObjectFactory
* @see DirStateFactory
* @since 1.3
*/
public interface StateFactory {
/** {@collect.stats}
* Retrieves the state of an object for binding.
*<p>
* <tt>NamingManager.getStateToBind()</tt>
* successively loads in state factories and invokes this method
* on them until one produces a non-null answer.
* <tt>DirectoryManager.getStateToBind()</tt>
* successively loads in state factories. If a factory implements
* <tt>DirStateFactory</tt>, then <tt>DirectoryManager</tt>
* invokes <tt>DirStateFactory.getStateToBind()</tt>; otherwise
* it invokes <tt>StateFactory.getStateToBind()</tt>.
*<p> When an exception
* is thrown by a factory, the exception is passed on to the caller
* of <tt>NamingManager.getStateToBind()</tt> and
* <tt>DirectoryManager.getStateToBind()</tt>.
* The search for other factories
* that may produce a non-null answer is halted.
* A factory should only throw an exception if it is sure that
* it is the only intended factory and that no other factories
* should be tried.
* If this factory cannot create an object using the arguments supplied,
* it should return null.
* <p>
* The <code>name</code> and <code>nameCtx</code> parameters may
* optionally be used to specify the name of the object being created.
* See the description of "Name and Context Parameters" in
* {@link ObjectFactory#getObjectInstance ObjectFactory.getObjectInstance()}
* for details.
* If a factory uses <code>nameCtx</code> it should synchronize its use
* against concurrent access, since context implementations are not
* guaranteed to be thread-safe.
* <p>
* The <tt>name</tt> and <tt>environment</tt> parameters
* are owned by the caller.
* The implementation will not modify these objects or keep references
* to them, although it may keep references to clones or copies.
*
* @param obj A non-null object whose state is to be retrieved.
* @param name The name of this object relative to <code>nameCtx</code>,
* or null if no name is specified.
* @param nameCtx The context relative to which the <code>name</code>
* parameter is specified, or null if <code>name</code> is
* relative to the default initial context.
* @param environment The possibly null environment to
* be used in the creation of the object's state.
* @return The object's state for binding;
* null if the factory is not returning any changes.
* @exception NamingException if this factory encountered an exception
* while attempting to get the object's state, and no other factories are
* to be tried.
*
* @see NamingManager#getStateToBind
* @see DirectoryManager#getStateToBind
*/
public Object getStateToBind(Object obj, Name name, Context nameCtx,
Hashtable<?,?> environment)
throws NamingException;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.spi;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.net.MalformedURLException;
import javax.naming.*;
import com.sun.naming.internal.VersionHelper;
import com.sun.naming.internal.ResourceManager;
import com.sun.naming.internal.FactoryEnumeration;
/** {@collect.stats}
* This class contains methods for creating context objects
* and objects referred to by location information in the naming
* or directory service.
*<p>
* This class cannot be instantiated. It has only static methods.
*<p>
* The mention of URL in the documentation for this class refers to
* a URL string as defined by RFC 1738 and its related RFCs. It is
* any string that conforms to the syntax described therein, and
* may not always have corresponding support in the java.net.URL
* class or Web browsers.
*<p>
* NamingManager is safe for concurrent access by multiple threads.
*<p>
* Except as otherwise noted,
* a <tt>Name</tt> or environment parameter
* passed to any method is owned by the caller.
* The implementation will not modify the object or keep a reference
* to it, although it may keep a reference to a clone or copy.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class NamingManager {
/*
* Disallow anyone from creating one of these.
* Made package private so that DirectoryManager can subclass.
*/
NamingManager() {}
// should be protected and package private
static final VersionHelper helper = VersionHelper.getVersionHelper();
// --------- object factory stuff
/** {@collect.stats}
* Package-private; used by DirectoryManager and NamingManager.
*/
private static ObjectFactoryBuilder object_factory_builder = null;
/** {@collect.stats}
* The ObjectFactoryBuilder determines the policy used when
* trying to load object factories.
* See getObjectInstance() and class ObjectFactory for a description
* of the default policy.
* setObjectFactoryBuilder() overrides this default policy by installing
* an ObjectFactoryBuilder. Subsequent object factories will
* be loaded and created using the installed builder.
*<p>
* The builder can only be installed if the executing thread is allowed
* (by the security manager's checkSetFactory() method) to do so.
* Once installed, the builder cannot be replaced.
*<p>
* @param builder The factory builder to install. If null, no builder
* is installed.
* @exception SecurityException builder cannot be installed
* for security reasons.
* @exception NamingException builder cannot be installed for
* a non-security-related reason.
* @exception IllegalStateException If a factory has already been installed.
* @see #getObjectInstance
* @see ObjectFactory
* @see ObjectFactoryBuilder
* @see java.lang.SecurityManager#checkSetFactory
*/
public static synchronized void setObjectFactoryBuilder(
ObjectFactoryBuilder builder) throws NamingException {
if (object_factory_builder != null)
throw new IllegalStateException("ObjectFactoryBuilder already set");
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkSetFactory();
}
object_factory_builder = builder;
}
/** {@collect.stats}
* Used for accessing object factory builder.
*/
static synchronized ObjectFactoryBuilder getObjectFactoryBuilder() {
return object_factory_builder;
}
/** {@collect.stats}
* Retrieves the ObjectFactory for the object identified by a reference,
* using the reference's factory class name and factory codebase
* to load in the factory's class.
* @param ref The non-null reference to use.
* @param factoryName The non-null class name of the factory.
* @return The object factory for the object identified by ref; null
* if unable to load the factory.
*/
static ObjectFactory getObjectFactoryFromReference(
Reference ref, String factoryName)
throws IllegalAccessException,
InstantiationException,
MalformedURLException {
Class clas = null;
// Try to use current class loader
try {
clas = helper.loadClass(factoryName);
} catch (ClassNotFoundException e) {
// ignore and continue
// e.printStackTrace();
}
// All other exceptions are passed up.
// Not in class path; try to use codebase
String codebase;
if (clas == null &&
(codebase = ref.getFactoryClassLocation()) != null) {
try {
clas = helper.loadClass(factoryName, codebase);
} catch (ClassNotFoundException e) {
}
}
return (clas != null) ? (ObjectFactory) clas.newInstance() : null;
}
/** {@collect.stats}
* Creates an object using the factories specified in the
* <tt>Context.OBJECT_FACTORIES</tt> property of the environment
* or of the provider resource file associated with <tt>nameCtx</tt>.
*
* @return factory created; null if cannot create
*/
private static Object createObjectFromFactories(Object obj, Name name,
Context nameCtx, Hashtable environment) throws Exception {
FactoryEnumeration factories = ResourceManager.getFactories(
Context.OBJECT_FACTORIES, environment, nameCtx);
if (factories == null)
return null;
// Try each factory until one succeeds
ObjectFactory factory;
Object answer = null;
while (answer == null && factories.hasMore()) {
factory = (ObjectFactory)factories.next();
answer = factory.getObjectInstance(obj, name, nameCtx, environment);
}
return answer;
}
private static String getURLScheme(String str) {
int colon_posn = str.indexOf(':');
int slash_posn = str.indexOf('/');
if (colon_posn > 0 && (slash_posn == -1 || colon_posn < slash_posn))
return str.substring(0, colon_posn);
return null;
}
/** {@collect.stats}
* Creates an instance of an object for the specified object
* and environment.
* <p>
* If an object factory builder has been installed, it is used to
* create a factory for creating the object.
* Otherwise, the following rules are used to create the object:
*<ol>
* <li>If <code>refInfo</code> is a <code>Reference</code>
* or <code>Referenceable</code> containing a factory class name,
* use the named factory to create the object.
* Return <code>refInfo</code> if the factory cannot be created.
* Under JDK 1.1, if the factory class must be loaded from a location
* specified in the reference, a <tt>SecurityManager</tt> must have
* been installed or the factory creation will fail.
* If an exception is encountered while creating the factory,
* it is passed up to the caller.
* <li>If <tt>refInfo</tt> is a <tt>Reference</tt> or
* <tt>Referenceable</tt> with no factory class name,
* and the address or addresses are <tt>StringRefAddr</tt>s with
* address type "URL",
* try the URL context factory corresponding to each URL's scheme id
* to create the object (see <tt>getURLContext()</tt>).
* If that fails, continue to the next step.
* <li> Use the object factories specified in
* the <tt>Context.OBJECT_FACTORIES</tt> property of the environment,
* and of the provider resource file associated with
* <tt>nameCtx</tt>, in that order.
* The value of this property is a colon-separated list of factory
* class names that are tried in order, and the first one that succeeds
* in creating an object is the one used.
* If none of the factories can be loaded,
* return <code>refInfo</code>.
* If an exception is encountered while creating the object, the
* exception is passed up to the caller.
*</ol>
*<p>
* Service providers that implement the <tt>DirContext</tt>
* interface should use
* <tt>DirectoryManager.getObjectInstance()</tt>, not this method.
* Service providers that implement only the <tt>Context</tt>
* interface should use this method.
* <p>
* Note that an object factory (an object that implements the ObjectFactory
* interface) must be public and must have a public constructor that
* accepts no arguments.
* <p>
* The <code>name</code> and <code>nameCtx</code> parameters may
* optionally be used to specify the name of the object being created.
* <code>name</code> is the name of the object, relative to context
* <code>nameCtx</code>. This information could be useful to the object
* factory or to the object implementation.
* If there are several possible contexts from which the object
* could be named -- as will often be the case -- it is up to
* the caller to select one. A good rule of thumb is to select the
* "deepest" context available.
* If <code>nameCtx</code> is null, <code>name</code> is relative
* to the default initial context. If no name is being specified, the
* <code>name</code> parameter should be null.
*
* @param refInfo The possibly null object for which to create an object.
* @param name The name of this object relative to <code>nameCtx</code>.
* Specifying a name is optional; if it is
* omitted, <code>name</code> should be null.
* @param nameCtx The context relative to which the <code>name</code>
* parameter is specified. If null, <code>name</code> is
* relative to the default initial context.
* @param environment The possibly null environment to
* be used in the creation of the object factory and the object.
* @return An object created using <code>refInfo</code>; or
* <code>refInfo</code> if an object cannot be created using
* the algorithm described above.
* @exception NamingException if a naming exception was encountered
* while attempting to get a URL context, or if one of the
* factories accessed throws a NamingException.
* @exception Exception if one of the factories accessed throws an
* exception, or if an error was encountered while loading
* and instantiating the factory and object classes.
* A factory should only throw an exception if it does not want
* other factories to be used in an attempt to create an object.
* See ObjectFactory.getObjectInstance().
* @see #getURLContext
* @see ObjectFactory
* @see ObjectFactory#getObjectInstance
*/
public static Object
getObjectInstance(Object refInfo, Name name, Context nameCtx,
Hashtable<?,?> environment)
throws Exception
{
ObjectFactory factory;
// Use builder if installed
ObjectFactoryBuilder builder = getObjectFactoryBuilder();
if (builder != null) {
// builder must return non-null factory
factory = builder.createObjectFactory(refInfo, environment);
return factory.getObjectInstance(refInfo, name, nameCtx,
environment);
}
// Use reference if possible
Reference ref = null;
if (refInfo instanceof Reference) {
ref = (Reference) refInfo;
} else if (refInfo instanceof Referenceable) {
ref = ((Referenceable)(refInfo)).getReference();
}
Object answer;
if (ref != null) {
String f = ref.getFactoryClassName();
if (f != null) {
// if reference identifies a factory, use exclusively
factory = getObjectFactoryFromReference(ref, f);
if (factory != null) {
return factory.getObjectInstance(ref, name, nameCtx,
environment);
}
// No factory found, so return original refInfo.
// Will reach this point if factory class is not in
// class path and reference does not contain a URL for it
return refInfo;
} else {
// if reference has no factory, check for addresses
// containing URLs
answer = processURLAddrs(ref, name, nameCtx, environment);
if (answer != null) {
return answer;
}
}
}
// try using any specified factories
answer =
createObjectFromFactories(refInfo, name, nameCtx, environment);
return (answer != null) ? answer : refInfo;
}
/*
* Ref has no factory. For each address of type "URL", try its URL
* context factory. Returns null if unsuccessful in creating and
* invoking a factory.
*/
static Object processURLAddrs(Reference ref, Name name, Context nameCtx,
Hashtable environment)
throws NamingException {
for (int i = 0; i < ref.size(); i++) {
RefAddr addr = ref.get(i);
if (addr instanceof StringRefAddr &&
addr.getType().equalsIgnoreCase("URL")) {
String url = (String)addr.getContent();
Object answer = processURL(url, name, nameCtx, environment);
if (answer != null) {
return answer;
}
}
}
return null;
}
private static Object processURL(Object refInfo, Name name,
Context nameCtx, Hashtable environment)
throws NamingException {
Object answer;
// If refInfo is a URL string, try to use its URL context factory
// If no context found, continue to try object factories.
if (refInfo instanceof String) {
String url = (String)refInfo;
String scheme = getURLScheme(url);
if (scheme != null) {
answer = getURLObject(scheme, refInfo, name, nameCtx,
environment);
if (answer != null) {
return answer;
}
}
}
// If refInfo is an array of URL strings,
// try to find a context factory for any one of its URLs.
// If no context found, continue to try object factories.
if (refInfo instanceof String[]) {
String[] urls = (String[])refInfo;
for (int i = 0; i <urls.length; i++) {
String scheme = getURLScheme(urls[i]);
if (scheme != null) {
answer = getURLObject(scheme, refInfo, name, nameCtx,
environment);
if (answer != null)
return answer;
}
}
}
return null;
}
/** {@collect.stats}
* Retrieves a context identified by <code>obj</code>, using the specified
* environment.
* Used by ContinuationContext.
*
* @param obj The object identifying the context.
* @param name The name of the context being returned, relative to
* <code>nameCtx</code>, or null if no name is being
* specified.
* See the <code>getObjectInstance</code> method for
* details.
* @param ctx The context relative to which <code>name</code> is
* specified, or null for the default initial context.
* See the <code>getObjectInstance</code> method for
* details.
* @param environment Environment specifying characteristics of the
* resulting context.
* @return A context identified by <code>obj</code>.
*
* @see #getObjectInstance
*/
static Context getContext(Object obj, Name name, Context nameCtx,
Hashtable environment) throws NamingException {
Object answer;
if (obj instanceof Context) {
// %%% Ignore environment for now. OK since method not public.
return (Context)obj;
}
try {
answer = getObjectInstance(obj, name, nameCtx, environment);
} catch (NamingException e) {
throw e;
} catch (Exception e) {
NamingException ne = new NamingException();
ne.setRootCause(e);
throw ne;
}
return (answer instanceof Context)
? (Context)answer
: null;
}
// Used by ContinuationContext
static Resolver getResolver(Object obj, Name name, Context nameCtx,
Hashtable environment) throws NamingException {
Object answer;
if (obj instanceof Resolver) {
// %%% Ignore environment for now. OK since method not public.
return (Resolver)obj;
}
try {
answer = getObjectInstance(obj, name, nameCtx, environment);
} catch (NamingException e) {
throw e;
} catch (Exception e) {
NamingException ne = new NamingException();
ne.setRootCause(e);
throw ne;
}
return (answer instanceof Resolver)
? (Resolver)answer
: null;
}
/** {@collect.stats}*************** URL Context implementations ***************/
/** {@collect.stats}
* Creates a context for the given URL scheme id.
* <p>
* The resulting context is for resolving URLs of the
* scheme <code>scheme</code>. The resulting context is not tied
* to a specific URL. It is able to handle arbitrary URLs with
* the specified scheme.
*<p>
* The class name of the factory that creates the resulting context
* has the naming convention <i>scheme-id</i>URLContextFactory
* (e.g. "ftpURLContextFactory" for the "ftp" scheme-id),
* in the package specified as follows.
* The <tt>Context.URL_PKG_PREFIXES</tt> environment property (which
* may contain values taken from applet parameters, system properties,
* or application resource files)
* contains a colon-separated list of package prefixes.
* Each package prefix in
* the property is tried in the order specified to load the factory class.
* The default package prefix is "com.sun.jndi.url" (if none of the
* specified packages work, this default is tried).
* The complete package name is constructed using the package prefix,
* concatenated with the scheme id.
*<p>
* For example, if the scheme id is "ldap", and the
* <tt>Context.URL_PKG_PREFIXES</tt> property
* contains "com.widget:com.wiz.jndi",
* the naming manager would attempt to load the following classes
* until one is successfully instantiated:
*<ul>
* <li>com.widget.ldap.ldapURLContextFactory
* <li>com.wiz.jndi.ldap.ldapURLContextFactory
* <li>com.sun.jndi.url.ldap.ldapURLContextFactory
*</ul>
* If none of the package prefixes work, null is returned.
*<p>
* If a factory is instantiated, it is invoked with the following
* parameters to produce the resulting context.
* <p>
* <code>factory.getObjectInstance(null, environment);</code>
* <p>
* For example, invoking getObjectInstance() as shown above
* on a LDAP URL context factory would return a
* context that can resolve LDAP urls
* (e.g. "ldap://ldap.wiz.com/o=wiz,c=us",
* "ldap://ldap.umich.edu/o=umich,c=us", ...).
*<p>
* Note that an object factory (an object that implements the ObjectFactory
* interface) must be public and must have a public constructor that
* accepts no arguments.
*
* @param scheme The non-null scheme-id of the URLs supported by the context.
* @param environment The possibly null environment properties to be
* used in the creation of the object factory and the context.
* @return A context for resolving URLs with the
* scheme id <code>scheme</code>;
* <code>null</code> if the factory for creating the
* context is not found.
* @exception NamingException If a naming exception occurs while creating
* the context.
* @see #getObjectInstance
* @see ObjectFactory#getObjectInstance
*/
public static Context getURLContext(String scheme,
Hashtable<?,?> environment)
throws NamingException
{
// pass in 'null' to indicate creation of generic context for scheme
// (i.e. not specific to a URL).
Object answer = getURLObject(scheme, null, null, null, environment);
if (answer instanceof Context) {
return (Context)answer;
} else {
return null;
}
}
private static final String defaultPkgPrefix = "com.sun.jndi.url";
/** {@collect.stats}
* Creates an object for the given URL scheme id using
* the supplied urlInfo.
* <p>
* If urlInfo is null, the result is a context for resolving URLs
* with the scheme id 'scheme'.
* If urlInfo is a URL, the result is a context named by the URL.
* Names passed to this context is assumed to be relative to this
* context (i.e. not a URL). For example, if urlInfo is
* "ldap://ldap.wiz.com/o=Wiz,c=us", the resulting context will
* be that pointed to by "o=Wiz,c=us" on the server 'ldap.wiz.com'.
* Subsequent names that can be passed to this context will be
* LDAP names relative to this context (e.g. cn="Barbs Jensen").
* If urlInfo is an array of URLs, the URLs are assumed
* to be equivalent in terms of the context to which they refer.
* The resulting context is like that of the single URL case.
* If urlInfo is of any other type, that is handled by the
* context factory for the URL scheme.
* @param scheme the URL scheme id for the context
* @param urlInfo information used to create the context
* @param name name of this object relative to <code>nameCtx</code>
* @param nameCtx Context whose provider resource file will be searched
* for package prefix values (or null if none)
* @param environment Environment properties for creating the context
* @see javax.naming.InitialContext
*/
private static Object getURLObject(String scheme, Object urlInfo,
Name name, Context nameCtx,
Hashtable environment)
throws NamingException {
// e.g. "ftpURLContextFactory"
ObjectFactory factory = (ObjectFactory)ResourceManager.getFactory(
Context.URL_PKG_PREFIXES, environment, nameCtx,
"." + scheme + "." + scheme + "URLContextFactory", defaultPkgPrefix);
if (factory == null)
return null;
// Found object factory
try {
return factory.getObjectInstance(urlInfo, name, nameCtx, environment);
} catch (NamingException e) {
throw e;
} catch (Exception e) {
NamingException ne = new NamingException();
ne.setRootCause(e);
throw ne;
}
}
// ------------ Initial Context Factory Stuff
private static InitialContextFactoryBuilder initctx_factory_builder = null;
/** {@collect.stats}
* Use this method for accessing initctx_factory_builder while
* inside an unsynchronized method.
*/
private static synchronized InitialContextFactoryBuilder
getInitialContextFactoryBuilder() {
return initctx_factory_builder;
}
/** {@collect.stats}
* Creates an initial context using the specified environment
* properties.
*<p>
* If an InitialContextFactoryBuilder has been installed,
* it is used to create the factory for creating the initial context.
* Otherwise, the class specified in the
* <tt>Context.INITIAL_CONTEXT_FACTORY</tt> environment property is used.
* Note that an initial context factory (an object that implements the
* InitialContextFactory interface) must be public and must have a
* public constructor that accepts no arguments.
*
* @param env The possibly null environment properties used when
* creating the context.
* @return A non-null initial context.
* @exception NoInitialContextException If the
* <tt>Context.INITIAL_CONTEXT_FACTORY</tt> property
* is not found or names a nonexistent
* class or a class that cannot be instantiated,
* or if the initial context could not be created for some other
* reason.
* @exception NamingException If some other naming exception was encountered.
* @see javax.naming.InitialContext
* @see javax.naming.directory.InitialDirContext
*/
public static Context getInitialContext(Hashtable<?,?> env)
throws NamingException {
InitialContextFactory factory;
InitialContextFactoryBuilder builder = getInitialContextFactoryBuilder();
if (builder == null) {
// No factory installed, use property
// Get initial context factory class name
String className = env != null ?
(String)env.get(Context.INITIAL_CONTEXT_FACTORY) : null;
if (className == null) {
NoInitialContextException ne = new NoInitialContextException(
"Need to specify class name in environment or system " +
"property, or as an applet parameter, or in an " +
"application resource file: " +
Context.INITIAL_CONTEXT_FACTORY);
throw ne;
}
try {
factory = (InitialContextFactory)
helper.loadClass(className).newInstance();
} catch(Exception e) {
NoInitialContextException ne =
new NoInitialContextException(
"Cannot instantiate class: " + className);
ne.setRootCause(e);
throw ne;
}
} else {
factory = builder.createInitialContextFactory(env);
}
return factory.getInitialContext(env);
}
/** {@collect.stats}
* Sets the InitialContextFactory builder to be builder.
*
*<p>
* The builder can only be installed if the executing thread is allowed by
* the security manager to do so. Once installed, the builder cannot
* be replaced.
* @param builder The initial context factory builder to install. If null,
* no builder is set.
* @exception SecurityException builder cannot be installed for security
* reasons.
* @exception NamingException builder cannot be installed for
* a non-security-related reason.
* @exception IllegalStateException If a builder was previous installed.
* @see #hasInitialContextFactoryBuilder
* @see java.lang.SecurityManager#checkSetFactory
*/
public static synchronized void setInitialContextFactoryBuilder(
InitialContextFactoryBuilder builder)
throws NamingException {
if (initctx_factory_builder != null)
throw new IllegalStateException(
"InitialContextFactoryBuilder already set");
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkSetFactory();
}
initctx_factory_builder = builder;
}
/** {@collect.stats}
* Determines whether an initial context factory builder has
* been set.
* @return true if an initial context factory builder has
* been set; false otherwise.
* @see #setInitialContextFactoryBuilder
*/
public static boolean hasInitialContextFactoryBuilder() {
return (getInitialContextFactoryBuilder() != null);
}
// ----- Continuation Context Stuff
/** {@collect.stats}
* Constant that holds the name of the environment property into
* which <tt>getContinuationContext()</tt> stores the value of its
* <tt>CannotProceedException</tt> parameter.
* This property is inherited by the continuation context, and may
* be used by that context's service provider to inspect the
* fields of the exception.
*<p>
* The value of this constant is "java.naming.spi.CannotProceedException".
*
* @see #getContinuationContext
* @since 1.3
*/
public static final String CPE = "java.naming.spi.CannotProceedException";
/** {@collect.stats}
* Creates a context in which to continue a context operation.
*<p>
* In performing an operation on a name that spans multiple
* namespaces, a context from one naming system may need to pass
* the operation on to the next naming system. The context
* implementation does this by first constructing a
* <code>CannotProceedException</code> containing information
* pinpointing how far it has proceeded. It then obtains a
* continuation context from JNDI by calling
* <code>getContinuationContext</code>. The context
* implementation should then resume the context operation by
* invoking the same operation on the continuation context, using
* the remainder of the name that has not yet been resolved.
*<p>
* Before making use of the <tt>cpe</tt> parameter, this method
* updates the environment associated with that object by setting
* the value of the property <a href="#CPE"><tt>CPE</tt></a>
* to <tt>cpe</tt>. This property will be inherited by the
* continuation context, and may be used by that context's
* service provider to inspect the fields of this exception.
*
* @param cpe
* The non-null exception that triggered this continuation.
* @return A non-null Context object for continuing the operation.
* @exception NamingException If a naming exception occurred.
*/
public static Context getContinuationContext(CannotProceedException cpe)
throws NamingException {
Hashtable env = cpe.getEnvironment();
if (env == null) {
env = new Hashtable(7);
} else {
// Make a (shallow) copy of the environment.
env = (Hashtable) env.clone();
}
env.put(CPE, cpe);
ContinuationContext cctx = new ContinuationContext(cpe, env);
return cctx.getTargetContext();
}
// ------------ State Factory Stuff
/** {@collect.stats}
* Retrieves the state of an object for binding.
* <p>
* Service providers that implement the <tt>DirContext</tt> interface
* should use <tt>DirectoryManager.getStateToBind()</tt>, not this method.
* Service providers that implement only the <tt>Context</tt> interface
* should use this method.
*<p>
* This method uses the specified state factories in
* the <tt>Context.STATE_FACTORIES</tt> property from the environment
* properties, and from the provider resource file associated with
* <tt>nameCtx</tt>, in that order.
* The value of this property is a colon-separated list of factory
* class names that are tried in order, and the first one that succeeds
* in returning the object's state is the one used.
* If no object's state can be retrieved in this way, return the
* object itself.
* If an exception is encountered while retrieving the state, the
* exception is passed up to the caller.
* <p>
* Note that a state factory
* (an object that implements the StateFactory
* interface) must be public and must have a public constructor that
* accepts no arguments.
* <p>
* The <code>name</code> and <code>nameCtx</code> parameters may
* optionally be used to specify the name of the object being created.
* See the description of "Name and Context Parameters" in
* {@link ObjectFactory#getObjectInstance
* ObjectFactory.getObjectInstance()}
* for details.
* <p>
* This method may return a <tt>Referenceable</tt> object. The
* service provider obtaining this object may choose to store it
* directly, or to extract its reference (using
* <tt>Referenceable.getReference()</tt>) and store that instead.
*
* @param obj The non-null object for which to get state to bind.
* @param name The name of this object relative to <code>nameCtx</code>,
* or null if no name is specified.
* @param nameCtx The context relative to which the <code>name</code>
* parameter is specified, or null if <code>name</code> is
* relative to the default initial context.
* @param environment The possibly null environment to
* be used in the creation of the state factory and
* the object's state.
* @return The non-null object representing <tt>obj</tt>'s state for
* binding. It could be the object (<tt>obj</tt>) itself.
* @exception NamingException If one of the factories accessed throws an
* exception, or if an error was encountered while loading
* and instantiating the factory and object classes.
* A factory should only throw an exception if it does not want
* other factories to be used in an attempt to create an object.
* See <tt>StateFactory.getStateToBind()</tt>.
* @see StateFactory
* @see StateFactory#getStateToBind
* @see DirectoryManager#getStateToBind
* @since 1.3
*/
public static Object
getStateToBind(Object obj, Name name, Context nameCtx,
Hashtable<?,?> environment)
throws NamingException
{
FactoryEnumeration factories = ResourceManager.getFactories(
Context.STATE_FACTORIES, environment, nameCtx);
if (factories == null) {
return obj;
}
// Try each factory until one succeeds
StateFactory factory;
Object answer = null;
while (answer == null && factories.hasMore()) {
factory = (StateFactory)factories.next();
answer = factory.getStateToBind(obj, name, nameCtx, environment);
}
return (answer != null) ? answer : obj;
}
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.spi;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
/** {@collect.stats}
* This interface represents an "intermediate context" for name resolution.
*<p>
* The Resolver interface contains methods that are implemented by contexts
* that do not support subtypes of Context, but which can act as
* intermediate contexts for resolution purposes.
*<p>
* A <tt>Name</tt> parameter passed to any method is owned
* by the caller. The service provider will not modify the object
* or keep a reference to it.
* A <tt>ResolveResult</tt> object returned by any
* method is owned by the caller. The caller may subsequently modify it;
* the service provider may not.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public interface Resolver {
/** {@collect.stats}
* Partially resolves a name. Stops at the first
* context that is an instance of a given subtype of
* <code>Context</code>.
*
* @param name
* the name to resolve
* @param contextType
* the type of object to resolve. This should
* be a subtype of <code>Context</code>.
* @return the object that was found, along with the unresolved
* suffix of <code>name</code>. Cannot be null.
*
* @throws javax.naming.NotContextException
* if no context of the appropriate type is found
* @throws NamingException if a naming exception was encountered
*
* @see #resolveToClass(String, Class)
*/
public ResolveResult resolveToClass(Name name,
Class<? extends Context> contextType)
throws NamingException;
/** {@collect.stats}
* Partially resolves a name.
* See {@link #resolveToClass(Name, Class)} for details.
*
* @param name
* the name to resolve
* @param contextType
* the type of object to resolve. This should
* be a subtype of <code>Context</code>.
* @return the object that was found, along with the unresolved
* suffix of <code>name</code>. Cannot be null.
*
* @throws javax.naming.NotContextException
* if no context of the appropriate type is found
* @throws NamingException if a naming exception was encountered
*/
public ResolveResult resolveToClass(String name,
Class<? extends Context> contextType)
throws NamingException;
};
|
Java
|
/*
* Copyright (c) 1999, 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.naming.spi;
import java.util.Hashtable;
import javax.naming.Name;
import javax.naming.NamingEnumeration;
import javax.naming.CompositeName;
import javax.naming.NamingException;
import javax.naming.CannotProceedException;
import javax.naming.OperationNotSupportedException;
import javax.naming.Context;
import javax.naming.directory.DirContext;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.ModificationItem;
/** {@collect.stats}
* This class is the continuation context for invoking DirContext methods.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
class ContinuationDirContext extends ContinuationContext implements DirContext {
ContinuationDirContext(CannotProceedException cpe, Hashtable env) {
super(cpe, env);
}
protected DirContextNamePair getTargetContext(Name name)
throws NamingException {
if (cpe.getResolvedObj() == null)
throw (NamingException)cpe.fillInStackTrace();
Context ctx = NamingManager.getContext(cpe.getResolvedObj(),
cpe.getAltName(),
cpe.getAltNameCtx(),
env);
if (ctx == null)
throw (NamingException)cpe.fillInStackTrace();
if (ctx instanceof DirContext)
return new DirContextNamePair((DirContext)ctx, name);
if (ctx instanceof Resolver) {
Resolver res = (Resolver)ctx;
ResolveResult rr = res.resolveToClass(name, DirContext.class);
// Reached a DirContext; return result.
DirContext dctx = (DirContext)rr.getResolvedObj();
return (new DirContextNamePair(dctx, rr.getRemainingName()));
}
// Resolve all the way using lookup(). This may allow the operation
// to succeed if it doesn't require the penultimate context.
Object ultimate = ctx.lookup(name);
if (ultimate instanceof DirContext) {
return (new DirContextNamePair((DirContext)ultimate,
new CompositeName()));
}
throw (NamingException)cpe.fillInStackTrace();
}
protected DirContextStringPair getTargetContext(String name)
throws NamingException {
if (cpe.getResolvedObj() == null)
throw (NamingException)cpe.fillInStackTrace();
Context ctx = NamingManager.getContext(cpe.getResolvedObj(),
cpe.getAltName(),
cpe.getAltNameCtx(),
env);
if (ctx instanceof DirContext)
return new DirContextStringPair((DirContext)ctx, name);
if (ctx instanceof Resolver) {
Resolver res = (Resolver)ctx;
ResolveResult rr = res.resolveToClass(name, DirContext.class);
// Reached a DirContext; return result.
DirContext dctx = (DirContext)rr.getResolvedObj();
Name tmp = rr.getRemainingName();
String remains = (tmp != null) ? tmp.toString() : "";
return (new DirContextStringPair(dctx, remains));
}
// Resolve all the way using lookup(). This may allow the operation
// to succeed if it doesn't require the penultimate context.
Object ultimate = ctx.lookup(name);
if (ultimate instanceof DirContext) {
return (new DirContextStringPair((DirContext)ultimate, ""));
}
throw (NamingException)cpe.fillInStackTrace();
}
public Attributes getAttributes(String name) throws NamingException {
DirContextStringPair res = getTargetContext(name);
return res.getDirContext().getAttributes(res.getString());
}
public Attributes getAttributes(String name, String[] attrIds)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
return res.getDirContext().getAttributes(res.getString(), attrIds);
}
public Attributes getAttributes(Name name) throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().getAttributes(res.getName());
}
public Attributes getAttributes(Name name, String[] attrIds)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().getAttributes(res.getName(), attrIds);
}
public void modifyAttributes(Name name, int mod_op, Attributes attrs)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
res.getDirContext().modifyAttributes(res.getName(), mod_op, attrs);
}
public void modifyAttributes(String name, int mod_op, Attributes attrs)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
res.getDirContext().modifyAttributes(res.getString(), mod_op, attrs);
}
public void modifyAttributes(Name name, ModificationItem[] mods)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
res.getDirContext().modifyAttributes(res.getName(), mods);
}
public void modifyAttributes(String name, ModificationItem[] mods)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
res.getDirContext().modifyAttributes(res.getString(), mods);
}
public void bind(Name name, Object obj, Attributes attrs)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
res.getDirContext().bind(res.getName(), obj, attrs);
}
public void bind(String name, Object obj, Attributes attrs)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
res.getDirContext().bind(res.getString(), obj, attrs);
}
public void rebind(Name name, Object obj, Attributes attrs)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
res.getDirContext().rebind(res.getName(), obj, attrs);
}
public void rebind(String name, Object obj, Attributes attrs)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
res.getDirContext().rebind(res.getString(), obj, attrs);
}
public DirContext createSubcontext(Name name, Attributes attrs)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().createSubcontext(res.getName(), attrs);
}
public DirContext createSubcontext(String name, Attributes attrs)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
return
res.getDirContext().createSubcontext(res.getString(), attrs);
}
public NamingEnumeration search(Name name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().search(res.getName(), matchingAttributes,
attributesToReturn);
}
public NamingEnumeration search(String name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
return res.getDirContext().search(res.getString(),
matchingAttributes,
attributesToReturn);
}
public NamingEnumeration search(Name name,
Attributes matchingAttributes)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().search(res.getName(), matchingAttributes);
}
public NamingEnumeration search(String name,
Attributes matchingAttributes)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
return res.getDirContext().search(res.getString(),
matchingAttributes);
}
public NamingEnumeration search(Name name,
String filter,
SearchControls cons)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().search(res.getName(), filter, cons);
}
public NamingEnumeration search(String name,
String filter,
SearchControls cons)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
return res.getDirContext().search(res.getString(), filter, cons);
}
public NamingEnumeration search(Name name,
String filterExpr,
Object[] args,
SearchControls cons)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().search(res.getName(), filterExpr, args,
cons);
}
public NamingEnumeration search(String name,
String filterExpr,
Object[] args,
SearchControls cons)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
return res.getDirContext().search(res.getString(), filterExpr, args,
cons);
}
public DirContext getSchema(String name) throws NamingException {
DirContextStringPair res = getTargetContext(name);
return res.getDirContext().getSchema(res.getString());
}
public DirContext getSchema(Name name) throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().getSchema(res.getName());
}
public DirContext getSchemaClassDefinition(String name)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
return res.getDirContext().getSchemaClassDefinition(res.getString());
}
public DirContext getSchemaClassDefinition(Name name)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().getSchemaClassDefinition(res.getName());
}
}
class DirContextNamePair {
DirContext ctx;
Name name;
DirContextNamePair(DirContext ctx, Name name) {
this.ctx = ctx;
this.name = name;
}
DirContext getDirContext() {
return ctx;
}
Name getName() {
return name;
}
}
class DirContextStringPair {
DirContext ctx;
String str;
DirContextStringPair(DirContext ctx, String str) {
this.ctx = ctx;
this.str = str;
}
DirContext getDirContext() {
return ctx;
}
String getString() {
return str;
}
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.spi;
import java.util.Hashtable;
import javax.naming.*;
import javax.naming.directory.Attributes;
/** {@collect.stats}
* This interface represents a factory for creating an object given
* an object and attributes about the object.
*<p>
* The JNDI framework allows for object implementations to
* be loaded in dynamically via <em>object factories</em>. See
* <tt>ObjectFactory</tt> for details.
* <p>
* A <tt>DirObjectFactory</tt> extends <tt>ObjectFactory</tt> by allowing
* an <tt>Attributes</tt> instance
* to be supplied to the <tt>getObjectInstance()</tt> method.
* <tt>DirObjectFactory</tt> implementations are intended to be used by <tt>DirContext</tt>
* service providers. The service provider, in addition reading an
* object from the directory, might already have attributes that
* are useful for the object factory to check to see whether the
* factory is supposed to process the object. For instance, an LDAP-style
* service provider might have read the "objectclass" of the object.
* A CORBA object factory might be interested only in LDAP entries
* with "objectclass=corbaObject". By using the attributes supplied by
* the LDAP service provider, the CORBA object factory can quickly
* eliminate objects that it need not worry about, and non-CORBA object
* factories can quickly eliminate CORBA-related LDAP entries.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see NamingManager#getObjectInstance
* @see DirectoryManager#getObjectInstance
* @see ObjectFactory
* @since 1.3
*/
public interface DirObjectFactory extends ObjectFactory {
/** {@collect.stats}
* Creates an object using the location or reference information, and attributes
* specified.
* <p>
* Special requirements of this object are supplied
* using <code>environment</code>.
* An example of such an environment property is user identity
* information.
*<p>
* <tt>DirectoryManager.getObjectInstance()</tt>
* successively loads in object factories. If it encounters a <tt>DirObjectFactory</tt>,
* it will invoke <tt>DirObjectFactory.getObjectInstance()</tt>;
* otherwise, it invokes
* <tt>ObjectFactory.getObjectInstance()</tt>. It does this until a factory
* produces a non-null answer.
* <p> When an exception
* is thrown by an object factory, the exception is passed on to the caller
* of <tt>DirectoryManager.getObjectInstance()</tt>. The search for other factories
* that may produce a non-null answer is halted.
* An object factory should only throw an exception if it is sure that
* it is the only intended factory and that no other object factories
* should be tried.
* If this factory cannot create an object using the arguments supplied,
* it should return null.
*<p>Since <tt>DirObjectFactory</tt> extends <tt>ObjectFactory</tt>, it
* effectively
* has two <tt>getObjectInstance()</tt> methods, where one differs from the other by
* the attributes argument. Given a factory that implements <tt>DirObjectFactory</tt>,
* <tt>DirectoryManager.getObjectInstance()</tt> will only
* use the method that accepts the attributes argument, while
* <tt>NamingManager.getObjectInstance()</tt> will only use the one that does not accept
* the attributes argument.
*<p>
* See <tt>ObjectFactory</tt> for a description URL context factories and other
* properties of object factories that apply equally to <tt>DirObjectFactory</tt>.
*<p>
* The <tt>name</tt>, <tt>attrs</tt>, and <tt>environment</tt> parameters
* are owned by the caller.
* The implementation will not modify these objects or keep references
* to them, although it may keep references to clones or copies.
*
* @param obj The possibly null object containing location or reference
* information that can be used in creating an object.
* @param name The name of this object relative to <code>nameCtx</code>,
* or null if no name is specified.
* @param nameCtx The context relative to which the <code>name</code>
* parameter is specified, or null if <code>name</code> is
* relative to the default initial context.
* @param environment The possibly null environment that is used in
* creating the object.
* @param attrs The possibly null attributes containing some of <tt>obj</tt>'s
* attributes. <tt>attrs</tt> might not necessarily have all of <tt>obj</tt>'s
* attributes. If the object factory requires more attributes, it needs
* to get it, either using <tt>obj</tt>, or <tt>name</tt> and <tt>nameCtx</tt>.
* The factory must not modify attrs.
* @return The object created; null if an object cannot be created.
* @exception Exception If this object factory encountered an exception
* while attempting to create an object, and no other object factories are
* to be tried.
*
* @see DirectoryManager#getObjectInstance
* @see NamingManager#getURLContext
*/
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable<?,?> environment,
Attributes attrs)
throws Exception;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.spi;
import java.util.Hashtable;
import javax.naming.NamingException;
/** {@collect.stats}
* This interface represents a builder that creates initial context factories.
*<p>
* The JNDI framework allows for different initial context implementations
* to be specified at runtime. An initial context is created using
* an initial context factory. A program can install its own builder
* that creates initial context factories, thereby overriding the
* default policies used by the framework, by calling
* NamingManager.setInitialContextFactoryBuilder().
* The InitialContextFactoryBuilder interface must be implemented by
* such a builder.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see InitialContextFactory
* @see NamingManager#getInitialContext
* @see NamingManager#setInitialContextFactoryBuilder
* @see NamingManager#hasInitialContextFactoryBuilder
* @see javax.naming.InitialContext
* @see javax.naming.directory.InitialDirContext
* @since 1.3
*/
public interface InitialContextFactoryBuilder {
/** {@collect.stats}
* Creates an initial context factory using the specified
* environment.
*<p>
* The environment parameter is owned by the caller.
* The implementation will not modify the object or keep a reference
* to it, although it may keep a reference to a clone or copy.
*
* @param environment Environment used in creating an initial
* context implementation. Can be null.
* @return A non-null initial context factory.
* @exception NamingException If an initial context factory could not be created.
*/
public InitialContextFactory
createInitialContextFactory(Hashtable<?,?> environment)
throws NamingException;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.spi;
import javax.naming.Name;
import javax.naming.Context;
import javax.naming.CompositeName;
import javax.naming.InvalidNameException;
/** {@collect.stats}
* This class represents the result of resolution of a name.
* It contains the object to which name was resolved, and the portion
* of the name that has not been resolved.
*<p>
* A ResolveResult instance is not synchronized against concurrent
* multithreaded access. Multiple threads trying to access and modify
* a single ResolveResult instance should lock the object.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class ResolveResult implements java.io.Serializable {
/** {@collect.stats}
* Field containing the Object that was resolved to successfully.
* It can be null only when constructed using a subclass.
* Constructors should always initialize this.
* @serial
*/
protected Object resolvedObj;
/** {@collect.stats}
* Field containing the remaining name yet to be resolved.
* It can be null only when constructed using a subclass.
* Constructors should always initialize this.
* @serial
*/
protected Name remainingName;
/** {@collect.stats}
* Constructs an instance of ResolveResult with the
* resolved object and remaining name both initialized to null.
*/
protected ResolveResult() {
resolvedObj = null;
remainingName = null;
}
/** {@collect.stats}
* Constructs a new instance of ResolveResult consisting of
* the resolved object and the remaining unresolved component.
*
* @param robj The non-null object resolved to.
* @param rcomp The single remaining name component that has yet to be
* resolved. Cannot be null (but can be empty).
*/
public ResolveResult(Object robj, String rcomp) {
resolvedObj = robj;
try {
remainingName = new CompositeName(rcomp);
// remainingName.appendComponent(rcomp);
} catch (InvalidNameException e) {
// ignore; shouldn't happen
}
}
/** {@collect.stats}
* Constructs a new instance of ResolveResult consisting of
* the resolved Object and the remaining name.
*
* @param robj The non-null Object resolved to.
* @param rname The non-null remaining name that has yet to be resolved.
*/
public ResolveResult(Object robj, Name rname) {
resolvedObj = robj;
setRemainingName(rname);
}
/** {@collect.stats}
* Retrieves the remaining unresolved portion of the name.
*
* @return The remaining unresolved portion of the name.
* Cannot be null but empty OK.
* @see #appendRemainingName
* @see #appendRemainingComponent
* @see #setRemainingName
*/
public Name getRemainingName() {
return this.remainingName;
}
/** {@collect.stats}
* Retrieves the Object to which resolution was successful.
*
* @return The Object to which resolution was successful. Cannot be null.
* @see #setResolvedObj
*/
public Object getResolvedObj() {
return this.resolvedObj;
}
/** {@collect.stats}
* Sets the remaining name field of this result to name.
* A copy of name is made so that modifying the copy within
* this ResolveResult does not affect <code>name</code> and
* vice versa.
*
* @param name The name to set remaining name to. Cannot be null.
* @see #getRemainingName
* @see #appendRemainingName
* @see #appendRemainingComponent
*/
public void setRemainingName(Name name) {
if (name != null)
this.remainingName = (Name)(name.clone());
else {
// ??? should throw illegal argument exception
this.remainingName = null;
}
}
/** {@collect.stats}
* Adds components to the end of remaining name.
*
* @param name The components to add. Can be null.
* @see #getRemainingName
* @see #setRemainingName
* @see #appendRemainingComponent
*/
public void appendRemainingName(Name name) {
// System.out.println("appendingRemainingName: " + name.toString());
// Exception e = new Exception();
// e.printStackTrace();
if (name != null) {
if (this.remainingName != null) {
try {
this.remainingName.addAll(name);
} catch (InvalidNameException e) {
// ignore; shouldn't happen for composite name
}
} else {
this.remainingName = (Name)(name.clone());
}
}
}
/** {@collect.stats}
* Adds a single component to the end of remaining name.
*
* @param name The component to add. Can be null.
* @see #getRemainingName
* @see #appendRemainingName
*/
public void appendRemainingComponent(String name) {
if (name != null) {
CompositeName rname = new CompositeName();
try {
rname.add(name);
} catch (InvalidNameException e) {
// ignore; shouldn't happen for empty composite name
}
appendRemainingName(rname);
}
}
/** {@collect.stats}
* Sets the resolved Object field of this result to obj.
*
* @param obj The object to use for setting the resolved obj field.
* Cannot be null.
* @see #getResolvedObj
*/
public void setResolvedObj(Object obj) {
this.resolvedObj = obj;
// ??? should check for null?
}
private static final long serialVersionUID = -4552108072002407559L;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.spi;
import java.util.Hashtable;
import javax.naming.NamingException;
/** {@collect.stats}
* This interface represents a builder that creates object factories.
*<p>
* The JNDI framework allows for object implementations to
* be loaded in dynamically via <em>object factories</em>.
* For example, when looking up a printer bound in the name space,
* if the print service binds printer names to References, the printer
* Reference could be used to create a printer object, so that
* the caller of lookup can directly operate on the printer object
* after the lookup. An ObjectFactory is responsible for creating
* objects of a specific type. JNDI uses a default policy for using
* and loading object factories. You can override this default policy
* by calling <tt>NamingManager.setObjectFactoryBuilder()</tt> with an ObjectFactoryBuilder,
* which contains the program-defined way of creating/loading
* object factories.
* Any <tt>ObjectFactoryBuilder</tt> implementation must implement this
* interface that for creating object factories.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see ObjectFactory
* @see NamingManager#getObjectInstance
* @see NamingManager#setObjectFactoryBuilder
* @since 1.3
*/
public interface ObjectFactoryBuilder {
/** {@collect.stats}
* Creates a new object factory using the environment supplied.
*<p>
* The environment parameter is owned by the caller.
* The implementation will not modify the object or keep a reference
* to it, although it may keep a reference to a clone or copy.
*
* @param obj The possibly null object for which to create a factory.
* @param environment Environment to use when creating the factory.
* Can be null.
* @return A non-null new instance of an ObjectFactory.
* @exception NamingException If an object factory cannot be created.
*
*/
public ObjectFactory createObjectFactory(Object obj,
Hashtable<?,?> environment)
throws NamingException;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.spi;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.Reference;
import javax.naming.Referenceable;
import javax.naming.NamingException;
import javax.naming.CannotProceedException;
import javax.naming.directory.DirContext;
import javax.naming.directory.Attributes;
import com.sun.naming.internal.ResourceManager;
import com.sun.naming.internal.FactoryEnumeration;
/** {@collect.stats}
* This class contains methods for supporting <tt>DirContext</tt>
* implementations.
*<p>
* This class is an extension of <tt>NamingManager</tt>. It contains methods
* for use by service providers for accessing object factories and
* state factories, and for getting continuation contexts for
* supporting federation.
*<p>
* <tt>DirectoryManager</tt> is safe for concurrent access by multiple threads.
*<p>
* Except as otherwise noted,
* a <tt>Name</tt>, <tt>Attributes</tt>, or environment parameter
* passed to any method is owned by the caller.
* The implementation will not modify the object or keep a reference
* to it, although it may keep a reference to a clone or copy.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see DirObjectFactory
* @see DirStateFactory
* @since 1.3
*/
public class DirectoryManager extends NamingManager {
/*
* Disallow anyone from creating one of these.
*/
DirectoryManager() {}
/** {@collect.stats}
* Creates a context in which to continue a <tt>DirContext</tt> operation.
* Operates just like <tt>NamingManager.getContinuationContext()</tt>,
* only the continuation context returned is a <tt>DirContext</tt>.
*
* @param cpe
* The non-null exception that triggered this continuation.
* @return A non-null <tt>DirContext</tt> object for continuing the operation.
* @exception NamingException If a naming exception occurred.
*
* @see NamingManager#getContinuationContext(CannotProceedException)
*/
public static DirContext getContinuationDirContext(
CannotProceedException cpe) throws NamingException {
Hashtable env = cpe.getEnvironment();
if (env == null) {
env = new Hashtable(7);
} else {
// Make a (shallow) copy of the environment.
env = (Hashtable) env.clone();
}
env.put(CPE, cpe);
return (new ContinuationDirContext(cpe, env));
}
/** {@collect.stats}
* Creates an instance of an object for the specified object,
* attributes, and environment.
* <p>
* This method is the same as <tt>NamingManager.getObjectInstance</tt>
* except for the following differences:
*<ul>
*<li>
* It accepts an <tt>Attributes</tt> parameter that contains attributes
* associated with the object. The <tt>DirObjectFactory</tt> might use these
* attributes to save having to look them up from the directory.
*<li>
* The object factories tried must implement either
* <tt>ObjectFactory</tt> or <tt>DirObjectFactory</tt>.
* If it implements <tt>DirObjectFactory</tt>,
* <tt>DirObjectFactory.getObjectInstance()</tt> is used, otherwise,
* <tt>ObjectFactory.getObjectInstance()</tt> is used.
*</ul>
* Service providers that implement the <tt>DirContext</tt> interface
* should use this method, not <tt>NamingManager.getObjectInstance()</tt>.
*<p>
*
* @param refInfo The possibly null object for which to create an object.
* @param name The name of this object relative to <code>nameCtx</code>.
* Specifying a name is optional; if it is
* omitted, <code>name</code> should be null.
* @param nameCtx The context relative to which the <code>name</code>
* parameter is specified. If null, <code>name</code> is
* relative to the default initial context.
* @param environment The possibly null environment to
* be used in the creation of the object factory and the object.
* @param attrs The possibly null attributes associated with refInfo.
* This might not be the complete set of attributes for refInfo;
* you might be able to read more attributes from the directory.
* @return An object created using <code>refInfo</code> and <tt>attrs</tt>; or
* <code>refInfo</code> if an object cannot be created by
* a factory.
* @exception NamingException If a naming exception was encountered
* while attempting to get a URL context, or if one of the
* factories accessed throws a NamingException.
* @exception Exception If one of the factories accessed throws an
* exception, or if an error was encountered while loading
* and instantiating the factory and object classes.
* A factory should only throw an exception if it does not want
* other factories to be used in an attempt to create an object.
* See <tt>DirObjectFactory.getObjectInstance()</tt>.
* @see NamingManager#getURLContext
* @see DirObjectFactory
* @see DirObjectFactory#getObjectInstance
* @since 1.3
*/
public static Object
getObjectInstance(Object refInfo, Name name, Context nameCtx,
Hashtable<?,?> environment, Attributes attrs)
throws Exception {
ObjectFactory factory;
ObjectFactoryBuilder builder = getObjectFactoryBuilder();
if (builder != null) {
// builder must return non-null factory
factory = builder.createObjectFactory(refInfo, environment);
if (factory instanceof DirObjectFactory) {
return ((DirObjectFactory)factory).getObjectInstance(
refInfo, name, nameCtx, environment, attrs);
} else {
return factory.getObjectInstance(refInfo, name, nameCtx,
environment);
}
}
// use reference if possible
Reference ref = null;
if (refInfo instanceof Reference) {
ref = (Reference) refInfo;
} else if (refInfo instanceof Referenceable) {
ref = ((Referenceable)(refInfo)).getReference();
}
Object answer;
if (ref != null) {
String f = ref.getFactoryClassName();
if (f != null) {
// if reference identifies a factory, use exclusively
factory = getObjectFactoryFromReference(ref, f);
if (factory instanceof DirObjectFactory) {
return ((DirObjectFactory)factory).getObjectInstance(
ref, name, nameCtx, environment, attrs);
} else if (factory != null) {
return factory.getObjectInstance(ref, name, nameCtx,
environment);
}
// No factory found, so return original refInfo.
// Will reach this point if factory class is not in
// class path and reference does not contain a URL for it
return refInfo;
} else {
// if reference has no factory, check for addresses
// containing URLs
// ignore name & attrs params; not used in URL factory
answer = processURLAddrs(ref, name, nameCtx, environment);
if (answer != null) {
return answer;
}
}
}
// try using any specified factories
answer = createObjectFromFactories(refInfo, name, nameCtx,
environment, attrs);
return (answer != null) ? answer : refInfo;
}
private static Object createObjectFromFactories(Object obj, Name name,
Context nameCtx, Hashtable environment, Attributes attrs)
throws Exception {
FactoryEnumeration factories = ResourceManager.getFactories(
Context.OBJECT_FACTORIES, environment, nameCtx);
if (factories == null)
return null;
ObjectFactory factory;
Object answer = null;
// Try each factory until one succeeds
while (answer == null && factories.hasMore()) {
factory = (ObjectFactory)factories.next();
if (factory instanceof DirObjectFactory) {
answer = ((DirObjectFactory)factory).
getObjectInstance(obj, name, nameCtx, environment, attrs);
} else {
answer =
factory.getObjectInstance(obj, name, nameCtx, environment);
}
}
return answer;
}
/** {@collect.stats}
* Retrieves the state of an object for binding when given the original
* object and its attributes.
* <p>
* This method is like <tt>NamingManager.getStateToBind</tt> except
* for the following differences:
*<ul>
*<li>It accepts an <tt>Attributes</tt> parameter containing attributes
* that were passed to the <tt>DirContext.bind()</tt> method.
*<li>It returns a non-null <tt>DirStateFactory.Result</tt> instance
* containing the object to be bound, and the attributes to
* accompany the binding. Either the object or the attributes may be null.
*<li>
* The state factories tried must each implement either
* <tt>StateFactory</tt> or <tt>DirStateFactory</tt>.
* If it implements <tt>DirStateFactory</tt>, then
* <tt>DirStateFactory.getStateToBind()</tt> is called; otherwise,
* <tt>StateFactory.getStateToBind()</tt> is called.
*</ul>
*
* Service providers that implement the <tt>DirContext</tt> interface
* should use this method, not <tt>NamingManager.getStateToBind()</tt>.
*<p>
* See NamingManager.getStateToBind() for a description of how
* the list of state factories to be tried is determined.
*<p>
* The object returned by this method is owned by the caller.
* The implementation will not subsequently modify it.
* It will contain either a new <tt>Attributes</tt> object that is
* likewise owned by the caller, or a reference to the original
* <tt>attrs</tt> parameter.
*
* @param obj The non-null object for which to get state to bind.
* @param name The name of this object relative to <code>nameCtx</code>,
* or null if no name is specified.
* @param nameCtx The context relative to which the <code>name</code>
* parameter is specified, or null if <code>name</code> is
* relative to the default initial context.
* @param environment The possibly null environment to
* be used in the creation of the state factory and
* the object's state.
* @param attrs The possibly null Attributes that is to be bound with the
* object.
* @return A non-null DirStateFactory.Result containing
* the object and attributes to be bound.
* If no state factory returns a non-null answer, the result will contain
* the object (<tt>obj</tt>) itself with the original attributes.
* @exception NamingException If a naming exception was encountered
* while using the factories.
* A factory should only throw an exception if it does not want
* other factories to be used in an attempt to create an object.
* See <tt>DirStateFactory.getStateToBind()</tt>.
* @see DirStateFactory
* @see DirStateFactory#getStateToBind
* @see NamingManager#getStateToBind
* @since 1.3
*/
public static DirStateFactory.Result
getStateToBind(Object obj, Name name, Context nameCtx,
Hashtable<?,?> environment, Attributes attrs)
throws NamingException {
// Get list of state factories
FactoryEnumeration factories = ResourceManager.getFactories(
Context.STATE_FACTORIES, environment, nameCtx);
if (factories == null) {
// no factories to try; just return originals
return new DirStateFactory.Result(obj, attrs);
}
// Try each factory until one succeeds
StateFactory factory;
Object objanswer;
DirStateFactory.Result answer = null;
while (answer == null && factories.hasMore()) {
factory = (StateFactory)factories.next();
if (factory instanceof DirStateFactory) {
answer = ((DirStateFactory)factory).
getStateToBind(obj, name, nameCtx, environment, attrs);
} else {
objanswer =
factory.getStateToBind(obj, name, nameCtx, environment);
if (objanswer != null) {
answer = new DirStateFactory.Result(objanswer, attrs);
}
}
}
return (answer != null) ? answer :
new DirStateFactory.Result(obj, attrs); // nothing new
}
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown when a context implementation does not support
* the operation being invoked.
* For example, if a server does not support the Context.bind() method
* it would throw OperationNotSupportedException when the bind() method
* is invoked on it.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class OperationNotSupportedException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of OperationNotSupportedException.
* All fields default to null.
*/
public OperationNotSupportedException() {
super();
}
/** {@collect.stats}
* Constructs a new instance of OperationNotSupportedException using an
* explanation. All other fields default to null.
*
* @param explanation Possibly null additional detail about this exception
* @see java.lang.Throwable#getMessage
*/
public OperationNotSupportedException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 5493232822427682064L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception indicates that the name being specified does
* not conform to the naming syntax of a naming system.
* This exception is thrown by any of the methods that does name
* parsing (such as those in Context, DirContext, CompositeName and CompoundName).
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see Context
* @see javax.naming.directory.DirContext
* @see CompositeName
* @see CompoundName
* @see NameParser
* @since 1.3
*/
public class InvalidNameException extends NamingException {
/** {@collect.stats}
* Constructs an instance of InvalidNameException using an
* explanation of the problem.
* All other fields are initialized to null.
* @param explanation A possibly null message explaining the problem.
* @see java.lang.Throwable#getMessage
*/
public InvalidNameException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs an instance of InvalidNameException with
* all fields set to null.
*/
public InvalidNameException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -8370672380823801105L;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming;
import java.util.Enumeration;
import java.util.Properties;
/** {@collect.stats}
* This class represents a compound name -- a name from
* a hierarchical name space.
* Each component in a compound name is an atomic name.
* <p>
* The components of a compound name are numbered. The indexes of a
* compound name with N components range from 0 up to, but not including, N.
* This range may be written as [0,N).
* The most significant component is at index 0.
* An empty compound name has no components.
*<p>
* <h4>Compound Name Syntax</h4>
* The syntax of a compound name is specified using a set of properties:
*<dl>
* <dt>jndi.syntax.direction
* <dd>Direction for parsing ("right_to_left", "left_to_right", "flat").
* If unspecified, defaults to "flat", which means the namespace is flat
* with no hierarchical structure.
*
* <dt>jndi.syntax.separator
* <dd>Separator between atomic name components.
* Required unless direction is "flat".
*
* <dt>jndi.syntax.ignorecase
* <dd>If present, "true" means ignore the case when comparing name
* components. If its value is not "true", or if the property is not
* present, case is considered when comparing name components.
*
* <dt>jndi.syntax.escape
* <dd>If present, specifies the escape string for overriding separator,
* escapes and quotes.
*
* <dt>jndi.syntax.beginquote
* <dd>If present, specifies the string delimiting start of a quoted string.
*
* <dt>jndi.syntax.endquote
* <dd>String delimiting end of quoted string.
* If present, specifies the string delimiting the end of a quoted string.
* If not present, use syntax.beginquote as end quote.
* <dt>jndi.syntax.beginquote2
* <dd>Alternative set of begin/end quotes.
*
* <dt>jndi.syntax.endquote2
* <dd>Alternative set of begin/end quotes.
*
* <dt>jndi.syntax.trimblanks
* <dd>If present, "true" means trim any leading and trailing whitespaces
* in a name component for comparison purposes. If its value is not
* "true", or if the property is not present, blanks are significant.
* <dt>jndi.syntax.separator.ava
* <dd>If present, specifies the string that separates
* attribute-value-assertions when specifying multiple attribute/value
* pairs. (e.g. "," in age=65,gender=male).
* <dt>jndi.syntax.separator.typeval
* <dd>If present, specifies the string that separators attribute
* from value (e.g. "=" in "age=65")
*</dl>
* These properties are interpreted according to the following rules:
*<ol>
*<li>
* In a string without quotes or escapes, any instance of the
* separator delimits two atomic names. Each atomic name is referred
* to as a <em>component</em>.
*<li>
* A separator, quote or escape is escaped if preceded immediately
* (on the left) by the escape.
*<li>
* If there are two sets of quotes, a specific begin-quote must be matched
* by its corresponding end-quote.
*<li>
* A non-escaped begin-quote which precedes a component must be
* matched by a non-escaped end-quote at the end of the component.
* A component thus quoted is referred to as a
* <em>quoted component</em>. It is parsed by
* removing the being- and end- quotes, and by treating the intervening
* characters as ordinary characters unless one of the rules involving
* quoted components listed below applies.
*<li>
* Quotes embedded in non-quoted components are treated as ordinary strings
* and need not be matched.
*<li>
* A separator that is escaped or appears between non-escaped
* quotes is treated as an ordinary string and not a separator.
*<li>
* An escape string within a quoted component acts as an escape only when
* followed by the corresponding end-quote string.
* This can be used to embed an escaped quote within a quoted component.
*<li>
* An escaped escape string is not treated as an escape string.
*<li>
* An escape string that does not precede a meta string (quotes or separator)
* and is not at the end of a component is treated as an ordinary string.
*<li>
* A leading separator (the compound name string begins with
* a separator) denotes a leading empty atomic component (consisting
* of an empty string).
* A trailing separator (the compound name string ends with
* a separator) denotes a trailing empty atomic component.
* Adjacent separators denote an empty atomic component.
*</ol>
* <p>
* The string form of the compound name follows the syntax described above.
* When the components of the compound name are turned into their
* string representation, the reserved syntax rules described above are
* applied (e.g. embedded separators are escaped or quoted)
* so that when the same string is parsed, it will yield the same components
* of the original compound name.
*<p>
*<h4>Multithreaded Access</h4>
* A <tt>CompoundName</tt> instance is not synchronized against concurrent
* multithreaded access. Multiple threads trying to access and modify a
* <tt>CompoundName</tt> should lock the object.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class CompoundName implements Name {
/** {@collect.stats}
* Implementation of this compound name.
* This field is initialized by the constructors and cannot be null.
* It should be treated as a read-only variable by subclasses.
*/
protected transient NameImpl impl;
/** {@collect.stats}
* Syntax properties for this compound name.
* This field is initialized by the constructors and cannot be null.
* It should be treated as a read-only variable by subclasses.
* Any necessary changes to mySyntax should be made within constructors
* and not after the compound name has been instantiated.
*/
protected transient Properties mySyntax;
/** {@collect.stats}
* Constructs a new compound name instance using the components
* specified in comps and syntax. This protected method is intended to be
* to be used by subclasses of CompoundName when they override
* methods such as clone(), getPrefix(), getSuffix().
*
* @param comps A non-null enumeration of the components to add.
* Each element of the enumeration is of class String.
* The enumeration will be consumed to extract its
* elements.
* @param syntax A non-null properties that specify the syntax of
* this compound name. See class description for
* contents of properties.
*/
protected CompoundName(Enumeration<String> comps, Properties syntax) {
if (syntax == null) {
throw new NullPointerException();
}
mySyntax = syntax;
impl = new NameImpl(syntax, comps);
}
/** {@collect.stats}
* Constructs a new compound name instance by parsing the string n
* using the syntax specified by the syntax properties supplied.
*
* @param n The non-null string to parse.
* @param syntax A non-null list of properties that specify the syntax of
* this compound name. See class description for
* contents of properties.
* @exception InvalidNameException If 'n' violates the syntax specified
* by <code>syntax</code>.
*/
public CompoundName(String n, Properties syntax) throws InvalidNameException {
if (syntax == null) {
throw new NullPointerException();
}
mySyntax = syntax;
impl = new NameImpl(syntax, n);
}
/** {@collect.stats}
* Generates the string representation of this compound name, using
* the syntax rules of the compound name. The syntax rules
* are described in the class description.
* An empty component is represented by an empty string.
*
* The string representation thus generated can be passed to
* the CompoundName constructor with the same syntax properties
* to create a new equivalent compound name.
*
* @return A non-null string representation of this compound name.
*/
public String toString() {
return (impl.toString());
}
/** {@collect.stats}
* Determines whether obj is syntactically equal to this compound name.
* If obj is null or not a CompoundName, false is returned.
* Two compound names are equal if each component in one is "equal"
* to the corresponding component in the other.
*<p>
* Equality is also defined in terms of the syntax of this compound name.
* The default implementation of CompoundName uses the syntax properties
* jndi.syntax.ignorecase and jndi.syntax.trimblanks when comparing
* two components for equality. If case is ignored, two strings
* with the same sequence of characters but with different cases
* are considered equal. If blanks are being trimmed, leading and trailing
* blanks are ignored for the purpose of the comparison.
*<p>
* Both compound names must have the same number of components.
*<p>
* Implementation note: Currently the syntax properties of the two compound
* names are not compared for equality. They might be in the future.
*
* @param obj The possibly null object to compare against.
* @return true if obj is equal to this compound name, false otherwise.
* @see #compareTo(java.lang.Object obj)
*/
public boolean equals(Object obj) {
// %%% check syntax too?
return (obj != null &&
obj instanceof CompoundName &&
impl.equals(((CompoundName)obj).impl));
}
/** {@collect.stats}
* Computes the hash code of this compound name.
* The hash code is the sum of the hash codes of the "canonicalized"
* forms of individual components of this compound name.
* Each component is "canonicalized" according to the
* compound name's syntax before its hash code is computed.
* For a case-insensitive name, for example, the uppercased form of
* a name has the same hash code as its lowercased equivalent.
*
* @return An int representing the hash code of this name.
*/
public int hashCode() {
return impl.hashCode();
}
/** {@collect.stats}
* Creates a copy of this compound name.
* Changes to the components of this compound name won't
* affect the new copy and vice versa.
* The clone and this compound name share the same syntax.
*
* @return A non-null copy of this compound name.
*/
public Object clone() {
return (new CompoundName(getAll(), mySyntax));
}
/** {@collect.stats}
* Compares this CompoundName with the specified Object for order.
* Returns a
* negative integer, zero, or a positive integer as this Name is less
* than, equal to, or greater than the given Object.
* <p>
* If obj is null or not an instance of CompoundName, ClassCastException
* is thrown.
* <p>
* See equals() for what it means for two compound names to be equal.
* If two compound names are equal, 0 is returned.
*<p>
* Ordering of compound names depend on the syntax of the compound name.
* By default, they follow lexicographical rules for string comparison
* with the extension that this applies to all the components in the
* compound name and that comparison of individual components is
* affected by the jndi.syntax.ignorecase and jndi.syntax.trimblanks
* properties, identical to how they affect equals().
* If this compound name is "lexicographically" lesser than obj,
* a negative number is returned.
* If this compound name is "lexicographically" greater than obj,
* a positive number is returned.
*<p>
* Implementation note: Currently the syntax properties of the two compound
* names are not compared when checking order. They might be in the future.
* @param obj The non-null object to compare against.
* @return a negative integer, zero, or a positive integer as this Name
* is less than, equal to, or greater than the given Object.
* @exception ClassCastException if obj is not a CompoundName.
* @see #equals(java.lang.Object)
*/
public int compareTo(Object obj) {
if (!(obj instanceof CompoundName)) {
throw new ClassCastException("Not a CompoundName");
}
return impl.compareTo(((CompoundName)obj).impl);
}
/** {@collect.stats}
* Retrieves the number of components in this compound name.
*
* @return The nonnegative number of components in this compound name.
*/
public int size() {
return (impl.size());
}
/** {@collect.stats}
* Determines whether this compound name is empty.
* A compound name is empty if it has zero components.
*
* @return true if this compound name is empty, false otherwise.
*/
public boolean isEmpty() {
return (impl.isEmpty());
}
/** {@collect.stats}
* Retrieves the components of this compound name as an enumeration
* of strings.
* The effects of updates to this compound name on this enumeration
* is undefined.
*
* @return A non-null enumeration of the components of this
* compound name. Each element of the enumeration is of class String.
*/
public Enumeration<String> getAll() {
return (impl.getAll());
}
/** {@collect.stats}
* Retrieves a component of this compound name.
*
* @param posn The 0-based index of the component to retrieve.
* Must be in the range [0,size()).
* @return The component at index posn.
* @exception ArrayIndexOutOfBoundsException if posn is outside the
* specified range.
*/
public String get(int posn) {
return (impl.get(posn));
}
/** {@collect.stats}
* Creates a compound name whose components consist of a prefix of the
* components in this compound name.
* The result and this compound name share the same syntax.
* Subsequent changes to
* this compound name does not affect the name that is returned and
* vice versa.
*
* @param posn The 0-based index of the component at which to stop.
* Must be in the range [0,size()].
* @return A compound name consisting of the components at indexes in
* the range [0,posn).
* @exception ArrayIndexOutOfBoundsException
* If posn is outside the specified range.
*/
public Name getPrefix(int posn) {
Enumeration comps = impl.getPrefix(posn);
return (new CompoundName(comps, mySyntax));
}
/** {@collect.stats}
* Creates a compound name whose components consist of a suffix of the
* components in this compound name.
* The result and this compound name share the same syntax.
* Subsequent changes to
* this compound name does not affect the name that is returned.
*
* @param posn The 0-based index of the component at which to start.
* Must be in the range [0,size()].
* @return A compound name consisting of the components at indexes in
* the range [posn,size()). If posn is equal to
* size(), an empty compound name is returned.
* @exception ArrayIndexOutOfBoundsException
* If posn is outside the specified range.
*/
public Name getSuffix(int posn) {
Enumeration comps = impl.getSuffix(posn);
return (new CompoundName(comps, mySyntax));
}
/** {@collect.stats}
* Determines whether a compound name is a prefix of this compound name.
* A compound name 'n' is a prefix if it is equal to
* getPrefix(n.size())--in other words, this compound name
* starts with 'n'.
* If n is null or not a compound name, false is returned.
*<p>
* Implementation note: Currently the syntax properties of n
* are not used when doing the comparison. They might be in the future.
* @param n The possibly null compound name to check.
* @return true if n is a CompoundName and
* is a prefix of this compound name, false otherwise.
*/
public boolean startsWith(Name n) {
if (n instanceof CompoundName) {
return (impl.startsWith(n.size(), n.getAll()));
} else {
return false;
}
}
/** {@collect.stats}
* Determines whether a compound name is a suffix of this compound name.
* A compound name 'n' is a suffix if it it is equal to
* getSuffix(size()-n.size())--in other words, this
* compound name ends with 'n'.
* If n is null or not a compound name, false is returned.
*<p>
* Implementation note: Currently the syntax properties of n
* are not used when doing the comparison. They might be in the future.
* @param n The possibly null compound name to check.
* @return true if n is a CompoundName and
* is a suffix of this compound name, false otherwise.
*/
public boolean endsWith(Name n) {
if (n instanceof CompoundName) {
return (impl.endsWith(n.size(), n.getAll()));
} else {
return false;
}
}
/** {@collect.stats}
* Adds the components of a compound name -- in order -- to the end of
* this compound name.
*<p>
* Implementation note: Currently the syntax properties of suffix
* is not used or checked. They might be in the future.
* @param suffix The non-null components to add.
* @return The updated CompoundName, not a new one. Cannot be null.
* @exception InvalidNameException If suffix is not a compound name,
* or if the addition of the components violates the syntax
* of this compound name (e.g. exceeding number of components).
*/
public Name addAll(Name suffix) throws InvalidNameException {
if (suffix instanceof CompoundName) {
impl.addAll(suffix.getAll());
return this;
} else {
throw new InvalidNameException("Not a compound name: " +
suffix.toString());
}
}
/** {@collect.stats}
* Adds the components of a compound name -- in order -- at a specified
* position within this compound name.
* Components of this compound name at or after the index of the first
* new component are shifted up (away from index 0)
* to accommodate the new components.
*<p>
* Implementation note: Currently the syntax properties of suffix
* is not used or checked. They might be in the future.
*
* @param n The non-null components to add.
* @param posn The index in this name at which to add the new
* components. Must be in the range [0,size()].
* @return The updated CompoundName, not a new one. Cannot be null.
* @exception ArrayIndexOutOfBoundsException
* If posn is outside the specified range.
* @exception InvalidNameException If n is not a compound name,
* or if the addition of the components violates the syntax
* of this compound name (e.g. exceeding number of components).
*/
public Name addAll(int posn, Name n) throws InvalidNameException {
if (n instanceof CompoundName) {
impl.addAll(posn, n.getAll());
return this;
} else {
throw new InvalidNameException("Not a compound name: " +
n.toString());
}
}
/** {@collect.stats}
* Adds a single component to the end of this compound name.
*
* @param comp The non-null component to add.
* @return The updated CompoundName, not a new one. Cannot be null.
* @exception InvalidNameException If adding comp at end of the name
* would violate the compound name's syntax.
*/
public Name add(String comp) throws InvalidNameException{
impl.add(comp);
return this;
}
/** {@collect.stats}
* Adds a single component at a specified position within this
* compound name.
* Components of this compound name at or after the index of the new
* component are shifted up by one (away from index 0)
* to accommodate the new component.
*
* @param comp The non-null component to add.
* @param posn The index at which to add the new component.
* Must be in the range [0,size()].
* @exception ArrayIndexOutOfBoundsException
* If posn is outside the specified range.
* @return The updated CompoundName, not a new one. Cannot be null.
* @exception InvalidNameException If adding comp at the specified position
* would violate the compound name's syntax.
*/
public Name add(int posn, String comp) throws InvalidNameException{
impl.add(posn, comp);
return this;
}
/** {@collect.stats}
* Deletes a component from this compound name.
* The component of this compound name at position 'posn' is removed,
* and components at indices greater than 'posn'
* are shifted down (towards index 0) by one.
*
* @param posn The index of the component to delete.
* Must be in the range [0,size()).
* @return The component removed (a String).
* @exception ArrayIndexOutOfBoundsException
* If posn is outside the specified range (includes case where
* compound name is empty).
* @exception InvalidNameException If deleting the component
* would violate the compound name's syntax.
*/
public Object remove(int posn) throws InvalidNameException {
return impl.remove(posn);
}
/** {@collect.stats}
* Overridden to avoid implementation dependency.
* @serialData The syntax <tt>Properties</tt>, followed by
* the number of components (an <tt>int</tt>), and the individual
* components (each a <tt>String</tt>).
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
s.writeObject(mySyntax);
s.writeInt(size());
Enumeration comps = getAll();
while (comps.hasMoreElements()) {
s.writeObject(comps.nextElement());
}
}
/** {@collect.stats}
* Overridden to avoid implementation dependency.
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
mySyntax = (Properties)s.readObject();
impl = new NameImpl(mySyntax);
int n = s.readInt(); // number of components
try {
while (--n >= 0) {
add((String)s.readObject());
}
} catch (InvalidNameException e) {
throw (new java.io.StreamCorruptedException("Invalid name"));
}
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 3513100557083972036L;
/*
// For testing
public static void main(String[] args) {
Properties dotSyntax = new Properties();
dotSyntax.put("jndi.syntax.direction", "right_to_left");
dotSyntax.put("jndi.syntax.separator", ".");
dotSyntax.put("jndi.syntax.ignorecase", "true");
dotSyntax.put("jndi.syntax.escape", "\\");
// dotSyntax.put("jndi.syntax.beginquote", "\"");
// dotSyntax.put("jndi.syntax.beginquote2", "'");
Name first = null;
try {
for (int i = 0; i < args.length; i++) {
Name name;
Enumeration e;
System.out.println("Given name: " + args[i]);
name = new CompoundName(args[i], dotSyntax);
if (first == null) {
first = name;
}
e = name.getComponents();
while (e.hasMoreElements()) {
System.out.println("Element: " + e.nextElement());
}
System.out.println("Constructed name: " + name.toString());
System.out.println("Compare " + first.toString() + " with "
+ name.toString() + " = " + first.compareTo(name));
}
} catch (Exception ne) {
ne.printStackTrace();
}
}
*/
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown when there is a configuration problem.
* This can arise when installation of a provider was
* not done correctly, or if there are configuration problems with the
* server, or if configuration information required to access
* the provider or service is malformed or missing.
* For example, a request to use SSL as the security protocol when
* the service provider software was not configured with the SSL
* component would cause such an exception. Another example is
* if the provider requires that a URL be specified as one of the
* environment properties but the client failed to provide it.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class ConfigurationException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of ConfigurationException using an
* explanation. All other fields default to null.
*
* @param explanation A possibly null string containing
* additional detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public ConfigurationException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of ConfigurationException with
* all name resolution fields and explanation initialized to null.
*/
public ConfigurationException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -2535156726228855704L;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming;
/** {@collect.stats}
* This exception is thrown when attempting to communicate with a
* directory or naming service and that service is not available.
* It might be unavailable for different reasons. For example,
* the server might be too busy to service the request, or the server
* might not be registered to service any requests, etc.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @since 1.3
*/
public class ServiceUnavailableException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of ServiceUnavailableException using an
* explanation. All other fields default to null.
*
* @param explanation Possibly null additional detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public ServiceUnavailableException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of ServiceUnavailableException.
* All fields default to null.
*/
public ServiceUnavailableException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -4996964726566773444L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown when
* a loop was detected will attempting to resolve a link, or an implementation
* specific limit on link counts has been reached.
* <p>
* Synchronization and serialization issues that apply to LinkException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see LinkRef
* @since 1.3
*/
public class LinkLoopException extends LinkException {
/** {@collect.stats}
* Constructs a new instance of LinkLoopException with an explanation
* All the other fields are initialized to null.
* @param explanation A possibly null string containing additional
* detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public LinkLoopException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of LinkLoopException.
* All the non-link-related and link-related fields are initialized to null.
*/
public LinkLoopException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -3119189944325198009L;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming;
import java.util.Enumeration;
/** {@collect.stats}
* This interface is for enumerating lists returned by
* methods in the javax.naming and javax.naming.directory packages.
* It extends Enumeration to allow as exceptions to be thrown during
* the enumeration.
*<p>
* When a method such as list(), listBindings(), or search() returns
* a NamingEnumeration, any exceptions encountered are reserved until
* all results have been returned. At the end of the enumeration, the
* exception is thrown (by hasMore());
* <p>
* For example, if the list() is
* returning only a partial answer, the corresponding exception would
* be PartialResultException. list() would first return a NamingEnumeration.
* When the last of the results has been returned by the NamingEnumeration's
* next(), invoking hasMore() would result in PartialResultException being thrown.
*<p>
* In another example, if a search() method was invoked with a specified
* size limit of 'n'. If the answer consists of more than 'n' results,
* search() would first return a NamingEnumeration.
* When the n'th result has been returned by invoking next() on the
* NamingEnumeration, a SizeLimitExceedException would then thrown when
* hasMore() is invoked.
*<p>
* Note that if the program uses hasMoreElements() and nextElement() instead
* to iterate through the NamingEnumeration, because these methods
* cannot throw exceptions, no exception will be thrown. Instead,
* in the previous example, after the n'th result has been returned by
* nextElement(), invoking hasMoreElements() would return false.
*<p>
* Note also that NoSuchElementException is thrown if the program invokes
* next() or nextElement() when there are no elements left in the enumeration.
* The program can always avoid this exception by using hasMore() and
* hasMoreElements() to check whether the end of the enumeration has been reached.
*<p>
* If an exception is thrown during an enumeration,
* the enumeration becomes invalid.
* Subsequent invocation of any method on that enumeration
* will yield undefined results.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see Context#list
* @see Context#listBindings
* @see javax.naming.directory.DirContext#search
* @see javax.naming.directory.Attributes#getAll
* @see javax.naming.directory.Attributes#getIDs
* @see javax.naming.directory.Attribute#getAll
* @since 1.3
*/
public interface NamingEnumeration<T> extends Enumeration<T> {
/** {@collect.stats}
* Retrieves the next element in the enumeration.
* This method allows naming exceptions encountered while
* retrieving the next element to be caught and handled
* by the application.
* <p>
* Note that <tt>next()</tt> can also throw the runtime exception
* NoSuchElementException to indicate that the caller is
* attempting to enumerate beyond the end of the enumeration.
* This is different from a NamingException, which indicates
* that there was a problem in obtaining the next element,
* for example, due to a referral or server unavailability, etc.
*
* @return The possibly null element in the enumeration.
* null is only valid for enumerations that can return
* null (e.g. Attribute.getAll() returns an enumeration of
* attribute values, and an attribute value can be null).
* @exception NamingException If a naming exception is encountered while attempting
* to retrieve the next element. See NamingException
* and its subclasses for the possible naming exceptions.
* @exception java.util.NoSuchElementException If attempting to get the next element when none is available.
* @see java.util.Enumeration#nextElement
*/
public T next() throws NamingException;
/** {@collect.stats}
* Determines whether there are any more elements in the enumeration.
* This method allows naming exceptions encountered while
* determining whether there are more elements to be caught and handled
* by the application.
*
* @return true if there is more in the enumeration ; false otherwise.
* @exception NamingException
* If a naming exception is encountered while attempting
* to determine whether there is another element
* in the enumeration. See NamingException
* and its subclasses for the possible naming exceptions.
* @see java.util.Enumeration#hasMoreElements
*/
public boolean hasMore() throws NamingException;
/** {@collect.stats}
* Closes this enumeration.
*
* After this method has been invoked on this enumeration, the
* enumeration becomes invalid and subsequent invocation of any of
* its methods will yield undefined results.
* This method is intended for aborting an enumeration to free up resources.
* If an enumeration proceeds to the end--that is, until
* <tt>hasMoreElements()</tt> or <tt>hasMore()</tt> returns <tt>false</tt>--
* resources will be freed up automatically and there is no need to
* explicitly call <tt>close()</tt>.
*<p>
* This method indicates to the service provider that it is free
* to release resources associated with the enumeration, and can
* notify servers to cancel any outstanding requests. The <tt>close()</tt>
* method is a hint to implementations for managing their resources.
* Implementations are encouraged to use appropriate algorithms to
* manage their resources when client omits the <tt>close()</tt> calls.
*
* @exception NamingException If a naming exception is encountered
* while closing the enumeration.
* @since 1.3
*/
public void close() throws NamingException;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown when the client is
* unable to communicate with the directory or naming service.
* The inability to communicate with the service might be a result
* of many factors, such as network partitioning, hardware or interface problems,
* failures on either the client or server side.
* This exception is meant to be used to capture such communication problems.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class CommunicationException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of CommunicationException using the
* arguments supplied.
*
* @param explanation Additional detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public CommunicationException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of CommunicationException.
*/
public CommunicationException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 3618507780299986611L;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming;
/** {@collect.stats}
* This interface is used for parsing names from a hierarchical
* namespace. The NameParser contains knowledge of the syntactic
* information (like left-to-right orientation, name separator, etc.)
* needed to parse names.
*
* The equals() method, when used to compare two NameParsers, returns
* true if and only if they serve the same namespace.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see CompoundName
* @see Name
* @since 1.3
*/
public interface NameParser {
/** {@collect.stats}
* Parses a name into its components.
*
* @param name The non-null string name to parse.
* @return A non-null parsed form of the name using the naming convention
* of this parser.
* @exception InvalidNameException If name does not conform to
* syntax defined for the namespace.
* @exception NamingException If a naming exception was encountered.
*/
Name parse(String name) throws NamingException;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming;
/** {@collect.stats}
* This is the superclass of security-related exceptions
* thrown by operations in the Context and DirContext interfaces.
* The nature of the failure is described by the name of the subclass.
*<p>
* If the program wants to handle this exception in particular, it
* should catch NamingSecurityException explicitly before attempting to
* catch NamingException. A program might want to do this, for example,
* if it wants to treat security-related exceptions specially from
* other sorts of naming exception.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public abstract class NamingSecurityException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of NamingSecurityException using the
* explanation supplied. All other fields default to null.
*
* @param explanation Possibly null additional detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public NamingSecurityException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of NamingSecurityException.
* All fields are initialized to null.
*/
public NamingSecurityException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 5855287647294685775L;
};
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.ldap;
/** {@collect.stats}
* This interface represents an LDAP extended operation response as defined in
* <A HREF="ftp://ftp.isi.edu/in-notes/rfc2251.txt">RFC 2251</A>.
* <pre>
* ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
* COMPONENTS OF LDAPResult,
* responseName [10] LDAPOID OPTIONAL,
* response [11] OCTET STRING OPTIONAL }
* </pre>
* It comprises an optional object identifier and an optional ASN.1 BER
* encoded value.
*
*<p>
* The methods in this class can be used by the application to get low
* level information about the extended operation response. However, typically,
* the application will be using methods specific to the class that
* implements this interface. Such a class should have decoded the BER buffer
* in the response and should provide methods that allow the user to
* access that data in the response in a type-safe and friendly manner.
*<p>
* For example, suppose the LDAP server supported a 'get time' extended operation.
* It would supply GetTimeRequest and GetTimeResponse classes.
* The GetTimeResponse class might look like:
*<blockquote><pre>
* public class GetTimeResponse implements ExtendedResponse {
* public java.util.Date getDate() {...};
* public long getTime() {...};
* ....
* }
*</pre></blockquote>
* A program would use then these classes as follows:
*<blockquote><pre>
* GetTimeResponse resp =
* (GetTimeResponse) ectx.extendedOperation(new GetTimeRequest());
* java.util.Date now = resp.getDate();
*</pre></blockquote>
*
* @author Rosanna Lee
* @author Scott Seligman
* @author Vincent Ryan
*
* @see ExtendedRequest
* @since 1.3
*/
public interface ExtendedResponse extends java.io.Serializable {
/** {@collect.stats}
* Retrieves the object identifier of the response.
* The LDAP protocol specifies that the response object identifier is optional.
* If the server does not send it, the response will contain no ID (i.e. null).
*
* @return A possibly null object identifier string representing the LDAP
* <tt>ExtendedResponse.responseName</tt> component.
*/
public String getID();
/** {@collect.stats}
* Retrieves the ASN.1 BER encoded value of the LDAP extended operation
* response. Null is returned if the value is absent from the response
* sent by the LDAP server.
* The result is the raw BER bytes including the tag and length of
* the response value. It does not include the response OID.
*
* @return A possibly null byte array representing the ASN.1 BER encoded
* contents of the LDAP <tt>ExtendedResponse.response</tt>
* component.
*/
public byte[] getEncodedValue();
//static final long serialVersionUID = -3320509678029180273L;
}
|
Java
|
/*
* Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.ldap;
import javax.naming.NamingException;
/** {@collect.stats}
* This interface represents an LDAPv3 extended operation request as defined in
* <A HREF="ftp://ftp.isi.edu/in-notes/rfc2251.txt">RFC 2251</A>.
* <pre>
* ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
* requestName [0] LDAPOID,
* requestValue [1] OCTET STRING OPTIONAL }
* </pre>
* It comprises an object identifier string and an optional ASN.1 BER
* encoded value.
*<p>
* The methods in this class are used by the service provider to construct
* the bits to send to the LDAP server. Applications typically only deal with
* the classes that implement this interface, supplying them with
* any information required for a particular extended operation request.
* It would then pass such a class as an argument to the
* <tt>LdapContext.extendedOperation()</tt> method for performing the
* LDAPv3 extended operation.
*<p>
* For example, suppose the LDAP server supported a 'get time' extended operation.
* It would supply GetTimeRequest and GetTimeResponse classes:
*<blockquote><pre>
* public class GetTimeRequest implements ExtendedRequest {
* public GetTimeRequest() {... };
* public ExtendedResponse createExtendedResponse(String id,
* byte[] berValue, int offset, int length)
* throws NamingException {
* return new GetTimeResponse(id, berValue, offset, length);
* }
* ...
* }
* public class GetTimeResponse implements ExtendedResponse {
* long time;
* public GetTimeResponse(String id, byte[] berValue, int offset,
* int length) throws NamingException {
* time = ... // decode berValue to get time
* }
* public java.util.Date getDate() { return new java.util.Date(time) };
* public long getTime() { return time };
* ...
* }
*</pre></blockquote>
* A program would use then these classes as follows:
*<blockquote><pre>
* GetTimeResponse resp =
* (GetTimeResponse) ectx.extendedOperation(new GetTimeRequest());
* long time = resp.getTime();
*</pre></blockquote>
*
* @author Rosanna Lee
* @author Scott Seligman
* @author Vincent Ryan
*
* @see ExtendedResponse
* @see LdapContext#extendedOperation
* @since 1.3
*/
public interface ExtendedRequest extends java.io.Serializable {
/** {@collect.stats}
* Retrieves the object identifier of the request.
*
* @return The non-null object identifier string representing the LDAP
* <tt>ExtendedRequest.requestName</tt> component.
*/
public String getID();
/** {@collect.stats}
* Retrieves the ASN.1 BER encoded value of the LDAP extended operation
* request. Null is returned if the value is absent.
*
* The result is the raw BER bytes including the tag and length of
* the request value. It does not include the request OID.
* This method is called by the service provider to get the bits to
* put into the extended operation to be sent to the LDAP server.
*
* @return A possibly null byte array representing the ASN.1 BER encoded
* contents of the LDAP <tt>ExtendedRequest.requestValue</tt>
* component.
* @exception IllegalStateException If the encoded value cannot be retrieved
* because the request contains insufficient or invalid data/state.
*/
public byte[] getEncodedValue();
/** {@collect.stats}
* Creates the response object that corresponds to this request.
*<p>
* After the service provider has sent the extended operation request
* to the LDAP server, it will receive a response from the server.
* If the operation failed, the provider will throw a NamingException.
* If the operation succeeded, the provider will invoke this method
* using the data that it got back in the response.
* It is the job of this method to return a class that implements
* the ExtendedResponse interface that is appropriate for the
* extended operation request.
*<p>
* For example, a Start TLS extended request class would need to know
* how to process a Start TLS extended response. It does this by creating
* a class that implements ExtendedResponse.
*
* @param id The possibly null object identifier of the response
* control.
* @param berValue The possibly null ASN.1 BER encoded value of the
* response control.
* This is the raw BER bytes including the tag and length of
* the response value. It does not include the response OID.
* @param offset The starting position in berValue of the bytes to use.
* @param length The number of bytes in berValue to use.
*
* @return A non-null object.
* @exception NamingException if cannot create extended response
* due to an error.
* @see ExtendedResponse
*/
public ExtendedResponse createExtendedResponse(String id,
byte[] berValue, int offset, int length) throws NamingException;
// static final long serialVersionUID = -7560110759229059814L;
}
|
Java
|
/*
* Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.ldap;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import java.util.Hashtable;
/** {@collect.stats}
* This interface represents a context in which you can perform
* operations with LDAPv3-style controls and perform LDAPv3-style
* extended operations.
*
* For applications that do not require such controls or extended
* operations, the more generic <tt>javax.naming.directory.DirContext</tt>
* should be used instead.
*
* <h3>Usage Details About Controls</h3>
*
* This interface provides support for LDAP v3 controls.
* At a high level, this support allows a user
* program to set request controls for LDAP operations that are executed
* in the course of the user program's invocation of
* <tt>Context</tt>/<tt>DirContext</tt>
* methods, and read response controls resulting from LDAP operations.
* At the implementation level, there are some details that developers of
* both the user program and service providers need to understand in order
* to correctly use request and response controls.
*
* <h3>Request Controls</h3>
* <p>
* There are two types of request controls:
* <ul>
* <li>Request controls that affect how a connection is created
* <li>Request controls that affect context methods
* </ul>
*
* The former is used whenever a connection needs to be established or
* re-established with an LDAP server. The latter is used when all other
* LDAP operations are sent to the LDAP server. The reason why a
* distinction between these two types of request controls is necessary
* is because JNDI is a high-level API that does not deal directly with
* connections. It is the job of service providers to do any necessary
* connection management. Consequently, a single
* connection may be shared by multiple context instances, and a service provider
* is free to use its own algorithms to conserve connection and network
* usage. Thus, when a method is invoked on the context instance, the service
* provider might need to do some connection management in addition to
* performing the corresponding LDAP operations. For connection management,
* it uses the <em>connection request controls</em>, while for the normal
* LDAP operations, it uses the <em>context request controls</em>.
*<p>Unless explicitly qualified, the term "request controls" refers to
* context request controls.
*
* <h4>Context Request Controls</h4>
* There are two ways in which a context instance gets its request controls:
* <ol>
* <tt>
* <li>ldapContext.newInstance(<strong>reqCtls</strong>)
* <li>ldapContext.setRequestControls(<strong>reqCtls</strong>)
* </tt>
* </ol>
* where <tt>ldapContext</tt> is an instance of <tt>LdapContext</tt>.
* Specifying <tt>null</tt> or an empty array for <tt>reqCtls</tt>
* means no request controls.
* <tt>newInstance()</tt> creates a new instance of a context using
* <tt>reqCtls</tt>, while <tt>setRequestControls()</tt>
* updates an existing context instance's request controls to <tt>reqCtls</tt>.
* <p>
* Unlike environment properties, request controls of a context instance
* <em>are not inherited</em> by context instances that are derived from
* it. Derived context instances have <tt>null</tt> as their context
* request controls. You must set the request controls of a derived context
* instance explicitly using <tt>setRequestControls()</tt>.
* <p>
* A context instance's request controls are retrieved using
* the method <tt>getRequestControls()</tt>.
*
* <h4>Connection Request Controls</h4>
* There are three ways in which connection request controls are set:
* <ol>
* <tt>
* <li>
* new InitialLdapContext(env, <strong>connCtls</strong>)
* <li>refException.getReferralContext(env, <strong>connCtls</strong>)
* <li>ldapContext.reconnect(<strong>connCtls</strong>);
* </tt>
* </ol>
* where <tt>refException</tt> is an instance of
* <tt>LdapReferralException</tt>, and <tt>ldapContext</tt> is an
* instance of <tt>LdapContext</tt>.
* Specifying <tt>null</tt> or an empty array for <tt>connCtls</tt>
* means no connection request controls.
* <p>
* Like environment properties, connection request controls of a context
* <em>are inherited</em> by contexts that are derived from it.
* Typically, you initialize the connection request controls using the
* <tt>InitialLdapContext</tt> constructor or
* <tt>LdapReferralContext.getReferralContext()</tt>. These connection
* request controls are inherited by contexts that share the same
* connection--that is, contexts derived from the initial or referral
* contexts.
* <p>
* Use <tt>reconnect()</tt> to change the connection request controls of
* a context.
* Invoking <tt>ldapContext.reconnect()</tt> affects only the
* connection used by <tt>ldapContext</tt> and any new contexts instances that are
* derived form <tt>ldapContext</tt>. Contexts that previously shared the
* connection with <tt>ldapContext</tt> remain unchanged. That is, a context's
* connection request controls must be explicitly changed and is not
* affected by changes to another context's connection request
* controls.
* <p>
* A context instance's connection request controls are retrieved using
* the method <tt>getConnectControls()</tt>.
*
* <h4>Service Provider Requirements</h4>
*
* A service provider supports connection and context request controls
* in the following ways. Context request controls must be associated on
* a per context instance basis while connection request controls must be
* associated on a per connection instance basis. The service provider
* must look for the connection request controls in the environment
* property "java.naming.ldap.control.connect" and pass this environment
* property on to context instances that it creates.
*
* <h3>Response Controls</h3>
*
* The method <tt>LdapContext.getResponseControls()</tt> is used to
* retrieve the response controls generated by LDAP operations executed
* as the result of invoking a <tt>Context</tt>/<tt>DirContext</tt>
* operation. The result is all of the responses controls generated
* by the underlying LDAP operations, including any implicit reconnection.
* To get only the reconnection response controls,
* use <tt>reconnect()</tt> followed by <tt>getResponseControls()</tt>.
*
* <h3>Parameters</h3>
*
* A <tt>Control[]</tt> array
* passed as a parameter to any method is owned by the caller.
* The service provider will not modify the array or keep a reference to it,
* although it may keep references to the individual <tt>Control</tt> objects
* in the array.
* A <tt>Control[]</tt> array returned by any method is immutable, and may
* not subsequently be modified by either the caller or the service provider.
*
* @author Rosanna Lee
* @author Scott Seligman
* @author Vincent Ryan
*
* @see InitialLdapContext
* @see LdapReferralException#getReferralContext(java.util.Hashtable,javax.naming.ldap.Control[])
* @since 1.3
*/
public interface LdapContext extends DirContext {
/** {@collect.stats}
* Performs an extended operation.
*
* This method is used to support LDAPv3 extended operations.
* @param request The non-null request to be performed.
* @return The possibly null response of the operation. null means
* the operation did not generate any response.
* @throws NamingException If an error occurred while performing the
* extended operation.
*/
public ExtendedResponse extendedOperation(ExtendedRequest request)
throws NamingException;
/** {@collect.stats}
* Creates a new instance of this context initialized using request controls.
*
* This method is a convenience method for creating a new instance
* of this context for the purposes of multithreaded access.
* For example, if multiple threads want to use different context
* request controls,
* each thread may use this method to get its own copy of this context
* and set/get context request controls without having to synchronize with other
* threads.
*<p>
* The new context has the same environment properties and connection
* request controls as this context. See the class description for details.
* Implementations might also allow this context and the new context
* to share the same network connection or other resources if doing
* so does not impede the independence of either context.
*
* @param requestControls The possibly null request controls
* to use for the new context.
* If null, the context is initialized with no request controls.
*
* @return A non-null <tt>LdapContext</tt> instance.
* @exception NamingException If an error occurred while creating
* the new instance.
* @see InitialLdapContext
*/
public LdapContext newInstance(Control[] requestControls)
throws NamingException;
/** {@collect.stats}
* Reconnects to the LDAP server using the supplied controls and
* this context's environment.
*<p>
* This method is a way to explicitly initiate an LDAP "bind" operation.
* For example, you can use this method to set request controls for
* the LDAP "bind" operation, or to explicitly connect to the server
* to get response controls returned by the LDAP "bind" operation.
*<p>
* This method sets this context's <tt>connCtls</tt>
* to be its new connection request controls. This context's
* context request controls are not affected.
* After this method has been invoked, any subsequent
* implicit reconnections will be done using <tt>connCtls</tt>.
* <tt>connCtls</tt> are also used as
* connection request controls for new context instances derived from this
* context.
* These connection request controls are not
* affected by <tt>setRequestControls()</tt>.
*<p>
* Service provider implementors should read the "Service Provider" section
* in the class description for implementation details.
* @param connCtls The possibly null controls to use. If null, no
* controls are used.
* @exception NamingException If an error occurred while reconnecting.
* @see #getConnectControls
* @see #newInstance
*/
public void reconnect(Control[] connCtls) throws NamingException;
/** {@collect.stats}
* Retrieves the connection request controls in effect for this context.
* The controls are owned by the JNDI implementation and are
* immutable. Neither the array nor the controls may be modified by the
* caller.
*
* @return A possibly-null array of controls. null means no connect controls
* have been set for this context.
* @exception NamingException If an error occurred while getting the request
* controls.
*/
public Control[] getConnectControls() throws NamingException;
/** {@collect.stats}
* Sets the request controls for methods subsequently
* invoked on this context.
* The request controls are owned by the JNDI implementation and are
* immutable. Neither the array nor the controls may be modified by the
* caller.
* <p>
* This removes any previous request controls and adds
* <tt>requestControls</tt>
* for use by subsequent methods invoked on this context.
* This method does not affect this context's connection request controls.
*<p>
* Note that <tt>requestControls</tt> will be in effect until the next
* invocation of <tt>setRequestControls()</tt>. You need to explicitly
* invoke <tt>setRequestControls()</tt> with <tt>null</tt> or an empty
* array to clear the controls if you don't want them to affect the
* context methods any more.
* To check what request controls are in effect for this context, use
* <tt>getRequestControls()</tt>.
* @param requestControls The possibly null controls to use. If null, no
* controls are used.
* @exception NamingException If an error occurred while setting the
* request controls.
* @see #getRequestControls
*/
public void setRequestControls(Control[] requestControls)
throws NamingException;
/** {@collect.stats}
* Retrieves the request controls in effect for this context.
* The request controls are owned by the JNDI implementation and are
* immutable. Neither the array nor the controls may be modified by the
* caller.
*
* @return A possibly-null array of controls. null means no request controls
* have been set for this context.
* @exception NamingException If an error occurred while getting the request
* controls.
* @see #setRequestControls
*/
public Control[] getRequestControls() throws NamingException;
/** {@collect.stats}
* Retrieves the response controls produced as a result of the last
* method invoked on this context.
* The response controls are owned by the JNDI implementation and are
* immutable. Neither the array nor the controls may be modified by the
* caller.
*<p>
* These response controls might have been generated by a successful or
* failed operation.
*<p>
* When a context method that may return response controls is invoked,
* response controls from the previous method invocation are cleared.
* <tt>getResponseControls()</tt> returns all of the response controls
* generated by LDAP operations used by the context method in the order
* received from the LDAP server.
* Invoking <tt>getResponseControls()</tt> does not
* clear the response controls. You can call it many times (and get
* back the same controls) until the next context method that may return
* controls is invoked.
*<p>
* @return A possibly null array of controls. If null, the previous
* method invoked on this context did not produce any controls.
* @exception NamingException If an error occurred while getting the response
* controls.
*/
public Control[] getResponseControls() throws NamingException;
/** {@collect.stats}
* Constant that holds the name of the environment property
* for specifying the list of control factories to use. The value
* of the property should be a colon-separated list of the fully
* qualified class names of factory classes that will create a control
* given another control. See
* <tt>ControlFactory.getControlInstance()</tt> for details.
* This property may be specified in the environment, an applet
* parameter, a system property, or one or more resource files.
*<p>
* The value of this constant is "java.naming.factory.control".
*<p>
* @see ControlFactory
* @see javax.naming.Context#addToEnvironment
* @see javax.naming.Context#removeFromEnvironment
*/
static final String CONTROL_FACTORIES = "java.naming.factory.control";
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.ldap;
import javax.naming.NamingException;
/** {@collect.stats}
* This interface is for returning controls with objects returned
* in NamingEnumerations.
* For example, suppose a server sends back controls with the results
* of a search operation, the service provider would return a NamingEnumeration of
* objects that are both SearchResult and implement HasControls.
*<blockquote><pre>
* NamingEnumeration elts = ectx.search((Name)name, filter, sctls);
* while (elts.hasMore()) {
* Object entry = elts.next();
*
* // Get search result
* SearchResult res = (SearchResult)entry;
* // do something with it
*
* // Get entry controls
* if (entry instanceof HasControls) {
* Control[] entryCtls = ((HasControls)entry).getControls();
* // do something with controls
* }
* }
*</pre></blockquote>
*
* @author Rosanna Lee
* @author Scott Seligman
* @author Vincent Ryan
* @since 1.3
*
*/
public interface HasControls {
/** {@collect.stats}
* Retrieves an array of <tt>Control</tt>s from the object that
* implements this interface. It is null if there are no controls.
*
* @return A possibly null array of <tt>Control</tt> objects.
* @throws NamingException If cannot return controls due to an error.
*/
public Control[] getControls() throws NamingException;
}
|
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.naming.ldap;
/** {@collect.stats}
* A sort key and its associated sort parameters.
* This class implements a sort key which is used by the LDAPv3
* Control for server-side sorting of search results as defined in
* <a href="http://www.ietf.org/rfc/rfc2891.txt">RFC 2891</a>.
*
* @since 1.5
* @see SortControl
* @author Vincent Ryan
*/
public class SortKey {
/*
* The ID of the attribute to sort by.
*/
private String attrID;
/*
* The sort order. Ascending order, by default.
*/
private boolean reverseOrder = false;
/*
* The ID of the matching rule to use for ordering attribute values.
*/
private String matchingRuleID = null;
/** {@collect.stats}
* Creates the default sort key for an attribute. Entries will be sorted
* according to the specified attribute in ascending order using the
* ordering matching rule defined for use with that attribute.
*
* @param attrID The non-null ID of the attribute to be used as a sort
* key.
*/
public SortKey(String attrID) {
this.attrID = attrID;
}
/** {@collect.stats}
* Creates a sort key for an attribute. Entries will be sorted according to
* the specified attribute in the specified sort order and using the
* specified matching rule, if supplied.
*
* @param attrID The non-null ID of the attribute to be used as
* a sort key.
* @param ascendingOrder If true then entries are arranged in ascending
* order. Otherwise there are arranged in
* descending order.
* @param matchingRuleID The possibly null ID of the matching rule to
* use to order the attribute values. If not
* specified then the ordering matching rule
* defined for the sort key attribute is used.
*/
public SortKey(String attrID, boolean ascendingOrder,
String matchingRuleID) {
this.attrID = attrID;
reverseOrder = (! ascendingOrder);
this.matchingRuleID = matchingRuleID;
}
/** {@collect.stats}
* Retrieves the attribute ID of the sort key.
*
* @return The non-null Attribute ID of the sort key.
*/
public String getAttributeID() {
return attrID;
}
/** {@collect.stats}
* Determines the sort order.
*
* @return true if the sort order is ascending, false if descending.
*/
public boolean isAscending() {
return (! reverseOrder);
}
/** {@collect.stats}
* Retrieves the matching rule ID used to order the attribute values.
*
* @return The possibly null matching rule ID. If null then the
* ordering matching rule defined for the sort key attribute
* is used.
*/
public String getMatchingRuleID() {
return matchingRuleID;
}
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.ldap;
import javax.naming.ReferralException;
import javax.naming.Context;
import javax.naming.NamingException;
import java.util.Hashtable;
/** {@collect.stats}
* This abstract class is used to represent an LDAP referral exception.
* It extends the base <tt>ReferralException</tt> by providing a
* <tt>getReferralContext()</tt> method that accepts request controls.
* LdapReferralException is an abstract class. Concrete implementations of it
* determine its synchronization and serialization properties.
*<p>
* A <tt>Control[]</tt> array passed as a parameter to
* the <tt>getReferralContext()</tt> method is owned by the caller.
* The service provider will not modify the array or keep a reference to it,
* although it may keep references to the individual <tt>Control</tt> objects
* in the array.
*
* @author Rosanna Lee
* @author Scott Seligman
* @author Vincent Ryan
* @since 1.3
*/
public abstract class LdapReferralException extends ReferralException {
/** {@collect.stats}
* Constructs a new instance of LdapReferralException using the
* explanation supplied. All other fields are set to null.
*
* @param explanation Additional detail about this exception. Can be null.
* @see java.lang.Throwable#getMessage
*/
protected LdapReferralException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of LdapReferralException.
* All fields are set to null.
*/
protected LdapReferralException() {
super();
}
/** {@collect.stats}
* Retrieves the context at which to continue the method using the
* context's environment and no controls.
* The referral context is created using the environment properties of
* the context that threw the <tt>ReferralException</tt> and no controls.
*<p>
* This method is equivalent to
*<blockquote><pre>
* getReferralContext(ctx.getEnvironment(), null);
*</pre></blockquote>
* where <tt>ctx</tt> is the context that threw the <tt>ReferralException.</tt>
*<p>
* It is overridden in this class for documentation purposes only.
* See <tt>ReferralException</tt> for how to use this method.
*
* @return The non-null context at which to continue the method.
* @exception NamingException If a naming exception was encountered.
* Call either <tt>retryReferral()</tt> or <tt>skipReferral()</tt>
* to continue processing referrals.
*/
public abstract Context getReferralContext() throws NamingException;
/** {@collect.stats}
* Retrieves the context at which to continue the method using
* environment properties and no controls.
* The referral context is created using <tt>env</tt> as its environment
* properties and no controls.
*<p>
* This method is equivalent to
*<blockquote><pre>
* getReferralContext(env, null);
*</pre></blockquote>
*<p>
* It is overridden in this class for documentation purposes only.
* See <tt>ReferralException</tt> for how to use this method.
*
* @param env The possibly null environment to use when retrieving the
* referral context. If null, no environment properties will be used.
*
* @return The non-null context at which to continue the method.
* @exception NamingException If a naming exception was encountered.
* Call either <tt>retryReferral()</tt> or <tt>skipReferral()</tt>
* to continue processing referrals.
*/
public abstract Context
getReferralContext(Hashtable<?,?> env)
throws NamingException;
/** {@collect.stats}
* Retrieves the context at which to continue the method using
* request controls and environment properties.
* Regardless of whether a referral is encountered directly during a
* context operation, or indirectly, for example, during a search
* enumeration, the referral exception should provide a context
* at which to continue the operation.
* To continue the operation, the client program should re-invoke
* the method using the same arguments as the original invocation.
*<p>
* <tt>reqCtls</tt> is used when creating the connection to the referred
* server. These controls will be used as the connection request controls for
* the context and context instances
* derived from the context.
* <tt>reqCtls</tt> will also be the context's request controls for
* subsequent context operations. See the <tt>LdapContext</tt> class
* description for details.
*<p>
* This method should be used instead of the other two overloaded forms
* when the caller needs to supply request controls for creating
* the referral context. It might need to do this, for example, when
* it needs to supply special controls relating to authentication.
*<p>
* Service provider implementors should read the "Service Provider" section
* in the <tt>LdapContext</tt> class description for implementation details.
*
* @param reqCtls The possibly null request controls to use for the new context.
* If null or the empty array means use no request controls.
* @param env The possibly null environment properties to use when
* for the new context. If null, the context is initialized with no environment
* properties.
* @return The non-null context at which to continue the method.
* @exception NamingException If a naming exception was encountered.
* Call either <tt>retryReferral()</tt> or <tt>skipReferral()</tt>
* to continue processing referrals.
*/
public abstract Context
getReferralContext(Hashtable<?,?> env,
Control[] reqCtls)
throws NamingException;
private static final long serialVersionUID = -1668992791764950804L;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.ldap;
import javax.naming.*;
import javax.naming.directory.*;
import java.util.Hashtable;
/** {@collect.stats}
* This class is the starting context for performing
* LDAPv3-style extended operations and controls.
*<p>
* See <tt>javax.naming.InitialContext</tt> and
* <tt>javax.naming.InitialDirContext</tt> for details on synchronization,
* and the policy for how an initial context is created.
*
* <h4>Request Controls</h4>
* When you create an initial context (<tt>InitialLdapContext</tt>),
* you can specify a list of request controls.
* These controls will be used as the request controls for any
* implicit LDAP "bind" operation performed by the context or contexts
* derived from the context. These are called <em>connection request controls</em>.
* Use <tt>getConnectControls()</tt> to get a context's connection request
* controls.
*<p>
* The request controls supplied to the initial context constructor
* are <em>not</em> used as the context request controls
* for subsequent context operations such as searches and lookups.
* Context request controls are set and updated by using
* <tt>setRequestControls()</tt>.
*<p>
* As shown, there can be two different sets of request controls
* associated with a context: connection request controls and context
* request controls.
* This is required for those applications needing to send critical
* controls that might not be applicable to both the context operation and
* any implicit LDAP "bind" operation.
* A typical user program would do the following:
*<blockquote><pre>
* InitialLdapContext lctx = new InitialLdapContext(env, critConnCtls);
* lctx.setRequestControls(critModCtls);
* lctx.modifyAttributes(name, mods);
* Controls[] respCtls = lctx.getResponseControls();
*</pre></blockquote>
* It specifies first the critical controls for creating the initial context
* (<tt>critConnCtls</tt>), and then sets the context's request controls
* (<tt>critModCtls</tt>) for the context operation. If for some reason
* <tt>lctx</tt> needs to reconnect to the server, it will use
* <tt>critConnCtls</tt>. See the <tt>LdapContext</tt> interface for
* more discussion about request controls.
*<p>
* Service provider implementors should read the "Service Provider" section
* in the <tt>LdapContext</tt> class description for implementation details.
*
* @author Rosanna Lee
* @author Scott Seligman
* @author Vincent Ryan
*
* @see LdapContext
* @see javax.naming.InitialContext
* @see javax.naming.directory.InitialDirContext
* @see javax.naming.spi.NamingManager#setInitialContextFactoryBuilder
* @since 1.3
*/
public class InitialLdapContext extends InitialDirContext implements LdapContext {
private static final String
BIND_CONTROLS_PROPERTY = "java.naming.ldap.control.connect";
/** {@collect.stats}
* Constructs an initial context using no environment properties or
* connection request controls.
* Equivalent to <tt>new InitialLdapContext(null, null)</tt>.
*
* @throws NamingException if a naming exception is encountered
*/
public InitialLdapContext() throws NamingException {
super(null);
}
/** {@collect.stats}
* Constructs an initial context
* using environment properties and connection request controls.
* See <tt>javax.naming.InitialContext</tt> for a discussion of
* environment properties.
*
* <p> This constructor will not modify its parameters or
* save references to them, but may save a clone or copy.
*
* <p> <tt>connCtls</tt> is used as the underlying context instance's
* connection request controls. See the class description
* for details.
*
* @param environment
* environment used to create the initial DirContext.
* Null indicates an empty environment.
* @param connCtls
* connection request controls for the initial context.
* If null, no connection request controls are used.
*
* @throws NamingException if a naming exception is encountered
*
* @see #reconnect
* @see LdapContext#reconnect
*/
public InitialLdapContext(Hashtable<?,?> environment,
Control[] connCtls)
throws NamingException {
super(true); // don't initialize yet
// Clone environment since caller owns it.
Hashtable env = (environment == null)
? new Hashtable(11)
: (Hashtable)environment.clone();
// Put connect controls into environment. Copy them first since
// caller owns the array.
if (connCtls != null) {
Control[] copy = new Control[connCtls.length];
System.arraycopy(connCtls, 0, copy, 0, connCtls.length);
env.put(BIND_CONTROLS_PROPERTY, copy);
}
// set version to LDAPv3
env.put("java.naming.ldap.version", "3");
// Initialize with updated environment
init(env);
}
/** {@collect.stats}
* Retrieves the initial LDAP context.
*
* @return The non-null cached initial context.
* @exception NotContextException If the initial context is not an
* instance of <tt>LdapContext</tt>.
* @exception NamingException If a naming exception was encountered.
*/
private LdapContext getDefaultLdapInitCtx() throws NamingException{
Context answer = getDefaultInitCtx();
if (!(answer instanceof LdapContext)) {
if (answer == null) {
throw new NoInitialContextException();
} else {
throw new NotContextException(
"Not an instance of LdapContext");
}
}
return (LdapContext)answer;
}
// LdapContext methods
// Most Javadoc is deferred to the LdapContext interface.
public ExtendedResponse extendedOperation(ExtendedRequest request)
throws NamingException {
return getDefaultLdapInitCtx().extendedOperation(request);
}
public LdapContext newInstance(Control[] reqCtls)
throws NamingException {
return getDefaultLdapInitCtx().newInstance(reqCtls);
}
public void reconnect(Control[] connCtls) throws NamingException {
getDefaultLdapInitCtx().reconnect(connCtls);
}
public Control[] getConnectControls() throws NamingException {
return getDefaultLdapInitCtx().getConnectControls();
}
public void setRequestControls(Control[] requestControls)
throws NamingException {
getDefaultLdapInitCtx().setRequestControls(requestControls);
}
public Control[] getRequestControls() throws NamingException {
return getDefaultLdapInitCtx().getRequestControls();
}
public Control[] getResponseControls() throws NamingException {
return getDefaultLdapInitCtx().getResponseControls();
}
}
|
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.naming.ldap;
import java.io.IOException;
import com.sun.jndi.ldap.Ber;
import com.sun.jndi.ldap.BerEncoder;
/** {@collect.stats}
* Requests that the results of a search operation be sorted by the LDAP server
* before being returned.
* The sort criteria are specified using an ordered list of one or more sort
* keys, with associated sort parameters.
* Search results are sorted at the LDAP server according to the parameters
* supplied in the sort control and then returned to the requestor. If sorting
* is not supported at the server (and the sort control is marked as critical)
* then the search operation is not performed and an error is returned.
* <p>
* The following code sample shows how the class may be used:
* <pre>
*
* // Open an LDAP association
* LdapContext ctx = new InitialLdapContext();
*
* // Activate sorting
* String sortKey = "cn";
* ctx.setRequestControls(new Control[]{
* new SortControl(sortKey, Control.CRITICAL) });
*
* // Perform a search
* NamingEnumeration results =
* ctx.search("", "(objectclass=*)", new SearchControls());
*
* // Iterate over search results
* while (results != null && results.hasMore()) {
* // Display an entry
* SearchResult entry = (SearchResult)results.next();
* System.out.println(entry.getName());
* System.out.println(entry.getAttributes());
*
* // Handle the entry's response controls (if any)
* if (entry instanceof HasControls) {
* // ((HasControls)entry).getControls();
* }
* }
* // Examine the sort control response
* Control[] controls = ctx.getResponseControls();
* if (controls != null) {
* for (int i = 0; i < controls.length; i++) {
* if (controls[i] instanceof SortResponseControl) {
* SortResponseControl src = (SortResponseControl)controls[i];
* if (! src.isSorted()) {
* throw src.getException();
* }
* } else {
* // Handle other response controls (if any)
* }
* }
* }
*
* // Close the LDAP association
* ctx.close();
* ...
*
* </pre>
* <p>
* This class implements the LDAPv3 Request Control for server-side sorting
* as defined in
* <a href="http://www.ietf.org/rfc/rfc2891.txt">RFC 2891</a>.
*
* The control's value has the following ASN.1 definition:
* <pre>
*
* SortKeyList ::= SEQUENCE OF SEQUENCE {
* attributeType AttributeDescription,
* orderingRule [0] MatchingRuleId OPTIONAL,
* reverseOrder [1] BOOLEAN DEFAULT FALSE }
*
* </pre>
*
* @since 1.5
* @see SortKey
* @see SortResponseControl
* @author Vincent Ryan
*/
final public class SortControl extends BasicControl {
/** {@collect.stats}
* The server-side sort control's assigned object identifier
* is 1.2.840.113556.1.4.473.
*/
public static final String OID = "1.2.840.113556.1.4.473";
private static final long serialVersionUID = -1965961680233330744L;
/** {@collect.stats}
* Constructs a control to sort on a single attribute in ascending order.
* Sorting will be performed using the ordering matching rule defined
* for use with the specified attribute.
*
* @param sortBy An attribute ID to sort by.
* @param criticality If true then the server must honor the control
* and return the search results sorted as
* requested or refuse to perform the search.
* If false, then the server need not honor the
* control.
* @exception IOException If an error was encountered while encoding the
* supplied arguments into a control.
*/
public SortControl(String sortBy, boolean criticality) throws IOException {
super(OID, criticality, null);
super.value = setEncodedValue(new SortKey[]{ new SortKey(sortBy) });
}
/** {@collect.stats}
* Constructs a control to sort on a list of attributes in ascending order.
* Sorting will be performed using the ordering matching rule defined
* for use with each of the specified attributes.
*
* @param sortBy A non-null list of attribute IDs to sort by.
* The list is in order of highest to lowest sort key
* precedence.
* @param criticality If true then the server must honor the control
* and return the search results sorted as
* requested or refuse to perform the search.
* If false, then the server need not honor the
* control.
* @exception IOException If an error was encountered while encoding the
* supplied arguments into a control.
*/
public SortControl(String[] sortBy, boolean criticality)
throws IOException {
super(OID, criticality, null);
SortKey[] sortKeys = new SortKey[sortBy.length];
for (int i = 0; i < sortBy.length; i++) {
sortKeys[i] = new SortKey(sortBy[i]);
}
super.value = setEncodedValue(sortKeys);
}
/** {@collect.stats}
* Constructs a control to sort on a list of sort keys.
* Each sort key specifies the sort order and ordering matching rule to use.
*
* @param sortBy A non-null list of keys to sort by.
* The list is in order of highest to lowest sort key
* precedence.
* @param criticality If true then the server must honor the control
* and return the search results sorted as
* requested or refuse to perform the search.
* If false, then the server need not honor the
* control.
* @exception IOException If an error was encountered while encoding the
* supplied arguments into a control.
*/
public SortControl(SortKey[] sortBy, boolean criticality)
throws IOException {
super(OID, criticality, null);
super.value = setEncodedValue(sortBy);
}
/*
* Encodes the sort control's value using ASN.1 BER.
* The result includes the BER tag and length for the control's value but
* does not include the control's object identifer and criticality setting.
*
* @param sortKeys A non-null list of keys to sort by.
* @return A possibly null byte array representing the ASN.1 BER encoded
* value of the sort control.
* @exception IOException If a BER encoding error occurs.
*/
private byte[] setEncodedValue(SortKey[] sortKeys) throws IOException {
// build the ASN.1 BER encoding
BerEncoder ber = new BerEncoder(30 * sortKeys.length + 10);
String matchingRule;
ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
for (int i = 0; i < sortKeys.length; i++) {
ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
ber.encodeString(sortKeys[i].getAttributeID(), true); // v3
if ((matchingRule = sortKeys[i].getMatchingRuleID()) != null) {
ber.encodeString(matchingRule, (Ber.ASN_CONTEXT | 0), true);
}
if (! sortKeys[i].isAscending()) {
ber.encodeBoolean(true, (Ber.ASN_CONTEXT | 1));
}
ber.endSeq();
}
ber.endSeq();
return ber.getTrimmedBuf();
}
}
|
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.naming.ldap;
import java.util.List;
import java.util.ArrayList;
import javax.naming.InvalidNameException;
/*
* RFC2253Parser implements a recursive descent parser for a single DN.
*/
final class Rfc2253Parser {
private final String name; // DN being parsed
private final char[] chars; // characters in LDAP name being parsed
private final int len; // length of "chars"
private int cur = 0; // index of first unconsumed char in "chars"
/*
* Given an LDAP DN in string form, returns a parser for it.
*/
Rfc2253Parser(String name) {
this.name = name;
len = name.length();
chars = name.toCharArray();
}
/*
* Parses the DN, returning a List of its RDNs.
*/
// public List<Rdn> getDN() throws InvalidNameException {
List parseDn() throws InvalidNameException {
cur = 0;
// ArrayList<Rdn> rdns =
// new ArrayList<Rdn>(len / 3 + 10); // leave room for growth
ArrayList rdns =
new ArrayList(len / 3 + 10); // leave room for growth
if (len == 0) {
return rdns;
}
rdns.add(doParse(new Rdn()));
while (cur < len) {
if (chars[cur] == ',' || chars[cur] == ';') {
++cur;
rdns.add(0, doParse(new Rdn()));
} else {
throw new InvalidNameException("Invalid name: " + name);
}
}
return rdns;
}
/*
* Parses the DN, if it is known to contain a single RDN.
*/
Rdn parseRdn() throws InvalidNameException {
return parseRdn(new Rdn());
}
/*
* Parses the DN, if it is known to contain a single RDN.
*/
Rdn parseRdn(Rdn rdn) throws InvalidNameException {
rdn = doParse(rdn);
if (cur < len) {
throw new InvalidNameException("Invalid RDN: " + name);
}
return rdn;
}
/*
* Parses the next RDN and returns it. Throws an exception if
* none is found. Leading and trailing whitespace is consumed.
*/
private Rdn doParse(Rdn rdn) throws InvalidNameException {
while (cur < len) {
consumeWhitespace();
String attrType = parseAttrType();
consumeWhitespace();
if (cur >= len || chars[cur] != '=') {
throw new InvalidNameException("Invalid name: " + name);
}
++cur; // consume '='
consumeWhitespace();
String value = parseAttrValue();
consumeWhitespace();
rdn.put(attrType, Rdn.unescapeValue(value));
if (cur >= len || chars[cur] != '+') {
break;
}
++cur; // consume '+'
}
rdn.sort();
return rdn;
}
/*
* Returns the attribute type that begins at the next unconsumed
* char. No leading whitespace is expected.
* This routine is more generous than RFC 2253. It accepts
* attribute types composed of any nonempty combination of Unicode
* letters, Unicode digits, '.', '-', and internal space characters.
*/
private String parseAttrType() throws InvalidNameException {
final int beg = cur;
while (cur < len) {
char c = chars[cur];
if (Character.isLetterOrDigit(c) ||
c == '.' ||
c == '-' ||
c == ' ') {
++cur;
} else {
break;
}
}
// Back out any trailing spaces.
while ((cur > beg) && (chars[cur - 1] == ' ')) {
--cur;
}
if (beg == cur) {
throw new InvalidNameException("Invalid name: " + name);
}
return new String(chars, beg, cur - beg);
}
/*
* Returns the attribute value that begins at the next unconsumed
* char. No leading whitespace is expected.
*/
private String parseAttrValue() throws InvalidNameException {
if (cur < len && chars[cur] == '#') {
return parseBinaryAttrValue();
} else if (cur < len && chars[cur] == '"') {
return parseQuotedAttrValue();
} else {
return parseStringAttrValue();
}
}
private String parseBinaryAttrValue() throws InvalidNameException {
final int beg = cur;
++cur; // consume '#'
while ((cur < len) &&
Character.isLetterOrDigit(chars[cur])) {
++cur;
}
return new String(chars, beg, cur - beg);
}
private String parseQuotedAttrValue() throws InvalidNameException {
final int beg = cur;
++cur; // consume '"'
while ((cur < len) && chars[cur] != '"') {
if (chars[cur] == '\\') {
++cur; // consume backslash, then what follows
}
++cur;
}
if (cur >= len) { // no closing quote
throw new InvalidNameException("Invalid name: " + name);
}
++cur; // consume closing quote
return new String(chars, beg, cur - beg);
}
private String parseStringAttrValue() throws InvalidNameException {
final int beg = cur;
int esc = -1; // index of the most recently escaped character
while ((cur < len) && !atTerminator()) {
if (chars[cur] == '\\') {
++cur; // consume backslash, then what follows
esc = cur;
}
++cur;
}
if (cur > len) { // 'twas backslash followed by nothing
throw new InvalidNameException("Invalid name: " + name);
}
// Trim off (unescaped) trailing whitespace.
int end;
for (end = cur; end > beg; end--) {
if (!isWhitespace(chars[end - 1]) || (esc == end - 1)) {
break;
}
}
return new String(chars, beg, end - beg);
}
private void consumeWhitespace() {
while ((cur < len) && isWhitespace(chars[cur])) {
++cur;
}
}
/*
* Returns true if next unconsumed character is one that terminates
* a string attribute value.
*/
private boolean atTerminator() {
return (cur < len &&
(chars[cur] == ',' ||
chars[cur] == ';' ||
chars[cur] == '+'));
}
/*
* Best guess as to what RFC 2253 means by "whitespace".
*/
private static boolean isWhitespace(char c) {
return (c == ' ' || c == '\r');
}
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.ldap;
import javax.naming.event.NamingListener;
/** {@collect.stats}
* This interface is for handling <tt>UnsolicitedNotificationEvent</tt>.
* "Unsolicited notification" is defined in
* <A HREF="ftp://ftp.isi.edu/in-notes/rfc2251.txt">RFC 2251</A>.
* It allows the server to send unsolicited notifications to the client.
* A <tt>UnsolicitedNotificationListener</tt> must:
*<ol>
* <li>Implement this interface and its method
* <li>Implement <tt>NamingListener.namingExceptionThrown()</tt> so
* that it will be notified of exceptions thrown while attempting to
* collect unsolicited notification events.
* <li>Register with the context using one of the <tt>addNamingListener()</tt>
* methods from <tt>EventContext</tt> or <tt>EventDirContext</tt>.
* Only the <tt>NamingListener</tt> argument of these methods are applicable;
* the rest are ignored for a <tt>UnsolicitedNotificationListener</tt>.
* (These arguments might be applicable to the listener if it implements
* other listener interfaces).
*</ol>
*
* @author Rosanna Lee
* @author Scott Seligman
* @author Vincent Ryan
*
* @see UnsolicitedNotificationEvent
* @see UnsolicitedNotification
* @see javax.naming.event.EventContext#addNamingListener
* @see javax.naming.event.EventDirContext#addNamingListener
* @see javax.naming.event.EventContext#removeNamingListener
* @since 1.3
*/
public interface UnsolicitedNotificationListener extends NamingListener {
/** {@collect.stats}
* Called when an unsolicited notification has been received.
*
* @param evt The non-null UnsolicitedNotificationEvent
*/
void notificationReceived(UnsolicitedNotificationEvent evt);
}
|
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.naming.ldap;
import java.io.IOException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.HostnameVerifier;
/** {@collect.stats}
* This class implements the LDAPv3 Extended Response for StartTLS as
* defined in
* <a href="http://www.ietf.org/rfc/rfc2830.txt">Lightweight Directory
* Access Protocol (v3): Extension for Transport Layer Security</a>
*
* The object identifier for StartTLS is 1.3.6.1.4.1.1466.20037
* and no extended response value is defined.
*
*<p>
* The Start TLS extended request and response are used to establish
* a TLS connection over the existing LDAP connection associated with
* the JNDI context on which <tt>extendedOperation()</tt> is invoked.
* Typically, a JNDI program uses the StartTLS extended request and response
* classes as follows.
* <blockquote><pre>
* import javax.naming.ldap.*;
*
* // Open an LDAP association
* LdapContext ctx = new InitialLdapContext();
*
* // Perform a StartTLS extended operation
* StartTlsResponse tls =
* (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
*
* // Open a TLS connection (over the existing LDAP association) and get details
* // of the negotiated TLS session: cipher suite, peer certificate, ...
* SSLSession session = tls.negotiate();
*
* // ... use ctx to perform protected LDAP operations
*
* // Close the TLS connection (revert back to the underlying LDAP association)
* tls.close();
*
* // ... use ctx to perform unprotected LDAP operations
*
* // Close the LDAP association
* ctx.close;
* </pre></blockquote>
*
* @since 1.4
* @see StartTlsRequest
* @author Vincent Ryan
*/
public abstract class StartTlsResponse implements ExtendedResponse {
// Constant
/** {@collect.stats}
* The StartTLS extended response's assigned object identifier
* is 1.3.6.1.4.1.1466.20037.
*/
public static final String OID = "1.3.6.1.4.1.1466.20037";
// Called by subclass
/** {@collect.stats}
* Constructs a StartTLS extended response.
* A concrete subclass must have a public no-arg constructor.
*/
protected StartTlsResponse() {
}
// ExtendedResponse methods
/** {@collect.stats}
* Retrieves the StartTLS response's object identifier string.
*
* @return The object identifier string, "1.3.6.1.4.1.1466.20037".
*/
public String getID() {
return OID;
}
/** {@collect.stats}
* Retrieves the StartTLS response's ASN.1 BER encoded value.
* Since the response has no defined value, null is always
* returned.
*
* @return The null value.
*/
public byte[] getEncodedValue() {
return null;
}
// StartTls-specific methods
/** {@collect.stats}
* Overrides the default list of cipher suites enabled for use on the
* TLS connection. The cipher suites must have already been listed by
* <tt>SSLSocketFactory.getSupportedCipherSuites()</tt> as being supported.
* Even if a suite has been enabled, it still might not be used because
* the peer does not support it, or because the requisite certificates
* (and private keys) are not available.
*
* @param suites The non-null list of names of all the cipher suites to
* enable.
* @see #negotiate
*/
public abstract void setEnabledCipherSuites(String[] suites);
/** {@collect.stats}
* Sets the hostname verifier used by <tt>negotiate()</tt>
* after the TLS handshake has completed and the default hostname
* verification has failed.
* <tt>setHostnameVerifier()</tt> must be called before
* <tt>negotiate()</tt> is invoked for it to have effect.
* If called after
* <tt>negotiate()</tt>, this method does not do anything.
*
* @param verifier The non-null hostname verifier callback.
* @see #negotiate
*/
public abstract void setHostnameVerifier(HostnameVerifier verifier);
/** {@collect.stats}
* Negotiates a TLS session using the default SSL socket factory.
* <p>
* This method is equivalent to <tt>negotiate(null)</tt>.
*
* @return The negotiated SSL session
* @throws IOException If an IO error was encountered while establishing
* the TLS session.
* @see #setEnabledCipherSuites
* @see #setHostnameVerifier
*/
public abstract SSLSession negotiate() throws IOException;
/** {@collect.stats}
* Negotiates a TLS session using an SSL socket factory.
* <p>
* Creates an SSL socket using the supplied SSL socket factory and
* attaches it to the existing connection. Performs the TLS handshake
* and returns the negotiated session information.
* <p>
* If cipher suites have been set via <tt>setEnabledCipherSuites</tt>
* then they are enabled before the TLS handshake begins.
* <p>
* Hostname verification is performed after the TLS handshake completes.
* The default hostname verification performs a match of the server's
* hostname against the hostname information found in the server's certificate.
* If this verification fails and no callback has been set via
* <tt>setHostnameVerifier</tt> then the negotiation fails.
* If this verification fails and a callback has been set via
* <tt>setHostnameVerifier</tt>, then the callback is used to determine whether
* the negotiation succeeds.
* <p>
* If an error occurs then the SSL socket is closed and an IOException
* is thrown. The underlying connection remains intact.
*
* @param factory The possibly null SSL socket factory to use.
* If null, the default SSL socket factory is used.
* @return The negotiated SSL session
* @throws IOException If an IO error was encountered while establishing
* the TLS session.
* @see #setEnabledCipherSuites
* @see #setHostnameVerifier
*/
public abstract SSLSession negotiate(SSLSocketFactory factory)
throws IOException;
/** {@collect.stats}
* Closes the TLS connection gracefully and reverts back to the underlying
* connection.
*
* @throws IOException If an IO error was encountered while closing the
* TLS connection
*/
public abstract void close() throws IOException;
private static final long serialVersionUID = 8372842182579276418L;
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming.ldap;
import javax.naming.NamingException;
import javax.naming.Context;
import java.util.Hashtable;
import com.sun.naming.internal.FactoryEnumeration;
import com.sun.naming.internal.ResourceManager;
/** {@collect.stats}
* This abstract class represents a factory for creating LDAPv3 controls.
* LDAPv3 controls are defined in
* <A HREF="ftp://ftp.isi.edu/in-notes/rfc2251.txt">RFC 2251</A>.
*<p>
* When a service provider receives a response control, it uses control
* factories to return the specific/appropriate control class implementation.
*
* @author Rosanna Lee
* @author Scott Seligman
* @author Vincent Ryan
*
* @see Control
* @since 1.3
*/
public abstract class ControlFactory {
/*
* Creates a new instance of a control factory.
*/
protected ControlFactory() {
}
/** {@collect.stats}
* Creates a control using this control factory.
*<p>
* The factory is used by the service provider to return controls
* that it reads from the LDAP protocol as specialized control classes.
* Without this mechanism, the provider would be returning
* controls that only contained data in BER encoded format.
*<p>
* Typically, <tt>ctl</tt> is a "basic" control containing
* BER encoded data. The factory is used to create a specialized
* control implementation, usually by decoding the BER encoded data,
* that provides methods to access that data in a type-safe and friendly
* manner.
* <p>
* For example, a factory might use the BER encoded data in
* basic control and return an instance of a VirtualListReplyControl.
*<p>
* If this factory cannot create a control using the argument supplied,
* it should return null.
* A factory should only throw an exception if it is sure that
* it is the only intended factory and that no other control factories
* should be tried. This might happen, for example, if the BER data
* in the control does not match what is expected of a control with
* the given OID. Since this method throws <tt>NamingException</tt>,
* any other internally generated exception that should be propagated
* must be wrapped inside a <tt>NamingException</tt>.
*
* @param ctl A non-null control.
*
* @return A possibly null Control.
* @exception NamingException If <tt>ctl</tt> contains invalid data that prevents it
* from being used to create a control. A factory should only throw
* an exception if it knows how to produce the control (identified by the OID)
* but is unable to because of, for example invalid BER data.
*/
public abstract Control getControlInstance(Control ctl) throws NamingException;
/** {@collect.stats}
* Creates a control using known control factories.
* <p>
* The following rule is used to create the control:
*<ul>
* <li> Use the control factories specified in
* the <tt>LdapContext.CONTROL_FACTORIES</tt> property of the
* environment, and of the provider resource file associated with
* <tt>ctx</tt>, in that order.
* The value of this property is a colon-separated list of factory
* class names that are tried in order, and the first one that succeeds
* in creating the control is the one used.
* If none of the factories can be loaded,
* return <code>ctl</code>.
* If an exception is encountered while creating the control, the
* exception is passed up to the caller.
*</ul>
* <p>
* Note that a control factory
* must be public and must have a public constructor that accepts no arguments.
* <p>
* @param ctl The non-null control object containing the OID and BER data.
* @param ctx The possibly null context in which the control is being created.
* If null, no such information is available.
* @param env The possibly null environment of the context. This is used
* to find the value of the <tt>LdapContext.CONTROL_FACTORIES</tt> property.
* @return A control object created using <code>ctl</code>; or
* <code>ctl</code> if a control object cannot be created using
* the algorithm described above.
* @exception NamingException if a naming exception was encountered
* while attempting to create the control object.
* If one of the factories accessed throws an
* exception, it is propagated up to the caller.
* If an error was encountered while loading
* and instantiating the factory and object classes, the exception
* is wrapped inside a <tt>NamingException</tt> and then rethrown.
*/
public static Control getControlInstance(Control ctl, Context ctx,
Hashtable<?,?> env)
throws NamingException {
// Get object factories list from environment properties or
// provider resource file.
FactoryEnumeration factories = ResourceManager.getFactories(
LdapContext.CONTROL_FACTORIES, env, ctx);
if (factories == null) {
return ctl;
}
// Try each factory until one succeeds
Control answer = null;
ControlFactory factory;
while (answer == null && factories.hasMore()) {
factory = (ControlFactory)factories.next();
answer = factory.getControlInstance(ctl);
}
return (answer != null)? answer : ctl;
}
}
|
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.naming.ldap;
import java.io.IOException;
import com.sun.jndi.ldap.Ber;
import com.sun.jndi.ldap.BerEncoder;
/** {@collect.stats}
* Requests that the results of a search operation be returned by the LDAP
* server in batches of a specified size.
* The requestor controls the rate at which batches are returned by the rate
* at which it invokes search operations.
* <p>
* The following code sample shows how the class may be used:
* <pre>
*
* // Open an LDAP association
* LdapContext ctx = new InitialLdapContext();
*
* // Activate paged results
* int pageSize = 20; // 20 entries per page
* byte[] cookie = null;
* int total;
* ctx.setRequestControls(new Control[]{
* new PagedResultsControl(pageSize, Control.CRITICAL) });
*
* do {
* // Perform the search
* NamingEnumeration results =
* ctx.search("", "(objectclass=*)", new SearchControls());
*
* // Iterate over a batch of search results
* while (results != null && results.hasMore()) {
* // Display an entry
* SearchResult entry = (SearchResult)results.next();
* System.out.println(entry.getName());
* System.out.println(entry.getAttributes());
*
* // Handle the entry's response controls (if any)
* if (entry instanceof HasControls) {
* // ((HasControls)entry).getControls();
* }
* }
* // Examine the paged results control response
* Control[] controls = ctx.getResponseControls();
* if (controls != null) {
* for (int i = 0; i < controls.length; i++) {
* if (controls[i] instanceof PagedResultsResponseControl) {
* PagedResultsResponseControl prrc =
* (PagedResultsResponseControl)controls[i];
* total = prrc.getResultSize();
* cookie = prrc.getCookie();
* } else {
* // Handle other response controls (if any)
* }
* }
* }
*
* // Re-activate paged results
* ctx.setRequestControls(new Control[]{
* new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
* } while (cookie != null);
*
* // Close the LDAP association
* ctx.close();
* ...
*
* </pre>
* <p>
* This class implements the LDAPv3 Control for paged-results as defined in
* <a href="http://www.ietf.org/rfc/rfc2696.txt">RFC 2696</a>.
*
* The control's value has the following ASN.1 definition:
* <pre>
*
* realSearchControlValue ::= SEQUENCE {
* size INTEGER (0..maxInt),
* -- requested page size from client
* -- result set size estimate from server
* cookie OCTET STRING
* }
*
* </pre>
*
* @since 1.5
* @see PagedResultsResponseControl
* @author Vincent Ryan
*/
final public class PagedResultsControl extends BasicControl {
/** {@collect.stats}
* The paged-results control's assigned object identifier
* is 1.2.840.113556.1.4.319.
*/
public static final String OID = "1.2.840.113556.1.4.319";
private static final byte[] EMPTY_COOKIE = new byte[0];
private static final long serialVersionUID = 6684806685736844298L;
/** {@collect.stats}
* Constructs a control to set the number of entries to be returned per
* page of results.
*
* @param pageSize The number of entries to return in a page.
* @param criticality If true then the server must honor the control
* and return search results as indicated by
* pageSize or refuse to perform the search.
* If false, then the server need not honor the
* control.
* @exception IOException If an error was encountered while encoding the
* supplied arguments into a control.
*/
public PagedResultsControl(int pageSize, boolean criticality)
throws IOException {
super(OID, criticality, null);
value = setEncodedValue(pageSize, EMPTY_COOKIE);
}
/** {@collect.stats}
* Constructs a control to set the number of entries to be returned per
* page of results. The cookie is provided by the server and may be
* obtained from the paged-results response control.
* <p>
* A sequence of paged-results can be abandoned by setting the pageSize
* to zero and setting the cookie to the last cookie received from the
* server.
*
* @param pageSize The number of entries to return in a page.
* @param cookie A possibly null server-generated cookie.
* @param criticality If true then the server must honor the control
* and return search results as indicated by
* pageSize or refuse to perform the search.
* If false, then the server need not honor the
* control.
* @exception IOException If an error was encountered while encoding the
* supplied arguments into a control.
*/
public PagedResultsControl(int pageSize, byte[] cookie,
boolean criticality) throws IOException {
super(OID, criticality, null);
if (cookie == null) {
cookie = EMPTY_COOKIE;
}
value = setEncodedValue(pageSize, cookie);
}
/*
* Encodes the paged-results control's value using ASN.1 BER.
* The result includes the BER tag and length for the control's value but
* does not include the control's object identifier and criticality setting.
*
* @param pageSize The number of entries to return in a page.
* @param cookie A non-null server-generated cookie.
* @return A possibly null byte array representing the ASN.1 BER encoded
* value of the LDAP paged-results control.
* @exception IOException If a BER encoding error occurs.
*/
private byte[] setEncodedValue(int pageSize, byte[] cookie)
throws IOException {
// build the ASN.1 encoding
BerEncoder ber = new BerEncoder(10 + cookie.length);
ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
ber.encodeInt(pageSize);
ber.encodeOctetString(cookie, Ber.ASN_OCTET_STR);
ber.endSeq();
return ber.getTrimmedBuf();
}
}
|
Java
|
/*
* Copyright (c) 2000, 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.naming.ldap;
import java.util.Iterator;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.naming.ConfigurationException;
import javax.naming.NamingException;
import com.sun.naming.internal.VersionHelper;
import java.util.ServiceLoader;
import java.util.ServiceConfigurationError;
/** {@collect.stats}
* This class implements the LDAPv3 Extended Request for StartTLS as
* defined in
* <a href="http://www.ietf.org/rfc/rfc2830.txt">Lightweight Directory
* Access Protocol (v3): Extension for Transport Layer Security</a>
*
* The object identifier for StartTLS is 1.3.6.1.4.1.1466.20037
* and no extended request value is defined.
*<p>
* <tt>StartTlsRequest</tt>/<tt>StartTlsResponse</tt> are used to establish
* a TLS connection over the existing LDAP connection associated with
* the JNDI context on which <tt>extendedOperation()</tt> is invoked.
* Typically, a JNDI program uses these classes as follows.
* <blockquote><pre>
* import javax.naming.ldap.*;
*
* // Open an LDAP association
* LdapContext ctx = new InitialLdapContext();
*
* // Perform a StartTLS extended operation
* StartTlsResponse tls =
* (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
*
* // Open a TLS connection (over the existing LDAP association) and get details
* // of the negotiated TLS session: cipher suite, peer certificate, etc.
* SSLSession session = tls.negotiate();
*
* // ... use ctx to perform protected LDAP operations
*
* // Close the TLS connection (revert back to the underlying LDAP association)
* tls.close();
*
* // ... use ctx to perform unprotected LDAP operations
*
* // Close the LDAP association
* ctx.close;
* </pre></blockquote>
*
* @since 1.4
* @see StartTlsResponse
* @author Vincent Ryan
*/
public class StartTlsRequest implements ExtendedRequest {
// Constant
/** {@collect.stats}
* The StartTLS extended request's assigned object identifier
* is 1.3.6.1.4.1.1466.20037.
*/
public static final String OID = "1.3.6.1.4.1.1466.20037";
// Constructors
/** {@collect.stats}
* Constructs a StartTLS extended request.
*/
public StartTlsRequest() {
}
// ExtendedRequest methods
/** {@collect.stats}
* Retrieves the StartTLS request's object identifier string.
*
* @return The object identifier string, "1.3.6.1.4.1.1466.20037".
*/
public String getID() {
return OID;
}
/** {@collect.stats}
* Retrieves the StartTLS request's ASN.1 BER encoded value.
* Since the request has no defined value, null is always
* returned.
*
* @return The null value.
*/
public byte[] getEncodedValue() {
return null;
}
/** {@collect.stats}
* Creates an extended response object that corresponds to the
* LDAP StartTLS extended request.
* <p>
* The result must be a concrete subclass of StartTlsResponse
* and must have a public zero-argument constructor.
* <p>
* This method locates the implementation class by locating
* configuration files that have the name:
* <blockquote><tt>
* META-INF/services/javax.naming.ldap.StartTlsResponse
* </tt></blockquote>
* The configuration files and their corresponding implementation classes must
* be accessible to the calling thread's context class loader.
* <p>
* Each configuration file should contain a list of fully-qualified class
* names, one per line. Space and tab characters surrounding each name, as
* well as blank lines, are ignored. The comment character is <tt>'#'</tt>
* (<tt>0x23</tt>); on each line all characters following the first comment
* character are ignored. The file must be encoded in UTF-8.
* <p>
* This method will return an instance of the first implementation
* class that it is able to load and instantiate successfully from
* the list of class names collected from the configuration files.
* This method uses the calling thread's context classloader to find the
* configuration files and to load the implementation class.
* <p>
* If no class can be found in this way, this method will use
* an implementation-specific way to locate an implementation.
* If none is found, a NamingException is thrown.
*
* @param id The object identifier of the extended response.
* Its value must be "1.3.6.1.4.1.1466.20037" or null.
* Both values are equivalent.
* @param berValue The possibly null ASN.1 BER encoded value of the
* extended response. This is the raw BER bytes
* including the tag and length of the response value.
* It does not include the response OID.
* Its value is ignored because a Start TLS response
* is not expected to contain any response value.
* @param offset The starting position in berValue of the bytes to use.
* Its value is ignored because a Start TLS response
* is not expected to contain any response value.
* @param length The number of bytes in berValue to use.
* Its value is ignored because a Start TLS response
* is not expected to contain any response value.
* @return The StartTLS extended response object.
* @exception NamingException If a naming exception was encountered
* while creating the StartTLS extended response object.
*/
public ExtendedResponse createExtendedResponse(String id, byte[] berValue,
int offset, int length) throws NamingException {
// Confirm that the object identifier is correct
if ((id != null) && (!id.equals(OID))) {
throw new ConfigurationException(
"Start TLS received the following response instead of " +
OID + ": " + id);
}
StartTlsResponse resp = null;
ServiceLoader<StartTlsResponse> sl = ServiceLoader.load(
StartTlsResponse.class, getContextClassLoader());
Iterator<StartTlsResponse> iter = sl.iterator();
while (resp == null && privilegedHasNext(iter)) {
resp = iter.next();
}
if (resp != null) {
return resp;
}
try {
VersionHelper helper = VersionHelper.getVersionHelper();
Class clas = helper.loadClass(
"com.sun.jndi.ldap.ext.StartTlsResponseImpl");
resp = (StartTlsResponse) clas.newInstance();
} catch (IllegalAccessException e) {
throw wrapException(e);
} catch (InstantiationException e) {
throw wrapException(e);
} catch (ClassNotFoundException e) {
throw wrapException(e);
}
return resp;
}
/*
* Wrap an exception, thrown while attempting to load the StartTlsResponse
* class, in a configuration exception.
*/
private ConfigurationException wrapException(Exception e) {
ConfigurationException ce = new ConfigurationException(
"Cannot load implementation of javax.naming.ldap.StartTlsResponse");
ce.setRootCause(e);
return ce;
}
/*
* Acquire the class loader associated with this thread.
*/
private final ClassLoader getContextClassLoader() {
return (ClassLoader) AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
return Thread.currentThread().getContextClassLoader();
}
}
);
}
private final static boolean privilegedHasNext(final Iterator iter) {
Boolean answer = (Boolean) AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
return Boolean.valueOf(iter.hasNext());
}
});
return answer.booleanValue();
}
private static final long serialVersionUID = 4441679576360753397L;
}
|
Java
|
/*
* Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.ldap;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.ArrayList;
import java.util.Collections;
import javax.naming.InvalidNameException;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.Attributes;
import javax.naming.directory.Attribute;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* This class represents a relative distinguished name, or RDN, which is a
* component of a distinguished name as specified by
* <a href="http://ietf.org/rfc/rfc2253.txt">RFC 2253</a>.
* An example of an RDN is "OU=Sales+CN=J.Smith". In this example,
* the RDN consist of multiple attribute type/value pairs. The
* RDN is parsed as described in the class description for
* {@link javax.naming.ldap.LdapName <tt>LdapName</tt>}.
* <p>
* The Rdn class represents an RDN as attribute type/value mappings,
* which can be viewed using
* {@link javax.naming.directory.Attributes Attributes}.
* In addition, it contains convenience methods that allow easy retrieval
* of type and value when the Rdn consist of a single type/value pair,
* which is how it appears in a typical usage.
* It also contains helper methods that allow escaping of the unformatted
* attribute value and unescaping of the value formatted according to the
* escaping syntax defined in RFC2253. For methods that take or return
* attribute value as an Object, the value is either a String
* (in unescaped form) or a byte array.
* <p>
* <code>Rdn</code> will properly parse all valid RDNs, but
* does not attempt to detect all possible violations when parsing
* invalid RDNs. It is "generous" in accepting invalid RDNs.
* The "validity" of a name is determined ultimately when it
* is supplied to an LDAP server, which may accept or
* reject the name based on factors such as its schema information
* and interoperability considerations.
*
* <p>
* The following code example shows how to construct an Rdn using the
* constructor that takes type and value as arguments:
* <pre>
* Rdn rdn = new Rdn("cn", "Juicy, Fruit");
* System.out.println(rdn.toString());
* </pre>
* The last line will print <tt>cn=Juicy\, Fruit</tt>. The
* {@link #unescapeValue(String) <tt>unescapeValue()</tt>} method can be
* used to unescape the escaped comma resulting in the original
* value <tt>"Juicy, Fruit"</tt>. The {@link #escapeValue(Object)
* <tt>escapeValue()</tt>} method adds the escape back preceding the comma.
* <p>
* This class can be instantiated by a string representation
* of the RDN defined in RFC 2253 as shown in the following code example:
* <pre>
* Rdn rdn = new Rdn("cn=Juicy\\, Fruit");
* System.out.println(rdn.toString());
* </pre>
* The last line will print <tt>cn=Juicy\, Fruit</tt>.
* <p>
* Concurrent multithreaded read-only access of an instance of
* <tt>Rdn</tt> need not be synchronized.
* <p>
* Unless otherwise noted, the behavior of passing a null argument
* to a constructor or method in this class will cause NullPointerException
* to be thrown.
*
* @since 1.5
*/
public class Rdn implements Serializable, Comparable<Object> {
// private transient ArrayList<RdnEntry> entries;
private transient ArrayList entries;
// The common case.
private static final int DEFAULT_SIZE = 1;
private static final long serialVersionUID = -5994465067210009656L;
/** {@collect.stats}
* Constructs an Rdn from the given attribute set. See
* {@link javax.naming.directory.Attributes Attributes}.
* <p>
* The string attribute values are not interpretted as
* <a href="http://ietf.org/rfc/rfc2253.txt">RFC 2253</a>
* formatted RDN strings. That is, the values are used
* literally (not parsed) and assumed to be unescaped.
*
* @param attrSet The non-null and non-empty attributes containing
* type/value mappings.
* @throws InvalidNameException If contents of <tt>attrSet</tt> cannot
* be used to construct a valid RDN.
*/
public Rdn(Attributes attrSet) throws InvalidNameException {
if (attrSet.size() == 0) {
throw new InvalidNameException("Attributes cannot be empty");
}
entries = new ArrayList(attrSet.size());
NamingEnumeration attrs = attrSet.getAll();
try {
for (int nEntries = 0; attrs.hasMore(); nEntries++) {
RdnEntry entry = new RdnEntry();
Attribute attr = (Attribute) attrs.next();
entry.type = attr.getID();
entry.value = attr.get();
entries.add(nEntries, entry);
}
} catch (NamingException e) {
InvalidNameException e2 = new InvalidNameException(
e.getMessage());
e2.initCause(e);
throw e2;
}
sort(); // arrange entries for comparison
}
/** {@collect.stats}
* Constructs an Rdn from the given string.
* This constructor takes a string formatted according to the rules
* defined in <a href="http://ietf.org//rfc/rfc2253.txt">RFC 2253</a>
* and described in the class description for
* {@link javax.naming.ldap.LdapName}.
*
* @param rdnString The non-null and non-empty RFC2253 formatted string.
* @throws InvalidNameException If a syntax error occurs during
* parsing of the rdnString.
*/
public Rdn(String rdnString) throws InvalidNameException {
entries = new ArrayList(DEFAULT_SIZE);
(new Rfc2253Parser(rdnString)).parseRdn(this);
}
/** {@collect.stats}
* Constructs an Rdn from the given <tt>rdn</tt>.
* The contents of the <tt>rdn</tt> are simply copied into the newly
* created Rdn.
* @param rdn The non-null Rdn to be copied.
*/
public Rdn(Rdn rdn) {
entries = new ArrayList(rdn.entries.size());
entries.addAll(rdn.entries);
}
/** {@collect.stats}
* Constructs an Rdn from the given attribute type and
* value.
* The string attribute values are not interpretted as
* <a href="http://ietf.org/rfc/rfc2253.txt">RFC 2253</a>
* formatted RDN strings. That is, the values are used
* literally (not parsed) and assumed to be unescaped.
*
* @param type The non-null and non-empty string attribute type.
* @param value The non-null and non-empty attribute value.
* @throws InvalidNameException If type/value cannot be used to
* construct a valid RDN.
* @see #toString()
*/
public Rdn(String type, Object value) throws InvalidNameException {
if (value == null) {
throw new NullPointerException("Cannot set value to null");
}
if (type.equals("") || isEmptyValue(value)) {
throw new InvalidNameException(
"type or value cannot be empty, type:" + type +
" value:" + value);
}
entries = new ArrayList(DEFAULT_SIZE);
put(type, value);
}
private boolean isEmptyValue(Object val) {
return ((val instanceof String) && val.equals("")) ||
((val instanceof byte[]) && (((byte[]) val).length == 0));
}
// An empty constructor used by the parser
Rdn() {
entries = new ArrayList(DEFAULT_SIZE);
}
/*
* Adds the given attribute type and value to this Rdn.
* The string attribute values are not interpretted as
* <a href="http://ietf.org/rfc/rfc2253.txt">RFC 2253</a>
* formatted RDN strings. That is the values are used
* literally (not parsed) and assumed to be unescaped.
*
* @param type The non-null and non-empty string attribute type.
* @param value The non-null and non-empty attribute value.
* @return The updated Rdn, not a new one. Cannot be null.
* @see #toString()
*/
Rdn put(String type, Object value) {
// create new Entry
RdnEntry newEntry = new RdnEntry();
newEntry.type = type;
if (value instanceof byte[]) { // clone the byte array
newEntry.value = ((byte[]) value).clone();
} else {
newEntry.value = value;
}
entries.add(newEntry);
return this;
}
void sort() {
if (entries.size() > 1) {
Collections.sort(entries);
}
}
/** {@collect.stats}
* Retrieves one of this Rdn's value.
* This is a convenience method for obtaining the value,
* when the RDN contains a single type and value mapping,
* which is the common RDN usage.
* <p>
* For a multi-valued RDN, this method returns value corresponding
* to the type returned by {@link #getType() getType()} method.
*
* @return The non-null attribute value.
*/
public Object getValue() {
return ((RdnEntry) entries.get(0)).getValue();
}
/** {@collect.stats}
* Retrieves one of this Rdn's type.
* This is a convenience method for obtaining the type,
* when the RDN contains a single type and value mapping,
* which is the common RDN usage.
* <p>
* For a multi-valued RDN, the type/value pairs have
* no specific order defined on them. In that case, this method
* returns type of one of the type/value pairs.
* The {@link #getValue() getValue()} method returns the
* value corresponding to the type returned by this method.
*
* @return The non-null attribute type.
*/
public String getType() {
return ((RdnEntry) entries.get(0)).getType();
}
/** {@collect.stats}
* Returns this Rdn as a string represented in a format defined by
* <a href="http://ietf.org//rfc/rfc2253.txt">RFC 2253</a> and described
* in the class description for {@link javax.naming.ldap.LdapName LdapName}.
*
* @return The string representation of the Rdn.
*/
public String toString() {
StringBuilder builder = new StringBuilder();
int size = entries.size();
if (size > 0) {
builder.append(entries.get(0));
}
for (int next = 1; next < size; next++) {
builder.append('+');
builder.append(entries.get(next));
}
return builder.toString();
}
/** {@collect.stats}
* Compares this Rdn with the specified Object for order.
* Returns a negative integer, zero, or a positive integer as this
* Rdn is less than, equal to, or greater than the given Object.
* <p>
* If obj is null or not an instance of Rdn, ClassCastException
* is thrown.
* <p>
* The attribute type and value pairs of the RDNs are lined up
* against each other and compared lexicographically. The order of
* components in multi-valued Rdns (such as "ou=Sales+cn=Bob") is not
* significant.
*
* @param obj The non-null object to compare against.
* @return A negative integer, zero, or a positive integer as this Rdn
* is less than, equal to, or greater than the given Object.
* @exception ClassCastException if obj is null or not a Rdn.
* <p>
*/
public int compareTo(Object obj) {
if (!(obj instanceof Rdn)) {
throw new ClassCastException("The obj is not a Rdn");
}
if (obj == this) {
return 0;
}
Rdn that = (Rdn) obj;
int minSize = Math.min(entries.size(), that.entries.size());
for (int i = 0; i < minSize; i++) {
// Compare a single pair of type/value pairs.
int diff = ((RdnEntry) entries.get(i)).compareTo(
that.entries.get(i));
if (diff != 0) {
return diff;
}
}
return (entries.size() - that.entries.size()); // longer RDN wins
}
/** {@collect.stats}
* Compares the specified Object with this Rdn for equality.
* Returns true if the given object is also a Rdn and the two Rdns
* represent the same attribute type and value mappings. The order of
* components in multi-valued Rdns (such as "ou=Sales+cn=Bob") is not
* significant.
* <p>
* Type and value equalilty matching is done as below:
* <ul>
* <li> The types are compared for equality with their case ignored.
* <li> String values with different but equivalent usage of quoting,
* escaping, or UTF8-hex-encoding are considered equal.
* The case of the values is ignored during the comparison.
* </ul>
* <p>
* If obj is null or not an instance of Rdn, false is returned.
* <p>
* @param obj object to be compared for equality with this Rdn.
* @return true if the specified object is equal to this Rdn.
* @see #hashCode()
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Rdn)) {
return false;
}
Rdn that = (Rdn) obj;
if (entries.size() != that.size()) {
return false;
}
for (int i = 0; i < entries.size(); i++) {
if (!entries.get(i).equals(that.entries.get(i))) {
return false;
}
}
return true;
}
/** {@collect.stats}
* Returns the hash code of this RDN. Two RDNs that are
* equal (according to the equals method) will have the same
* hash code.
*
* @return An int representing the hash code of this Rdn.
* @see #equals
*/
public int hashCode() {
// Sum up the hash codes of the components.
int hash = 0;
// For each type/value pair...
for (int i = 0; i < entries.size(); i++) {
hash += entries.get(i).hashCode();
}
return hash;
}
/** {@collect.stats}
* Retrieves the {@link javax.naming.directory.Attributes Attributes}
* view of the type/value mappings contained in this Rdn.
*
* @return The non-null attributes containing the type/value
* mappings of this Rdn.
*/
public Attributes toAttributes() {
Attributes attrs = new BasicAttributes(true);
for (int i = 0; i < entries.size(); i++) {
RdnEntry entry = (RdnEntry) entries.get(i);
Attribute attr = attrs.put(entry.getType(), entry.getValue());
if (attr != null) {
attr.add(entry.getValue());
attrs.put(attr);
}
}
return attrs;
}
private static class RdnEntry implements Comparable {
private String type;
private Object value;
// If non-null, a cannonical representation of the value suitable
// for comparison using String.compareTo()
private String comparable = null;
String getType() {
return type;
}
Object getValue() {
return value;
}
public int compareTo(Object obj) {
// Any change here affecting equality must be
// reflected in hashCode().
RdnEntry that = (RdnEntry) obj;
int diff = type.toUpperCase().compareTo(
that.type.toUpperCase());
if (diff != 0) {
return diff;
}
if (value.equals(that.value)) { // try shortcut
return 0;
}
return getValueComparable().compareTo(
that.getValueComparable());
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof RdnEntry)) {
return false;
}
// Any change here must be reflected in hashCode()
RdnEntry that = (RdnEntry) obj;
return (type.equalsIgnoreCase(that.type)) &&
(getValueComparable().equals(
that.getValueComparable()));
}
public int hashCode() {
return (type.toUpperCase().hashCode() +
getValueComparable().hashCode());
}
public String toString() {
return type + "=" + escapeValue(value);
}
private String getValueComparable() {
if (comparable != null) {
return comparable; // return cached result
}
// cache result
if (value instanceof byte[]) {
comparable = escapeBinaryValue((byte[]) value);
} else {
comparable = ((String) value).toUpperCase();
}
return comparable;
}
}
/** {@collect.stats}
* Retrieves the number of attribute type/value pairs in this Rdn.
* @return The non-negative number of type/value pairs in this Rdn.
*/
public int size() {
return entries.size();
}
/** {@collect.stats}
* Given the value of an attribute, returns a string escaped according
* to the rules specified in
* <a href="http://ietf.org/rfc/rfc2253.txt">RFC 2253</a>.
* <p>
* For example, if the val is "Sue, Grabbit and Runn", the escaped
* value returned by this method is "Sue\, Grabbit and Runn".
* <p>
* A string value is represented as a String and binary value
* as a byte array.
*
* @param val The non-null object to be escaped.
* @return Escaped string value.
* @throws ClassCastException if val is is not a String or byte array.
*/
public static String escapeValue(Object val) {
return (val instanceof byte[])
? escapeBinaryValue((byte[])val)
: escapeStringValue((String)val);
}
/*
* Given the value of a string-valued attribute, returns a
* string suitable for inclusion in a DN. This is accomplished by
* using backslash (\) to escape the following characters:
* leading and trailing whitespace
* , = + < > # ; " \
*/
private static final String escapees = ",=+<>#;\"\\";
private static String escapeStringValue(String val) {
char[] chars = val.toCharArray();
StringBuilder builder = new StringBuilder(2 * val.length());
// Find leading and trailing whitespace.
int lead; // index of first char that is not leading whitespace
for (lead = 0; lead < chars.length; lead++) {
if (!isWhitespace(chars[lead])) {
break;
}
}
int trail; // index of last char that is not trailing whitespace
for (trail = chars.length - 1; trail >= 0; trail--) {
if (!isWhitespace(chars[trail])) {
break;
}
}
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if ((i < lead) || (i > trail) || (escapees.indexOf(c) >= 0)) {
builder.append('\\');
}
builder.append(c);
}
return builder.toString();
}
/*
* Given the value of a binary attribute, returns a string
* suitable for inclusion in a DN (such as "#CEB1DF80").
* TBD: This method should actually generate the ber encoding
* of the binary value
*/
private static String escapeBinaryValue(byte[] val) {
StringBuilder builder = new StringBuilder(1 + 2 * val.length);
builder.append("#");
for (int i = 0; i < val.length; i++) {
byte b = val[i];
builder.append(Character.forDigit(0xF & (b >>> 4), 16));
builder.append(Character.forDigit(0xF & b, 16));
}
return builder.toString();
// return builder.toString().toUpperCase();
}
/** {@collect.stats}
* Given an attribute value string formated according to the rules
* specified in
* <a href="http://ietf.org//rfc/rfc2253.txt">RFC 2253</a>,
* returns the unformated value. Escapes and quotes are
* stripped away, and hex-encoded UTF-8 is converted to equivalent
* UTF-16 characters. Returns a string value as a String, and a
* binary value as a byte array.
* <p>
* Legal and illegal values are defined in RFC 2253.
* This method is generous in accepting the values and does not
* catch all illegal values.
* Therefore, passing in an illegal value might not necessarily
* trigger an <tt>IllegalArgumentException</tt>.
*
* @param val The non-null string to be unescaped.
* @return Unescaped value.
* @throws IllegalArgumentException When an Illegal value
* is provided.
*/
public static Object unescapeValue(String val) {
char[] chars = val.toCharArray();
int beg = 0;
int end = chars.length;
// Trim off leading and trailing whitespace.
while ((beg < end) && isWhitespace(chars[beg])) {
++beg;
}
while ((beg < end) && isWhitespace(chars[end - 1])) {
--end;
}
// Add back the trailing whitespace with a preceeding '\'
// (escaped or unescaped) that was taken off in the above
// loop. Whether or not to retain this whitespace is decided below.
if (end != chars.length &&
(beg < end) &&
chars[end - 1] == '\\') {
end++;
}
if (beg >= end) {
return "";
}
if (chars[beg] == '#') {
// Value is binary (eg: "#CEB1DF80").
return decodeHexPairs(chars, ++beg, end);
}
// Trim off quotes.
if ((chars[beg] == '\"') && (chars[end - 1] == '\"')) {
++beg;
--end;
}
StringBuilder builder = new StringBuilder(end - beg);
int esc = -1; // index of the last escaped character
for (int i = beg; i < end; i++) {
if ((chars[i] == '\\') && (i + 1 < end)) {
if (!Character.isLetterOrDigit(chars[i + 1])) {
++i; // skip backslash
builder.append(chars[i]); // snarf escaped char
esc = i;
} else {
// Convert hex-encoded UTF-8 to 16-bit chars.
byte[] utf8 = getUtf8Octets(chars, i, end);
if (utf8.length > 0) {
try {
builder.append(new String(utf8, "UTF8"));
} catch (java.io.UnsupportedEncodingException e) {
// shouldn't happen
}
i += utf8.length * 3 - 1;
} else { // no utf8 bytes available, invalid DN
// '/' has no meaning, throw exception
throw new IllegalArgumentException(
"Not a valid attribute string value:" +
val + ",improper usage of backslash");
}
}
} else {
builder.append(chars[i]); // snarf unescaped char
}
}
// Get rid of the unescaped trailing whitespace with the
// preceeding '\' character that was previously added back.
int len = builder.length();
if (isWhitespace(builder.charAt(len - 1)) && esc != (end - 1)) {
builder.setLength(len - 1);
}
return builder.toString();
}
/*
* Given an array of chars (with starting and ending indexes into it)
* representing bytes encoded as hex-pairs (such as "CEB1DF80"),
* returns a byte array containing the decoded bytes.
*/
private static byte[] decodeHexPairs(char[] chars, int beg, int end) {
byte[] bytes = new byte[(end - beg) / 2];
for (int i = 0; beg + 1 < end; i++) {
int hi = Character.digit(chars[beg], 16);
int lo = Character.digit(chars[beg + 1], 16);
if (hi < 0 || lo < 0) {
break;
}
bytes[i] = (byte)((hi<<4) + lo);
beg += 2;
}
if (beg != end) {
throw new IllegalArgumentException(
"Illegal attribute value: " + new String(chars));
}
return bytes;
}
/*
* Given an array of chars (with starting and ending indexes into it),
* finds the largest prefix consisting of hex-encoded UTF-8 octets,
* and returns a byte array containing the corresponding UTF-8 octets.
*
* Hex-encoded UTF-8 octets look like this:
* \03\B1\DF\80
*/
private static byte[] getUtf8Octets(char[] chars, int beg, int end) {
byte[] utf8 = new byte[(end - beg) / 3]; // allow enough room
int len = 0; // index of first unused byte in utf8
while ((beg + 2 < end) &&
(chars[beg++] == '\\')) {
int hi = Character.digit(chars[beg++], 16);
int lo = Character.digit(chars[beg++], 16);
if (hi < 0 || lo < 0) {
break;
}
utf8[len++] = (byte)((hi<<4) + lo);
}
if (len == utf8.length) {
return utf8;
} else {
byte[] res = new byte[len];
System.arraycopy(utf8, 0, res, 0, len);
return res;
}
}
/*
* Best guess as to what RFC 2253 means by "whitespace".
*/
private static boolean isWhitespace(char c) {
return (c == ' ' || c == '\r');
}
/** {@collect.stats}
* Serializes only the unparsed RDN, for compactness and to avoid
* any implementation dependency.
*
* @serialData The RDN string
*/
private void writeObject(ObjectOutputStream s)
throws java.io.IOException {
s.defaultWriteObject();
s.writeObject(toString());
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
entries = new ArrayList(DEFAULT_SIZE);
String unparsed = (String) s.readObject();
try {
(new Rfc2253Parser(unparsed)).parseRdn(this);
} catch (InvalidNameException e) {
// shouldn't happen
throw new java.io.StreamCorruptedException(
"Invalid name: " + unparsed);
}
}
}
|
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.naming.ldap;
import java.io.IOException;
import com.sun.jndi.ldap.Ber;
import com.sun.jndi.ldap.BerDecoder;
/** {@collect.stats}
* Indicates the end of a batch of search results.
* Contains an estimate of the total number of entries in the result set
* and an opaque cookie. The cookie must be supplied to the next search
* operation in order to get the next batch of results.
* <p>
* The code sample in {@link PagedResultsControl} shows how this class may
* be used.
* <p>
* This class implements the LDAPv3 Response Control for
* paged-results as defined in
* <a href="http://www.ietf.org/rfc/rfc2696">RFC 2696</a>.
*
* The control's value has the following ASN.1 definition:
* <pre>
*
* realSearchControlValue ::= SEQUENCE {
* size INTEGER (0..maxInt),
* -- requested page size from client
* -- result set size estimate from server
* cookie OCTET STRING
* }
*
* </pre>
*
* @since 1.5
* @see PagedResultsControl
* @author Vincent Ryan
*/
final public class PagedResultsResponseControl extends BasicControl {
/** {@collect.stats}
* The paged-results response control's assigned object identifier
* is 1.2.840.113556.1.4.319.
*/
public static final String OID = "1.2.840.113556.1.4.319";
private static final long serialVersionUID = -8819778744844514666L;
/** {@collect.stats}
* An estimate of the number of entries in the search result.
*
* @serial
*/
private int resultSize;
/** {@collect.stats}
* A server-generated cookie.
*
* @serial
*/
private byte[] cookie;
/** {@collect.stats}
* Constructs a paged-results response control.
*
* @param id The control's object identifier string.
* @param criticality The control's criticality.
* @param value The control's ASN.1 BER encoded value.
* It is not cloned - any changes to value
* will affect the contents of the control.
* @exception IOException If an error was encountered while decoding
* the control's value.
*/
public PagedResultsResponseControl(String id, boolean criticality,
byte[] value) throws IOException {
super(id, criticality, value);
// decode value
BerDecoder ber = new BerDecoder(value, 0, value.length);
ber.parseSeq(null);
resultSize = ber.parseInt();
cookie = ber.parseOctetString(Ber.ASN_OCTET_STR, null);
}
/** {@collect.stats}
* Retrieves (an estimate of) the number of entries in the search result.
*
* @return The number of entries in the search result, or zero if unknown.
*/
public int getResultSize() {
return resultSize;
}
/** {@collect.stats}
* Retrieves the server-generated cookie. Null is returned when there are
* no more entries for the server to return.
*
* @return A possibly null server-generated cookie. It is not cloned - any
* changes to the cookie will update the control's state and thus
* are not recommended.
*/
public byte[] getCookie() {
if (cookie.length == 0) {
return null;
} else {
return cookie;
}
}
}
|
Java
|
/*
* Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.ldap;
/** {@collect.stats}
* This class represents an event fired in response to an unsolicited
* notification sent by the LDAP server.
*
* @author Rosanna Lee
* @author Scott Seligman
* @author Vincent Ryan
*
* @see UnsolicitedNotification
* @see UnsolicitedNotificationListener
* @see javax.naming.event.EventContext#addNamingListener
* @see javax.naming.event.EventDirContext#addNamingListener
* @see javax.naming.event.EventContext#removeNamingListener
* @since 1.3
*/
public class UnsolicitedNotificationEvent extends java.util.EventObject {
/** {@collect.stats}
* The notification that caused this event to be fired.
* @serial
*/
private UnsolicitedNotification notice;
/** {@collect.stats}
* Constructs a new instance of <tt>UnsolicitedNotificationEvent</tt>.
*
* @param src The non-null source that fired the event.
* @param notice The non-null unsolicited notification.
*/
public UnsolicitedNotificationEvent(Object src,
UnsolicitedNotification notice) {
super(src);
this.notice = notice;
}
/** {@collect.stats}
* Returns the unsolicited notification.
* @return The non-null unsolicited notification that caused this
* event to be fired.
*/
public UnsolicitedNotification getNotification() {
return notice;
}
/** {@collect.stats}
* Invokes the <tt>notificationReceived()</tt> method on
* a listener using this event.
* @param listener The non-null listener on which to invoke
* <tt>notificationReceived</tt>.
*/
public void dispatch(UnsolicitedNotificationListener listener) {
listener.notificationReceived(this);
}
private static final long serialVersionUID = -2382603380799883705L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.ldap;
/** {@collect.stats}
* This interface represents an LDAPv3 control as defined in
* <A HREF="ftp://ftp.isi.edu/in-notes/rfc2251.txt">RFC 2251</A>.
*<p>
* The LDAPv3 protocol uses controls to send and receive additional data
* to affect the behavior of predefined operations.
* Controls can be sent along with any LDAP operation to the server.
* These are referred to as <em>request controls</em>. For example, a
* "sort" control can be sent with an LDAP search operation to
* request that the results be returned in a particular order.
* Solicited and unsolicited controls can also be returned with
* responses from the server. Such controls are referred to as
* <em>response controls</em>. For example, an LDAP server might
* define a special control to return change notifications.
*<p>
* This interface is used to represent both request and response controls.
*
* @author Rosanna Lee
* @author Scott Seligman
* @author Vincent Ryan
*
* @see ControlFactory
* @since 1.3
*/
public interface Control extends java.io.Serializable {
/** {@collect.stats}
* Indicates a critical control.
* The value of this constant is <tt>true</tt>.
*/
public static final boolean CRITICAL = true;
/** {@collect.stats}
* Indicates a non-critical control.
* The value of this constant is <tt>false</tt>.
*/
public static final boolean NONCRITICAL = false;
/** {@collect.stats}
* Retrieves the object identifier assigned for the LDAP control.
*
* @return The non-null object identifier string.
*/
public String getID();
/** {@collect.stats}
* Determines the criticality of the LDAP control.
* A critical control must not be ignored by the server.
* In other words, if the server receives a critical control
* that it does not support, regardless of whether the control
* makes sense for the operation, the operation will not be performed
* and an <tt>OperationNotSupportedException</tt> will be thrown.
* @return true if this control is critical; false otherwise.
*/
public boolean isCritical();
/** {@collect.stats}
* Retrieves the ASN.1 BER encoded value of the LDAP control.
* The result is the raw BER bytes including the tag and length of
* the control's value. It does not include the controls OID or criticality.
*
* Null is returned if the value is absent.
*
* @return A possibly null byte array representing the ASN.1 BER encoded
* value of the LDAP control.
*/
public byte[] getEncodedValue();
// static final long serialVersionUID = -591027748900004825L;
}
|
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.naming.ldap;
/** {@collect.stats}
* This class provides a basic implementation of the <tt>Control</tt>
* interface. It represents an LDAPv3 Control as defined in
* <a href="http://www.ietf.org/rfc/rfc2251.txt">RFC 2251</a>.
*
* @since 1.5
* @author Vincent Ryan
*/
public class BasicControl implements Control {
/** {@collect.stats}
* The control's object identifier string.
*
* @serial
*/
protected String id;
/** {@collect.stats}
* The control's criticality.
*
* @serial
*/
protected boolean criticality = false; // default
/** {@collect.stats}
* The control's ASN.1 BER encoded value.
*
* @serial
*/
protected byte[] value = null;
private static final long serialVersionUID = -4233907508771791687L;
/** {@collect.stats}
* Constructs a non-critical control.
*
* @param id The control's object identifier string.
*
*/
public BasicControl(String id) {
this.id = id;
}
/** {@collect.stats}
* Constructs a control using the supplied arguments.
*
* @param id The control's object identifier string.
* @param criticality The control's criticality.
* @param value The control's ASN.1 BER encoded value.
* It is not cloned - any changes to value
* will affect the contents of the control.
* It may be null.
*/
public BasicControl(String id, boolean criticality, byte[] value) {
this.id = id;
this.criticality = criticality;
this.value = value;
}
/** {@collect.stats}
* Retrieves the control's object identifier string.
*
* @return The non-null object identifier string.
*/
public String getID() {
return id;
}
/** {@collect.stats}
* Determines the control's criticality.
*
* @return true if the control is critical; false otherwise.
*/
public boolean isCritical() {
return criticality;
}
/** {@collect.stats}
* Retrieves the control's ASN.1 BER encoded value.
* The result includes the BER tag and length for the control's value but
* does not include the control's object identifier and criticality setting.
*
* @return A possibly null byte array representing the control's
* ASN.1 BER encoded value. It is not cloned - any changes to the
* returned value will affect the contents of the control.
*/
public byte[] getEncodedValue() {
return value;
}
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.ldap;
import javax.naming.NamingException;
/** {@collect.stats}
* This interface represents an unsolicited notification as defined in
* <A HREF="ftp://ftp.isi.edu/in-notes/rfc2251.txt">RFC 2251</A>.
* An unsolicited notification is sent by the LDAP server to the LDAP
* client without any provocation from the client.
* Its format is that of an extended response (<tt>ExtendedResponse</tt>).
*
* @author Rosanna Lee
* @author Scott Seligman
* @author Vincent Ryan
*
* @see ExtendedResponse
* @see UnsolicitedNotificationEvent
* @see UnsolicitedNotificationListener
* @since 1.3
*/
public interface UnsolicitedNotification extends ExtendedResponse, HasControls {
/** {@collect.stats}
* Retrieves the referral(s) sent by the server.
*
* @return A possibly null array of referrals, each of which is represented
* by a URL string. If null, no referral was sent by the server.
*/
public String[] getReferrals();
/** {@collect.stats}
* Retrieves the exception as constructed using information
* sent by the server.
* @return A possibly null exception as constructed using information
* sent by the server. If null, a "success" status was indicated by
* the server.
*/
public NamingException getException();
}
|
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.naming.ldap;
import javax.naming.Name;
import javax.naming.InvalidNameException;
import java.util.Enumeration;
import java.util.Collection;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collections;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* This class represents a distinguished name as specified by
* <a href="http://ietf.org//rfc/rfc2253.txt">RFC 2253</a>.
* A distinguished name, or DN, is composed of an ordered list of
* components called <em>relative distinguished name</em>s, or RDNs.
* Details of a DN's syntax are described in RFC 2253.
*<p>
* This class resolves a few ambiguities found in RFC 2253
* as follows:
* <ul>
* <li> RFC 2253 leaves the term "whitespace" undefined. The
* ASCII space character 0x20 (" ") is used in its place.
* <li> Whitespace is allowed on either side of ',', ';', '=', and '+'.
* Such whitespace is accepted but not generated by this code,
* and is ignored when comparing names.
* <li> AttributeValue strings containing '=' or non-leading '#'
* characters (unescaped) are accepted.
* </ul>
*<p>
* String names passed to <code>LdapName</code> or returned by it
* use the full Unicode character set. They may also contain
* characters encoded into UTF-8 with each octet represented by a
* three-character substring such as "\\B4".
* They may not, however, contain characters encoded into UTF-8 with
* each octet represented by a single character in the string: the
* meaning would be ambiguous.
*<p>
* <code>LdapName</code> will properly parse all valid names, but
* does not attempt to detect all possible violations when parsing
* invalid names. It is "generous" in accepting invalid names.
* The "validity" of a name is determined ultimately when it
* is supplied to an LDAP server, which may accept or
* reject the name based on factors such as its schema information
* and interoperability considerations.
*<p>
* When names are tested for equality, attribute types, both binary
* and string values, are case-insensitive.
* String values with different but equivalent usage of quoting,
* escaping, or UTF8-hex-encoding are considered equal. The order of
* components in multi-valued RDNs (such as "ou=Sales+cn=Bob") is not
* significant.
* <p>
* The components of a LDAP name, that is, RDNs, are numbered. The
* indexes of a LDAP name with n RDNs range from 0 to n-1.
* This range may be written as [0,n).
* The right most RDN is at index 0, and the left most RDN is at
* index n-1. For example, the distinguished name:
* "CN=Steve Kille, O=Isode Limited, C=GB" is numbered in the following
* sequence ranging from 0 to 2: {C=GB, O=Isode Limited, CN=Steve Kille}. An
* empty LDAP name is represented by an empty RDN list.
*<p>
* Concurrent multithreaded read-only access of an instance of
* <tt>LdapName</tt> need not be synchronized.
*<p>
* Unless otherwise noted, the behavior of passing a null argument
* to a constructor or method in this class will cause a
* NullPointerException to be thrown.
*
* @author Scott Seligman
* @since 1.5
*/
public class LdapName implements Name {
// private transient ArrayList<Rdn> rdns; // parsed name components
private transient ArrayList rdns; // parsed name components
private transient String unparsed; // if non-null, the DN in unparsed form
private static final long serialVersionUID = -1595520034788997356L;
/** {@collect.stats}
* Constructs an LDAP name from the given distinguished name.
*
* @param name This is a non-null distinguished name formatted
* according to the rules defined in
* <a href="http://ietf.org/rfc/rfc2253.txt">RFC 2253</a>.
*
* @throws InvalidNameException if a syntax violation is detected.
* @see Rdn#escapeValue(Object value)
*/
public LdapName(String name) throws InvalidNameException {
unparsed = name;
parse();
}
/** {@collect.stats}
* Constructs an LDAP name given its parsed RDN components.
* <p>
* The indexing of RDNs in the list follows the numbering of
* RDNs described in the class description.
*
* @param rdns The non-null list of <tt>Rdn</tt>s forming this LDAP name.
*/
public LdapName(List<Rdn> rdns) {
// if (rdns instanceof ArrayList<Rdn>) {
// this.rdns = rdns.clone();
// } else if (rdns instanceof List<Rdn>) {
// this.rdns = new ArrayList<Rdn>(rdns);
// } else {
// throw IllegalArgumentException(
// "Invalid entries, list entries must be of type Rdn");
// }
this.rdns = new ArrayList(rdns.size());
for (int i = 0; i < rdns.size(); i++) {
Object obj = rdns.get(i);
if (!(obj instanceof Rdn)) {
throw new IllegalArgumentException("Entry:" + obj +
" not a valid type;list entries must be of type Rdn");
}
this.rdns.add(obj);
}
}
/*
* Constructs an LDAP name given its parsed components (the elements
* of "rdns" in the range [beg,end)) and, optionally
* (if "name" is not null), the unparsed DN.
*
*/
// private LdapName(String name, List<Rdn> rdns, int beg, int end) {
private LdapName(String name, ArrayList rdns, int beg, int end) {
unparsed = name;
// this.rdns = rdns.subList(beg, end);
List sList = rdns.subList(beg, end);
this.rdns = new ArrayList(sList);
}
/** {@collect.stats}
* Retrieves the number of components in this LDAP name.
* @return The non-negative number of components in this LDAP name.
*/
public int size() {
return rdns.size();
}
/** {@collect.stats}
* Determines whether this LDAP name is empty.
* An empty name is one with zero components.
* @return true if this LDAP name is empty, false otherwise.
*/
public boolean isEmpty() {
return rdns.isEmpty();
}
/** {@collect.stats}
* Retrieves the components of this name as an enumeration
* of strings. The effect of updates to this name on this enumeration
* is undefined. If the name has zero components, an empty (non-null)
* enumeration is returned.
* The order of the components returned by the enumeration is same as
* the order in which the components are numbered as described in the
* class description.
*
* @return A non-null enumeration of the components of this LDAP name.
* Each element of the enumeration is of class String.
*/
public Enumeration<String> getAll() {
final Iterator iter = rdns.iterator();
return new Enumeration<String>() {
public boolean hasMoreElements() {
return iter.hasNext();
}
public String nextElement() {
return iter.next().toString();
}
};
}
/** {@collect.stats}
* Retrieves a component of this LDAP name as a string.
* @param posn The 0-based index of the component to retrieve.
* Must be in the range [0,size()).
* @return The non-null component at index posn.
* @exception IndexOutOfBoundsException if posn is outside the
* specified range.
*/
public String get(int posn) {
return rdns.get(posn).toString();
}
/** {@collect.stats}
* Retrieves an RDN of this LDAP name as an Rdn.
* @param posn The 0-based index of the RDN to retrieve.
* Must be in the range [0,size()).
* @return The non-null RDN at index posn.
* @exception IndexOutOfBoundsException if posn is outside the
* specified range.
*/
public Rdn getRdn(int posn) {
return (Rdn) rdns.get(posn);
}
/** {@collect.stats}
* Creates a name whose components consist of a prefix of the
* components of this LDAP name.
* Subsequent changes to this name will not affect the name
* that is returned and vice versa.
* @param posn The 0-based index of the component at which to stop.
* Must be in the range [0,size()].
* @return An instance of <tt>LdapName</tt> consisting of the
* components at indexes in the range [0,posn).
* If posn is zero, an empty LDAP name is returned.
* @exception IndexOutOfBoundsException
* If posn is outside the specified range.
*/
public Name getPrefix(int posn) {
try {
return new LdapName(null, rdns, 0, posn);
} catch (IllegalArgumentException e) {
throw new IndexOutOfBoundsException(
"Posn: " + posn + ", Size: "+ rdns.size());
}
}
/** {@collect.stats}
* Creates a name whose components consist of a suffix of the
* components in this LDAP name.
* Subsequent changes to this name do not affect the name that is
* returned and vice versa.
*
* @param posn The 0-based index of the component at which to start.
* Must be in the range [0,size()].
* @return An instance of <tt>LdapName</tt> consisting of the
* components at indexes in the range [posn,size()).
* If posn is equal to size(), an empty LDAP name is
* returned.
* @exception IndexOutOfBoundsException
* If posn is outside the specified range.
*/
public Name getSuffix(int posn) {
try {
return new LdapName(null, rdns, posn, rdns.size());
} catch (IllegalArgumentException e) {
throw new IndexOutOfBoundsException(
"Posn: " + posn + ", Size: "+ rdns.size());
}
}
/** {@collect.stats}
* Determines whether this LDAP name starts with a specified LDAP name
* prefix.
* A name <tt>n</tt> is a prefix if it is equal to
* <tt>getPrefix(n.size())</tt>--in other words this LDAP
* name starts with 'n'. If n is null or not a RFC2253 formatted name
* as described in the class description, false is returned.
*
* @param n The LDAP name to check.
* @return true if <tt>n</tt> is a prefix of this LDAP name,
* false otherwise.
* @see #getPrefix(int posn)
*/
public boolean startsWith(Name n) {
if (n == null) {
return false;
}
int len1 = rdns.size();
int len2 = n.size();
return (len1 >= len2 &&
matches(0, len2, n));
}
/** {@collect.stats}
* Determines whether the specified RDN sequence forms a prefix of this
* LDAP name. Returns true if this LdapName is at least as long as rdns,
* and for every position p in the range [0, rdns.size()) the component
* getRdn(p) matches rdns.get(p). Returns false otherwise. If rdns is
* null, false is returned.
*
* @param rdns The sequence of <tt>Rdn</tt>s to check.
* @return true if <tt>rdns</tt> form a prefix of this LDAP name,
* false otherwise.
*/
public boolean startsWith(List<Rdn> rdns) {
if (rdns == null) {
return false;
}
int len1 = this.rdns.size();
int len2 = rdns.size();
return (len1 >= len2 &&
doesListMatch(0, len2, rdns));
}
/** {@collect.stats}
* Determines whether this LDAP name ends with a specified
* LDAP name suffix.
* A name <tt>n</tt> is a suffix if it is equal to
* <tt>getSuffix(size()-n.size())</tt>--in other words this LDAP
* name ends with 'n'. If n is null or not a RFC2253 formatted name
* as described in the class description, false is returned.
*
* @param n The LDAP name to check.
* @return true if <tt>n</tt> is a suffix of this name, false otherwise.
* @see #getSuffix(int posn)
*/
public boolean endsWith(Name n) {
if (n == null) {
return false;
}
int len1 = rdns.size();
int len2 = n.size();
return (len1 >= len2 &&
matches(len1 - len2, len1, n));
}
/** {@collect.stats}
* Determines whether the specified RDN sequence forms a suffix of this
* LDAP name. Returns true if this LdapName is at least as long as rdns,
* and for every position p in the range [size() - rdns.size(), size())
* the component getRdn(p) matches rdns.get(p). Returns false otherwise.
* If rdns is null, false is returned.
*
* @param rdns The sequence of <tt>Rdn</tt>s to check.
* @return true if <tt>rdns</tt> form a suffix of this LDAP name,
* false otherwise.
*/
public boolean endsWith(List<Rdn> rdns) {
if (rdns == null) {
return false;
}
int len1 = this.rdns.size();
int len2 = rdns.size();
return (len1 >= len2 &&
doesListMatch(len1 - len2, len1, rdns));
}
private boolean doesListMatch(int beg, int end, List rdns) {
for (int i = beg; i < end; i++) {
if (!this.rdns.get(i).equals(rdns.get(i - beg))) {
return false;
}
}
return true;
}
/*
* Helper method for startsWith() and endsWith().
* Returns true if components [beg,end) match the components of "n".
* If "n" is not an LdapName, each of its components is parsed as
* the string form of an RDN.
* The following must hold: end - beg == n.size().
*/
private boolean matches(int beg, int end, Name n) {
if (n instanceof LdapName) {
LdapName ln = (LdapName) n;
return doesListMatch(beg, end, ln.rdns);
} else {
for (int i = beg; i < end; i++) {
Rdn rdn;
String rdnString = n.get(i - beg);
try {
rdn = (new Rfc2253Parser(rdnString)).parseRdn();
} catch (InvalidNameException e) {
return false;
}
if (!rdn.equals(rdns.get(i))) {
return false;
}
}
}
return true;
}
/** {@collect.stats}
* Adds the components of a name -- in order -- to the end of this name.
*
* @param suffix The non-null components to add.
* @return The updated name (not a new instance).
*
* @throws InvalidNameException if <tt>suffix</tt> is not a valid LDAP
* name, or if the addition of the components would violate the
* syntax rules of this LDAP name.
*/
public Name addAll(Name suffix) throws InvalidNameException {
return addAll(size(), suffix);
}
/** {@collect.stats}
* Adds the RDNs of a name -- in order -- to the end of this name.
*
* @param suffixRdns The non-null suffix <tt>Rdn</tt>s to add.
* @return The updated name (not a new instance).
*/
public Name addAll(List<Rdn> suffixRdns) {
return addAll(size(), suffixRdns);
}
/** {@collect.stats}
* Adds the components of a name -- in order -- at a specified position
* within this name. Components of this LDAP name at or after the
* index (if any) of the first new component are shifted up
* (away from index 0) to accomodate the new components.
*
* @param suffix The non-null components to add.
* @param posn The index at which to add the new component.
* Must be in the range [0,size()].
*
* @return The updated name (not a new instance).
*
* @throws InvalidNameException if <tt>suffix</tt> is not a valid LDAP
* name, or if the addition of the components would violate the
* syntax rules of this LDAP name.
* @throws IndexOutOfBoundsException.
* If posn is outside the specified range.
*/
public Name addAll(int posn, Name suffix)
throws InvalidNameException {
unparsed = null; // no longer valid
if (suffix instanceof LdapName) {
LdapName s = (LdapName) suffix;
rdns.addAll(posn, s.rdns);
} else {
Enumeration comps = suffix.getAll();
while (comps.hasMoreElements()) {
rdns.add(posn++,
(new Rfc2253Parser((String) comps.nextElement()).
parseRdn()));
}
}
return this;
}
/** {@collect.stats}
* Adds the RDNs of a name -- in order -- at a specified position
* within this name. RDNs of this LDAP name at or after the
* index (if any) of the first new RDN are shifted up (away from index 0) to
* accomodate the new RDNs.
*
* @param suffixRdns The non-null suffix <tt>Rdn</tt>s to add.
* @param posn The index at which to add the suffix RDNs.
* Must be in the range [0,size()].
*
* @return The updated name (not a new instance).
* @throws IndexOutOfBoundsException.
* If posn is outside the specified range.
*/
public Name addAll(int posn, List<Rdn> suffixRdns) {
unparsed = null;
for (int i = 0; i < suffixRdns.size(); i++) {
Object obj = suffixRdns.get(i);
if (!(obj instanceof Rdn)) {
throw new IllegalArgumentException("Entry:" + obj +
" not a valid type;suffix list entries must be of type Rdn");
}
rdns.add(i + posn, obj);
}
return this;
}
/** {@collect.stats}
* Adds a single component to the end of this LDAP name.
*
* @param comp The non-null component to add.
* @return The updated LdapName, not a new instance.
* Cannot be null.
* @exception InvalidNameException If adding comp at end of the name
* would violate the name's syntax.
*/
public Name add(String comp) throws InvalidNameException {
return add(size(), comp);
}
/** {@collect.stats}
* Adds a single RDN to the end of this LDAP name.
*
* @param comp The non-null RDN to add.
*
* @return The updated LdapName, not a new instance.
* Cannot be null.
*/
public Name add(Rdn comp) {
return add(size(), comp);
}
/** {@collect.stats}
* Adds a single component at a specified position within this
* LDAP name.
* Components of this LDAP name at or after the index (if any) of the new
* component are shifted up by one (away from index 0) to accommodate
* the new component.
*
* @param comp The non-null component to add.
* @param posn The index at which to add the new component.
* Must be in the range [0,size()].
* @return The updated LdapName, not a new instance.
* Cannot be null.
* @exception IndexOutOfBoundsException.
* If posn is outside the specified range.
* @exception InvalidNameException If adding comp at the
* specified position would violate the name's syntax.
*/
public Name add(int posn, String comp) throws InvalidNameException {
Rdn rdn = (new Rfc2253Parser(comp)).parseRdn();
rdns.add(posn, rdn);
unparsed = null; // no longer valid
return this;
}
/** {@collect.stats}
* Adds a single RDN at a specified position within this
* LDAP name.
* RDNs of this LDAP name at or after the index (if any) of the new
* RDN are shifted up by one (away from index 0) to accommodate
* the new RDN.
*
* @param comp The non-null RDN to add.
* @param posn The index at which to add the new RDN.
* Must be in the range [0,size()].
* @return The updated LdapName, not a new instance.
* Cannot be null.
* @exception IndexOutOfBoundsException
* If posn is outside the specified range.
*/
public Name add(int posn, Rdn comp) {
if (comp == null) {
throw new NullPointerException("Cannot set comp to null");
}
rdns.add(posn, comp);
unparsed = null; // no longer valid
return this;
}
/** {@collect.stats}
* Removes a component from this LDAP name.
* The component of this name at the specified position is removed.
* Components with indexes greater than this position (if any)
* are shifted down (toward index 0) by one.
*
* @param posn The index of the component to remove.
* Must be in the range [0,size()).
* @return The component removed (a String).
*
* @throws IndexOutOfBoundsException
* if posn is outside the specified range.
* @throws InvalidNameException if deleting the component
* would violate the syntax rules of the name.
*/
public Object remove(int posn) throws InvalidNameException {
unparsed = null; // no longer valid
return rdns.remove(posn).toString();
}
/** {@collect.stats}
* Retrieves the list of relative distinguished names.
* The contents of the list are unmodifiable.
* The indexing of RDNs in the returned list follows the numbering of
* RDNs as described in the class description.
* If the name has zero components, an empty list is returned.
*
* @return The name as a list of RDNs which are instances of
* the class {@link Rdn Rdn}.
*/
public List<Rdn> getRdns() {
return Collections.unmodifiableList(rdns);
}
/** {@collect.stats}
* Generates a new copy of this name.
* Subsequent changes to the components of this name will not
* affect the new copy, and vice versa.
*
* @return A copy of the this LDAP name.
*/
public Object clone() {
return new LdapName(unparsed, rdns, 0, rdns.size());
}
/** {@collect.stats}
* Returns a string representation of this LDAP name in a format
* defined by <a href="http://ietf.org/rfc/rfc2253.txt">RFC 2253</a>
* and described in the class description. If the name has zero
* components an empty string is returned.
*
* @return The string representation of the LdapName.
*/
public String toString() {
if (unparsed != null) {
return unparsed;
}
StringBuilder builder = new StringBuilder();
int size = rdns.size();
if ((size - 1) >= 0) {
builder.append((Rdn) rdns.get(size - 1));
}
for (int next = size - 2; next >= 0; next--) {
builder.append(',');
builder.append((Rdn) rdns.get(next));
}
unparsed = builder.toString();
return unparsed;
}
/** {@collect.stats}
* Determines whether two LDAP names are equal.
* If obj is null or not an LDAP name, false is returned.
* <p>
* Two LDAP names are equal if each RDN in one is equal
* to the corresponding RDN in the other. This implies
* both have the same number of RDNs, and each RDN's
* equals() test against the corresponding RDN in the other
* name returns true. See {@link Rdn#equals(Object obj)}
* for a definition of RDN equality.
*
* @param obj The possibly null object to compare against.
* @return true if obj is equal to this LDAP name,
* false otherwise.
* @see #hashCode
*/
public boolean equals(Object obj) {
// check possible shortcuts
if (obj == this) {
return true;
}
if (!(obj instanceof LdapName)) {
return false;
}
LdapName that = (LdapName) obj;
if (rdns.size() != that.rdns.size()) {
return false;
}
if (unparsed != null && unparsed.equalsIgnoreCase(
that.unparsed)) {
return true;
}
// Compare RDNs one by one for equality
for (int i = 0; i < rdns.size(); i++) {
// Compare a single pair of RDNs.
Rdn rdn1 = (Rdn) rdns.get(i);
Rdn rdn2 = (Rdn) that.rdns.get(i);
if (!rdn1.equals(rdn2)) {
return false;
}
}
return true;
}
/** {@collect.stats}
* Compares this LdapName with the specified Object for order.
* Returns a negative integer, zero, or a positive integer as this
* Name is less than, equal to, or greater than the given Object.
* <p>
* If obj is null or not an instance of LdapName, ClassCastException
* is thrown.
* <p>
* Ordering of LDAP names follows the lexicographical rules for
* string comparison, with the extension that this applies to all
* the RDNs in the LDAP name. All the RDNs are lined up in their
* specified order and compared lexicographically.
* See {@link Rdn#compareTo(Object obj) Rdn.compareTo(Object obj)}
* for RDN comparison rules.
* <p>
* If this LDAP name is lexicographically lesser than obj,
* a negative number is returned.
* If this LDAP name is lexicographically greater than obj,
* a positive number is returned.
* @param obj The non-null LdapName instance to compare against.
*
* @return A negative integer, zero, or a positive integer as this Name
* is less than, equal to, or greater than the given obj.
* @exception ClassCastException if obj is null or not a LdapName.
*/
public int compareTo(Object obj) {
if (!(obj instanceof LdapName)) {
throw new ClassCastException("The obj is not a LdapName");
}
// check possible shortcuts
if (obj == this) {
return 0;
}
LdapName that = (LdapName) obj;
if (unparsed != null && unparsed.equalsIgnoreCase(
that.unparsed)) {
return 0;
}
// Compare RDNs one by one, lexicographically.
int minSize = Math.min(rdns.size(), that.rdns.size());
for (int i = 0; i < minSize; i++) {
// Compare a single pair of RDNs.
Rdn rdn1 = (Rdn)rdns.get(i);
Rdn rdn2 = (Rdn)that.rdns.get(i);
int diff = rdn1.compareTo(rdn2);
if (diff != 0) {
return diff;
}
}
return (rdns.size() - that.rdns.size()); // longer DN wins
}
/** {@collect.stats}
* Computes the hash code of this LDAP name.
* The hash code is the sum of the hash codes of individual RDNs
* of this name.
*
* @return An int representing the hash code of this name.
* @see #equals
*/
public int hashCode() {
// Sum up the hash codes of the components.
int hash = 0;
// For each RDN...
for (int i = 0; i < rdns.size(); i++) {
Rdn rdn = (Rdn) rdns.get(i);
hash += rdn.hashCode();
}
return hash;
}
/** {@collect.stats}
* Serializes only the unparsed DN, for compactness and to avoid
* any implementation dependency.
*
* @serialData The DN string
*/
private void writeObject(ObjectOutputStream s)
throws java.io.IOException {
s.defaultWriteObject();
s.writeObject(toString());
}
private void readObject(ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
unparsed = (String)s.readObject();
try {
parse();
} catch (InvalidNameException e) {
// shouldn't happen
throw new java.io.StreamCorruptedException(
"Invalid name: " + unparsed);
}
}
private void parse() throws InvalidNameException {
// rdns = (ArrayList<Rdn>) (new RFC2253Parser(unparsed)).getDN();
rdns = (ArrayList) (new Rfc2253Parser(unparsed)).parseDn();
}
}
|
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.naming.ldap;
/** {@collect.stats}
* Requests that referral and other special LDAP objects be manipulated
* as normal LDAP objects. It enables the requestor to interrogate or
* update such objects.
*<p>
* This class implements the LDAPv3 Request Control for ManageDsaIT
* as defined in
* <a href="http://www.ietf.org/rfc/rfc3296.txt">RFC 3296</a>.
*
* The control has no control value.
*
* @since 1.5
* @author Vincent Ryan
*/
final public class ManageReferralControl extends BasicControl {
/** {@collect.stats}
* The ManageReferral control's assigned object identifier
* is 2.16.840.1.113730.3.4.2.
*/
public static final String OID = "2.16.840.1.113730.3.4.2";
private static final long serialVersionUID = 3017756160149982566L;
/** {@collect.stats}
* Constructs a critical ManageReferral control.
*/
public ManageReferralControl() {
super(OID, true, null);
}
/** {@collect.stats}
* Constructs a ManageReferral control.
*
* @param criticality The control's criticality setting.
*/
public ManageReferralControl(boolean criticality) {
super(OID, criticality, null);
}
}
|
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.naming.ldap;
import java.io.IOException;
import javax.naming.*;
import javax.naming.directory.*;
import com.sun.jndi.ldap.Ber;
import com.sun.jndi.ldap.BerDecoder;
import com.sun.jndi.ldap.LdapCtx;
/** {@collect.stats}
* Indicates whether the requested sort of search results was successful or not.
* When the result code indicates success then the results have been sorted as
* requested. Otherwise the sort was unsuccessful and additional details
* regarding the cause of the error may have been provided by the server.
* <p>
* The code sample in {@link SortControl} shows how this class may be used.
* <p>
* This class implements the LDAPv3 Response Control for server-side sorting
* as defined in
* <a href="http://www.ietf.org/rfc/rfc2891.txt">RFC 2891</a>.
*
* The control's value has the following ASN.1 definition:
* <pre>
*
* SortResult ::= SEQUENCE {
* sortResult ENUMERATED {
* success (0), -- results are sorted
* operationsError (1), -- server internal failure
* timeLimitExceeded (3), -- timelimit reached before
* -- sorting was completed
* strongAuthRequired (8), -- refused to return sorted
* -- results via insecure
* -- protocol
* adminLimitExceeded (11), -- too many matching entries
* -- for the server to sort
* noSuchAttribute (16), -- unrecognized attribute
* -- type in sort key
* inappropriateMatching (18), -- unrecognized or inappro-
* -- priate matching rule in
* -- sort key
* insufficientAccessRights (50), -- refused to return sorted
* -- results to this client
* busy (51), -- too busy to process
* unwillingToPerform (53), -- unable to sort
* other (80)
* },
* attributeType [0] AttributeType OPTIONAL }
*
* </pre>
*
* @since 1.5
* @see SortControl
* @author Vincent Ryan
*/
final public class SortResponseControl extends BasicControl {
/** {@collect.stats}
* The server-side sort response control's assigned object identifier
* is 1.2.840.113556.1.4.474.
*/
public static final String OID = "1.2.840.113556.1.4.474";
private static final long serialVersionUID = 5142939176006310877L;
/** {@collect.stats}
* The sort result code.
*
* @serial
*/
private int resultCode = 0;
/** {@collect.stats}
* The ID of the attribute that caused the sort to fail.
*
* @serial
*/
private String badAttrId = null;
/** {@collect.stats}
* Constructs a control to indicate the outcome of a sort request.
*
* @param id The control's object identifier string.
* @param criticality The control's criticality.
* @param value The control's ASN.1 BER encoded value.
* It is not cloned - any changes to value
* will affect the contents of the control.
* @exception IOException if an error is encountered
* while decoding the control's value.
*/
public SortResponseControl(String id, boolean criticality, byte[] value)
throws IOException {
super(id, criticality, value);
// decode value
BerDecoder ber = new BerDecoder(value, 0, value.length);
ber.parseSeq(null);
resultCode = ber.parseEnumeration();
if ((ber.bytesLeft() > 0) && (ber.peekByte() == Ber.ASN_CONTEXT)) {
badAttrId = ber.parseStringWithTag(Ber.ASN_CONTEXT, true, null);
}
}
/** {@collect.stats}
* Determines if the search results have been successfully sorted.
* If an error occurred during sorting a NamingException is thrown.
*
* @return true if the search results have been sorted.
*/
public boolean isSorted() {
return (resultCode == 0); // a result code of zero indicates success
}
/** {@collect.stats}
* Retrieves the LDAP result code of the sort operation.
*
* @return The result code. A zero value indicates success.
*/
public int getResultCode() {
return resultCode;
}
/** {@collect.stats}
* Retrieves the ID of the attribute that caused the sort to fail.
* Returns null if no ID was returned by the server.
*
* @return The possibly null ID of the bad attribute.
*/
public String getAttributeID() {
return badAttrId;
}
/** {@collect.stats}
* Retrieves the NamingException appropriate for the result code.
*
* @return A NamingException or null if the result code indicates
* success.
*/
public NamingException getException() {
return LdapCtx.mapErrorCode(resultCode, null);
}
}
|
Java
|
/*
* Copyright (c) 1999, 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.naming;
import java.util.Vector;
import java.util.Enumeration;
/** {@collect.stats}
* This class represents a reference to an object that is found outside of
* the naming/directory system.
*<p>
* Reference provides a way of recording address information about
* objects which themselves are not directly bound to the naming/directory system.
*<p>
* A Reference consists of an ordered list of addresses and class information
* about the object being referenced.
* Each address in the list identifies a communications endpoint
* for the same conceptual object. The "communications endpoint"
* is information that indicates how to contact the object. It could
* be, for example, a network address, a location in memory on the
* local machine, another process on the same machine, etc.
* The order of the addresses in the list may be of significance
* to object factories that interpret the reference.
*<p>
* Multiple addresses may arise for
* various reasons, such as replication or the object offering interfaces
* over more than one communication mechanism. The addresses are indexed
* starting with zero.
*<p>
* A Reference also contains information to assist in creating an instance
* of the object to which this Reference refers. It contains the class name
* of that object, and the class name and location of the factory to be used
* to create the object.
* The class factory location is a space-separated list of URLs representing
* the class path used to load the factory. When the factory class (or
* any class or resource upon which it depends) needs to be loaded,
* each URL is used (in order) to attempt to load the class.
*<p>
* A Reference instance is not synchronized against concurrent access by multiple
* threads. Threads that need to access a single Reference concurrently should
* synchronize amongst themselves and provide the necessary locking.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see RefAddr
* @see StringRefAddr
* @see BinaryRefAddr
* @since 1.3
*/
/*<p>
* The serialized form of a Reference object consists of the class
* name of the object being referenced (a String), a Vector of the
* addresses (each a RefAddr), the name of the class factory (a
* String), and the location of the class factory (a String).
*/
public class Reference implements Cloneable, java.io.Serializable {
/** {@collect.stats}
* Contains the fully-qualified name of the class of the object to which
* this Reference refers.
* @serial
* @see java.lang.Class#getName
*/
protected String className;
/** {@collect.stats}
* Contains the addresses contained in this Reference.
* Initialized by constructor.
* @serial
*/
protected Vector<RefAddr> addrs = null;
/** {@collect.stats}
* Contains the name of the factory class for creating
* an instance of the object to which this Reference refers.
* Initialized to null.
* @serial
*/
protected String classFactory = null;
/** {@collect.stats}
* Contains the location of the factory class.
* Initialized to null.
* @serial
*/
protected String classFactoryLocation = null;
/** {@collect.stats}
* Constructs a new reference for an object with class name 'className'.
* Class factory and class factory location are set to null.
* The newly created reference contains zero addresses.
*
* @param className The non-null class name of the object to which
* this reference refers.
*/
public Reference(String className) {
this.className = className;
addrs = new Vector();
}
/** {@collect.stats}
* Constructs a new reference for an object with class name 'className' and
* an address.
* Class factory and class factory location are set to null.
*
* @param className The non-null class name of the object to
* which this reference refers.
* @param addr The non-null address of the object.
*/
public Reference(String className, RefAddr addr) {
this.className = className;
addrs = new Vector();
addrs.addElement(addr);
}
/** {@collect.stats}
* Constructs a new reference for an object with class name 'className',
* and the class name and location of the object's factory.
*
* @param className The non-null class name of the object to which
* this reference refers.
* @param factory The possibly null class name of the object's factory.
* @param factoryLocation
* The possibly null location from which to load
* the factory (e.g. URL)
* @see javax.naming.spi.ObjectFactory
* @see javax.naming.spi.NamingManager#getObjectInstance
*/
public Reference(String className, String factory, String factoryLocation) {
this(className);
classFactory = factory;
classFactoryLocation = factoryLocation;
}
/** {@collect.stats}
* Constructs a new reference for an object with class name 'className',
* the class name and location of the object's factory, and the address for
* the object.
*
* @param className The non-null class name of the object to
* which this reference refers.
* @param factory The possibly null class name of the object's factory.
* @param factoryLocation The possibly null location from which
* to load the factory (e.g. URL)
* @param addr The non-null address of the object.
* @see javax.naming.spi.ObjectFactory
* @see javax.naming.spi.NamingManager#getObjectInstance
*/
public Reference(String className, RefAddr addr,
String factory, String factoryLocation) {
this(className, addr);
classFactory = factory;
classFactoryLocation = factoryLocation;
}
/** {@collect.stats}
* Retrieves the class name of the object to which this reference refers.
*
* @return The non-null fully-qualified class name of the object.
* (e.g. "java.lang.String")
*/
public String getClassName() {
return className;
}
/** {@collect.stats}
* Retrieves the class name of the factory of the object
* to which this reference refers.
*
* @return The possibly null fully-qualified class name of the factory.
* (e.g. "java.lang.String")
*/
public String getFactoryClassName() {
return classFactory;
}
/** {@collect.stats}
* Retrieves the location of the factory of the object
* to which this reference refers.
* If it is a codebase, then it is an ordered list of URLs,
* separated by spaces, listing locations from where the factory
* class definition should be loaded.
*
* @return The possibly null string containing the
* location for loading in the factory's class.
*/
public String getFactoryClassLocation() {
return classFactoryLocation;
}
/** {@collect.stats}
* Retrieves the first address that has the address type 'addrType'.
* String.compareTo() is used to test the equality of the address types.
*
* @param addrType The non-null address type for which to find the address.
* @return The address in this reference with address type 'addrType;
* null if no such address exist.
*/
public RefAddr get(String addrType) {
int len = addrs.size();
RefAddr addr;
for (int i = 0; i < len; i++) {
addr = (RefAddr) addrs.elementAt(i);
if (addr.getType().compareTo(addrType) == 0)
return addr;
}
return null;
}
/** {@collect.stats}
* Retrieves the address at index posn.
* @param posn The index of the address to retrieve.
* @return The address at the 0-based index posn. It must be in the
* range [0,getAddressCount()).
* @exception ArrayIndexOutOfBoundsException If posn not in the specified
* range.
*/
public RefAddr get(int posn) {
return ((RefAddr) addrs.elementAt(posn));
}
/** {@collect.stats}
* Retrieves an enumeration of the addresses in this reference.
* When addresses are added, changed or removed from this reference,
* its effects on this enumeration are undefined.
*
* @return An non-null enumeration of the addresses
* (<tt>RefAddr</tt>) in this reference.
* If this reference has zero addresses, an enumeration with
* zero elements is returned.
*/
public Enumeration<RefAddr> getAll() {
return addrs.elements();
}
/** {@collect.stats}
* Retrieves the number of addresses in this reference.
*
* @return The nonnegative number of addresses in this reference.
*/
public int size() {
return addrs.size();
}
/** {@collect.stats}
* Adds an address to the end of the list of addresses.
*
* @param addr The non-null address to add.
*/
public void add(RefAddr addr) {
addrs.addElement(addr);
}
/** {@collect.stats}
* Adds an address to the list of addresses at index posn.
* All addresses at index posn or greater are shifted up
* the list by one (away from index 0).
*
* @param posn The 0-based index of the list to insert addr.
* @param addr The non-null address to add.
* @exception ArrayIndexOutOfBoundsException If posn not in the specified
* range.
*/
public void add(int posn, RefAddr addr) {
addrs.insertElementAt(addr, posn);
}
/** {@collect.stats}
* Deletes the address at index posn from the list of addresses.
* All addresses at index greater than posn are shifted down
* the list by one (towards index 0).
*
* @param posn The 0-based index of in address to delete.
* @return The address removed.
* @exception ArrayIndexOutOfBoundsException If posn not in the specified
* range.
*/
public Object remove(int posn) {
Object r = addrs.elementAt(posn);
addrs.removeElementAt(posn);
return r;
}
/** {@collect.stats}
* Deletes all addresses from this reference.
*/
public void clear() {
addrs.setSize(0);
}
/** {@collect.stats}
* Determines whether obj is a reference with the same addresses
* (in same order) as this reference.
* The addresses are checked using RefAddr.equals().
* In addition to having the same addresses, the Reference also needs to
* have the same class name as this reference.
* The class factory and class factory location are not checked.
* If obj is null or not an instance of Reference, null is returned.
*
* @param obj The possibly null object to check.
* @return true if obj is equal to this reference; false otherwise.
*/
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof Reference)) {
Reference target = (Reference)obj;
// ignore factory information
if (target.className.equals(this.className) &&
target.size() == this.size()) {
Enumeration mycomps = getAll();
Enumeration comps = target.getAll();
while (mycomps.hasMoreElements())
if (!(mycomps.nextElement().equals(comps.nextElement())))
return false;
return true;
}
}
return false;
}
/** {@collect.stats}
* Computes the hash code of this reference.
* The hash code is the sum of the hash code of its addresses.
*
* @return A hash code of this reference as an int.
*/
public int hashCode() {
int hash = className.hashCode();
for (Enumeration e = getAll(); e.hasMoreElements();)
hash += e.nextElement().hashCode();
return hash;
}
/** {@collect.stats}
* Generates the string representation of this reference.
* The string consists of the class name to which this reference refers,
* and the string representation of each of its addresses.
* This representation is intended for display only and not to be parsed.
*
* @return The non-null string representation of this reference.
*/
public String toString() {
StringBuffer buf = new StringBuffer("Reference Class Name: " +
className + "\n");
int len = addrs.size();
for (int i = 0; i < len; i++)
buf.append(get(i).toString());
return buf.toString();
}
/** {@collect.stats}
* Makes a copy of this reference using its class name
* list of addresses, class factory name and class factory location.
* Changes to the newly created copy does not affect this Reference
* and vice versa.
*/
public Object clone() {
Reference r = new Reference(className, classFactory, classFactoryLocation);
Enumeration<RefAddr> a = getAll();
r.addrs = new Vector();
while (a.hasMoreElements())
r.addrs.addElement(a.nextElement());
return r;
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -1673475790065791735L;
};
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.io.*;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Dialog;
import java.awt.Window;
import java.awt.Component;
import java.awt.Container;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.awt.event.WindowListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.IllegalComponentStateException;
import java.awt.Point;
import java.awt.Rectangle;
import java.text.*;
import java.util.Locale;
import javax.accessibility.*;
import javax.swing.event.*;
import javax.swing.text.*;
/** {@collect.stats} A class to monitor the progress of some operation. If it looks
* like the operation will take a while, a progress dialog will be popped up.
* When the ProgressMonitor is created it is given a numeric range and a
* descriptive string. As the operation progresses, call the setProgress method
* to indicate how far along the [min,max] range the operation is.
* Initially, there is no ProgressDialog. After the first millisToDecideToPopup
* milliseconds (default 500) the progress monitor will predict how long
* the operation will take. If it is longer than millisToPopup (default 2000,
* 2 seconds) a ProgressDialog will be popped up.
* <p>
* From time to time, when the Dialog box is visible, the progress bar will
* be updated when setProgress is called. setProgress won't always update
* the progress bar, it will only be done if the amount of progress is
* visibly significant.
*
* <p>
*
* For further documentation and examples see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html">How to Monitor Progress</a>,
* a section in <em>The Java Tutorial.</em>
*
* @see ProgressMonitorInputStream
* @author James Gosling
* @author Lynn Monsanto (accessibility)
*/
public class ProgressMonitor extends Object implements Accessible
{
private ProgressMonitor root;
private JDialog dialog;
private JOptionPane pane;
private JProgressBar myBar;
private JLabel noteLabel;
private Component parentComponent;
private String note;
private Object[] cancelOption = null;
private Object message;
private long T0;
private int millisToDecideToPopup = 500;
private int millisToPopup = 2000;
private int min;
private int max;
/** {@collect.stats}
* Constructs a graphic object that shows progress, typically by filling
* in a rectangular bar as the process nears completion.
*
* @param parentComponent the parent component for the dialog box
* @param message a descriptive message that will be shown
* to the user to indicate what operation is being monitored.
* This does not change as the operation progresses.
* See the message parameters to methods in
* {@link JOptionPane#message}
* for the range of values.
* @param note a short note describing the state of the
* operation. As the operation progresses, you can call
* setNote to change the note displayed. This is used,
* for example, in operations that iterate through a
* list of files to show the name of the file being processes.
* If note is initially null, there will be no note line
* in the dialog box and setNote will be ineffective
* @param min the lower bound of the range
* @param max the upper bound of the range
* @see JDialog
* @see JOptionPane
*/
public ProgressMonitor(Component parentComponent,
Object message,
String note,
int min,
int max) {
this(parentComponent, message, note, min, max, null);
}
private ProgressMonitor(Component parentComponent,
Object message,
String note,
int min,
int max,
ProgressMonitor group) {
this.min = min;
this.max = max;
this.parentComponent = parentComponent;
cancelOption = new Object[1];
cancelOption[0] = UIManager.getString("OptionPane.cancelButtonText");
this.message = message;
this.note = note;
if (group != null) {
root = (group.root != null) ? group.root : group;
T0 = root.T0;
dialog = root.dialog;
}
else {
T0 = System.currentTimeMillis();
}
}
private class ProgressOptionPane extends JOptionPane
{
ProgressOptionPane(Object messageList) {
super(messageList,
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.DEFAULT_OPTION,
null,
ProgressMonitor.this.cancelOption,
null);
}
public int getMaxCharactersPerLineCount() {
return 60;
}
// Equivalent to JOptionPane.createDialog,
// but create a modeless dialog.
// This is necessary because the Solaris implementation doesn't
// support Dialog.setModal yet.
public JDialog createDialog(Component parentComponent, String title) {
final JDialog dialog;
Window window = JOptionPane.getWindowForComponent(parentComponent);
if (window instanceof Frame) {
dialog = new JDialog((Frame)window, title, false);
} else {
dialog = new JDialog((Dialog)window, title, false);
}
if (window instanceof SwingUtilities.SharedOwnerFrame) {
WindowListener ownerShutdownListener =
(WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener();
dialog.addWindowListener(ownerShutdownListener);
}
Container contentPane = dialog.getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(this, BorderLayout.CENTER);
dialog.pack();
dialog.setLocationRelativeTo(parentComponent);
dialog.addWindowListener(new WindowAdapter() {
boolean gotFocus = false;
public void windowClosing(WindowEvent we) {
setValue(cancelOption[0]);
}
public void windowActivated(WindowEvent we) {
// Once window gets focus, set initial focus
if (!gotFocus) {
selectInitialValue();
gotFocus = true;
}
}
});
addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if(dialog.isVisible() &&
event.getSource() == ProgressOptionPane.this &&
(event.getPropertyName().equals(VALUE_PROPERTY) ||
event.getPropertyName().equals(INPUT_VALUE_PROPERTY))){
dialog.setVisible(false);
dialog.dispose();
}
}
});
return dialog;
}
/////////////////
// Accessibility support for ProgressOptionPane
////////////////
/** {@collect.stats}
* Gets the AccessibleContext for the ProgressOptionPane
*
* @return the AccessibleContext for the ProgressOptionPane
* @since 1.5
*/
public AccessibleContext getAccessibleContext() {
return ProgressMonitor.this.getAccessibleContext();
}
/*
* Returns the AccessibleJOptionPane
*/
private AccessibleContext getAccessibleJOptionPane() {
return super.getAccessibleContext();
}
}
/** {@collect.stats}
* Indicate the progress of the operation being monitored.
* If the specified value is >= the maximum, the progress
* monitor is closed.
* @param nv an int specifying the current value, between the
* maximum and minimum specified for this component
* @see #setMinimum
* @see #setMaximum
* @see #close
*/
public void setProgress(int nv) {
if (nv >= max) {
close();
}
else {
if (myBar != null) {
myBar.setValue(nv);
}
else {
long T = System.currentTimeMillis();
long dT = (int)(T-T0);
if (dT >= millisToDecideToPopup) {
int predictedCompletionTime;
if (nv > min) {
predictedCompletionTime = (int)((long)dT *
(max - min) /
(nv - min));
}
else {
predictedCompletionTime = millisToPopup;
}
if (predictedCompletionTime >= millisToPopup) {
myBar = new JProgressBar();
myBar.setMinimum(min);
myBar.setMaximum(max);
myBar.setValue(nv);
if (note != null) noteLabel = new JLabel(note);
pane = new ProgressOptionPane(new Object[] {message,
noteLabel,
myBar});
dialog = pane.createDialog(parentComponent,
UIManager.getString(
"ProgressMonitor.progressText"));
dialog.show();
}
}
}
}
}
/** {@collect.stats}
* Indicate that the operation is complete. This happens automatically
* when the value set by setProgress is >= max, but it may be called
* earlier if the operation ends early.
*/
public void close() {
if (dialog != null) {
dialog.setVisible(false);
dialog.dispose();
dialog = null;
pane = null;
myBar = null;
}
}
/** {@collect.stats}
* Returns the minimum value -- the lower end of the progress value.
*
* @return an int representing the minimum value
* @see #setMinimum
*/
public int getMinimum() {
return min;
}
/** {@collect.stats}
* Specifies the minimum value.
*
* @param m an int specifying the minimum value
* @see #getMinimum
*/
public void setMinimum(int m) {
if (myBar != null) {
myBar.setMinimum(m);
}
min = m;
}
/** {@collect.stats}
* Returns the maximum value -- the higher end of the progress value.
*
* @return an int representing the maximum value
* @see #setMaximum
*/
public int getMaximum() {
return max;
}
/** {@collect.stats}
* Specifies the maximum value.
*
* @param m an int specifying the maximum value
* @see #getMaximum
*/
public void setMaximum(int m) {
if (myBar != null) {
myBar.setMaximum(m);
}
max = m;
}
/** {@collect.stats}
* Returns true if the user hits the Cancel button in the progress dialog.
*/
public boolean isCanceled() {
if (pane == null) return false;
Object v = pane.getValue();
return ((v != null) &&
(cancelOption.length == 1) &&
(v.equals(cancelOption[0])));
}
/** {@collect.stats}
* Specifies the amount of time to wait before deciding whether or
* not to popup a progress monitor.
*
* @param millisToDecideToPopup an int specifying the time to wait,
* in milliseconds
* @see #getMillisToDecideToPopup
*/
public void setMillisToDecideToPopup(int millisToDecideToPopup) {
this.millisToDecideToPopup = millisToDecideToPopup;
}
/** {@collect.stats}
* Returns the amount of time this object waits before deciding whether
* or not to popup a progress monitor.
*
* @see #setMillisToDecideToPopup
*/
public int getMillisToDecideToPopup() {
return millisToDecideToPopup;
}
/** {@collect.stats}
* Specifies the amount of time it will take for the popup to appear.
* (If the predicted time remaining is less than this time, the popup
* won't be displayed.)
*
* @param millisToPopup an int specifying the time in milliseconds
* @see #getMillisToPopup
*/
public void setMillisToPopup(int millisToPopup) {
this.millisToPopup = millisToPopup;
}
/** {@collect.stats}
* Returns the amount of time it will take for the popup to appear.
*
* @see #setMillisToPopup
*/
public int getMillisToPopup() {
return millisToPopup;
}
/** {@collect.stats}
* Specifies the additional note that is displayed along with the
* progress message. Used, for example, to show which file the
* is currently being copied during a multiple-file copy.
*
* @param note a String specifying the note to display
* @see #getNote
*/
public void setNote(String note) {
this.note = note;
if (noteLabel != null) {
noteLabel.setText(note);
}
}
/** {@collect.stats}
* Specifies the additional note that is displayed along with the
* progress message.
*
* @return a String specifying the note to display
* @see #setNote
*/
public String getNote() {
return note;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* The <code>AccessibleContext</code> for the <code>ProgressMonitor</code>
* @since 1.5
*/
protected AccessibleContext accessibleContext = null;
private AccessibleContext accessibleJOptionPane = null;
/** {@collect.stats}
* Gets the <code>AccessibleContext</code> for the
* <code>ProgressMonitor</code>
*
* @return the <code>AccessibleContext</code> for the
* <code>ProgressMonitor</code>
* @since 1.5
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleProgressMonitor();
}
if (pane != null && accessibleJOptionPane == null) {
// Notify the AccessibleProgressMonitor that the
// ProgressOptionPane was created. It is necessary
// to poll for ProgressOptionPane creation because
// the ProgressMonitor does not have a Component
// to add a listener to until the ProgressOptionPane
// is created.
if (accessibleContext instanceof AccessibleProgressMonitor) {
((AccessibleProgressMonitor)accessibleContext).optionPaneCreated();
}
}
return accessibleContext;
}
/** {@collect.stats}
* <code>AccessibleProgressMonitor</code> implements accessibility
* support for the <code>ProgressMonitor</code> class.
* @since 1.5
*/
protected class AccessibleProgressMonitor extends AccessibleContext
implements AccessibleText, ChangeListener, PropertyChangeListener {
/*
* The accessibility hierarchy for ProgressMonitor is a flattened
* version of the ProgressOptionPane component hierarchy.
*
* The ProgressOptionPane component hierarchy is:
* JDialog
* ProgressOptionPane
* JPanel
* JPanel
* JLabel
* JLabel
* JProgressBar
*
* The AccessibleProgessMonitor accessibility hierarchy is:
* AccessibleJDialog
* AccessibleProgressMonitor
* AccessibleJLabel
* AccessibleJLabel
* AccessibleJProgressBar
*
* The abstraction presented to assitive technologies by
* the AccessibleProgressMonitor is that a dialog contains a
* progress monitor with three children: a message, a note
* label and a progress bar.
*/
private Object oldModelValue;
/** {@collect.stats}
* AccessibleProgressMonitor constructor
*/
protected AccessibleProgressMonitor() {
}
/*
* Initializes the AccessibleContext now that the ProgressOptionPane
* has been created. Because the ProgressMonitor is not a Component
* implementing the Accessible interface, an AccessibleContext
* must be synthesized from the ProgressOptionPane and its children.
*
* For other AWT and Swing classes, the inner class that implements
* accessibility for the class extends the inner class that implements
* implements accessibility for the super class. AccessibleProgressMonitor
* cannot extend AccessibleJOptionPane and must therefore delegate calls
* to the AccessibleJOptionPane.
*/
private void optionPaneCreated() {
accessibleJOptionPane =
((ProgressOptionPane)pane).getAccessibleJOptionPane();
// add a listener for progress bar ChangeEvents
if (myBar != null) {
myBar.addChangeListener(this);
}
// add a listener for note label PropertyChangeEvents
if (noteLabel != null) {
noteLabel.addPropertyChangeListener(this);
}
}
/** {@collect.stats}
* Invoked when the target of the listener has changed its state.
*
* @param e a <code>ChangeEvent</code> object. Must not be null.
* @throws NullPointerException if the parameter is null.
*/
public void stateChanged(ChangeEvent e) {
if (e == null) {
return;
}
if (myBar != null) {
// the progress bar value changed
Object newModelValue = myBar.getValue();
firePropertyChange(ACCESSIBLE_VALUE_PROPERTY,
oldModelValue,
newModelValue);
oldModelValue = newModelValue;
}
}
/** {@collect.stats}
* This method gets called when a bound property is changed.
*
* @param e A <code>PropertyChangeEvent</code> object describing
* the event source and the property that has changed. Must not be null.
* @throws NullPointerException if the parameter is null.
*/
public void propertyChange(PropertyChangeEvent e) {
if (e.getSource() == noteLabel && e.getPropertyName() == "text") {
// the note label text changed
firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, 0);
}
}
/* ===== Begin AccessileContext ===== */
/** {@collect.stats}
* Gets the accessibleName property of this object. The accessibleName
* property of an object is a localized String that designates the purpose
* of the object. For example, the accessibleName property of a label
* or button might be the text of the label or button itself. In the
* case of an object that doesn't display its name, the accessibleName
* should still be set. For example, in the case of a text field used
* to enter the name of a city, the accessibleName for the en_US locale
* could be 'city.'
*
* @return the localized name of the object; null if this
* object does not have a name
*
* @see #setAccessibleName
*/
public String getAccessibleName() {
if (accessibleName != null) { // defined in AccessibleContext
return accessibleName;
} else if (accessibleJOptionPane != null) {
// delegate to the AccessibleJOptionPane
return accessibleJOptionPane.getAccessibleName();
}
return null;
}
/** {@collect.stats}
* Gets the accessibleDescription property of this object. The
* accessibleDescription property of this object is a short localized
* phrase describing the purpose of the object. For example, in the
* case of a 'Cancel' button, the accessibleDescription could be
* 'Ignore changes and close dialog box.'
*
* @return the localized description of the object; null if
* this object does not have a description
*
* @see #setAccessibleDescription
*/
public String getAccessibleDescription() {
if (accessibleDescription != null) { // defined in AccessibleContext
return accessibleDescription;
} else if (accessibleJOptionPane != null) {
// delegate to the AccessibleJOptionPane
return accessibleJOptionPane.getAccessibleDescription();
}
return null;
}
/** {@collect.stats}
* Gets the role of this object. The role of the object is the generic
* purpose or use of the class of this object. For example, the role
* of a push button is AccessibleRole.PUSH_BUTTON. The roles in
* AccessibleRole are provided so component developers can pick from
* a set of predefined roles. This enables assistive technologies to
* provide a consistent interface to various tweaked subclasses of
* components (e.g., use AccessibleRole.PUSH_BUTTON for all components
* that act like a push button) as well as distinguish between sublasses
* that behave differently (e.g., AccessibleRole.CHECK_BOX for check boxes
* and AccessibleRole.RADIO_BUTTON for radio buttons).
* <p>Note that the AccessibleRole class is also extensible, so
* custom component developers can define their own AccessibleRole's
* if the set of predefined roles is inadequate.
*
* @return an instance of AccessibleRole describing the role of the object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.PROGRESS_MONITOR;
}
/** {@collect.stats}
* Gets the state set of this object. The AccessibleStateSet of an object
* is composed of a set of unique AccessibleStates. A change in the
* AccessibleStateSet of an object will cause a PropertyChangeEvent to
* be fired for the ACCESSIBLE_STATE_PROPERTY property.
*
* @return an instance of AccessibleStateSet containing the
* current state set of the object
* @see AccessibleStateSet
* @see AccessibleState
* @see #addPropertyChangeListener
*/
public AccessibleStateSet getAccessibleStateSet() {
if (accessibleJOptionPane != null) {
// delegate to the AccessibleJOptionPane
return accessibleJOptionPane.getAccessibleStateSet();
}
return null;
}
/** {@collect.stats}
* Gets the Accessible parent of this object.
*
* @return the Accessible parent of this object; null if this
* object does not have an Accessible parent
*/
public Accessible getAccessibleParent() {
if (dialog != null) {
return (Accessible)dialog;
}
return null;
}
/*
* Returns the parent AccessibleContext
*/
private AccessibleContext getParentAccessibleContext() {
if (dialog != null) {
return dialog.getAccessibleContext();
}
return null;
}
/** {@collect.stats}
* Gets the 0-based index of this object in its accessible parent.
*
* @return the 0-based index of this object in its parent; -1 if this
* object does not have an accessible parent.
*
* @see #getAccessibleParent
* @see #getAccessibleChildrenCount
* @see #getAccessibleChild
*/
public int getAccessibleIndexInParent() {
if (accessibleJOptionPane != null) {
// delegate to the AccessibleJOptionPane
return accessibleJOptionPane.getAccessibleIndexInParent();
}
return -1;
}
/** {@collect.stats}
* Returns the number of accessible children of the object.
*
* @return the number of accessible children of the object.
*/
public int getAccessibleChildrenCount() {
// return the number of children in the JPanel containing
// the message, note label and progress bar
AccessibleContext ac = getPanelAccessibleContext();
if (ac != null) {
return ac.getAccessibleChildrenCount();
}
return 0;
}
/** {@collect.stats}
* Returns the specified Accessible child of the object. The Accessible
* children of an Accessible object are zero-based, so the first child
* of an Accessible child is at index 0, the second child is at index 1,
* and so on.
*
* @param i zero-based index of child
* @return the Accessible child of the object
* @see #getAccessibleChildrenCount
*/
public Accessible getAccessibleChild(int i) {
// return a child in the JPanel containing the message, note label
// and progress bar
AccessibleContext ac = getPanelAccessibleContext();
if (ac != null) {
return ac.getAccessibleChild(i);
}
return null;
}
/*
* Returns the AccessibleContext for the JPanel containing the
* message, note label and progress bar
*/
private AccessibleContext getPanelAccessibleContext() {
if (myBar != null) {
Component c = myBar.getParent();
if (c instanceof Accessible) {
return ((Accessible)c).getAccessibleContext();
}
}
return null;
}
/** {@collect.stats}
* Gets the locale of the component. If the component does not have a
* locale, then the locale of its parent is returned.
*
* @return this component's locale. If this component does not have
* a locale, the locale of its parent is returned.
*
* @exception IllegalComponentStateException
* If the Component does not have its own locale and has not yet been
* added to a containment hierarchy such that the locale can be
* determined from the containing parent.
*/
public Locale getLocale() throws IllegalComponentStateException {
if (accessibleJOptionPane != null) {
// delegate to the AccessibleJOptionPane
return accessibleJOptionPane.getLocale();
}
return null;
}
/* ===== end AccessibleContext ===== */
/** {@collect.stats}
* Gets the AccessibleComponent associated with this object that has a
* graphical representation.
*
* @return AccessibleComponent if supported by object; else return null
* @see AccessibleComponent
*/
public AccessibleComponent getAccessibleComponent() {
if (accessibleJOptionPane != null) {
// delegate to the AccessibleJOptionPane
return accessibleJOptionPane.getAccessibleComponent();
}
return null;
}
/** {@collect.stats}
* Gets the AccessibleValue associated with this object that supports a
* Numerical value.
*
* @return AccessibleValue if supported by object; else return null
* @see AccessibleValue
*/
public AccessibleValue getAccessibleValue() {
if (myBar != null) {
// delegate to the AccessibleJProgressBar
return myBar.getAccessibleContext().getAccessibleValue();
}
return null;
}
/** {@collect.stats}
* Gets the AccessibleText associated with this object presenting
* text on the display.
*
* @return AccessibleText if supported by object; else return null
* @see AccessibleText
*/
public AccessibleText getAccessibleText() {
if (getNoteLabelAccessibleText() != null) {
return this;
}
return null;
}
/*
* Returns the note label AccessibleText
*/
private AccessibleText getNoteLabelAccessibleText() {
if (noteLabel != null) {
// AccessibleJLabel implements AccessibleText if the
// JLabel contains HTML text
return noteLabel.getAccessibleContext().getAccessibleText();
}
return null;
}
/* ===== Begin AccessibleText impl ===== */
/** {@collect.stats}
* Given a point in local coordinates, return the zero-based index
* of the character under that Point. If the point is invalid,
* this method returns -1.
*
* @param p the Point in local coordinates
* @return the zero-based index of the character under Point p; if
* Point is invalid return -1.
*/
public int getIndexAtPoint(Point p) {
AccessibleText at = getNoteLabelAccessibleText();
if (at != null && sameWindowAncestor(pane, noteLabel)) {
// convert point from the option pane bounds
// to the note label bounds.
Point noteLabelPoint = SwingUtilities.convertPoint(pane,
p,
noteLabel);
if (noteLabelPoint != null) {
return at.getIndexAtPoint(noteLabelPoint);
}
}
return -1;
}
/** {@collect.stats}
* Determines the bounding box of the character at the given
* index into the string. The bounds are returned in local
* coordinates. If the index is invalid an empty rectangle is returned.
*
* @param i the index into the String
* @return the screen coordinates of the character's bounding box,
* if index is invalid return an empty rectangle.
*/
public Rectangle getCharacterBounds(int i) {
AccessibleText at = getNoteLabelAccessibleText();
if (at != null && sameWindowAncestor(pane, noteLabel)) {
// return rectangle in the option pane bounds
Rectangle noteLabelRect = at.getCharacterBounds(i);
if (noteLabelRect != null) {
return SwingUtilities.convertRectangle(noteLabel,
noteLabelRect,
pane);
}
}
return null;
}
/*
* Returns whether source and destination components have the
* same window ancestor
*/
private boolean sameWindowAncestor(Component src, Component dest) {
if (src == null || dest == null) {
return false;
}
return SwingUtilities.getWindowAncestor(src) ==
SwingUtilities.getWindowAncestor(dest);
}
/** {@collect.stats}
* Returns the number of characters (valid indicies)
*
* @return the number of characters
*/
public int getCharCount() {
AccessibleText at = getNoteLabelAccessibleText();
if (at != null) { // JLabel contains HTML text
return at.getCharCount();
}
return -1;
}
/** {@collect.stats}
* Returns the zero-based offset of the caret.
*
* Note: That to the right of the caret will have the same index
* value as the offset (the caret is between two characters).
* @return the zero-based offset of the caret.
*/
public int getCaretPosition() {
AccessibleText at = getNoteLabelAccessibleText();
if (at != null) { // JLabel contains HTML text
return at.getCaretPosition();
}
return -1;
}
/** {@collect.stats}
* Returns the String at a given index.
*
* @param part the CHARACTER, WORD, or SENTENCE to retrieve
* @param index an index within the text
* @return the letter, word, or sentence
*/
public String getAtIndex(int part, int index) {
AccessibleText at = getNoteLabelAccessibleText();
if (at != null) { // JLabel contains HTML text
return at.getAtIndex(part, index);
}
return null;
}
/** {@collect.stats}
* Returns the String after a given index.
*
* @param part the CHARACTER, WORD, or SENTENCE to retrieve
* @param index an index within the text
* @return the letter, word, or sentence
*/
public String getAfterIndex(int part, int index) {
AccessibleText at = getNoteLabelAccessibleText();
if (at != null) { // JLabel contains HTML text
return at.getAfterIndex(part, index);
}
return null;
}
/** {@collect.stats}
* Returns the String before a given index.
*
* @param part the CHARACTER, WORD, or SENTENCE to retrieve
* @param index an index within the text
* @return the letter, word, or sentence
*/
public String getBeforeIndex(int part, int index) {
AccessibleText at = getNoteLabelAccessibleText();
if (at != null) { // JLabel contains HTML text
return at.getBeforeIndex(part, index);
}
return null;
}
/** {@collect.stats}
* Returns the AttributeSet for a given character at a given index
*
* @param i the zero-based index into the text
* @return the AttributeSet of the character
*/
public AttributeSet getCharacterAttribute(int i) {
AccessibleText at = getNoteLabelAccessibleText();
if (at != null) { // JLabel contains HTML text
return at.getCharacterAttribute(i);
}
return null;
}
/** {@collect.stats}
* Returns the start offset within the selected text.
* If there is no selection, but there is
* a caret, the start and end offsets will be the same.
*
* @return the index into the text of the start of the selection
*/
public int getSelectionStart() {
AccessibleText at = getNoteLabelAccessibleText();
if (at != null) { // JLabel contains HTML text
return at.getSelectionStart();
}
return -1;
}
/** {@collect.stats}
* Returns the end offset within the selected text.
* If there is no selection, but there is
* a caret, the start and end offsets will be the same.
*
* @return the index into teh text of the end of the selection
*/
public int getSelectionEnd() {
AccessibleText at = getNoteLabelAccessibleText();
if (at != null) { // JLabel contains HTML text
return at.getSelectionEnd();
}
return -1;
}
/** {@collect.stats}
* Returns the portion of the text that is selected.
*
* @return the String portion of the text that is selected
*/
public String getSelectedText() {
AccessibleText at = getNoteLabelAccessibleText();
if (at != null) { // JLabel contains HTML text
return at.getSelectedText();
}
return null;
}
/* ===== End AccessibleText impl ===== */
}
// inner class AccessibleProgressMonitor
}
|
Java
|
/*
* Copyright (c) 1998, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
/** {@collect.stats}
* A mutable version of <code>ComboBoxModel</code>.
*
* @author Tom Santos
*/
public interface MutableComboBoxModel extends ComboBoxModel {
/** {@collect.stats}
* Adds an item at the end of the model. The implementation of this method
* should notify all registered <code>ListDataListener</code>s that the
* item has been added.
*
* @param obj the <code>Object</code> to be added
*/
public void addElement( Object obj );
/** {@collect.stats}
* Removes an item from the model. The implementation of this method should
* should notify all registered <code>ListDataListener</code>s that the
* item has been removed.
*
* @param obj the <code>Object</code> to be removed
*/
public void removeElement( Object obj );
/** {@collect.stats}
* Adds an item at a specific index. The implementation of this method
* should notify all registered <code>ListDataListener</code>s that the
* item has been added.
*
* @param obj the <code>Object</code> to be added
* @param index location to add the object
*/
public void insertElementAt( Object obj, int index );
/** {@collect.stats}
* Removes an item at a specific index. The implementation of this method
* should notify all registered <code>ListDataListener</code>s that the
* item has been removed.
*
* @param index location of object to be removed
*/
public void removeElementAt( int index );
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.event.*;
import java.awt.*;
import javax.swing.event.*;
/** {@collect.stats}
* State model for buttons.
* <p>
* This model is used for regular buttons, as well as check boxes
* and radio buttons, which are special kinds of buttons. In practice,
* a button's UI takes the responsibility of calling methods on its
* model to manage the state, as detailed below:
* <p>
* In simple terms, pressing and releasing the mouse over a regular
* button triggers the button and causes and <code>ActionEvent</code>
* to be fired. The same behavior can be produced via a keyboard key
* defined by the look and feel of the button (typically the SPACE BAR).
* Pressing and releasing this key while the button has
* focus will give the same results. For check boxes and radio buttons, the
* mouse or keyboard equivalent sequence just described causes the button
* to become selected.
* <p>
* In details, the state model for buttons works as follows
* when used with the mouse:
* <br>
* Pressing the mouse on top of a button makes the model both
* armed and pressed. As long as the mouse remains down,
* the model remains pressed, even if the mouse moves
* outside the button. On the contrary, the model is only
* armed while the mouse remains pressed within the bounds of
* the button (it can move in or out of the button, but the model
* is only armed during the portion of time spent within the button).
* A button is triggered, and an <code>ActionEvent</code> is fired,
* when the mouse is released while the model is armed
* - meaning when it is released over top of the button after the mouse
* has previously been pressed on that button (and not already released).
* Upon mouse release, the model becomes unarmed and unpressed.
* <p>
* In details, the state model for buttons works as follows
* when used with the keyboard:
* <br>
* Pressing the look and feel defined keyboard key while the button
* has focus makes the model both armed and pressed. As long as this key
* remains down, the model remains in this state. Releasing the key sets
* the model to unarmed and unpressed, triggers the button, and causes an
* <code>ActionEvent</code> to be fired.
*
* @author Jeff Dinkins
*/
public interface ButtonModel extends ItemSelectable {
/** {@collect.stats}
* Indicates partial commitment towards triggering the
* button.
*
* @return <code>true</code> if the button is armed,
* and ready to be triggered
* @see #setArmed
*/
boolean isArmed();
/** {@collect.stats}
* Indicates if the button has been selected. Only needed for
* certain types of buttons - such as radio buttons and check boxes.
*
* @return <code>true</code> if the button is selected
*/
boolean isSelected();
/** {@collect.stats}
* Indicates if the button can be selected or triggered by
* an input device, such as a mouse pointer.
*
* @return <code>true</code> if the button is enabled
*/
boolean isEnabled();
/** {@collect.stats}
* Indicates if the button is pressed.
*
* @return <code>true</code> if the button is pressed
*/
boolean isPressed();
/** {@collect.stats}
* Indicates that the mouse is over the button.
*
* @return <code>true</code> if the mouse is over the button
*/
boolean isRollover();
/** {@collect.stats}
* Marks the button as armed or unarmed.
*
* @param b whether or not the button should be armed
*/
public void setArmed(boolean b);
/** {@collect.stats}
* Selects or deselects the button.
*
* @param b <code>true</code> selects the button,
* <code>false</code> deselects the button
*/
public void setSelected(boolean b);
/** {@collect.stats}
* Enables or disables the button.
*
* @param b whether or not the button should be enabled
* @see #isEnabled
*/
public void setEnabled(boolean b);
/** {@collect.stats}
* Sets the button to pressed or unpressed.
*
* @param b whether or not the button should be pressed
* @see #isPressed
*/
public void setPressed(boolean b);
/** {@collect.stats}
* Sets or clears the button's rollover state
*
* @param b whether or not the button is in the rollover state
* @see #isRollover
*/
public void setRollover(boolean b);
/** {@collect.stats}
* Sets the keyboard mnemonic (shortcut key or
* accelerator key) for the button.
*
* @param key an int specifying the accelerator key
*/
public void setMnemonic(int key);
/** {@collect.stats}
* Gets the keyboard mnemonic for the button.
*
* @return an int specifying the accelerator key
* @see #setMnemonic
*/
public int getMnemonic();
/** {@collect.stats}
* Sets the action command string that gets sent as part of the
* <code>ActionEvent</code> when the button is triggered.
*
* @param s the <code>String</code> that identifies the generated event
* @see #getActionCommand
* @see java.awt.event.ActionEvent#getActionCommand
*/
public void setActionCommand(String s);
/** {@collect.stats}
* Returns the action command string for the button.
*
* @return the <code>String</code> that identifies the generated event
* @see #setActionCommand
*/
public String getActionCommand();
/** {@collect.stats}
* Identifies the group the button belongs to --
* needed for radio buttons, which are mutually
* exclusive within their group.
*
* @param group the <code>ButtonGroup</code> the button belongs to
*/
public void setGroup(ButtonGroup group);
/** {@collect.stats}
* Adds an <code>ActionListener</code> to the model.
*
* @param l the listener to add
*/
void addActionListener(ActionListener l);
/** {@collect.stats}
* Removes an <code>ActionListener</code> from the model.
*
* @param l the listener to remove
*/
void removeActionListener(ActionListener l);
/** {@collect.stats}
* Adds an <code>ItemListener</code> to the model.
*
* @param l the listener to add
*/
void addItemListener(ItemListener l);
/** {@collect.stats}
* Removes an <code>ItemListener</code> from the model.
*
* @param l the listener to remove
*/
void removeItemListener(ItemListener l);
/** {@collect.stats}
* Adds a <code>ChangeListener</code> to the model.
*
* @param l the listener to add
*/
void addChangeListener(ChangeListener l);
/** {@collect.stats}
* Removes a <code>ChangeListener</code> from the model.
*
* @param l the listener to remove
*/
void removeChangeListener(ChangeListener l);
}
|
Java
|
/*
* Copyright (c) 1999, 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.swing;
/** {@collect.stats}
* A <code>SizeSequence</code> object
* efficiently maintains an ordered list
* of sizes and corresponding positions.
* One situation for which <code>SizeSequence</code>
* might be appropriate is in a component
* that displays multiple rows of unequal size.
* In this case, a single <code>SizeSequence</code>
* object could be used to track the heights
* and Y positions of all rows.
* <p>
* Another example would be a multi-column component,
* such as a <code>JTable</code>,
* in which the column sizes are not all equal.
* The <code>JTable</code> might use a single
* <code>SizeSequence</code> object
* to store the widths and X positions of all the columns.
* The <code>JTable</code> could then use the
* <code>SizeSequence</code> object
* to find the column corresponding to a certain position.
* The <code>JTable</code> could update the
* <code>SizeSequence</code> object
* whenever one or more column sizes changed.
*
* <p>
* The following figure shows the relationship between size and position data
* for a multi-column component.
* <p>
* <center>
* <img src="doc-files/SizeSequence-1.gif" width=384 height = 100
* alt="The first item begins at position 0, the second at the position equal
to the size of the previous item, and so on.">
* </center>
* <p>
* In the figure, the first index (0) corresponds to the first column,
* the second index (1) to the second column, and so on.
* The first column's position starts at 0,
* and the column occupies <em>size<sub>0</sub></em> pixels,
* where <em>size<sub>0</sub></em> is the value returned by
* <code>getSize(0)</code>.
* Thus, the first column ends at <em>size<sub>0</sub></em> - 1.
* The second column then begins at
* the position <em>size<sub>0</sub></em>
* and occupies <em>size<sub>1</sub></em> (<code>getSize(1)</code>) pixels.
* <p>
* Note that a <code>SizeSequence</code> object simply represents intervals
* along an axis.
* In our examples, the intervals represent height or width in pixels.
* However, any other unit of measure (for example, time in days)
* could be just as valid.
*
* <p>
*
* <h4>Implementation Notes</h4>
*
* Normally when storing the size and position of entries,
* one would choose between
* storing the sizes or storing their positions
* instead. The two common operations that are needed during
* rendering are: <code>getIndex(position)</code>
* and <code>setSize(index, size)</code>.
* Whichever choice of internal format is made one of these
* operations is costly when the number of entries becomes large.
* If sizes are stored, finding the index of the entry
* that encloses a particular position is linear in the
* number of entries. If positions are stored instead, setting
* the size of an entry at a particular index requires updating
* the positions of the affected entries, which is also a linear
* calculation.
* <p>
* Like the above techniques this class holds an array of N integers
* internally but uses a hybrid encoding, which is halfway
* between the size-based and positional-based approaches.
* The result is a data structure that takes the same space to store
* the information but can perform most operations in Log(N) time
* instead of O(N), where N is the number of entries in the list.
* <p>
* Two operations that remain O(N) in the number of entries are
* the <code>insertEntries</code>
* and <code>removeEntries</code> methods, both
* of which are implemented by converting the internal array to
* a set of integer sizes, copying it into the new array, and then
* reforming the hybrid representation in place.
*
* @author Philip Milne
* @since 1.3
*/
/*
* Each method is implemented by taking the minimum and
* maximum of the range of integers that need to be operated
* upon. All the algorithms work by dividing this range
* into two smaller ranges and recursing. The recursion
* is terminated when the upper and lower bounds are equal.
*/
public class SizeSequence {
private static int[] emptyArray = new int[0];
private int a[];
/** {@collect.stats}
* Creates a new <code>SizeSequence</code> object
* that contains no entries. To add entries, you
* can use <code>insertEntries</code> or <code>setSizes</code>.
*
* @see #insertEntries
* @see #setSizes
*/
public SizeSequence() {
a = emptyArray;
}
/** {@collect.stats}
* Creates a new <code>SizeSequence</code> object
* that contains the specified number of entries,
* all initialized to have size 0.
*
* @param numEntries the number of sizes to track
* @exception NegativeArraySizeException if
* <code>numEntries < 0</code>
*/
public SizeSequence(int numEntries) {
this(numEntries, 0);
}
/** {@collect.stats}
* Creates a new <code>SizeSequence</code> object
* that contains the specified number of entries,
* all initialized to have size <code>value</code>.
*
* @param numEntries the number of sizes to track
* @param value the initial value of each size
*/
public SizeSequence(int numEntries, int value) {
this();
insertEntries(0, numEntries, value);
}
/** {@collect.stats}
* Creates a new <code>SizeSequence</code> object
* that contains the specified sizes.
*
* @param sizes the array of sizes to be contained in
* the <code>SizeSequence</code>
*/
public SizeSequence(int[] sizes) {
this();
setSizes(sizes);
}
/** {@collect.stats}
* Resets the size sequence to contain <code>length</code> items
* all with a size of <code>size</code>.
*/
void setSizes(int length, int size) {
if (a.length != length) {
a = new int[length];
}
setSizes(0, length, size);
}
private int setSizes(int from, int to, int size) {
if (to <= from) {
return 0;
}
int m = (from + to)/2;
a[m] = size + setSizes(from, m, size);
return a[m] + setSizes(m + 1, to, size);
}
/** {@collect.stats}
* Resets this <code>SizeSequence</code> object,
* using the data in the <code>sizes</code> argument.
* This method reinitializes this object so that it
* contains as many entries as the <code>sizes</code> array.
* Each entry's size is initialized to the value of the
* corresponding item in <code>sizes</code>.
*
* @param sizes the array of sizes to be contained in
* this <code>SizeSequence</code>
*/
public void setSizes(int[] sizes) {
if (a.length != sizes.length) {
a = new int[sizes.length];
}
setSizes(0, a.length, sizes);
}
private int setSizes(int from, int to, int[] sizes) {
if (to <= from) {
return 0;
}
int m = (from + to)/2;
a[m] = sizes[m] + setSizes(from, m, sizes);
return a[m] + setSizes(m + 1, to, sizes);
}
/** {@collect.stats}
* Returns the size of all entries.
*
* @return a new array containing the sizes in this object
*/
public int[] getSizes() {
int n = a.length;
int[] sizes = new int[n];
getSizes(0, n, sizes);
return sizes;
}
private int getSizes(int from, int to, int[] sizes) {
if (to <= from) {
return 0;
}
int m = (from + to)/2;
sizes[m] = a[m] - getSizes(from, m, sizes);
return a[m] + getSizes(m + 1, to, sizes);
}
/** {@collect.stats}
* Returns the start position for the specified entry.
* For example, <code>getPosition(0)</code> returns 0,
* <code>getPosition(1)</code> is equal to
* <code>getSize(0)</code>,
* <code>getPosition(2)</code> is equal to
* <code>getSize(0)</code> + <code>getSize(1)</code>,
* and so on.
* <p>Note that if <code>index</code> is greater than
* <code>length</code> the value returned may
* be meaningless.
*
* @param index the index of the entry whose position is desired
* @return the starting position of the specified entry
*/
public int getPosition(int index) {
return getPosition(0, a.length, index);
}
private int getPosition(int from, int to, int index) {
if (to <= from) {
return 0;
}
int m = (from + to)/2;
if (index <= m) {
return getPosition(from, m, index);
}
else {
return a[m] + getPosition(m + 1, to, index);
}
}
/** {@collect.stats}
* Returns the index of the entry
* that corresponds to the specified position.
* For example, <code>getIndex(0)</code> is 0,
* since the first entry always starts at position 0.
*
* @param position the position of the entry
* @return the index of the entry that occupies the specified position
*/
public int getIndex(int position) {
return getIndex(0, a.length, position);
}
private int getIndex(int from, int to, int position) {
if (to <= from) {
return from;
}
int m = (from + to)/2;
int pivot = a[m];
if (position < pivot) {
return getIndex(from, m, position);
}
else {
return getIndex(m + 1, to, position - pivot);
}
}
/** {@collect.stats}
* Returns the size of the specified entry.
* If <code>index</code> is out of the range
* <code>(0 <= index < getSizes().length)</code>
* the behavior is unspecified.
*
* @param index the index corresponding to the entry
* @return the size of the entry
*/
public int getSize(int index) {
return getPosition(index + 1) - getPosition(index);
}
/** {@collect.stats}
* Sets the size of the specified entry.
* Note that if the value of <code>index</code>
* does not fall in the range:
* <code>(0 <= index < getSizes().length)</code>
* the behavior is unspecified.
*
* @param index the index corresponding to the entry
* @param size the size of the entry
*/
public void setSize(int index, int size) {
changeSize(0, a.length, index, size - getSize(index));
}
private void changeSize(int from, int to, int index, int delta) {
if (to <= from) {
return;
}
int m = (from + to)/2;
if (index <= m) {
a[m] += delta;
changeSize(from, m, index, delta);
}
else {
changeSize(m + 1, to, index, delta);
}
}
/** {@collect.stats}
* Adds a contiguous group of entries to this <code>SizeSequence</code>.
* Note that the values of <code>start</code> and
* <code>length</code> must satisfy the following
* conditions: <code>(0 <= start < getSizes().length)
* AND (length >= 0)</code>. If these conditions are
* not met, the behavior is unspecified and an exception
* may be thrown.
*
* @param start the index to be assigned to the first entry
* in the group
* @param length the number of entries in the group
* @param value the size to be assigned to each new entry
* @exception ArrayIndexOutOfBoundsException if the parameters
* are outside of the range:
* (<code>0 <= start < (getSizes().length)) AND (length >= 0)</code>
*/
public void insertEntries(int start, int length, int value) {
int sizes[] = getSizes();
int end = start + length;
int n = a.length + length;
a = new int[n];
for (int i = 0; i < start; i++) {
a[i] = sizes[i] ;
}
for (int i = start; i < end; i++) {
a[i] = value ;
}
for (int i = end; i < n; i++) {
a[i] = sizes[i-length] ;
}
setSizes(a);
}
/** {@collect.stats}
* Removes a contiguous group of entries
* from this <code>SizeSequence</code>.
* Note that the values of <code>start</code> and
* <code>length</code> must satisfy the following
* conditions: <code>(0 <= start < getSizes().length)
* AND (length >= 0)</code>. If these conditions are
* not met, the behavior is unspecified and an exception
* may be thrown.
*
* @param start the index of the first entry to be removed
* @param length the number of entries to be removed
*/
public void removeEntries(int start, int length) {
int sizes[] = getSizes();
int end = start + length;
int n = a.length - length;
a = new int[n];
for (int i = 0; i < start; i++) {
a[i] = sizes[i] ;
}
for (int i = start; i < n; i++) {
a[i] = sizes[i+length] ;
}
setSizes(a);
}
}
|
Java
|
/*
* Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
/** {@collect.stats}
* An exception that indicates the requested look & feel
* management classes are not present on the user's system.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author unattributed
*/
public class UnsupportedLookAndFeelException extends Exception
{
/** {@collect.stats}
* Constructs an UnsupportedLookAndFeelException object.
* @param s a message String
*/
public UnsupportedLookAndFeelException(String s) {
super(s);
}
}
|
Java
|
/*
* Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.util.EventObject;
import javax.swing.event.*;
/** {@collect.stats}
* This interface defines the methods any general editor should be able
* to implement. <p>
*
* Having this interface enables complex components (the client of the
* editor) such as <code>JTree</code> and
* <code>JTable</code> to allow any generic editor to
* edit values in a table cell, or tree cell, etc. Without this generic
* editor interface, <code>JTable</code> would have to know about specific editors,
* such as <code>JTextField</code>, <code>JCheckBox</code>, <code>JComboBox</code>,
* etc. In addition, without this interface, clients of editors such as
* <code>JTable</code> would not be able
* to work with any editors developed in the future by the user
* or a 3rd party ISV. <p>
*
* To use this interface, a developer creating a new editor can have the
* new component implement the interface. Or the developer can
* choose a wrapper based approach and provide a companion object which
* implements the <code>CellEditor</code> interface (See
* <code>JCellEditor</code> for example). The wrapper approach
* is particularly useful if the user want to use a 3rd party ISV
* editor with <code>JTable</code>, but the ISV didn't implement the
* <code>CellEditor</code> interface. The user can simply create an object
* that contains an instance of the 3rd party editor object and "translate"
* the <code>CellEditor</code> API into the 3rd party editor's API.
*
* @see javax.swing.event.CellEditorListener
*
* @author Alan Chung
*/
public interface CellEditor {
/** {@collect.stats}
* Returns the value contained in the editor.
* @return the value contained in the editor
*/
public Object getCellEditorValue();
/** {@collect.stats}
* Asks the editor if it can start editing using <code>anEvent</code>.
* <code>anEvent</code> is in the invoking component coordinate system.
* The editor can not assume the Component returned by
* <code>getCellEditorComponent</code> is installed. This method
* is intended for the use of client to avoid the cost of setting up
* and installing the editor component if editing is not possible.
* If editing can be started this method returns true.
*
* @param anEvent the event the editor should use to consider
* whether to begin editing or not
* @return true if editing can be started
* @see #shouldSelectCell
*/
public boolean isCellEditable(EventObject anEvent);
/** {@collect.stats}
* Returns true if the editing cell should be selected, false otherwise.
* Typically, the return value is true, because is most cases the editing
* cell should be selected. However, it is useful to return false to
* keep the selection from changing for some types of edits.
* eg. A table that contains a column of check boxes, the user might
* want to be able to change those checkboxes without altering the
* selection. (See Netscape Communicator for just such an example)
* Of course, it is up to the client of the editor to use the return
* value, but it doesn't need to if it doesn't want to.
*
* @param anEvent the event the editor should use to start
* editing
* @return true if the editor would like the editing cell to be selected;
* otherwise returns false
* @see #isCellEditable
*/
public boolean shouldSelectCell(EventObject anEvent);
/** {@collect.stats}
* Tells the editor to stop editing and accept any partially edited
* value as the value of the editor. The editor returns false if
* editing was not stopped; this is useful for editors that validate
* and can not accept invalid entries.
*
* @return true if editing was stopped; false otherwise
*/
public boolean stopCellEditing();
/** {@collect.stats}
* Tells the editor to cancel editing and not accept any partially
* edited value.
*/
public void cancelCellEditing();
/** {@collect.stats}
* Adds a listener to the list that's notified when the editor
* stops, or cancels editing.
*
* @param l the CellEditorListener
*/
public void addCellEditorListener(CellEditorListener l);
/** {@collect.stats}
* Removes a listener from the list that's notified
*
* @param l the CellEditorListener
*/
public void removeCellEditorListener(CellEditorListener l);
}
|
Java
|
/*
* Copyright (c) 2000, 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.swing;
import java.util.*;
import java.io.Serializable;
/** {@collect.stats}
* A simple implementation of <code>SpinnerModel</code> whose
* values are defined by an array or a <code>List</code>.
* For example to create a model defined by
* an array of the names of the days of the week:
* <pre>
* String[] days = new DateFormatSymbols().getWeekdays();
* SpinnerModel model = new SpinnerListModel(Arrays.asList(days).subList(1, 8));
* </pre>
* This class only stores a reference to the array or <code>List</code>
* so if an element of the underlying sequence changes, it's up
* to the application to notify the <code>ChangeListeners</code> by calling
* <code>fireStateChanged</code>.
* <p>
* This model inherits a <code>ChangeListener</code>.
* The <code>ChangeListener</code>s are notified whenever the
* model's <code>value</code> or <code>list</code> properties changes.
*
* @see JSpinner
* @see SpinnerModel
* @see AbstractSpinnerModel
* @see SpinnerNumberModel
* @see SpinnerDateModel
*
* @author Hans Muller
* @since 1.4
*/
public class SpinnerListModel extends AbstractSpinnerModel implements Serializable
{
private List list;
private int index;
/** {@collect.stats}
* Constructs a <code>SpinnerModel</code> whose sequence of
* values is defined by the specified <code>List</code>.
* The initial value (<i>current element</i>)
* of the model will be <code>values.get(0)</code>.
* If <code>values</code> is <code>null</code> or has zero
* size, an <code>IllegalArugmentException</code> is thrown.
*
* @param values the sequence this model represents
* @throws IllegalArugmentException if <code>values</code> is
* <code>null</code> or zero size
*/
public SpinnerListModel(List<?> values) {
if (values == null || values.size() == 0) {
throw new IllegalArgumentException("SpinnerListModel(List) expects non-null non-empty List");
}
this.list = values;
this.index = 0;
}
/** {@collect.stats}
* Constructs a <code>SpinnerModel</code> whose sequence of values
* is defined by the specified array. The initial value of the model
* will be <code>values[0]</code>. If <code>values</code> is
* <code>null</code> or has zero length, an
* <code>IllegalArugmentException</code> is thrown.
*
* @param values the sequence this model represents
* @throws IllegalArugmentException if <code>values</code> is
* <code>null</code> or zero length
*/
public SpinnerListModel(Object[] values) {
if (values == null || values.length == 0) {
throw new IllegalArgumentException("SpinnerListModel(Object[]) expects non-null non-empty Object[]");
}
this.list = Arrays.asList(values);
this.index = 0;
}
/** {@collect.stats}
* Constructs an effectively empty <code>SpinnerListModel</code>.
* The model's list will contain a single
* <code>"empty"</code> string element.
*/
public SpinnerListModel() {
this(new Object[]{"empty"});
}
/** {@collect.stats}
* Returns the <code>List</code> that defines the sequence for this model.
*
* @return the value of the <code>list</code> property
* @see #setList
*/
public List<?> getList() {
return list;
}
/** {@collect.stats}
* Changes the list that defines this sequence and resets the index
* of the models <code>value</code> to zero. Note that <code>list</code>
* is not copied, the model just stores a reference to it.
* <p>
* This method fires a <code>ChangeEvent</code> if <code>list</code> is
* not equal to the current list.
*
* @param list the sequence that this model represents
* @throws IllegalArgumentException if <code>list</code> is
* <code>null</code> or zero length
* @see #getList
*/
public void setList(List<?> list) {
if ((list == null) || (list.size() == 0)) {
throw new IllegalArgumentException("invalid list");
}
if (!list.equals(this.list)) {
this.list = list;
index = 0;
fireStateChanged();
}
}
/** {@collect.stats}
* Returns the current element of the sequence.
*
* @return the <code>value</code> property
* @see SpinnerModel#getValue
* @see #setValue
*/
public Object getValue() {
return list.get(index);
}
/** {@collect.stats}
* Changes the current element of the sequence and notifies
* <code>ChangeListeners</code>. If the specified
* value is not equal to an element of the underlying sequence
* then an <code>IllegalArgumentException</code> is thrown.
* In the following example the <code>setValue</code> call
* would cause an exception to be thrown:
* <pre>
* String[] values = {"one", "two", "free", "four"};
* SpinnerModel model = new SpinnerListModel(values);
* model.setValue("TWO");
* </pre>
*
* @param elt the sequence element that will be model's current value
* @throws IllegalArgumentException if the specified value isn't allowed
* @see SpinnerModel#setValue
* @see #getValue
*/
public void setValue(Object elt) {
int index = list.indexOf(elt);
if (index == -1) {
throw new IllegalArgumentException("invalid sequence element");
}
else if (index != this.index) {
this.index = index;
fireStateChanged();
}
}
/** {@collect.stats}
* Returns the next legal value of the underlying sequence or
* <code>null</code> if value is already the last element.
*
* @return the next legal value of the underlying sequence or
* <code>null</code> if value is already the last element
* @see SpinnerModel#getNextValue
* @see #getPreviousValue
*/
public Object getNextValue() {
return (index >= (list.size() - 1)) ? null : list.get(index + 1);
}
/** {@collect.stats}
* Returns the previous element of the underlying sequence or
* <code>null</code> if value is already the first element.
*
* @return the previous element of the underlying sequence or
* <code>null</code> if value is already the first element
* @see SpinnerModel#getPreviousValue
* @see #getNextValue
*/
public Object getPreviousValue() {
return (index <= 0) ? null : list.get(index - 1);
}
/** {@collect.stats}
* Returns the next object that starts with <code>substring</code>.
*
* @param substring the string to be matched
* @return the match
*/
Object findNextMatch(String substring) {
int max = list.size();
if (max == 0) {
return null;
}
int counter = index;
do {
Object value = list.get(counter);
String string = value.toString();
if (string != null && string.startsWith(substring)) {
return value;
}
counter = (counter + 1) % max;
} while (counter != index);
return null;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.util.*;
/** {@collect.stats} Class used by DebugGraphics for maintaining information about how
* to render graphics calls.
*
* @author Dave Karlton
*/
class DebugGraphicsInfo {
Color flashColor = Color.red;
int flashTime = 100;
int flashCount = 2;
Hashtable componentToDebug;
JFrame debugFrame = null;
java.io.PrintStream stream = System.out;
void setDebugOptions(JComponent component, int debug) {
if (debug == 0) {
return;
}
if (componentToDebug == null) {
componentToDebug = new Hashtable();
}
if (debug > 0) {
componentToDebug.put(component, new Integer(debug));
} else {
componentToDebug.remove(component);
}
}
int getDebugOptions(JComponent component) {
if (componentToDebug == null) {
return 0;
} else {
Integer integer = (Integer)componentToDebug.get(component);
return integer == null ? 0 : integer.intValue();
}
}
void log(String string) {
stream.println(string);
}
}
|
Java
|
/*
* Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.beans.*;
import java.util.Vector;
import javax.accessibility.*;
import javax.swing.plaf.PopupMenuUI;
import javax.swing.plaf.basic.BasicComboPopup;
import javax.swing.event.*;
/** {@collect.stats}
* An implementation of a popup menu -- a small window that pops up
* and displays a series of choices. A <code>JPopupMenu</code> is used for the
* menu that appears when the user selects an item on the menu bar.
* It is also used for "pull-right" menu that appears when the
* selects a menu item that activates it. Finally, a <code>JPopupMenu</code>
* can also be used anywhere else you want a menu to appear. For
* example, when the user right-clicks in a specified area.
* <p>
* For information and examples of using popup menus, see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html">How to Use Menus</a>
* in <em>The Java Tutorial.</em>
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @beaninfo
* attribute: isContainer false
* description: A small window that pops up and displays a series of choices.
*
* @author Georges Saab
* @author David Karlton
* @author Arnaud Weber
*/
public class JPopupMenu extends JComponent implements Accessible,MenuElement {
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "PopupMenuUI";
/** {@collect.stats}
* Key used in AppContext to determine if light way popups are the default.
*/
private static final Object defaultLWPopupEnabledKey = new Object(); // JPopupMenu.defaultLWPopupEnabledKey
/** {@collect.stats} Bug#4425878-Property javax.swing.adjustPopupLocationToFit introduced */
static boolean popupPostionFixDisabled = false;
static {
popupPostionFixDisabled = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction(
"javax.swing.adjustPopupLocationToFit","")).equals("false");
}
transient Component invoker;
transient Popup popup;
transient Frame frame;
private int desiredLocationX,desiredLocationY;
private String label = null;
private boolean paintBorder = true;
private Insets margin = null;
/** {@collect.stats}
* Used to indicate if lightweight popups should be used.
*/
private boolean lightWeightPopup = true;
/*
* Model for the selected subcontrol.
*/
private SingleSelectionModel selectionModel;
/* Lock object used in place of class object for synchronization.
* (4187686)
*/
private static final Object classLock = new Object();
/* diagnostic aids -- should be false for production builds. */
private static final boolean TRACE = false; // trace creates and disposes
private static final boolean VERBOSE = false; // show reuse hits/misses
private static final boolean DEBUG = false; // show bad params, misc.
/** {@collect.stats}
* Sets the default value of the <code>lightWeightPopupEnabled</code>
* property.
*
* @param aFlag <code>true</code> if popups can be lightweight,
* otherwise <code>false</code>
* @see #getDefaultLightWeightPopupEnabled
* @see #setLightWeightPopupEnabled
*/
public static void setDefaultLightWeightPopupEnabled(boolean aFlag) {
SwingUtilities.appContextPut(defaultLWPopupEnabledKey,
Boolean.valueOf(aFlag));
}
/** {@collect.stats}
* Gets the <code>defaultLightWeightPopupEnabled</code> property,
* which by default is <code>true</code>.
*
* @return the value of the <code>defaultLightWeightPopupEnabled</code>
* property
*
* @see #setDefaultLightWeightPopupEnabled
*/
public static boolean getDefaultLightWeightPopupEnabled() {
Boolean b = (Boolean)
SwingUtilities.appContextGet(defaultLWPopupEnabledKey);
if (b == null) {
SwingUtilities.appContextPut(defaultLWPopupEnabledKey,
Boolean.TRUE);
return true;
}
return b.booleanValue();
}
/** {@collect.stats}
* Constructs a <code>JPopupMenu</code> without an "invoker".
*/
public JPopupMenu() {
this(null);
}
/** {@collect.stats}
* Constructs a <code>JPopupMenu</code> with the specified title.
*
* @param label the string that a UI may use to display as a title
* for the popup menu.
*/
public JPopupMenu(String label) {
this.label = label;
lightWeightPopup = getDefaultLightWeightPopupEnabled();
setSelectionModel(new DefaultSingleSelectionModel());
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
setFocusTraversalKeysEnabled(false);
updateUI();
}
/** {@collect.stats}
* Returns the look and feel (L&F) object that renders this component.
*
* @return the <code>PopupMenuUI</code> object that renders this component
*/
public PopupMenuUI getUI() {
return (PopupMenuUI)ui;
}
/** {@collect.stats}
* Sets the L&F object that renders this component.
*
* @param ui the new <code>PopupMenuUI</code> L&F object
* @see UIDefaults#getUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel.
*/
public void setUI(PopupMenuUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((PopupMenuUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return the string "PopupMenuUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
protected void processFocusEvent(FocusEvent evt) {
super.processFocusEvent(evt);
}
/** {@collect.stats}
* Processes key stroke events such as mnemonics and accelerators.
*
* @param evt the key event to be processed
*/
protected void processKeyEvent(KeyEvent evt) {
MenuSelectionManager.defaultManager().processKeyEvent(evt);
if (evt.isConsumed()) {
return;
}
super.processKeyEvent(evt);
}
/** {@collect.stats}
* Returns the model object that handles single selections.
*
* @return the <code>selectionModel</code> property
* @see SingleSelectionModel
*/
public SingleSelectionModel getSelectionModel() {
return selectionModel;
}
/** {@collect.stats}
* Sets the model object to handle single selections.
*
* @param model the new <code>SingleSelectionModel</code>
* @see SingleSelectionModel
* @beaninfo
* description: The selection model for the popup menu
* expert: true
*/
public void setSelectionModel(SingleSelectionModel model) {
selectionModel = model;
}
/** {@collect.stats}
* Appends the specified menu item to the end of this menu.
*
* @param menuItem the <code>JMenuItem</code> to add
* @return the <code>JMenuItem</code> added
*/
public JMenuItem add(JMenuItem menuItem) {
super.add(menuItem);
return menuItem;
}
/** {@collect.stats}
* Creates a new menu item with the specified text and appends
* it to the end of this menu.
*
* @param s the string for the menu item to be added
*/
public JMenuItem add(String s) {
return add(new JMenuItem(s));
}
/** {@collect.stats}
* Appends a new menu item to the end of the menu which
* dispatches the specified <code>Action</code> object.
*
* @param a the <code>Action</code> to add to the menu
* @return the new menu item
* @see Action
*/
public JMenuItem add(Action a) {
JMenuItem mi = createActionComponent(a);
mi.setAction(a);
add(mi);
return mi;
}
/** {@collect.stats}
* Returns an point which has been adjusted to take into account of the
* desktop bounds, taskbar and multi-monitor configuration.
* <p>
* This adustment may be cancelled by invoking the application with
* -Djavax.swing.adjustPopupLocationToFit=false
*/
Point adjustPopupLocationToFitScreen(int xposition, int yposition) {
Point p = new Point(xposition, yposition);
if(popupPostionFixDisabled == true || GraphicsEnvironment.isHeadless())
return p;
Toolkit toolkit = Toolkit.getDefaultToolkit();
Rectangle screenBounds;
GraphicsConfiguration gc = null;
// Try to find GraphicsConfiguration, that includes mouse
// pointer position
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gd = ge.getScreenDevices();
for(int i = 0; i < gd.length; i++) {
if(gd[i].getType() == GraphicsDevice.TYPE_RASTER_SCREEN) {
GraphicsConfiguration dgc =
gd[i].getDefaultConfiguration();
if(dgc.getBounds().contains(p)) {
gc = dgc;
break;
}
}
}
// If not found and we have invoker, ask invoker about his gc
if(gc == null && getInvoker() != null) {
gc = getInvoker().getGraphicsConfiguration();
}
if(gc != null) {
// If we have GraphicsConfiguration use it to get
// screen bounds
screenBounds = gc.getBounds();
} else {
// If we don't have GraphicsConfiguration use primary screen
screenBounds = new Rectangle(toolkit.getScreenSize());
}
Dimension size;
size = JPopupMenu.this.getPreferredSize();
// Use long variables to prevent overflow
long pw = (long) p.x + (long) size.width;
long ph = (long) p.y + (long) size.height;
if( pw > screenBounds.x + screenBounds.width )
p.x = screenBounds.x + screenBounds.width - size.width;
if( ph > screenBounds.y + screenBounds.height)
p.y = screenBounds.y + screenBounds.height - size.height;
/* Change is made to the desired (X,Y) values, when the
PopupMenu is too tall OR too wide for the screen
*/
if( p.x < screenBounds.x )
p.x = screenBounds.x ;
if( p.y < screenBounds.y )
p.y = screenBounds.y;
return p;
}
/** {@collect.stats}
* Factory method which creates the <code>JMenuItem</code> for
* <code>Actions</code> added to the <code>JPopupMenu</code>.
*
* @param a the <code>Action</code> for the menu item to be added
* @return the new menu item
* @see Action
*
* @since 1.3
*/
protected JMenuItem createActionComponent(Action a) {
JMenuItem mi = new JMenuItem() {
protected PropertyChangeListener createActionPropertyChangeListener(Action a) {
PropertyChangeListener pcl = createActionChangeListener(this);
if (pcl == null) {
pcl = super.createActionPropertyChangeListener(a);
}
return pcl;
}
};
mi.setHorizontalTextPosition(JButton.TRAILING);
mi.setVerticalTextPosition(JButton.CENTER);
return mi;
}
/** {@collect.stats}
* Returns a properly configured <code>PropertyChangeListener</code>
* which updates the control as changes to the <code>Action</code> occur.
*/
protected PropertyChangeListener createActionChangeListener(JMenuItem b) {
return b.createActionPropertyChangeListener0(b.getAction());
}
/** {@collect.stats}
* Removes the component at the specified index from this popup menu.
*
* @param pos the position of the item to be removed
* @exception IllegalArgumentException if the value of
* <code>pos</code> < 0, or if the value of
* <code>pos</code> is greater than the
* number of items
*/
public void remove(int pos) {
if (pos < 0) {
throw new IllegalArgumentException("index less than zero.");
}
if (pos > getComponentCount() -1) {
throw new IllegalArgumentException("index greater than the number of items.");
}
super.remove(pos);
}
/** {@collect.stats}
* Sets the value of the <code>lightWeightPopupEnabled</code> property,
* which by default is <code>true</code>.
* By default, when a look and feel displays a popup,
* it can choose to
* use a lightweight (all-Java) popup.
* Lightweight popup windows are more efficient than heavyweight
* (native peer) windows,
* but lightweight and heavyweight components do not mix well in a GUI.
* If your application mixes lightweight and heavyweight components,
* you should disable lightweight popups.
* Some look and feels might always use heavyweight popups,
* no matter what the value of this property.
*
* @param aFlag <code>false</code> to disable lightweight popups
* @beaninfo
* description: Determines whether lightweight popups are used when possible
* expert: true
*
* @see #isLightWeightPopupEnabled
*/
public void setLightWeightPopupEnabled(boolean aFlag) {
// NOTE: this use to set the flag on a shared JPopupMenu, which meant
// this effected ALL JPopupMenus.
lightWeightPopup = aFlag;
}
/** {@collect.stats}
* Gets the <code>lightWeightPopupEnabled</code> property.
*
* @return the value of the <code>lightWeightPopupEnabled</code> property
* @see #setLightWeightPopupEnabled
*/
public boolean isLightWeightPopupEnabled() {
return lightWeightPopup;
}
/** {@collect.stats}
* Returns the popup menu's label
*
* @return a string containing the popup menu's label
* @see #setLabel
*/
public String getLabel() {
return label;
}
/** {@collect.stats}
* Sets the popup menu's label. Different look and feels may choose
* to display or not display this.
*
* @param label a string specifying the label for the popup menu
*
* @see #setLabel
* @beaninfo
* description: The label for the popup menu.
* bound: true
*/
public void setLabel(String label) {
String oldValue = this.label;
this.label = label;
firePropertyChange("label", oldValue, label);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
oldValue, label);
}
invalidate();
repaint();
}
/** {@collect.stats}
* Appends a new separator at the end of the menu.
*/
public void addSeparator() {
add( new JPopupMenu.Separator() );
}
/** {@collect.stats}
* Inserts a menu item for the specified <code>Action</code> object at
* a given position.
*
* @param a the <code>Action</code> object to insert
* @param index specifies the position at which to insert the
* <code>Action</code>, where 0 is the first
* @exception IllegalArgumentException if <code>index</code> < 0
* @see Action
*/
public void insert(Action a, int index) {
JMenuItem mi = createActionComponent(a);
mi.setAction(a);
insert(mi, index);
}
/** {@collect.stats}
* Inserts the specified component into the menu at a given
* position.
*
* @param component the <code>Component</code> to insert
* @param index specifies the position at which
* to insert the component, where 0 is the first
* @exception IllegalArgumentException if <code>index</code> < 0
*/
public void insert(Component component, int index) {
if (index < 0) {
throw new IllegalArgumentException("index less than zero.");
}
int nitems = getComponentCount();
// PENDING(ges): Why not use an array?
Vector tempItems = new Vector();
/* Remove the item at index, nitems-index times
storing them in a temporary vector in the
order they appear on the menu.
*/
for (int i = index ; i < nitems; i++) {
tempItems.addElement(getComponent(index));
remove(index);
}
add(component);
/* Add the removed items back to the menu, they are
already in the correct order in the temp vector.
*/
for (int i = 0; i < tempItems.size() ; i++) {
add((Component)tempItems.elementAt(i));
}
}
/** {@collect.stats}
* Adds a <code>PopupMenu</code> listener.
*
* @param l the <code>PopupMenuListener</code> to add
*/
public void addPopupMenuListener(PopupMenuListener l) {
listenerList.add(PopupMenuListener.class,l);
}
/** {@collect.stats}
* Removes a <code>PopupMenu</code> listener.
*
* @param l the <code>PopupMenuListener</code> to remove
*/
public void removePopupMenuListener(PopupMenuListener l) {
listenerList.remove(PopupMenuListener.class,l);
}
/** {@collect.stats}
* Returns an array of all the <code>PopupMenuListener</code>s added
* to this JMenuItem with addPopupMenuListener().
*
* @return all of the <code>PopupMenuListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public PopupMenuListener[] getPopupMenuListeners() {
return (PopupMenuListener[])listenerList.getListeners(
PopupMenuListener.class);
}
/** {@collect.stats}
* Adds a <code>MenuKeyListener</code> to the popup menu.
*
* @param l the <code>MenuKeyListener</code> to be added
* @since 1.5
*/
public void addMenuKeyListener(MenuKeyListener l) {
listenerList.add(MenuKeyListener.class, l);
}
/** {@collect.stats}
* Removes a <code>MenuKeyListener</code> from the popup menu.
*
* @param l the <code>MenuKeyListener</code> to be removed
* @since 1.5
*/
public void removeMenuKeyListener(MenuKeyListener l) {
listenerList.remove(MenuKeyListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>MenuKeyListener</code>s added
* to this JPopupMenu with addMenuKeyListener().
*
* @return all of the <code>MenuKeyListener</code>s added or an empty
* array if no listeners have been added
* @since 1.5
*/
public MenuKeyListener[] getMenuKeyListeners() {
return (MenuKeyListener[])listenerList.getListeners(
MenuKeyListener.class);
}
/** {@collect.stats}
* Notifies <code>PopupMenuListener</code>s that this popup menu will
* become visible.
*/
protected void firePopupMenuWillBecomeVisible() {
Object[] listeners = listenerList.getListenerList();
PopupMenuEvent e=null;
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==PopupMenuListener.class) {
if (e == null)
e = new PopupMenuEvent(this);
((PopupMenuListener)listeners[i+1]).popupMenuWillBecomeVisible(e);
}
}
}
/** {@collect.stats}
* Notifies <code>PopupMenuListener</code>s that this popup menu will
* become invisible.
*/
protected void firePopupMenuWillBecomeInvisible() {
Object[] listeners = listenerList.getListenerList();
PopupMenuEvent e=null;
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==PopupMenuListener.class) {
if (e == null)
e = new PopupMenuEvent(this);
((PopupMenuListener)listeners[i+1]).popupMenuWillBecomeInvisible(e);
}
}
}
/** {@collect.stats}
* Notifies <code>PopupMenuListeners</code> that this popup menu is
* cancelled.
*/
protected void firePopupMenuCanceled() {
Object[] listeners = listenerList.getListenerList();
PopupMenuEvent e=null;
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==PopupMenuListener.class) {
if (e == null)
e = new PopupMenuEvent(this);
((PopupMenuListener)listeners[i+1]).popupMenuCanceled(e);
}
}
}
/** {@collect.stats}
* Always returns true since popups, by definition, should always
* be on top of all other windows.
* @return true
*/
// package private
boolean alwaysOnTop() {
return true;
}
/** {@collect.stats}
* Lays out the container so that it uses the minimum space
* needed to display its contents.
*/
public void pack() {
if(popup != null) {
Dimension pref = getPreferredSize();
if (pref == null || pref.width != getWidth() ||
pref.height != getHeight()) {
popup = getPopup();
} else {
validate();
}
}
}
/** {@collect.stats}
* Sets the visibility of the popup menu.
*
* @param b true to make the popup visible, or false to
* hide it
* @beaninfo
* bound: true
* description: Makes the popup visible
*/
public void setVisible(boolean b) {
if (DEBUG) {
System.out.println("JPopupMenu.setVisible " + b);
}
// Is it a no-op?
if (b == isVisible())
return;
// if closing, first close all Submenus
if (b == false) {
// 4234793: This is a workaround because JPopupMenu.firePopupMenuCanceled is
// a protected method and cannot be called from BasicPopupMenuUI directly
// The real solution could be to make
// firePopupMenuCanceled public and call it directly.
Boolean doCanceled = (Boolean)getClientProperty("JPopupMenu.firePopupMenuCanceled");
if (doCanceled != null && doCanceled == Boolean.TRUE) {
putClientProperty("JPopupMenu.firePopupMenuCanceled", Boolean.FALSE);
firePopupMenuCanceled();
}
getSelectionModel().clearSelection();
} else {
// This is a popup menu with MenuElement children,
// set selection path before popping up!
if (isPopupMenu()) {
MenuElement me[] = new MenuElement[1];
me[0] = (MenuElement) this;
MenuSelectionManager.defaultManager().setSelectedPath(me);
}
}
if(b) {
firePopupMenuWillBecomeVisible();
popup = getPopup();
firePropertyChange("visible", Boolean.FALSE, Boolean.TRUE);
} else if(popup != null) {
firePopupMenuWillBecomeInvisible();
popup.hide();
popup = null;
firePropertyChange("visible", Boolean.TRUE, Boolean.FALSE);
// 4694797: When popup menu is made invisible, selected path
// should be cleared
if (isPopupMenu()) {
MenuSelectionManager.defaultManager().clearSelectedPath();
}
}
}
/** {@collect.stats}
* Returns a <code>Popup</code> instance from the
* <code>PopupMenuUI</code> that has had <code>show</code> invoked on
* it. If the current <code>popup</code> is non-null,
* this will invoke <code>dispose</code> of it, and then
* <code>show</code> the new one.
* <p>
* This does NOT fire any events, it is up the caller to dispatch
* the necessary events.
*/
private Popup getPopup() {
Popup oldPopup = popup;
if (oldPopup != null) {
oldPopup.hide();
}
PopupFactory popupFactory = PopupFactory.getSharedInstance();
if (isLightWeightPopupEnabled()) {
popupFactory.setPopupType(PopupFactory.LIGHT_WEIGHT_POPUP);
}
else {
popupFactory.setPopupType(PopupFactory.MEDIUM_WEIGHT_POPUP);
}
// adjust the location of the popup
Point p = adjustPopupLocationToFitScreen(desiredLocationX,desiredLocationY);
desiredLocationX = p.x;
desiredLocationY = p.y;
Popup newPopup = getUI().getPopup(this, desiredLocationX,
desiredLocationY);
popupFactory.setPopupType(PopupFactory.LIGHT_WEIGHT_POPUP);
newPopup.show();
return newPopup;
}
/** {@collect.stats}
* Returns true if the popup menu is visible (currently
* being displayed).
*/
public boolean isVisible() {
if(popup != null)
return true;
else
return false;
}
/** {@collect.stats}
* Sets the location of the upper left corner of the
* popup menu using x, y coordinates.
*
* @param x the x coordinate of the popup's new position
* in the screen's coordinate space
* @param y the y coordinate of the popup's new position
* in the screen's coordinate space
* @beaninfo
* description: The location of the popup menu.
*/
public void setLocation(int x, int y) {
int oldX = desiredLocationX;
int oldY = desiredLocationY;
desiredLocationX = x;
desiredLocationY = y;
if(popup != null && (x != oldX || y != oldY)) {
popup = getPopup();
}
}
/** {@collect.stats}
* Returns true if the popup menu is a standalone popup menu
* rather than the submenu of a <code>JMenu</code>.
*
* @return true if this menu is a standalone popup menu, otherwise false
*/
private boolean isPopupMenu() {
return ((invoker != null) && !(invoker instanceof JMenu));
}
/** {@collect.stats}
* Returns the component which is the 'invoker' of this
* popup menu.
*
* @return the <code>Component</code> in which the popup menu is displayed
*/
public Component getInvoker() {
return this.invoker;
}
/** {@collect.stats}
* Sets the invoker of this popup menu -- the component in which
* the popup menu menu is to be displayed.
*
* @param invoker the <code>Component</code> in which the popup
* menu is displayed
* @beaninfo
* description: The invoking component for the popup menu
* expert: true
*/
public void setInvoker(Component invoker) {
Component oldInvoker = this.invoker;
this.invoker = invoker;
if ((oldInvoker != this.invoker) && (ui != null)) {
ui.uninstallUI(this);
ui.installUI(this);
}
invalidate();
}
/** {@collect.stats}
* Displays the popup menu at the position x,y in the coordinate
* space of the component invoker.
*
* @param invoker the component in whose space the popup menu is to appear
* @param x the x coordinate in invoker's coordinate space at which
* the popup menu is to be displayed
* @param y the y coordinate in invoker's coordinate space at which
* the popup menu is to be displayed
*/
public void show(Component invoker, int x, int y) {
if (DEBUG) {
System.out.println("in JPopupMenu.show " );
}
setInvoker(invoker);
Frame newFrame = getFrame(invoker);
if (newFrame != frame) {
// Use the invoker's frame so that events
// are propagated properly
if (newFrame!=null) {
this.frame = newFrame;
if(popup != null) {
setVisible(false);
}
}
}
Point invokerOrigin;
if (invoker != null) {
invokerOrigin = invoker.getLocationOnScreen();
// To avoid integer overflow
long lx, ly;
lx = ((long) invokerOrigin.x) +
((long) x);
ly = ((long) invokerOrigin.y) +
((long) y);
if(lx > Integer.MAX_VALUE) lx = Integer.MAX_VALUE;
if(lx < Integer.MIN_VALUE) lx = Integer.MIN_VALUE;
if(ly > Integer.MAX_VALUE) ly = Integer.MAX_VALUE;
if(ly < Integer.MIN_VALUE) ly = Integer.MIN_VALUE;
setLocation((int) lx, (int) ly);
} else {
setLocation(x, y);
}
setVisible(true);
}
/** {@collect.stats}
* Returns the popup menu which is at the root of the menu system
* for this popup menu.
*
* @return the topmost grandparent <code>JPopupMenu</code>
*/
JPopupMenu getRootPopupMenu() {
JPopupMenu mp = this;
while((mp!=null) && (mp.isPopupMenu()!=true) &&
(mp.getInvoker() != null) &&
(mp.getInvoker().getParent() != null) &&
(mp.getInvoker().getParent() instanceof JPopupMenu)
) {
mp = (JPopupMenu) mp.getInvoker().getParent();
}
return mp;
}
/** {@collect.stats}
* Returns the component at the specified index.
*
* @param i the index of the component, where 0 is the first
* @return the <code>Component</code> at that index
* @deprecated replaced by {@link java.awt.Container#getComponent(int)}
*/
@Deprecated
public Component getComponentAtIndex(int i) {
return getComponent(i);
}
/** {@collect.stats}
* Returns the index of the specified component.
*
* @param c the <code>Component</code> to find
* @return the index of the component, where 0 is the first;
* or -1 if the component is not found
*/
public int getComponentIndex(Component c) {
int ncomponents = this.getComponentCount();
Component[] component = this.getComponents();
for (int i = 0 ; i < ncomponents ; i++) {
Component comp = component[i];
if (comp == c)
return i;
}
return -1;
}
/** {@collect.stats}
* Sets the size of the Popup window using a <code>Dimension</code> object.
* This is equivalent to <code>setPreferredSize(d)</code>.
*
* @param d the <code>Dimension</code> specifying the new size
* of this component.
* @beaninfo
* description: The size of the popup menu
*/
public void setPopupSize(Dimension d) {
Dimension oldSize = getPreferredSize();
setPreferredSize(d);
if (popup != null) {
Dimension newSize = getPreferredSize();
if (!oldSize.equals(newSize)) {
popup = getPopup();
}
}
}
/** {@collect.stats}
* Sets the size of the Popup window to the specified width and
* height. This is equivalent to
* <code>setPreferredSize(new Dimension(width, height))</code>.
*
* @param width the new width of the Popup in pixels
* @param height the new height of the Popup in pixels
* @beaninfo
* description: The size of the popup menu
*/
public void setPopupSize(int width, int height) {
setPopupSize(new Dimension(width, height));
}
/** {@collect.stats}
* Sets the currently selected component, This will result
* in a change to the selection model.
*
* @param sel the <code>Component</code> to select
* @beaninfo
* description: The selected component on the popup menu
* expert: true
* hidden: true
*/
public void setSelected(Component sel) {
SingleSelectionModel model = getSelectionModel();
int index = getComponentIndex(sel);
model.setSelectedIndex(index);
}
/** {@collect.stats}
* Checks whether the border should be painted.
*
* @return true if the border is painted, false otherwise
* @see #setBorderPainted
*/
public boolean isBorderPainted() {
return paintBorder;
}
/** {@collect.stats}
* Sets whether the border should be painted.
*
* @param b if true, the border is painted.
* @see #isBorderPainted
* @beaninfo
* description: Is the border of the popup menu painted
*/
public void setBorderPainted(boolean b) {
paintBorder = b;
repaint();
}
/** {@collect.stats}
* Paints the popup menu's border if the <code>borderPainted</code>
* property is <code>true</code>.
* @param g the <code>Graphics</code> object
*
* @see JComponent#paint
* @see JComponent#setBorder
*/
protected void paintBorder(Graphics g) {
if (isBorderPainted()) {
super.paintBorder(g);
}
}
/** {@collect.stats}
* Returns the margin, in pixels, between the popup menu's border and
* its containees.
*
* @return an <code>Insets</code> object containing the margin values.
*/
public Insets getMargin() {
if(margin == null) {
return new Insets(0,0,0,0);
} else {
return margin;
}
}
/** {@collect.stats}
* Examines the list of menu items to determine whether
* <code>popup</code> is a popup menu.
*
* @param popup a <code>JPopupMenu</code>
* @return true if <code>popup</code>
*/
boolean isSubPopupMenu(JPopupMenu popup) {
int ncomponents = this.getComponentCount();
Component[] component = this.getComponents();
for (int i = 0 ; i < ncomponents ; i++) {
Component comp = component[i];
if (comp instanceof JMenu) {
JMenu menu = (JMenu)comp;
JPopupMenu subPopup = menu.getPopupMenu();
if (subPopup == popup)
return true;
if (subPopup.isSubPopupMenu(popup))
return true;
}
}
return false;
}
private static Frame getFrame(Component c) {
Component w = c;
while(!(w instanceof Frame) && (w!=null)) {
w = w.getParent();
}
return (Frame)w;
}
/** {@collect.stats}
* Returns a string representation of this <code>JPopupMenu</code>.
* This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JPopupMenu</code>.
*/
protected String paramString() {
String labelString = (label != null ?
label : "");
String paintBorderString = (paintBorder ?
"true" : "false");
String marginString = (margin != null ?
margin.toString() : "");
String lightWeightPopupEnabledString = (isLightWeightPopupEnabled() ?
"true" : "false");
return super.paramString() +
",desiredLocationX=" + desiredLocationX +
",desiredLocationY=" + desiredLocationY +
",label=" + labelString +
",lightWeightPopupEnabled=" + lightWeightPopupEnabledString +
",margin=" + marginString +
",paintBorder=" + paintBorderString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JPopupMenu.
* For JPopupMenus, the AccessibleContext takes the form of an
* AccessibleJPopupMenu.
* A new AccessibleJPopupMenu instance is created if necessary.
*
* @return an AccessibleJPopupMenu that serves as the
* AccessibleContext of this JPopupMenu
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJPopupMenu();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JPopupMenu</code> class. It provides an implementation of the
* Java Accessibility API appropriate to popup menu user-interface
* elements.
*/
protected class AccessibleJPopupMenu extends AccessibleJComponent
implements PropertyChangeListener {
/** {@collect.stats}
* AccessibleJPopupMenu constructor
*
* @since 1.5
*/
protected AccessibleJPopupMenu() {
JPopupMenu.this.addPropertyChangeListener(this);
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of
* the object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.POPUP_MENU;
}
/** {@collect.stats}
* This method gets called when a bound property is changed.
* @param e A <code>PropertyChangeEvent</code> object describing
* the event source and the property that has changed. Must not be null.
*
* @throws NullPointerException if the parameter is null.
* @since 1.5
*/
public void propertyChange(PropertyChangeEvent e) {
String propertyName = e.getPropertyName();
if (propertyName == "visible") {
if (e.getOldValue() == Boolean.FALSE &&
e.getNewValue() == Boolean.TRUE) {
handlePopupIsVisibleEvent(true);
} else if (e.getOldValue() == Boolean.TRUE &&
e.getNewValue() == Boolean.FALSE) {
handlePopupIsVisibleEvent(false);
}
}
}
/*
* Handles popup "visible" PropertyChangeEvent
*/
private void handlePopupIsVisibleEvent(boolean visible) {
if (visible) {
// notify listeners that the popup became visible
firePropertyChange(ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.VISIBLE);
// notify listeners that a popup list item is selected
fireActiveDescendant();
} else {
// notify listeners that the popup became hidden
firePropertyChange(ACCESSIBLE_STATE_PROPERTY,
AccessibleState.VISIBLE, null);
}
}
/*
* Fires AccessibleActiveDescendant PropertyChangeEvent to notify listeners
* on the popup menu invoker that a popup list item has been selected
*/
private void fireActiveDescendant() {
if (JPopupMenu.this instanceof BasicComboPopup) {
// get the popup list
JList popupList = ((BasicComboPopup)JPopupMenu.this).getList();
if (popupList == null) {
return;
}
// get the first selected item
AccessibleContext ac = popupList.getAccessibleContext();
AccessibleSelection selection = ac.getAccessibleSelection();
if (selection == null) {
return;
}
Accessible a = selection.getAccessibleSelection(0);
if (a == null) {
return;
}
AccessibleContext selectedItem = a.getAccessibleContext();
// fire the event with the popup invoker as the source.
if (selectedItem != null && invoker != null) {
AccessibleContext invokerContext = invoker.getAccessibleContext();
if (invokerContext != null) {
// Check invokerContext because Component.getAccessibleContext
// returns null. Classes that extend Component are responsible
// for returning a non-null AccessibleContext.
invokerContext.firePropertyChange(
ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY,
null, selectedItem);
}
}
}
}
} // inner class AccessibleJPopupMenu
////////////
// Serialization support.
////////////
private void writeObject(ObjectOutputStream s) throws IOException {
Vector values = new Vector();
s.defaultWriteObject();
// Save the invoker, if its Serializable.
if(invoker != null && invoker instanceof Serializable) {
values.addElement("invoker");
values.addElement(invoker);
}
// Save the popup, if its Serializable.
if(popup != null && popup instanceof Serializable) {
values.addElement("popup");
values.addElement(popup);
}
s.writeObject(values);
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
// implements javax.swing.MenuElement
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
Vector values = (Vector)s.readObject();
int indexCounter = 0;
int maxCounter = values.size();
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("invoker")) {
invoker = (Component)values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("popup")) {
popup = (Popup)values.elementAt(++indexCounter);
indexCounter++;
}
}
/** {@collect.stats}
* This method is required to conform to the
* <code>MenuElement</code> interface, but it not implemented.
* @see MenuElement#processMouseEvent(MouseEvent, MenuElement[], MenuSelectionManager)
*/
public void processMouseEvent(MouseEvent event,MenuElement path[],MenuSelectionManager manager) {}
/** {@collect.stats}
* Processes a key event forwarded from the
* <code>MenuSelectionManager</code> and changes the menu selection,
* if necessary, by using <code>MenuSelectionManager</code>'s API.
* <p>
* Note: you do not have to forward the event to sub-components.
* This is done automatically by the <code>MenuSelectionManager</code>.
*
* @param e a <code>KeyEvent</code>
* @param path the <code>MenuElement</code> path array
* @param manager the <code>MenuSelectionManager</code>
*/
public void processKeyEvent(KeyEvent e, MenuElement path[],
MenuSelectionManager manager) {
MenuKeyEvent mke = new MenuKeyEvent(e.getComponent(), e.getID(),
e.getWhen(), e.getModifiers(),
e.getKeyCode(), e.getKeyChar(),
path, manager);
processMenuKeyEvent(mke);
if (mke.isConsumed()) {
e.consume();
}
}
/** {@collect.stats}
* Handles a keystroke in a menu.
*
* @param e a <code>MenuKeyEvent</code> object
* @since 1.5
*/
private void processMenuKeyEvent(MenuKeyEvent e) {
switch (e.getID()) {
case KeyEvent.KEY_PRESSED:
fireMenuKeyPressed(e); break;
case KeyEvent.KEY_RELEASED:
fireMenuKeyReleased(e); break;
case KeyEvent.KEY_TYPED:
fireMenuKeyTyped(e); break;
default:
break;
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @param event a <code>MenuKeyEvent</code>
* @see EventListenerList
*/
private void fireMenuKeyPressed(MenuKeyEvent event) {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==MenuKeyListener.class) {
((MenuKeyListener)listeners[i+1]).menuKeyPressed(event);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @param event a <code>MenuKeyEvent</code>
* @see EventListenerList
*/
private void fireMenuKeyReleased(MenuKeyEvent event) {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==MenuKeyListener.class) {
((MenuKeyListener)listeners[i+1]).menuKeyReleased(event);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @param event a <code>MenuKeyEvent</code>
* @see EventListenerList
*/
private void fireMenuKeyTyped(MenuKeyEvent event) {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==MenuKeyListener.class) {
((MenuKeyListener)listeners[i+1]).menuKeyTyped(event);
}
}
}
/** {@collect.stats}
* Messaged when the menubar selection changes to activate or
* deactivate this menu. This implements the
* <code>javax.swing.MenuElement</code> interface.
* Overrides <code>MenuElement.menuSelectionChanged</code>.
*
* @param isIncluded true if this menu is active, false if
* it is not
* @see MenuElement#menuSelectionChanged(boolean)
*/
public void menuSelectionChanged(boolean isIncluded) {
if (DEBUG) {
System.out.println("In JPopupMenu.menuSelectionChanged " + isIncluded);
}
if(invoker instanceof JMenu) {
JMenu m = (JMenu) invoker;
if(isIncluded)
m.setPopupMenuVisible(true);
else
m.setPopupMenuVisible(false);
}
if (isPopupMenu() && !isIncluded)
setVisible(false);
}
/** {@collect.stats}
* Returns an array of <code>MenuElement</code>s containing the submenu
* for this menu component. It will only return items conforming to
* the <code>JMenuElement</code> interface.
* If popup menu is <code>null</code> returns
* an empty array. This method is required to conform to the
* <code>MenuElement</code> interface.
*
* @return an array of <code>MenuElement</code> objects
* @see MenuElement#getSubElements
*/
public MenuElement[] getSubElements() {
MenuElement result[];
Vector tmp = new Vector();
int c = getComponentCount();
int i;
Component m;
for(i=0 ; i < c ; i++) {
m = getComponent(i);
if(m instanceof MenuElement)
tmp.addElement(m);
}
result = new MenuElement[tmp.size()];
for(i=0,c=tmp.size() ; i < c ; i++)
result[i] = (MenuElement) tmp.elementAt(i);
return result;
}
/** {@collect.stats}
* Returns this <code>JPopupMenu</code> component.
* @return this <code>JPopupMenu</code> object
* @see MenuElement#getComponent
*/
public Component getComponent() {
return this;
}
/** {@collect.stats}
* A popup menu-specific separator.
*/
static public class Separator extends JSeparator
{
public Separator( )
{
super( JSeparator.HORIZONTAL );
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return the string "PopupMenuSeparatorUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID()
{
return "PopupMenuSeparatorUI";
}
}
/** {@collect.stats}
* Returns true if the <code>MouseEvent</code> is considered a popup trigger
* by the <code>JPopupMenu</code>'s currently installed UI.
*
* @return true if the mouse event is a popup trigger
* @since 1.3
*/
public boolean isPopupTrigger(MouseEvent e) {
return getUI().isPopupTrigger(e);
}
}
|
Java
|
/*
* Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.util.Vector;
import java.util.Enumeration;
import javax.swing.event.*;
/** {@collect.stats}
* This class loosely implements the <code>java.util.Vector</code>
* API, in that it implements the 1.1.x version of
* <code>java.util.Vector</code>, has no collection class support,
* and notifies the <code>ListDataListener</code>s when changes occur.
* Presently it delegates to a <code>Vector</code>,
* in a future release it will be a real Collection implementation.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Hans Muller
*/
public class DefaultListModel extends AbstractListModel
{
private Vector delegate = new Vector();
/** {@collect.stats}
* Returns the number of components in this list.
* <p>
* This method is identical to <code>size</code>, which implements the
* <code>List</code> interface defined in the 1.2 Collections framework.
* This method exists in conjunction with <code>setSize</code> so that
* <code>size</code> is identifiable as a JavaBean property.
*
* @return the number of components in this list
* @see #size()
*/
public int getSize() {
return delegate.size();
}
/** {@collect.stats}
* Returns the component at the specified index.
* <blockquote>
* <b>Note:</b> Although this method is not deprecated, the preferred
* method to use is <code>get(int)</code>, which implements the
* <code>List</code> interface defined in the 1.2 Collections framework.
* </blockquote>
* @param index an index into this list
* @return the component at the specified index
* @exception ArrayIndexOutOfBoundsException if the <code>index</code>
* is negative or greater than the current size of this
* list
* @see #get(int)
*/
public Object getElementAt(int index) {
return delegate.elementAt(index);
}
/** {@collect.stats}
* Copies the components of this list into the specified array.
* The array must be big enough to hold all the objects in this list,
* else an <code>IndexOutOfBoundsException</code> is thrown.
*
* @param anArray the array into which the components get copied
* @see Vector#copyInto(Object[])
*/
public void copyInto(Object anArray[]) {
delegate.copyInto(anArray);
}
/** {@collect.stats}
* Trims the capacity of this list to be the list's current size.
*
* @see Vector#trimToSize()
*/
public void trimToSize() {
delegate.trimToSize();
}
/** {@collect.stats}
* Increases the capacity of this list, if necessary, to ensure
* that it can hold at least the number of components specified by
* the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
* @see Vector#ensureCapacity(int)
*/
public void ensureCapacity(int minCapacity) {
delegate.ensureCapacity(minCapacity);
}
/** {@collect.stats}
* Sets the size of this list.
*
* @param newSize the new size of this list
* @see Vector#setSize(int)
*/
public void setSize(int newSize) {
int oldSize = delegate.size();
delegate.setSize(newSize);
if (oldSize > newSize) {
fireIntervalRemoved(this, newSize, oldSize-1);
}
else if (oldSize < newSize) {
fireIntervalAdded(this, oldSize, newSize-1);
}
}
/** {@collect.stats}
* Returns the current capacity of this list.
*
* @return the current capacity
* @see Vector#capacity()
*/
public int capacity() {
return delegate.capacity();
}
/** {@collect.stats}
* Returns the number of components in this list.
*
* @return the number of components in this list
* @see Vector#size()
*/
public int size() {
return delegate.size();
}
/** {@collect.stats}
* Tests whether this list has any components.
*
* @return <code>true</code> if and only if this list has
* no components, that is, its size is zero;
* <code>false</code> otherwise
* @see Vector#isEmpty()
*/
public boolean isEmpty() {
return delegate.isEmpty();
}
/** {@collect.stats}
* Returns an enumeration of the components of this list.
*
* @return an enumeration of the components of this list
* @see Vector#elements()
*/
public Enumeration<?> elements() {
return delegate.elements();
}
/** {@collect.stats}
* Tests whether the specified object is a component in this list.
*
* @param elem an object
* @return <code>true</code> if the specified object
* is the same as a component in this list
* @see Vector#contains(Object)
*/
public boolean contains(Object elem) {
return delegate.contains(elem);
}
/** {@collect.stats}
* Searches for the first occurrence of <code>elem</code>.
*
* @param elem an object
* @return the index of the first occurrence of the argument in this
* list; returns <code>-1</code> if the object is not found
* @see Vector#indexOf(Object)
*/
public int indexOf(Object elem) {
return delegate.indexOf(elem);
}
/** {@collect.stats}
* Searches for the first occurrence of <code>elem</code>, beginning
* the search at <code>index</code>.
*
* @param elem an desired component
* @param index the index from which to begin searching
* @return the index where the first occurrence of <code>elem</code>
* is found after <code>index</code>; returns <code>-1</code>
* if the <code>elem</code> is not found in the list
* @see Vector#indexOf(Object,int)
*/
public int indexOf(Object elem, int index) {
return delegate.indexOf(elem, index);
}
/** {@collect.stats}
* Returns the index of the last occurrence of <code>elem</code>.
*
* @param elem the desired component
* @return the index of the last occurrence of <code>elem</code>
* in the list; returns <code>-1</code> if the object is not found
* @see Vector#lastIndexOf(Object)
*/
public int lastIndexOf(Object elem) {
return delegate.lastIndexOf(elem);
}
/** {@collect.stats}
* Searches backwards for <code>elem</code>, starting from the
* specified index, and returns an index to it.
*
* @param elem the desired component
* @param index the index to start searching from
* @return the index of the last occurrence of the <code>elem</code>
* in this list at position less than <code>index</code>;
* returns <code>-1</code> if the object is not found
* @see Vector#lastIndexOf(Object,int)
*/
public int lastIndexOf(Object elem, int index) {
return delegate.lastIndexOf(elem, index);
}
/** {@collect.stats}
* Returns the component at the specified index.
* Throws an <code>ArrayIndexOutOfBoundsException</code> if the index
* is negative or not less than the size of the list.
* <blockquote>
* <b>Note:</b> Although this method is not deprecated, the preferred
* method to use is <code>get(int)</code>, which implements the
* <code>List</code> interface defined in the 1.2 Collections framework.
* </blockquote>
*
* @param index an index into this list
* @return the component at the specified index
* @see #get(int)
* @see Vector#elementAt(int)
*/
public Object elementAt(int index) {
return delegate.elementAt(index);
}
/** {@collect.stats}
* Returns the first component of this list.
* Throws a <code>NoSuchElementException</code> if this
* vector has no components.
* @return the first component of this list
* @see Vector#firstElement()
*/
public Object firstElement() {
return delegate.firstElement();
}
/** {@collect.stats}
* Returns the last component of the list.
* Throws a <code>NoSuchElementException</code> if this vector
* has no components.
*
* @return the last component of the list
* @see Vector#lastElement()
*/
public Object lastElement() {
return delegate.lastElement();
}
/** {@collect.stats}
* Sets the component at the specified <code>index</code> of this
* list to be the specified object. The previous component at that
* position is discarded.
* <p>
* Throws an <code>ArrayIndexOutOfBoundsException</code> if the index
* is invalid.
* <blockquote>
* <b>Note:</b> Although this method is not deprecated, the preferred
* method to use is <code>set(int,Object)</code>, which implements the
* <code>List</code> interface defined in the 1.2 Collections framework.
* </blockquote>
*
* @param obj what the component is to be set to
* @param index the specified index
* @see #set(int,Object)
* @see Vector#setElementAt(Object,int)
*/
public void setElementAt(Object obj, int index) {
delegate.setElementAt(obj, index);
fireContentsChanged(this, index, index);
}
/** {@collect.stats}
* Deletes the component at the specified index.
* <p>
* Throws an <code>ArrayIndexOutOfBoundsException</code> if the index
* is invalid.
* <blockquote>
* <b>Note:</b> Although this method is not deprecated, the preferred
* method to use is <code>remove(int)</code>, which implements the
* <code>List</code> interface defined in the 1.2 Collections framework.
* </blockquote>
*
* @param index the index of the object to remove
* @see #remove(int)
* @see Vector#removeElementAt(int)
*/
public void removeElementAt(int index) {
delegate.removeElementAt(index);
fireIntervalRemoved(this, index, index);
}
/** {@collect.stats}
* Inserts the specified object as a component in this list at the
* specified <code>index</code>.
* <p>
* Throws an <code>ArrayIndexOutOfBoundsException</code> if the index
* is invalid.
* <blockquote>
* <b>Note:</b> Although this method is not deprecated, the preferred
* method to use is <code>add(int,Object)</code>, which implements the
* <code>List</code> interface defined in the 1.2 Collections framework.
* </blockquote>
*
* @param obj the component to insert
* @param index where to insert the new component
* @exception ArrayIndexOutOfBoundsException if the index was invalid
* @see #add(int,Object)
* @see Vector#insertElementAt(Object,int)
*/
public void insertElementAt(Object obj, int index) {
delegate.insertElementAt(obj, index);
fireIntervalAdded(this, index, index);
}
/** {@collect.stats}
* Adds the specified component to the end of this list.
*
* @param obj the component to be added
* @see Vector#addElement(Object)
*/
public void addElement(Object obj) {
int index = delegate.size();
delegate.addElement(obj);
fireIntervalAdded(this, index, index);
}
/** {@collect.stats}
* Removes the first (lowest-indexed) occurrence of the argument
* from this list.
*
* @param obj the component to be removed
* @return <code>true</code> if the argument was a component of this
* list; <code>false</code> otherwise
* @see Vector#removeElement(Object)
*/
public boolean removeElement(Object obj) {
int index = indexOf(obj);
boolean rv = delegate.removeElement(obj);
if (index >= 0) {
fireIntervalRemoved(this, index, index);
}
return rv;
}
/** {@collect.stats}
* Removes all components from this list and sets its size to zero.
* <blockquote>
* <b>Note:</b> Although this method is not deprecated, the preferred
* method to use is <code>clear</code>, which implements the
* <code>List</code> interface defined in the 1.2 Collections framework.
* </blockquote>
*
* @see #clear()
* @see Vector#removeAllElements()
*/
public void removeAllElements() {
int index1 = delegate.size()-1;
delegate.removeAllElements();
if (index1 >= 0) {
fireIntervalRemoved(this, 0, index1);
}
}
/** {@collect.stats}
* Returns a string that displays and identifies this
* object's properties.
*
* @return a String representation of this object
*/
public String toString() {
return delegate.toString();
}
/* The remaining methods are included for compatibility with the
* Java 2 platform Vector class.
*/
/** {@collect.stats}
* Returns an array containing all of the elements in this list in the
* correct order.
*
* @return an array containing the elements of the list
* @see Vector#toArray()
*/
public Object[] toArray() {
Object[] rv = new Object[delegate.size()];
delegate.copyInto(rv);
return rv;
}
/** {@collect.stats}
* Returns the element at the specified position in this list.
* <p>
* Throws an <code>ArrayIndexOutOfBoundsException</code>
* if the index is out of range
* (<code>index < 0 || index >= size()</code>).
*
* @param index index of element to return
*/
public Object get(int index) {
return delegate.elementAt(index);
}
/** {@collect.stats}
* Replaces the element at the specified position in this list with the
* specified element.
* <p>
* Throws an <code>ArrayIndexOutOfBoundsException</code>
* if the index is out of range
* (<code>index < 0 || index >= size()</code>).
*
* @param index index of element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
*/
public Object set(int index, Object element) {
Object rv = delegate.elementAt(index);
delegate.setElementAt(element, index);
fireContentsChanged(this, index, index);
return rv;
}
/** {@collect.stats}
* Inserts the specified element at the specified position in this list.
* <p>
* Throws an <code>ArrayIndexOutOfBoundsException</code> if the
* index is out of range
* (<code>index < 0 || index > size()</code>).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
*/
public void add(int index, Object element) {
delegate.insertElementAt(element, index);
fireIntervalAdded(this, index, index);
}
/** {@collect.stats}
* Removes the element at the specified position in this list.
* Returns the element that was removed from the list.
* <p>
* Throws an <code>ArrayIndexOutOfBoundsException</code>
* if the index is out of range
* (<code>index < 0 || index >= size()</code>).
*
* @param index the index of the element to removed
*/
public Object remove(int index) {
Object rv = delegate.elementAt(index);
delegate.removeElementAt(index);
fireIntervalRemoved(this, index, index);
return rv;
}
/** {@collect.stats}
* Removes all of the elements from this list. The list will
* be empty after this call returns (unless it throws an exception).
*/
public void clear() {
int index1 = delegate.size()-1;
delegate.removeAllElements();
if (index1 >= 0) {
fireIntervalRemoved(this, 0, index1);
}
}
/** {@collect.stats}
* Deletes the components at the specified range of indexes.
* The removal is inclusive, so specifying a range of (1,5)
* removes the component at index 1 and the component at index 5,
* as well as all components in between.
* <p>
* Throws an <code>ArrayIndexOutOfBoundsException</code>
* if the index was invalid.
* Throws an <code>IllegalArgumentException</code> if
* <code>fromIndex > toIndex</code>.
*
* @param fromIndex the index of the lower end of the range
* @param toIndex the index of the upper end of the range
* @see #remove(int)
*/
public void removeRange(int fromIndex, int toIndex) {
if (fromIndex > toIndex) {
throw new IllegalArgumentException("fromIndex must be <= toIndex");
}
for(int i = toIndex; i >= fromIndex; i--) {
delegate.removeElementAt(i);
}
fireIntervalRemoved(this, fromIndex, toIndex);
}
/*
public void addAll(Collection c) {
}
public void addAll(int index, Collection c) {
}
*/
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.util.EventListener;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import javax.swing.plaf.*;
import javax.accessibility.*;
/** {@collect.stats}
* A menu item that can be selected or deselected. If selected, the menu
* item typically appears with a checkmark next to it. If unselected or
* deselected, the menu item appears without a checkmark. Like a regular
* menu item, a check box menu item can have either text or a graphic
* icon associated with it, or both.
* <p>
* Either <code>isSelected</code>/<code>setSelected</code> or
* <code>getState</code>/<code>setState</code> can be used
* to determine/specify the menu item's selection state. The
* preferred methods are <code>isSelected</code> and
* <code>setSelected</code>, which work for all menus and buttons.
* The <code>getState</code> and <code>setState</code> methods exist for
* compatibility with other component sets.
* <p>
* Menu items can be configured, and to some degree controlled, by
* <code><a href="Action.html">Action</a></code>s. Using an
* <code>Action</code> with a menu item has many benefits beyond directly
* configuring a menu item. Refer to <a href="Action.html#buttonActions">
* Swing Components Supporting <code>Action</code></a> for more
* details, and you can find more information in <a
* href="http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html">How
* to Use Actions</a>, a section in <em>The Java Tutorial</em>.
* <p>
* For further information and examples of using check box menu items,
* see <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html">How to Use Menus</a>,
* a section in <em>The Java Tutorial.</em>
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @beaninfo
* attribute: isContainer false
* description: A menu item which can be selected or deselected.
*
* @author Georges Saab
* @author David Karlton
*/
public class JCheckBoxMenuItem extends JMenuItem implements SwingConstants,
Accessible
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "CheckBoxMenuItemUI";
/** {@collect.stats}
* Creates an initially unselected check box menu item with no set text or icon.
*/
public JCheckBoxMenuItem() {
this(null, null, false);
}
/** {@collect.stats}
* Creates an initially unselected check box menu item with an icon.
*
* @param icon the icon of the CheckBoxMenuItem.
*/
public JCheckBoxMenuItem(Icon icon) {
this(null, icon, false);
}
/** {@collect.stats}
* Creates an initially unselected check box menu item with text.
*
* @param text the text of the CheckBoxMenuItem
*/
public JCheckBoxMenuItem(String text) {
this(text, null, false);
}
/** {@collect.stats}
* Creates a menu item whose properties are taken from the
* Action supplied.
*
* @since 1.3
*/
public JCheckBoxMenuItem(Action a) {
this();
setAction(a);
}
/** {@collect.stats}
* Creates an initially unselected check box menu item with the specified text and icon.
*
* @param text the text of the CheckBoxMenuItem
* @param icon the icon of the CheckBoxMenuItem
*/
public JCheckBoxMenuItem(String text, Icon icon) {
this(text, icon, false);
}
/** {@collect.stats}
* Creates a check box menu item with the specified text and selection state.
*
* @param text the text of the check box menu item.
* @param b the selected state of the check box menu item
*/
public JCheckBoxMenuItem(String text, boolean b) {
this(text, null, b);
}
/** {@collect.stats}
* Creates a check box menu item with the specified text, icon, and selection state.
*
* @param text the text of the check box menu item
* @param icon the icon of the check box menu item
* @param b the selected state of the check box menu item
*/
public JCheckBoxMenuItem(String text, Icon icon, boolean b) {
super(text, icon);
setModel(new JToggleButton.ToggleButtonModel());
setSelected(b);
setFocusable(false);
}
/** {@collect.stats}
* Returns the name of the L&F class
* that renders this component.
*
* @return "CheckBoxMenuItemUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Returns the selected-state of the item. This method
* exists for AWT compatibility only. New code should
* use isSelected() instead.
*
* @return true if the item is selected
*/
public boolean getState() {
return isSelected();
}
/** {@collect.stats}
* Sets the selected-state of the item. This method
* exists for AWT compatibility only. New code should
* use setSelected() instead.
*
* @param b a boolean value indicating the item's
* selected-state, where true=selected
* @beaninfo
* description: The selection state of the check box menu item
* hidden: true
*/
public synchronized void setState(boolean b) {
setSelected(b);
}
/** {@collect.stats}
* Returns an array (length 1) containing the check box menu item
* label or null if the check box is not selected.
*
* @return an array containing one Object -- the text of the menu item
* -- if the item is selected; otherwise null
*/
public Object[] getSelectedObjects() {
if (isSelected() == false)
return null;
Object[] selectedObjects = new Object[1];
selectedObjects[0] = getText();
return selectedObjects;
}
/** {@collect.stats}
* See readObject() and writeObject() in JComponent for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/** {@collect.stats}
* Returns a string representation of this JCheckBoxMenuItem. This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this JCheckBoxMenuItem.
*/
protected String paramString() {
return super.paramString();
}
/** {@collect.stats}
* Overriden to return true, JCheckBoxMenuItem supports
* the selected state.
*/
boolean shouldUpdateSelectedStateFromAction() {
return true;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JCheckBoxMenuItem.
* For JCheckBoxMenuItems, the AccessibleContext takes the form of an
* AccessibleJCheckBoxMenuItem.
* A new AccessibleJCheckBoxMenuItem instance is created if necessary.
*
* @return an AccessibleJCheckBoxMenuItem that serves as the
* AccessibleContext of this AccessibleJCheckBoxMenuItem
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJCheckBoxMenuItem();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JCheckBoxMenuItem</code> class. It provides an implementation
* of the Java Accessibility API appropriate to checkbox menu item
* user-interface elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJCheckBoxMenuItem extends AccessibleJMenuItem {
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.CHECK_BOX;
}
} // inner class AccessibleJCheckBoxMenuItem
}
|
Java
|
/*
* Copyright (c) 2000, 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.swing;
import java.util.*;
import java.io.Serializable;
/** {@collect.stats}
* A <code>SpinnerModel</code> for sequences of <code>Date</code>s.
* The upper and lower bounds of the sequence are defined by properties called
* <code>start</code> and <code>end</code> and the size
* of the increase or decrease computed by the <code>nextValue</code>
* and <code>previousValue</code> methods is defined by a property
* called <code>calendarField</code>. The <code>start</code>
* and <code>end</code> properties can be <code>null</code> to
* indicate that the sequence has no lower or upper limit.
* <p>
* The value of the <code>calendarField</code> property must be one of the
* <code>java.util.Calendar</code> constants that specify a field
* within a <code>Calendar</code>. The <code>getNextValue</code>
* and <code>getPreviousValue</code>
* methods change the date forward or backwards by this amount.
* For example, if <code>calendarField</code> is <code>Calendar.DAY_OF_WEEK</code>,
* then <code>nextValue</code> produces a <code>Date</code> that's 24
* hours after the current <code>value</code>, and <code>previousValue</code>
* produces a <code>Date</code> that's 24 hours earlier.
* <p>
* The legal values for <code>calendarField</code> are:
* <ul>
* <li><code>Calendar.ERA</code>
* <li><code>Calendar.YEAR</code>
* <li><code>Calendar.MONTH</code>
* <li><code>Calendar.WEEK_OF_YEAR</code>
* <li><code>Calendar.WEEK_OF_MONTH</code>
* <li><code>Calendar.DAY_OF_MONTH</code>
* <li><code>Calendar.DAY_OF_YEAR</code>
* <li><code>Calendar.DAY_OF_WEEK</code>
* <li><code>Calendar.DAY_OF_WEEK_IN_MONTH</code>
* <li><code>Calendar.AM_PM</code>
* <li><code>Calendar.HOUR</code>
* <li><code>Calendar.HOUR_OF_DAY</code>
* <li><code>Calendar.MINUTE</code>
* <li><code>Calendar.SECOND</code>
* <li><code>Calendar.MILLISECOND</code>
* </ul>
* However some UIs may set the calendarField before commiting the edit
* to spin the field under the cursor. If you only want one field to
* spin you can subclass and ignore the setCalendarField calls.
* <p>
* This model inherits a <code>ChangeListener</code>. The
* <code>ChangeListeners</code> are notified whenever the models
* <code>value</code>, <code>calendarField</code>,
* <code>start</code>, or <code>end</code> properties changes.
*
* @see JSpinner
* @see SpinnerModel
* @see AbstractSpinnerModel
* @see SpinnerListModel
* @see SpinnerNumberModel
* @see Calendar#add
*
* @author Hans Muller
* @since 1.4
*/
public class SpinnerDateModel extends AbstractSpinnerModel implements Serializable
{
private Comparable start, end;
private Calendar value;
private int calendarField;
private boolean calendarFieldOK(int calendarField) {
switch(calendarField) {
case Calendar.ERA:
case Calendar.YEAR:
case Calendar.MONTH:
case Calendar.WEEK_OF_YEAR:
case Calendar.WEEK_OF_MONTH:
case Calendar.DAY_OF_MONTH:
case Calendar.DAY_OF_YEAR:
case Calendar.DAY_OF_WEEK:
case Calendar.DAY_OF_WEEK_IN_MONTH:
case Calendar.AM_PM:
case Calendar.HOUR:
case Calendar.HOUR_OF_DAY:
case Calendar.MINUTE:
case Calendar.SECOND:
case Calendar.MILLISECOND:
return true;
default:
return false;
}
}
/** {@collect.stats}
* Creates a <code>SpinnerDateModel</code> that represents a sequence of dates
* between <code>start</code> and <code>end</code>. The
* <code>nextValue</code> and <code>previousValue</code> methods
* compute elements of the sequence by advancing or reversing
* the current date <code>value</code> by the
* <code>calendarField</code> time unit. For a precise description
* of what it means to increment or decrement a <code>Calendar</code>
* <code>field</code>, see the <code>add</code> method in
* <code>java.util.Calendar</code>.
* <p>
* The <code>start</code> and <code>end</code> parameters can be
* <code>null</code> to indicate that the range doesn't have an
* upper or lower bound. If <code>value</code> or
* <code>calendarField</code> is <code>null</code>, or if both
* <code>start</code> and <code>end</code> are specified and
* <code>mininum > maximum</code> then an
* <code>IllegalArgumentException</code> is thrown.
* Similarly if <code>(minimum <= value <= maximum)</code> is false,
* an IllegalArgumentException is thrown.
*
* @param value the current (non <code>null</code>) value of the model
* @param start the first date in the sequence or <code>null</code>
* @param end the last date in the sequence or <code>null</code>
* @param calendarField one of
* <ul>
* <li><code>Calendar.ERA</code>
* <li><code>Calendar.YEAR</code>
* <li><code>Calendar.MONTH</code>
* <li><code>Calendar.WEEK_OF_YEAR</code>
* <li><code>Calendar.WEEK_OF_MONTH</code>
* <li><code>Calendar.DAY_OF_MONTH</code>
* <li><code>Calendar.DAY_OF_YEAR</code>
* <li><code>Calendar.DAY_OF_WEEK</code>
* <li><code>Calendar.DAY_OF_WEEK_IN_MONTH</code>
* <li><code>Calendar.AM_PM</code>
* <li><code>Calendar.HOUR</code>
* <li><code>Calendar.HOUR_OF_DAY</code>
* <li><code>Calendar.MINUTE</code>
* <li><code>Calendar.SECOND</code>
* <li><code>Calendar.MILLISECOND</code>
* </ul>
*
* @throws IllegalArgumentException if <code>value</code> or
* <code>calendarField</code> are <code>null</code>,
* if <code>calendarField</code> isn't valid,
* or if the following expression is
* false: <code>(start <= value <= end)</code>.
*
* @see Calendar#add
* @see #setValue
* @see #setStart
* @see #setEnd
* @see #setCalendarField
*/
public SpinnerDateModel(Date value, Comparable start, Comparable end, int calendarField) {
if (value == null) {
throw new IllegalArgumentException("value is null");
}
if (!calendarFieldOK(calendarField)) {
throw new IllegalArgumentException("invalid calendarField");
}
if (!(((start == null) || (start.compareTo(value) <= 0)) &&
((end == null) || (end.compareTo(value) >= 0)))) {
throw new IllegalArgumentException("(start <= value <= end) is false");
}
this.value = Calendar.getInstance();
this.start = start;
this.end = end;
this.calendarField = calendarField;
this.value.setTime(value);
}
/** {@collect.stats}
* Constructs a <code>SpinnerDateModel</code> whose initial
* <code>value</code> is the current date, <code>calendarField</code>
* is equal to <code>Calendar.DAY_OF_MONTH</code>, and for which
* there are no <code>start</code>/<code>end</code> limits.
*/
public SpinnerDateModel() {
this(new Date(), null, null, Calendar.DAY_OF_MONTH);
}
/** {@collect.stats}
* Changes the lower limit for Dates in this sequence.
* If <code>start</code> is <code>null</code>,
* then there is no lower limit. No bounds checking is done here:
* the new start value may invalidate the
* <code>(start <= value <= end)</code>
* invariant enforced by the constructors. This is to simplify updating
* the model. Naturally one should ensure that the invariant is true
* before calling the <code>nextValue</code>, <code>previousValue</code>,
* or <code>setValue</code> methods.
* <p>
* Typically this property is a <code>Date</code> however it's possible to use
* a <code>Comparable</code> with a <code>compareTo</code> method for Dates.
* For example <code>start</code> might be an instance of a class like this:
* <pre>
* MyStartDate implements Comparable {
* long t = 12345;
* public int compareTo(Date d) {
* return (t < d.getTime() ? -1 : (t == d.getTime() ? 0 : 1));
* }
* public int compareTo(Object o) {
* return compareTo((Date)o);
* }
* }
* </pre>
* Note that the above example will throw a <code>ClassCastException</code>
* if the <code>Object</code> passed to <code>compareTo(Object)</code>
* is not a <code>Date</code>.
* <p>
* This method fires a <code>ChangeEvent</code> if the
* <code>start</code> has changed.
*
* @param start defines the first date in the sequence
* @see #getStart
* @see #setEnd
* @see #addChangeListener
*/
public void setStart(Comparable start) {
if ((start == null) ? (this.start != null) : !start.equals(this.start)) {
this.start = start;
fireStateChanged();
}
}
/** {@collect.stats}
* Returns the first <code>Date</code> in the sequence.
*
* @return the value of the <code>start</code> property
* @see #setStart
*/
public Comparable getStart() {
return start;
}
/** {@collect.stats}
* Changes the upper limit for <code>Date</code>s in this sequence.
* If <code>start</code> is <code>null</code>, then there is no upper
* limit. No bounds checking is done here: the new
* start value may invalidate the <code>(start <= value <= end)</code>
* invariant enforced by the constructors. This is to simplify updating
* the model. Naturally, one should ensure that the invariant is true
* before calling the <code>nextValue</code>, <code>previousValue</code>,
* or <code>setValue</code> methods.
* <p>
* Typically this property is a <code>Date</code> however it's possible to use
* <code>Comparable</code> with a <code>compareTo</code> method for
* <code>Date</code>s. See <code>setStart</code> for an example.
* <p>
* This method fires a <code>ChangeEvent</code> if the <code>end</code>
* has changed.
*
* @param end defines the last date in the sequence
* @see #getEnd
* @see #setStart
* @see #addChangeListener
*/
public void setEnd(Comparable end) {
if ((end == null) ? (this.end != null) : !end.equals(this.end)) {
this.end = end;
fireStateChanged();
}
}
/** {@collect.stats}
* Returns the last <code>Date</code> in the sequence.
*
* @return the value of the <code>end</code> property
* @see #setEnd
*/
public Comparable getEnd() {
return end;
}
/** {@collect.stats}
* Changes the size of the date value change computed
* by the <code>nextValue</code> and <code>previousValue</code> methods.
* The <code>calendarField</code> parameter must be one of the
* <code>Calendar</code> field constants like <code>Calendar.MONTH</code>
* or <code>Calendar.MINUTE</code>.
* The <code>nextValue</code> and <code>previousValue</code> methods
* simply move the specified <code>Calendar</code> field forward or backward
* by one unit with the <code>Calendar.add</code> method.
* You should use this method with care as some UIs may set the
* calendarField before commiting the edit to spin the field under
* the cursor. If you only want one field to spin you can subclass
* and ignore the setCalendarField calls.
*
* @param calendarField one of
* <ul>
* <li><code>Calendar.ERA</code>
* <li><code>Calendar.YEAR</code>
* <li><code>Calendar.MONTH</code>
* <li><code>Calendar.WEEK_OF_YEAR</code>
* <li><code>Calendar.WEEK_OF_MONTH</code>
* <li><code>Calendar.DAY_OF_MONTH</code>
* <li><code>Calendar.DAY_OF_YEAR</code>
* <li><code>Calendar.DAY_OF_WEEK</code>
* <li><code>Calendar.DAY_OF_WEEK_IN_MONTH</code>
* <li><code>Calendar.AM_PM</code>
* <li><code>Calendar.HOUR</code>
* <li><code>Calendar.HOUR_OF_DAY</code>
* <li><code>Calendar.MINUTE</code>
* <li><code>Calendar.SECOND</code>
* <li><code>Calendar.MILLISECOND</code>
* </ul>
* <p>
* This method fires a <code>ChangeEvent</code> if the
* <code>calendarField</code> has changed.
*
* @see #getCalendarField
* @see #getNextValue
* @see #getPreviousValue
* @see Calendar#add
* @see #addChangeListener
*/
public void setCalendarField(int calendarField) {
if (!calendarFieldOK(calendarField)) {
throw new IllegalArgumentException("invalid calendarField");
}
if (calendarField != this.calendarField) {
this.calendarField = calendarField;
fireStateChanged();
}
}
/** {@collect.stats}
* Returns the <code>Calendar</code> field that is added to or subtracted from
* by the <code>nextValue</code> and <code>previousValue</code> methods.
*
* @return the value of the <code>calendarField</code> property
* @see #setCalendarField
*/
public int getCalendarField() {
return calendarField;
}
/** {@collect.stats}
* Returns the next <code>Date</code> in the sequence, or <code>null</code> if
* the next date is after <code>end</code>.
*
* @return the next <code>Date</code> in the sequence, or <code>null</code> if
* the next date is after <code>end</code>.
*
* @see SpinnerModel#getNextValue
* @see #getPreviousValue
* @see #setCalendarField
*/
public Object getNextValue() {
Calendar cal = Calendar.getInstance();
cal.setTime(value.getTime());
cal.add(calendarField, 1);
Date next = cal.getTime();
return ((end == null) || (end.compareTo(next) >= 0)) ? next : null;
}
/** {@collect.stats}
* Returns the previous <code>Date</code> in the sequence, or <code>null</code>
* if the previous date is before <code>start</code>.
*
* @return the previous <code>Date</code> in the sequence, or
* <code>null</code> if the previous date
* is before <code>start</code>
*
* @see SpinnerModel#getPreviousValue
* @see #getNextValue
* @see #setCalendarField
*/
public Object getPreviousValue() {
Calendar cal = Calendar.getInstance();
cal.setTime(value.getTime());
cal.add(calendarField, -1);
Date prev = cal.getTime();
return ((start == null) || (start.compareTo(prev) <= 0)) ? prev : null;
}
/** {@collect.stats}
* Returns the current element in this sequence of <code>Date</code>s.
* This method is equivalent to <code>(Date)getValue</code>.
*
* @return the <code>value</code> property
* @see #setValue
*/
public Date getDate() {
return value.getTime();
}
/** {@collect.stats}
* Returns the current element in this sequence of <code>Date</code>s.
*
* @return the <code>value</code> property
* @see #setValue
* @see #getDate
*/
public Object getValue() {
return value.getTime();
}
/** {@collect.stats}
* Sets the current <code>Date</code> for this sequence.
* If <code>value</code> is <code>null</code>,
* an <code>IllegalArgumentException</code> is thrown. No bounds
* checking is done here:
* the new value may invalidate the <code>(start <= value < end)</code>
* invariant enforced by the constructors. Naturally, one should ensure
* that the <code>(start <= value <= maximum)</code> invariant is true
* before calling the <code>nextValue</code>, <code>previousValue</code>,
* or <code>setValue</code> methods.
* <p>
* This method fires a <code>ChangeEvent</code> if the
* <code>value</code> has changed.
*
* @param value the current (non <code>null</code>)
* <code>Date</code> for this sequence
* @throws IllegalArgumentException if value is <code>null</code>
* or not a <code>Date</code>
* @see #getDate
* @see #getValue
* @see #addChangeListener
*/
public void setValue(Object value) {
if ((value == null) || !(value instanceof Date)) {
throw new IllegalArgumentException("illegal value");
}
if (!value.equals(this.value.getTime())) {
this.value.setTime((Date)value);
fireStateChanged();
}
}
}
|
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.swing;
import java.awt.*;
import java.awt.event.*;
import java.util.Locale;
import java.io.Serializable;
import javax.accessibility.*;
/** {@collect.stats}
* A lightweight container
* that uses a BoxLayout object as its layout manager.
* Box provides several class methods
* that are useful for containers using BoxLayout --
* even non-Box containers.
*
* <p>
* The <code>Box</code> class can create several kinds
* of invisible components
* that affect layout:
* glue, struts, and rigid areas.
* If all the components your <code>Box</code> contains
* have a fixed size,
* you might want to use a glue component
* (returned by <code>createGlue</code>)
* to control the components' positions.
* If you need a fixed amount of space between two components,
* try using a strut
* (<code>createHorizontalStrut</code> or <code>createVerticalStrut</code>).
* If you need an invisible component
* that always takes up the same amount of space,
* get it by invoking <code>createRigidArea</code>.
* <p>
* If you are implementing a <code>BoxLayout</code> you
* can find further information and examples in
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/layout/box.html">How to Use BoxLayout</a>,
* a section in <em>The Java Tutorial.</em>
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see BoxLayout
*
* @author Timothy Prinzing
*/
public class Box extends JComponent implements Accessible {
/** {@collect.stats}
* Creates a <code>Box</code> that displays its components
* along the the specified axis.
*
* @param axis can be {@link BoxLayout#X_AXIS},
* {@link BoxLayout#Y_AXIS},
* {@link BoxLayout#LINE_AXIS} or
* {@link BoxLayout#PAGE_AXIS}.
* @throws AWTError if the <code>axis</code> is invalid
* @see #createHorizontalBox
* @see #createVerticalBox
*/
public Box(int axis) {
super();
super.setLayout(new BoxLayout(this, axis));
}
/** {@collect.stats}
* Creates a <code>Box</code> that displays its components
* from left to right. If you want a <code>Box</code> that
* respects the component orientation you should create the
* <code>Box</code> using the constructor and pass in
* <code>BoxLayout.LINE_AXIS</code>, eg:
* <pre>
* Box lineBox = new Box(BoxLayout.LINE_AXIS);
* </pre>
*
* @return the box
*/
public static Box createHorizontalBox() {
return new Box(BoxLayout.X_AXIS);
}
/** {@collect.stats}
* Creates a <code>Box</code> that displays its components
* from top to bottom. If you want a <code>Box</code> that
* respects the component orientation you should create the
* <code>Box</code> using the constructor and pass in
* <code>BoxLayout.PAGE_AXIS</code>, eg:
* <pre>
* Box lineBox = new Box(BoxLayout.PAGE_AXIS);
* </pre>
*
* @return the box
*/
public static Box createVerticalBox() {
return new Box(BoxLayout.Y_AXIS);
}
/** {@collect.stats}
* Creates an invisible component that's always the specified size.
* <!-- WHEN WOULD YOU USE THIS AS OPPOSED TO A STRUT? -->
*
* @param d the dimensions of the invisible component
* @return the component
* @see #createGlue
* @see #createHorizontalStrut
* @see #createVerticalStrut
*/
public static Component createRigidArea(Dimension d) {
return new Filler(d, d, d);
}
/** {@collect.stats}
* Creates an invisible, fixed-width component.
* In a horizontal box,
* you typically use this method
* to force a certain amount of space between two components.
* In a vertical box,
* you might use this method
* to force the box to be at least the specified width.
* The invisible component has no height
* unless excess space is available,
* in which case it takes its share of available space,
* just like any other component that has no maximum height.
*
* @param width the width of the invisible component, in pixels >= 0
* @return the component
* @see #createVerticalStrut
* @see #createGlue
* @see #createRigidArea
*/
public static Component createHorizontalStrut(int width) {
return new Filler(new Dimension(width,0), new Dimension(width,0),
new Dimension(width, Short.MAX_VALUE));
}
/** {@collect.stats}
* Creates an invisible, fixed-height component.
* In a vertical box,
* you typically use this method
* to force a certain amount of space between two components.
* In a horizontal box,
* you might use this method
* to force the box to be at least the specified height.
* The invisible component has no width
* unless excess space is available,
* in which case it takes its share of available space,
* just like any other component that has no maximum width.
*
* @param height the height of the invisible component, in pixels >= 0
* @return the component
* @see #createHorizontalStrut
* @see #createGlue
* @see #createRigidArea
*/
public static Component createVerticalStrut(int height) {
return new Filler(new Dimension(0,height), new Dimension(0,height),
new Dimension(Short.MAX_VALUE, height));
}
/** {@collect.stats}
* Creates an invisible "glue" component
* that can be useful in a Box
* whose visible components have a maximum width
* (for a horizontal box)
* or height (for a vertical box).
* You can think of the glue component
* as being a gooey substance
* that expands as much as necessary
* to fill the space between its neighboring components.
*
* <p>
*
* For example, suppose you have
* a horizontal box that contains two fixed-size components.
* If the box gets extra space,
* the fixed-size components won't become larger,
* so where does the extra space go?
* Without glue,
* the extra space goes to the right of the second component.
* If you put glue between the fixed-size components,
* then the extra space goes there.
* If you put glue before the first fixed-size component,
* the extra space goes there,
* and the fixed-size components are shoved against the right
* edge of the box.
* If you put glue before the first fixed-size component
* and after the second fixed-size component,
* the fixed-size components are centered in the box.
*
* <p>
*
* To use glue,
* call <code>Box.createGlue</code>
* and add the returned component to a container.
* The glue component has no minimum or preferred size,
* so it takes no space unless excess space is available.
* If excess space is available,
* then the glue component takes its share of available
* horizontal or vertical space,
* just like any other component that has no maximum width or height.
*
* @return the component
*/
public static Component createGlue() {
return new Filler(new Dimension(0,0), new Dimension(0,0),
new Dimension(Short.MAX_VALUE, Short.MAX_VALUE));
}
/** {@collect.stats}
* Creates a horizontal glue component.
*
* @return the component
*/
public static Component createHorizontalGlue() {
return new Filler(new Dimension(0,0), new Dimension(0,0),
new Dimension(Short.MAX_VALUE, 0));
}
/** {@collect.stats}
* Creates a vertical glue component.
*
* @return the component
*/
public static Component createVerticalGlue() {
return new Filler(new Dimension(0,0), new Dimension(0,0),
new Dimension(0, Short.MAX_VALUE));
}
/** {@collect.stats}
* Throws an AWTError, since a Box can use only a BoxLayout.
*
* @param l the layout manager to use
*/
public void setLayout(LayoutManager l) {
throw new AWTError("Illegal request");
}
/** {@collect.stats}
* Paints this <code>Box</code>. If this <code>Box</code> has a UI this
* method invokes super's implementation, otherwise if this
* <code>Box</code> is opaque the <code>Graphics</code> is filled
* using the background.
*
* @param g the <code>Graphics</code> to paint to
* @throws NullPointerException if <code>g</code> is null
* @since 1.6
*/
protected void paintComponent(Graphics g) {
if (ui != null) {
// On the off chance some one created a UI, honor it
super.paintComponent(g);
} else if (isOpaque()) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
}
/** {@collect.stats}
* An implementation of a lightweight component that participates in
* layout but has no view.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
public static class Filler extends JComponent implements Accessible {
/** {@collect.stats}
* Constructor to create shape with the given size ranges.
*
* @param min Minimum size
* @param pref Preferred size
* @param max Maximum size
*/
public Filler(Dimension min, Dimension pref, Dimension max) {
setMinimumSize(min);
setPreferredSize(pref);
setMaximumSize(max);
}
/** {@collect.stats}
* Change the size requests for this shape. An invalidate() is
* propagated upward as a result so that layout will eventually
* happen with using the new sizes.
*
* @param min Value to return for getMinimumSize
* @param pref Value to return for getPreferredSize
* @param max Value to return for getMaximumSize
*/
public void changeShape(Dimension min, Dimension pref, Dimension max) {
setMinimumSize(min);
setPreferredSize(pref);
setMaximumSize(max);
revalidate();
}
// ---- Component methods ------------------------------------------
/** {@collect.stats}
* Paints this <code>Filler</code>. If this
* <code>Filler</code> has a UI this method invokes super's
* implementation, otherwise if this <code>Filler</code> is
* opaque the <code>Graphics</code> is filled using the
* background.
*
* @param g the <code>Graphics</code> to paint to
* @throws NullPointerException if <code>g</code> is null
* @since 1.6
*/
protected void paintComponent(Graphics g) {
if (ui != null) {
// On the off chance some one created a UI, honor it
super.paintComponent(g);
} else if (isOpaque()) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
}
/////////////////
// Accessibility support for Box$Filler
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this Box.Filler.
* For box fillers, the AccessibleContext takes the form of an
* AccessibleBoxFiller.
* A new AccessibleAWTBoxFiller instance is created if necessary.
*
* @return an AccessibleBoxFiller that serves as the
* AccessibleContext of this Box.Filler.
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleBoxFiller();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>Box.Filler</code> class.
*/
protected class AccessibleBoxFiller extends AccessibleAWTComponent {
// AccessibleContext methods
//
/** {@collect.stats}
* Gets the role of this object.
*
* @return an instance of AccessibleRole describing the role of
* the object (AccessibleRole.FILLER)
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.FILLER;
}
}
}
/////////////////
// Accessibility support for Box
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this Box.
* For boxes, the AccessibleContext takes the form of an
* AccessibleBox.
* A new AccessibleAWTBox instance is created if necessary.
*
* @return an AccessibleBox that serves as the
* AccessibleContext of this Box
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleBox();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>Box</code> class.
*/
protected class AccessibleBox extends AccessibleAWTContainer {
// AccessibleContext methods
//
/** {@collect.stats}
* Gets the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object (AccessibleRole.FILLER)
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.FILLER;
}
} // inner class AccessibleBox
}
|
Java
|
/*
* Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import javax.swing.event.*;
import java.io.Serializable;
import java.util.EventListener;
/** {@collect.stats}
* A generic implementation of SingleSelectionModel.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Dave Moore
*/
public class DefaultSingleSelectionModel implements SingleSelectionModel,
Serializable {
/* Only one ModelChangeEvent is needed per model instance since the
* event's only (read-only) state is the source property. The source
* of events generated here is always "this".
*/
protected transient ChangeEvent changeEvent = null;
/** {@collect.stats} The collection of registered listeners */
protected EventListenerList listenerList = new EventListenerList();
private int index = -1;
// implements javax.swing.SingleSelectionModel
public int getSelectedIndex() {
return index;
}
// implements javax.swing.SingleSelectionModel
public void setSelectedIndex(int index) {
if (this.index != index) {
this.index = index;
fireStateChanged();
}
}
// implements javax.swing.SingleSelectionModel
public void clearSelection() {
setSelectedIndex(-1);
}
// implements javax.swing.SingleSelectionModel
public boolean isSelected() {
boolean ret = false;
if (getSelectedIndex() != -1) {
ret = true;
}
return ret;
}
/** {@collect.stats}
* Adds a <code>ChangeListener</code> to the button.
*/
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
/** {@collect.stats}
* Removes a <code>ChangeListener</code> from the button.
*/
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the change listeners
* registered on this <code>DefaultSingleSelectionModel</code>.
*
* @return all of this model's <code>ChangeListener</code>s
* or an empty
* array if no change listeners are currently registered
*
* @see #addChangeListener
* @see #removeChangeListener
*
* @since 1.4
*/
public ChangeListener[] getChangeListeners() {
return (ChangeListener[])listenerList.getListeners(
ChangeListener.class);
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is created lazily.
* @see EventListenerList
*/
protected void fireStateChanged() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ChangeListener.class) {
// Lazily create the event:
if (changeEvent == null)
changeEvent = new ChangeEvent(this);
((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
}
}
}
/** {@collect.stats}
* Returns an array of all the objects currently registered as
* <code><em>Foo</em>Listener</code>s
* upon this model.
* <code><em>Foo</em>Listener</code>s
* are registered using the <code>add<em>Foo</em>Listener</code> method.
* <p>
* You can specify the <code>listenerType</code> argument
* with a class literal, such as <code><em>Foo</em>Listener.class</code>.
* For example, you can query a <code>DefaultSingleSelectionModel</code>
* instance <code>m</code>
* for its change listeners
* with the following code:
*
* <pre>ChangeListener[] cls = (ChangeListener[])(m.getListeners(ChangeListener.class));</pre>
*
* If no such listeners exist,
* this method returns an empty array.
*
* @param listenerType the type of listeners requested;
* this parameter should specify an interface
* that descends from <code>java.util.EventListener</code>
* @return an array of all objects registered as
* <code><em>Foo</em>Listener</code>s
* on this model,
* or an empty array if no such
* listeners have been added
* @exception ClassCastException if <code>listenerType</code> doesn't
* specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @see #getChangeListeners
*
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
}
|
Java
|
/*
* Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.beans.*;
import javax.swing.event.*;
import sun.awt.EmbeddedFrame;
/** {@collect.stats}
* The KeyboardManager class is used to help dispatch keyboard actions for the
* WHEN_IN_FOCUSED_WINDOW style actions. Actions with other conditions are handled
* directly in JComponent.
*
* Here's a description of the symantics of how keyboard dispatching should work
* atleast as I understand it.
*
* KeyEvents are dispatched to the focused component. The focus manager gets first
* crack at processing this event. If the focus manager doesn't want it, then
* the JComponent calls super.processKeyEvent() this allows listeners a chance
* to process the event.
*
* If none of the listeners "consumes" the event then the keybindings get a shot.
* This is where things start to get interesting. First, KeyStokes defined with the
* WHEN_FOCUSED condition get a chance. If none of these want the event, then the component
* walks though it's parents looked for actions of type WHEN_ANCESTOR_OF_FOCUSED_COMPONENT.
*
* If no one has taken it yet, then it winds up here. We then look for components registered
* for WHEN_IN_FOCUSED_WINDOW events and fire to them. Note that if none of those are found
* then we pass the event to the menubars and let them have a crack at it. They're handled differently.
*
* Lastly, we check if we're looking at an internal frame. If we are and no one wanted the event
* then we move up to the InternalFrame's creator and see if anyone wants the event (and so on and so on).
*
*
* @see InputMap
*/
class KeyboardManager {
static KeyboardManager currentManager = new KeyboardManager();
/** {@collect.stats}
* maps top-level containers to a sub-hashtable full of keystrokes
*/
Hashtable containerMap = new Hashtable();
/** {@collect.stats}
* Maps component/keystroke pairs to a topLevel container
* This is mainly used for fast unregister operations
*/
Hashtable componentKeyStrokeMap = new Hashtable();
public static KeyboardManager getCurrentManager() {
return currentManager;
}
public static void setCurrentManager(KeyboardManager km) {
currentManager = km;
}
/** {@collect.stats}
* register keystrokes here which are for the WHEN_IN_FOCUSED_WINDOW
* case.
* Other types of keystrokes will be handled by walking the hierarchy
* That simplifies some potentially hairy stuff.
*/
public void registerKeyStroke(KeyStroke k, JComponent c) {
Container topContainer = getTopAncestor(c);
if (topContainer == null) {
return;
}
Hashtable keyMap = (Hashtable)containerMap.get(topContainer);
if (keyMap == null) { // lazy evaluate one
keyMap = registerNewTopContainer(topContainer);
}
Object tmp = keyMap.get(k);
if (tmp == null) {
keyMap.put(k,c);
} else if (tmp instanceof Vector) { // if there's a Vector there then add to it.
Vector v = (Vector)tmp;
if (!v.contains(c)) { // only add if this keystroke isn't registered for this component
v.addElement(c);
}
} else if (tmp instanceof JComponent) {
// if a JComponent is there then remove it and replace it with a vector
// Then add the old compoennt and the new compoent to the vector
// then insert the vector in the table
if (tmp != c) { // this means this is already registered for this component, no need to dup
Vector v = new Vector();
v.addElement(tmp);
v.addElement(c);
keyMap.put(k, v);
}
} else {
System.out.println("Unexpected condition in registerKeyStroke");
Thread.dumpStack();
}
componentKeyStrokeMap.put(new ComponentKeyStrokePair(c,k), topContainer);
// Check for EmbeddedFrame case, they know how to process accelerators even
// when focus is not in Java
if (topContainer instanceof EmbeddedFrame) {
((EmbeddedFrame)topContainer).registerAccelerator(k);
}
}
/** {@collect.stats}
* Find the top focusable Window, Applet, or InternalFrame
*/
private static Container getTopAncestor(JComponent c) {
for(Container p = c.getParent(); p != null; p = p.getParent()) {
if (p instanceof Window && ((Window)p).isFocusableWindow() ||
p instanceof Applet || p instanceof JInternalFrame) {
return p;
}
}
return null;
}
public void unregisterKeyStroke(KeyStroke ks, JComponent c) {
// component may have already been removed from the hierarchy, we
// need to look up the container using the componentKeyStrokeMap.
ComponentKeyStrokePair ckp = new ComponentKeyStrokePair(c,ks);
Object topContainer = componentKeyStrokeMap.get(ckp);
if (topContainer == null) { // never heard of this pairing, so bail
return;
}
Hashtable keyMap = (Hashtable)containerMap.get(topContainer);
if (keyMap == null) { // this should never happen, but I'm being safe
Thread.dumpStack();
return;
}
Object tmp = keyMap.get(ks);
if (tmp == null) { // this should never happen, but I'm being safe
Thread.dumpStack();
return;
}
if (tmp instanceof JComponent && tmp == c) {
keyMap.remove(ks); // remove the KeyStroke from the Map
//System.out.println("removed a stroke" + ks);
} else if (tmp instanceof Vector ) { // this means there is more than one component reg for this key
Vector v = (Vector)tmp;
v.removeElement(c);
if ( v.isEmpty() ) {
keyMap.remove(ks); // remove the KeyStroke from the Map
//System.out.println("removed a ks vector");
}
}
if ( keyMap.isEmpty() ) { // if no more bindings in this table
containerMap.remove(topContainer); // remove table to enable GC
//System.out.println("removed a container");
}
componentKeyStrokeMap.remove(ckp);
// Check for EmbeddedFrame case, they know how to process accelerators even
// when focus is not in Java
if (topContainer instanceof EmbeddedFrame) {
((EmbeddedFrame)topContainer).unregisterAccelerator(ks);
}
}
/** {@collect.stats}
* This method is called when the focused component (and none of
* its ancestors) want the key event. This will look up the keystroke
* to see if any chidren (or subchildren) of the specified container
* want a crack at the event.
* If one of them wants it, then it will "DO-THE-RIGHT-THING"
*/
public boolean fireKeyboardAction(KeyEvent e, boolean pressed, Container topAncestor) {
if (e.isConsumed()) {
System.out.println("Aquired pre-used event!");
Thread.dumpStack();
}
KeyStroke ks;
if(e.getID() == KeyEvent.KEY_TYPED) {
ks=KeyStroke.getKeyStroke(e.getKeyChar());
} else {
ks=KeyStroke.getKeyStroke(e.getKeyCode(), e.getModifiers(), !pressed);
}
Hashtable keyMap = (Hashtable)containerMap.get(topAncestor);
if (keyMap != null) { // this container isn't registered, so bail
Object tmp = keyMap.get(ks);
if (tmp == null) {
// don't do anything
} else if ( tmp instanceof JComponent) {
JComponent c = (JComponent)tmp;
if ( c.isShowing() && c.isEnabled() ) { // only give it out if enabled and visible
fireBinding(c, ks, e, pressed);
}
} else if ( tmp instanceof Vector) { //more than one comp registered for this
Vector v = (Vector)tmp;
// There is no well defined order for WHEN_IN_FOCUSED_WINDOW
// bindings, but we give precedence to those bindings just
// added. This is done so that JMenus WHEN_IN_FOCUSED_WINDOW
// bindings are accessed before those of the JRootPane (they
// both have a WHEN_IN_FOCUSED_WINDOW binding for enter).
for (int counter = v.size() - 1; counter >= 0; counter--) {
JComponent c = (JComponent)v.elementAt(counter);
//System.out.println("Trying collision: " + c + " vector = "+ v.size());
if ( c.isShowing() && c.isEnabled() ) { // don't want to give these out
fireBinding(c, ks, e, pressed);
if (e.isConsumed())
return true;
}
}
} else {
System.out.println( "Unexpected condition in fireKeyboardAction " + tmp);
// This means that tmp wasn't null, a JComponent, or a Vector. What is it?
Thread.dumpStack();
}
}
if (e.isConsumed()) {
return true;
}
// if no one else handled it, then give the menus a crack
// The're handled differently. The key is to let any JMenuBars
// process the event
if ( keyMap != null) {
Vector v = (Vector)keyMap.get(JMenuBar.class);
if (v != null) {
Enumeration iter = v.elements();
while (iter.hasMoreElements()) {
JMenuBar mb = (JMenuBar)iter.nextElement();
if ( mb.isShowing() && mb.isEnabled() ) { // don't want to give these out
fireBinding(mb, ks, e, pressed);
if (e.isConsumed()) {
return true;
}
}
}
}
}
return e.isConsumed();
}
void fireBinding(JComponent c, KeyStroke ks, KeyEvent e, boolean pressed) {
if (c.processKeyBinding(ks, e, JComponent.WHEN_IN_FOCUSED_WINDOW,
pressed)) {
e.consume();
}
}
public void registerMenuBar(JMenuBar mb) {
Container top = getTopAncestor(mb);
if (top == null) {
return;
}
Hashtable keyMap = (Hashtable)containerMap.get(top);
if (keyMap == null) { // lazy evaluate one
keyMap = registerNewTopContainer(top);
}
// use the menubar class as the key
Vector menuBars = (Vector)keyMap.get(JMenuBar.class);
if (menuBars == null) { // if we don't have a list of menubars,
// then make one.
menuBars = new Vector();
keyMap.put(JMenuBar.class, menuBars);
}
if (!menuBars.contains(mb)) {
menuBars.addElement(mb);
}
}
public void unregisterMenuBar(JMenuBar mb) {
Object topContainer = getTopAncestor(mb);
if (topContainer == null) {
return;
}
Hashtable keyMap = (Hashtable)containerMap.get(topContainer);
if (keyMap!=null) {
Vector v = (Vector)keyMap.get(JMenuBar.class);
if (v != null) {
v.removeElement(mb);
if (v.isEmpty()) {
keyMap.remove(JMenuBar.class);
if (keyMap.isEmpty()) {
// remove table to enable GC
containerMap.remove(topContainer);
}
}
}
}
}
protected Hashtable registerNewTopContainer(Container topContainer) {
Hashtable keyMap = new Hashtable();
containerMap.put(topContainer, keyMap);
return keyMap;
}
/** {@collect.stats}
* This class is used to create keys for a hashtable
* which looks up topContainers based on component, keystroke pairs
* This is used to make unregistering KeyStrokes fast
*/
class ComponentKeyStrokePair {
Object component;
Object keyStroke;
public ComponentKeyStrokePair(Object comp, Object key) {
component = comp;
keyStroke = key;
}
public boolean equals(Object o) {
if ( !(o instanceof ComponentKeyStrokePair)) {
return false;
}
ComponentKeyStrokePair ckp = (ComponentKeyStrokePair)o;
return ((component.equals(ckp.component)) && (keyStroke.equals(ckp.keyStroke)));
}
public int hashCode() {
return component.hashCode() * keyStroke.hashCode();
}
}
} // end KeyboardManager
|
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.swing;
import java.awt.Container;
import javax.swing.plaf.ComponentUI;
import sun.awt.AppContext;
/** {@collect.stats}
* <code>LayoutStyle</code> provides information about how to position
* components. This class is primarily useful for visual tools and
* layout managers. Most developers will not need to use this class.
* <p>
* You typically don't set or create a
* <code>LayoutStyle</code>. Instead use the static method
* <code>getInstance</code> to obtain the current instance.
*
* @since 1.6
*/
public abstract class LayoutStyle {
/** {@collect.stats}
* Sets the shared instance of <code>LayoutStyle</code>. Specifying
* <code>null</code> results in using the <code>LayoutStyle</code> from
* the current <code>LookAndFeel</code>.
*
* @param style the <code>LayoutStyle</code>, or <code>null</code>
* @see #getInstance
*/
public static void setInstance(LayoutStyle style) {
synchronized(LayoutStyle.class) {
if (style == null) {
AppContext.getAppContext().remove(LayoutStyle.class);
}
else {
AppContext.getAppContext().put(LayoutStyle.class, style);
}
}
}
/** {@collect.stats}
* Returns the shared instance of <code>LayoutStyle</code>. If an instance
* has not been specified in <code>setInstance</code>, this will return
* the <code>LayoutStyle</code> from the current <code>LookAndFeel</code>.
*
* @see LookAndFeel#getLayoutStyle
* @return the shared instance of <code>LayoutStyle</code>
*/
public static LayoutStyle getInstance() {
LayoutStyle style;
synchronized(LayoutStyle.class) {
style = (LayoutStyle)AppContext.getAppContext().
get(LayoutStyle.class);
}
if (style == null) {
return UIManager.getLookAndFeel().getLayoutStyle();
}
return style;
}
/** {@collect.stats}
* <code>ComponentPlacement</code> is an enumeration of the
* possible ways two components can be placed relative to each
* other. <code>ComponentPlacement</code> is used by the
* <code>LayoutStyle</code> method <code>getPreferredGap</code>. Refer to
* <code>LayoutStyle</code> for more information.
*
* @see LayoutStyle#getPreferredGap(JComponent,JComponent,
* ComponentPlacement,int,Container)
* @since 1.6
*/
public enum ComponentPlacement {
/** {@collect.stats}
* Enumeration value indicating the two components are
* visually related and will be placed in the same parent.
* For example, a <code>JLabel</code> providing a label for a
* <code>JTextField</code> is typically visually associated
* with the <code>JTextField</code>; the constant <code>RELATED</code>
* is used for this.
*/
RELATED,
/** {@collect.stats}
* Enumeration value indicating the two components are
* visually unrelated and will be placed in the same parent.
* For example, groupings of components are usually visually
* separated; the constant <code>UNRELATED</code> is used for this.
*/
UNRELATED,
/** {@collect.stats}
* Enumeration value indicating the distance to indent a component
* is being requested. For example, often times the children of
* a label will be horizontally indented from the label. To determine
* the preferred distance for such a gap use the
* <code>INDENT</code> type.
* <p>
* This value is typically only useful with a direction of
* <code>EAST</code> or <code>WEST</code>.
*/
INDENT;
}
/** {@collect.stats}
* Creates a new <code>LayoutStyle</code>. You generally don't
* create a <code>LayoutStyle</code>. Instead use the method
* <code>getInstance</code> to obtain the current
* <code>LayoutStyle</code>.
*/
public LayoutStyle() {
}
/** {@collect.stats}
* Returns the amount of space to use between two components.
* The return value indicates the distance to place
* <code>component2</code> relative to <code>component1</code>.
* For example, the following returns the amount of space to place
* between <code>component2</code> and <code>component1</code>
* when <code>component2</code> is placed vertically above
* <code>component1</code>:
* <pre>
* int gap = getPreferredGap(component1, component2,
* ComponentPlacement.RELATED,
* SwingConstants.NORTH, parent);
* </pre>
* The <code>type</code> parameter indicates the relation between
* the two components. If the two components will be contained in
* the same parent and are showing similar logically related
* items, use <code>RELATED</code>. If the two components will be
* contained in the same parent but show logically unrelated items
* use <code>UNRELATED</code>. Some look and feels may not
* distinguish between the <code>RELATED</code> and
* <code>UNRELATED</code> types.
* <p>
* The return value is not intended to take into account the
* current size and position of <code>component2</code> or
* <code>component1</code>. The return value may take into
* consideration various properties of the components. For
* example, the space may vary based on font size, or the preferred
* size of the component.
*
* @param component1 the <code>JComponent</code>
* <code>component2</code> is being placed relative to
* @param component2 the <code>JComponent</code> being placed
* @param position the position <code>component2</code> is being placed
* relative to <code>component1</code>; one of
* <code>SwingConstants.NORTH</code>,
* <code>SwingConstants.SOUTH</code>,
* <code>SwingConstants.EAST</code> or
* <code>SwingConstants.WEST</code>
* @param type how the two components are being placed
* @param parent the parent of <code>component2</code>; this may differ
* from the actual parent and it may be <code>null</code>
* @return the amount of space to place between the two components
* @throws NullPointerException if <code>component1</code>,
* <code>component2</code> or <code>type</code> is
* <code>null</code>
* @throws IllegalArgumentException if <code>position</code> is not
* one of <code>SwingConstants.NORTH</code>,
* <code>SwingConstants.SOUTH</code>,
* <code>SwingConstants.EAST</code> or
* <code>SwingConstants.WEST</code>
* @see LookAndFeel#getLayoutStyle
* @since 1.6
*/
public abstract int getPreferredGap(JComponent component1,
JComponent component2,
ComponentPlacement type, int position,
Container parent);
/** {@collect.stats}
* Returns the amount of space to place between the component and specified
* edge of its parent.
*
* @param component the <code>JComponent</code> being positioned
* @param position the position <code>component</code> is being placed
* relative to its parent; one of
* <code>SwingConstants.NORTH</code>,
* <code>SwingConstants.SOUTH</code>,
* <code>SwingConstants.EAST</code> or
* <code>SwingConstants.WEST</code>
* @param parent the parent of <code>component</code>; this may differ
* from the actual parent and may be <code>null</code>
* @return the amount of space to place between the component and specified
* edge
* @throws IllegalArgumentException if <code>position</code> is not
* one of <code>SwingConstants.NORTH</code>,
* <code>SwingConstants.SOUTH</code>,
* <code>SwingConstants.EAST</code> or
* <code>SwingConstants.WEST</code>
*/
public abstract int getContainerGap(JComponent component, int position,
Container parent);
}
|
Java
|
/*
* Copyright (c) 1997, 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.swing;
import javax.swing.event.*;
/** {@collect.stats}
* A model that supports at most one indexed selection.
*
* @author Dave Moore
*/
public interface SingleSelectionModel {
/** {@collect.stats}
* Returns the model's selection.
*
* @return the model's selection, or -1 if there is no selection
* @see #setSelectedIndex
*/
public int getSelectedIndex();
/** {@collect.stats}
* Sets the model's selected index to <I>index</I>.
*
* Notifies any listeners if the model changes
*
* @param index an int specifying the model selection
* @see #getSelectedIndex
* @see #addChangeListener
*/
public void setSelectedIndex(int index);
/** {@collect.stats}
* Clears the selection (to -1).
*/
public void clearSelection();
/** {@collect.stats}
* Returns true if the selection model currently has a selected value.
* @return true if a value is currently selected
*/
public boolean isSelected();
/** {@collect.stats}
* Adds <I>listener</I> as a listener to changes in the model.
* @param listener the ChangeListener to add
*/
void addChangeListener(ChangeListener listener);
/** {@collect.stats}
* Removes <I>listener</I> as a listener to changes in the model.
* @param listener the ChangeListener to remove
*/
void removeChangeListener(ChangeListener listener);
}
|
Java
|
/*
* Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.image.*;
import java.text.AttributedCharacterIterator;
/** {@collect.stats}
* Graphics subclass supporting graphics debugging. Overrides most methods
* from Graphics. DebugGraphics objects are rarely created by hand. They
* are most frequently created automatically when a JComponent's
* debugGraphicsOptions are changed using the setDebugGraphicsOptions()
* method.
* <p>
* NOTE: You must turn off double buffering to use DebugGraphics:
* RepaintManager repaintManager = RepaintManager.currentManager(component);
* repaintManager.setDoubleBufferingEnabled(false);
*
* @see JComponent#setDebugGraphicsOptions
* @see RepaintManager#currentManager
* @see RepaintManager#setDoubleBufferingEnabled
*
* @author Dave Karlton
*/
public class DebugGraphics extends Graphics {
Graphics graphics;
Image buffer;
int debugOptions;
int graphicsID = graphicsCount++;
int xOffset, yOffset;
private static int graphicsCount = 0;
private static ImageIcon imageLoadingIcon = new ImageIcon();
/** {@collect.stats} Log graphics operations. */
public static final int LOG_OPTION = 1 << 0;
/** {@collect.stats} Flash graphics operations. */
public static final int FLASH_OPTION = 1 << 1;
/** {@collect.stats} Show buffered operations in a separate <code>Frame</code>. */
public static final int BUFFERED_OPTION = 1 << 2;
/** {@collect.stats} Don't debug graphics operations. */
public static final int NONE_OPTION = -1;
static {
JComponent.DEBUG_GRAPHICS_LOADED = true;
}
/** {@collect.stats}
* Constructs a new debug graphics context that supports slowed
* down drawing.
*/
public DebugGraphics() {
super();
buffer = null;
xOffset = yOffset = 0;
}
/** {@collect.stats}
* Constructs a debug graphics context from an existing graphics
* context that slows down drawing for the specified component.
*
* @param graphics the Graphics context to slow down
* @param component the JComponent to draw slowly
*/
public DebugGraphics(Graphics graphics, JComponent component) {
this(graphics);
setDebugOptions(component.shouldDebugGraphics());
}
/** {@collect.stats}
* Constructs a debug graphics context from an existing graphics
* context that supports slowed down drawing.
*
* @param graphics the Graphics context to slow down
*/
public DebugGraphics(Graphics graphics) {
this();
this.graphics = graphics;
}
/** {@collect.stats}
* Overrides <code>Graphics.create</code> to return a DebugGraphics object.
*/
public Graphics create() {
DebugGraphics debugGraphics;
debugGraphics = new DebugGraphics();
debugGraphics.graphics = graphics.create();
debugGraphics.debugOptions = debugOptions;
debugGraphics.buffer = buffer;
return debugGraphics;
}
/** {@collect.stats}
* Overrides <code>Graphics.create</code> to return a DebugGraphics object.
*/
public Graphics create(int x, int y, int width, int height) {
DebugGraphics debugGraphics;
debugGraphics = new DebugGraphics();
debugGraphics.graphics = graphics.create(x, y, width, height);
debugGraphics.debugOptions = debugOptions;
debugGraphics.buffer = buffer;
debugGraphics.xOffset = xOffset + x;
debugGraphics.yOffset = yOffset + y;
return debugGraphics;
}
//------------------------------------------------
// NEW METHODS
//------------------------------------------------
/** {@collect.stats}
* Sets the Color used to flash drawing operations.
*/
public static void setFlashColor(Color flashColor) {
info().flashColor = flashColor;
}
/** {@collect.stats}
* Returns the Color used to flash drawing operations.
* @see #setFlashColor
*/
public static Color flashColor() {
return info().flashColor;
}
/** {@collect.stats}
* Sets the time delay of drawing operation flashing.
*/
public static void setFlashTime(int flashTime) {
info().flashTime = flashTime;
}
/** {@collect.stats}
* Returns the time delay of drawing operation flashing.
* @see #setFlashTime
*/
public static int flashTime() {
return info().flashTime;
}
/** {@collect.stats}
* Sets the number of times that drawing operations will flash.
*/
public static void setFlashCount(int flashCount) {
info().flashCount = flashCount;
}
/** {@collect.stats} Returns the number of times that drawing operations will flash.
* @see #setFlashCount
*/
public static int flashCount() {
return info().flashCount;
}
/** {@collect.stats} Sets the stream to which the DebugGraphics logs drawing operations.
*/
public static void setLogStream(java.io.PrintStream stream) {
info().stream = stream;
}
/** {@collect.stats} Returns the stream to which the DebugGraphics logs drawing operations.
* @see #setLogStream
*/
public static java.io.PrintStream logStream() {
return info().stream;
}
/** {@collect.stats} Sets the Font used for text drawing operations.
*/
public void setFont(Font aFont) {
if (debugLog()) {
info().log(toShortString() + " Setting font: " + aFont);
}
graphics.setFont(aFont);
}
/** {@collect.stats} Returns the Font used for text drawing operations.
* @see #setFont
*/
public Font getFont() {
return graphics.getFont();
}
/** {@collect.stats} Sets the color to be used for drawing and filling lines and shapes.
*/
public void setColor(Color aColor) {
if (debugLog()) {
info().log(toShortString() + " Setting color: " + aColor);
}
graphics.setColor(aColor);
}
/** {@collect.stats} Returns the Color used for text drawing operations.
* @see #setColor
*/
public Color getColor() {
return graphics.getColor();
}
//-----------------------------------------------
// OVERRIDDEN METHODS
//------------------------------------------------
/** {@collect.stats}
* Overrides <code>Graphics.getFontMetrics</code>.
*/
public FontMetrics getFontMetrics() {
return graphics.getFontMetrics();
}
/** {@collect.stats}
* Overrides <code>Graphics.getFontMetrics</code>.
*/
public FontMetrics getFontMetrics(Font f) {
return graphics.getFontMetrics(f);
}
/** {@collect.stats}
* Overrides <code>Graphics.translate</code>.
*/
public void translate(int x, int y) {
if (debugLog()) {
info().log(toShortString() +
" Translating by: " + new Point(x, y));
}
xOffset += x;
yOffset += y;
graphics.translate(x, y);
}
/** {@collect.stats}
* Overrides <code>Graphics.setPaintMode</code>.
*/
public void setPaintMode() {
if (debugLog()) {
info().log(toShortString() + " Setting paint mode");
}
graphics.setPaintMode();
}
/** {@collect.stats}
* Overrides <code>Graphics.setXORMode</code>.
*/
public void setXORMode(Color aColor) {
if (debugLog()) {
info().log(toShortString() + " Setting XOR mode: " + aColor);
}
graphics.setXORMode(aColor);
}
/** {@collect.stats}
* Overrides <code>Graphics.getClipBounds</code>.
*/
public Rectangle getClipBounds() {
return graphics.getClipBounds();
}
/** {@collect.stats}
* Overrides <code>Graphics.clipRect</code>.
*/
public void clipRect(int x, int y, int width, int height) {
graphics.clipRect(x, y, width, height);
if (debugLog()) {
info().log(toShortString() +
" Setting clipRect: " + (new Rectangle(x, y, width, height)) +
" New clipRect: " + graphics.getClip());
}
}
/** {@collect.stats}
* Overrides <code>Graphics.setClip</code>.
*/
public void setClip(int x, int y, int width, int height) {
graphics.setClip(x, y, width, height);
if (debugLog()) {
info().log(toShortString() +
" Setting new clipRect: " + graphics.getClip());
}
}
/** {@collect.stats}
* Overrides <code>Graphics.getClip</code>.
*/
public Shape getClip() {
return graphics.getClip();
}
/** {@collect.stats}
* Overrides <code>Graphics.setClip</code>.
*/
public void setClip(Shape clip) {
graphics.setClip(clip);
if (debugLog()) {
info().log(toShortString() +
" Setting new clipRect: " + graphics.getClip());
}
}
/** {@collect.stats}
* Overrides <code>Graphics.drawRect</code>.
*/
public void drawRect(int x, int y, int width, int height) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Drawing rect: " +
new Rectangle(x, y, width, height));
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawRect(x, y, width, height);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor);
graphics.drawRect(x, y, width, height);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.drawRect(x, y, width, height);
}
/** {@collect.stats}
* Overrides <code>Graphics.fillRect</code>.
*/
public void fillRect(int x, int y, int width, int height) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Filling rect: " +
new Rectangle(x, y, width, height));
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.fillRect(x, y, width, height);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor);
graphics.fillRect(x, y, width, height);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.fillRect(x, y, width, height);
}
/** {@collect.stats}
* Overrides <code>Graphics.clearRect</code>.
*/
public void clearRect(int x, int y, int width, int height) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Clearing rect: " +
new Rectangle(x, y, width, height));
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.clearRect(x, y, width, height);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor);
graphics.clearRect(x, y, width, height);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.clearRect(x, y, width, height);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawRoundRect</code>.
*/
public void drawRoundRect(int x, int y, int width, int height,
int arcWidth, int arcHeight) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Drawing round rect: " +
new Rectangle(x, y, width, height) +
" arcWidth: " + arcWidth +
" archHeight: " + arcHeight);
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawRoundRect(x, y, width, height,
arcWidth, arcHeight);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor);
graphics.drawRoundRect(x, y, width, height,
arcWidth, arcHeight);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.drawRoundRect(x, y, width, height, arcWidth, arcHeight);
}
/** {@collect.stats}
* Overrides <code>Graphics.fillRoundRect</code>.
*/
public void fillRoundRect(int x, int y, int width, int height,
int arcWidth, int arcHeight) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Filling round rect: " +
new Rectangle(x, y, width, height) +
" arcWidth: " + arcWidth +
" archHeight: " + arcHeight);
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.fillRoundRect(x, y, width, height,
arcWidth, arcHeight);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor);
graphics.fillRoundRect(x, y, width, height,
arcWidth, arcHeight);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.fillRoundRect(x, y, width, height, arcWidth, arcHeight);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawLine</code>.
*/
public void drawLine(int x1, int y1, int x2, int y2) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Drawing line: from " + pointToString(x1, y1) +
" to " + pointToString(x2, y2));
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawLine(x1, y1, x2, y2);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor);
graphics.drawLine(x1, y1, x2, y2);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.drawLine(x1, y1, x2, y2);
}
/** {@collect.stats}
* Overrides <code>Graphics.draw3DRect</code>.
*/
public void draw3DRect(int x, int y, int width, int height,
boolean raised) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Drawing 3D rect: " +
new Rectangle(x, y, width, height) +
" Raised bezel: " + raised);
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.draw3DRect(x, y, width, height, raised);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor);
graphics.draw3DRect(x, y, width, height, raised);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.draw3DRect(x, y, width, height, raised);
}
/** {@collect.stats}
* Overrides <code>Graphics.fill3DRect</code>.
*/
public void fill3DRect(int x, int y, int width, int height,
boolean raised) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Filling 3D rect: " +
new Rectangle(x, y, width, height) +
" Raised bezel: " + raised);
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.fill3DRect(x, y, width, height, raised);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor);
graphics.fill3DRect(x, y, width, height, raised);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.fill3DRect(x, y, width, height, raised);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawOval</code>.
*/
public void drawOval(int x, int y, int width, int height) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Drawing oval: " +
new Rectangle(x, y, width, height));
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawOval(x, y, width, height);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor);
graphics.drawOval(x, y, width, height);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.drawOval(x, y, width, height);
}
/** {@collect.stats}
* Overrides <code>Graphics.fillOval</code>.
*/
public void fillOval(int x, int y, int width, int height) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Filling oval: " +
new Rectangle(x, y, width, height));
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.fillOval(x, y, width, height);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor);
graphics.fillOval(x, y, width, height);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.fillOval(x, y, width, height);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawArc</code>.
*/
public void drawArc(int x, int y, int width, int height,
int startAngle, int arcAngle) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Drawing arc: " +
new Rectangle(x, y, width, height) +
" startAngle: " + startAngle +
" arcAngle: " + arcAngle);
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawArc(x, y, width, height,
startAngle, arcAngle);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor);
graphics.drawArc(x, y, width, height, startAngle, arcAngle);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.drawArc(x, y, width, height, startAngle, arcAngle);
}
/** {@collect.stats}
* Overrides <code>Graphics.fillArc</code>.
*/
public void fillArc(int x, int y, int width, int height,
int startAngle, int arcAngle) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Filling arc: " +
new Rectangle(x, y, width, height) +
" startAngle: " + startAngle +
" arcAngle: " + arcAngle);
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.fillArc(x, y, width, height,
startAngle, arcAngle);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor);
graphics.fillArc(x, y, width, height, startAngle, arcAngle);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.fillArc(x, y, width, height, startAngle, arcAngle);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawPolyline</code>.
*/
public void drawPolyline(int xPoints[], int yPoints[], int nPoints) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Drawing polyline: " +
" nPoints: " + nPoints +
" X's: " + xPoints +
" Y's: " + yPoints);
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawPolyline(xPoints, yPoints, nPoints);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor);
graphics.drawPolyline(xPoints, yPoints, nPoints);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.drawPolyline(xPoints, yPoints, nPoints);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawPolygon</code>.
*/
public void drawPolygon(int xPoints[], int yPoints[], int nPoints) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Drawing polygon: " +
" nPoints: " + nPoints +
" X's: " + xPoints +
" Y's: " + yPoints);
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawPolygon(xPoints, yPoints, nPoints);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor);
graphics.drawPolygon(xPoints, yPoints, nPoints);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.drawPolygon(xPoints, yPoints, nPoints);
}
/** {@collect.stats}
* Overrides <code>Graphics.fillPolygon</code>.
*/
public void fillPolygon(int xPoints[], int yPoints[], int nPoints) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Filling polygon: " +
" nPoints: " + nPoints +
" X's: " + xPoints +
" Y's: " + yPoints);
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.fillPolygon(xPoints, yPoints, nPoints);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor : oldColor);
graphics.fillPolygon(xPoints, yPoints, nPoints);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.fillPolygon(xPoints, yPoints, nPoints);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawString</code>.
*/
public void drawString(String aString, int x, int y) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Drawing string: \"" + aString +
"\" at: " + new Point(x, y));
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawString(aString, x, y);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor
: oldColor);
graphics.drawString(aString, x, y);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.drawString(aString, x, y);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawString</code>.
*/
public void drawString(AttributedCharacterIterator iterator, int x, int y) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info().log(toShortString() +
" Drawing text: \"" + iterator +
"\" at: " + new Point(x, y));
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawString(iterator, x, y);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor
: oldColor);
graphics.drawString(iterator, x, y);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.drawString(iterator, x, y);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawBytes</code>.
*/
public void drawBytes(byte data[], int offset, int length, int x, int y) {
DebugGraphicsInfo info = info();
Font font = graphics.getFont();
if (debugLog()) {
info().log(toShortString() +
" Drawing bytes at: " + new Point(x, y));
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawBytes(data, offset, length, x, y);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor
: oldColor);
graphics.drawBytes(data, offset, length, x, y);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.drawBytes(data, offset, length, x, y);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawChars</code>.
*/
public void drawChars(char data[], int offset, int length, int x, int y) {
DebugGraphicsInfo info = info();
Font font = graphics.getFont();
if (debugLog()) {
info().log(toShortString() +
" Drawing chars at " + new Point(x, y));
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawChars(data, offset, length, x, y);
debugGraphics.dispose();
}
} else if (debugFlash()) {
Color oldColor = getColor();
int i, count = (info.flashCount * 2) - 1;
for (i = 0; i < count; i++) {
graphics.setColor((i % 2) == 0 ? info.flashColor
: oldColor);
graphics.drawChars(data, offset, length, x, y);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
graphics.setColor(oldColor);
}
graphics.drawChars(data, offset, length, x, y);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawImage</code>.
*/
public boolean drawImage(Image img, int x, int y,
ImageObserver observer) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info.log(toShortString() +
" Drawing image: " + img +
" at: " + new Point(x, y));
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawImage(img, x, y, observer);
debugGraphics.dispose();
}
} else if (debugFlash()) {
int i, count = (info.flashCount * 2) - 1;
ImageProducer oldProducer = img.getSource();
ImageProducer newProducer
= new FilteredImageSource(oldProducer,
new DebugGraphicsFilter(info.flashColor));
Image newImage
= Toolkit.getDefaultToolkit().createImage(newProducer);
DebugGraphicsObserver imageObserver
= new DebugGraphicsObserver();
Image imageToDraw;
for (i = 0; i < count; i++) {
imageToDraw = (i % 2) == 0 ? newImage : img;
loadImage(imageToDraw);
graphics.drawImage(imageToDraw, x, y,
imageObserver);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
}
return graphics.drawImage(img, x, y, observer);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawImage</code>.
*/
public boolean drawImage(Image img, int x, int y, int width, int height,
ImageObserver observer) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info.log(toShortString() +
" Drawing image: " + img +
" at: " + new Rectangle(x, y, width, height));
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawImage(img, x, y, width, height, observer);
debugGraphics.dispose();
}
} else if (debugFlash()) {
int i, count = (info.flashCount * 2) - 1;
ImageProducer oldProducer = img.getSource();
ImageProducer newProducer
= new FilteredImageSource(oldProducer,
new DebugGraphicsFilter(info.flashColor));
Image newImage
= Toolkit.getDefaultToolkit().createImage(newProducer);
DebugGraphicsObserver imageObserver
= new DebugGraphicsObserver();
Image imageToDraw;
for (i = 0; i < count; i++) {
imageToDraw = (i % 2) == 0 ? newImage : img;
loadImage(imageToDraw);
graphics.drawImage(imageToDraw, x, y,
width, height, imageObserver);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
}
return graphics.drawImage(img, x, y, width, height, observer);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawImage</code>.
*/
public boolean drawImage(Image img, int x, int y,
Color bgcolor,
ImageObserver observer) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info.log(toShortString() +
" Drawing image: " + img +
" at: " + new Point(x, y) +
", bgcolor: " + bgcolor);
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawImage(img, x, y, bgcolor, observer);
debugGraphics.dispose();
}
} else if (debugFlash()) {
int i, count = (info.flashCount * 2) - 1;
ImageProducer oldProducer = img.getSource();
ImageProducer newProducer
= new FilteredImageSource(oldProducer,
new DebugGraphicsFilter(info.flashColor));
Image newImage
= Toolkit.getDefaultToolkit().createImage(newProducer);
DebugGraphicsObserver imageObserver
= new DebugGraphicsObserver();
Image imageToDraw;
for (i = 0; i < count; i++) {
imageToDraw = (i % 2) == 0 ? newImage : img;
loadImage(imageToDraw);
graphics.drawImage(imageToDraw, x, y,
bgcolor, imageObserver);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
}
return graphics.drawImage(img, x, y, bgcolor, observer);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawImage</code>.
*/
public boolean drawImage(Image img, int x, int y,int width, int height,
Color bgcolor,
ImageObserver observer) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info.log(toShortString() +
" Drawing image: " + img +
" at: " + new Rectangle(x, y, width, height) +
", bgcolor: " + bgcolor);
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawImage(img, x, y, width, height,
bgcolor, observer);
debugGraphics.dispose();
}
} else if (debugFlash()) {
int i, count = (info.flashCount * 2) - 1;
ImageProducer oldProducer = img.getSource();
ImageProducer newProducer
= new FilteredImageSource(oldProducer,
new DebugGraphicsFilter(info.flashColor));
Image newImage
= Toolkit.getDefaultToolkit().createImage(newProducer);
DebugGraphicsObserver imageObserver
= new DebugGraphicsObserver();
Image imageToDraw;
for (i = 0; i < count; i++) {
imageToDraw = (i % 2) == 0 ? newImage : img;
loadImage(imageToDraw);
graphics.drawImage(imageToDraw, x, y,
width, height, bgcolor, imageObserver);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
}
return graphics.drawImage(img, x, y, width, height, bgcolor, observer);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawImage</code>.
*/
public boolean drawImage(Image img,
int dx1, int dy1, int dx2, int dy2,
int sx1, int sy1, int sx2, int sy2,
ImageObserver observer) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info.log(toShortString() +
" Drawing image: " + img +
" destination: " + new Rectangle(dx1, dy1, dx2, dy2) +
" source: " + new Rectangle(sx1, sy1, sx2, sy2));
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawImage(img, dx1, dy1, dx2, dy2,
sx1, sy1, sx2, sy2, observer);
debugGraphics.dispose();
}
} else if (debugFlash()) {
int i, count = (info.flashCount * 2) - 1;
ImageProducer oldProducer = img.getSource();
ImageProducer newProducer
= new FilteredImageSource(oldProducer,
new DebugGraphicsFilter(info.flashColor));
Image newImage
= Toolkit.getDefaultToolkit().createImage(newProducer);
DebugGraphicsObserver imageObserver
= new DebugGraphicsObserver();
Image imageToDraw;
for (i = 0; i < count; i++) {
imageToDraw = (i % 2) == 0 ? newImage : img;
loadImage(imageToDraw);
graphics.drawImage(imageToDraw,
dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2,
imageObserver);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
}
return graphics.drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2,
observer);
}
/** {@collect.stats}
* Overrides <code>Graphics.drawImage</code>.
*/
public boolean drawImage(Image img,
int dx1, int dy1, int dx2, int dy2,
int sx1, int sy1, int sx2, int sy2,
Color bgcolor,
ImageObserver observer) {
DebugGraphicsInfo info = info();
if (debugLog()) {
info.log(toShortString() +
" Drawing image: " + img +
" destination: " + new Rectangle(dx1, dy1, dx2, dy2) +
" source: " + new Rectangle(sx1, sy1, sx2, sy2) +
", bgcolor: " + bgcolor);
}
if (isDrawingBuffer()) {
if (debugBuffered()) {
Graphics debugGraphics = debugGraphics();
debugGraphics.drawImage(img, dx1, dy1, dx2, dy2,
sx1, sy1, sx2, sy2, bgcolor, observer);
debugGraphics.dispose();
}
} else if (debugFlash()) {
int i, count = (info.flashCount * 2) - 1;
ImageProducer oldProducer = img.getSource();
ImageProducer newProducer
= new FilteredImageSource(oldProducer,
new DebugGraphicsFilter(info.flashColor));
Image newImage
= Toolkit.getDefaultToolkit().createImage(newProducer);
DebugGraphicsObserver imageObserver
= new DebugGraphicsObserver();
Image imageToDraw;
for (i = 0; i < count; i++) {
imageToDraw = (i % 2) == 0 ? newImage : img;
loadImage(imageToDraw);
graphics.drawImage(imageToDraw,
dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2,
bgcolor, imageObserver);
Toolkit.getDefaultToolkit().sync();
sleep(info.flashTime);
}
}
return graphics.drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2,
bgcolor, observer);
}
static void loadImage(Image img) {
imageLoadingIcon.loadImage(img);
}
/** {@collect.stats}
* Overrides <code>Graphics.copyArea</code>.
*/
public void copyArea(int x, int y, int width, int height,
int destX, int destY) {
if (debugLog()) {
info().log(toShortString() +
" Copying area from: " +
new Rectangle(x, y, width, height) +
" to: " + new Point(destX, destY));
}
graphics.copyArea(x, y, width, height, destX, destY);
}
final void sleep(int mSecs) {
try {
Thread.sleep(mSecs);
} catch (Exception e) {
}
}
/** {@collect.stats}
* Overrides <code>Graphics.dispose</code>.
*/
public void dispose() {
graphics.dispose();
graphics = null;
}
// ALERT!
/** {@collect.stats}
* Returns the drawingBuffer value.
*
* @return true if this object is drawing from a Buffer
*/
public boolean isDrawingBuffer() {
return buffer != null;
}
String toShortString() {
StringBuffer buffer = new StringBuffer("Graphics" + (isDrawingBuffer() ? "<B>" : "") + "(" + graphicsID + "-" + debugOptions + ")");
return buffer.toString();
}
String pointToString(int x, int y) {
StringBuffer buffer = new StringBuffer("(" + x + ", " + y + ")");
return buffer.toString();
}
/** {@collect.stats} Enables/disables diagnostic information about every graphics
* operation. The value of <b>options</b> indicates how this information
* should be displayed. LOG_OPTION causes a text message to be printed.
* FLASH_OPTION causes the drawing to flash several times. BUFFERED_OPTION
* creates a new Frame that shows each operation on an
* offscreen buffer. The value of <b>options</b> is bitwise OR'd into
* the current value. To disable debugging use NONE_OPTION.
*/
public void setDebugOptions(int options) {
if (options != 0) {
if (options == NONE_OPTION) {
if (debugOptions != 0) {
System.err.println(toShortString() + " Disabling debug");
debugOptions = 0;
}
} else {
if (debugOptions != options) {
debugOptions |= options;
if (debugLog()) {
System.err.println(toShortString() + " Enabling debug");
}
}
}
}
}
/** {@collect.stats} Returns the current debugging options for this DebugGraphics.
* @see #setDebugOptions
*/
public int getDebugOptions() {
return debugOptions;
}
/** {@collect.stats} Static wrapper method for DebugGraphicsInfo.setDebugOptions(). Stores
* options on a per component basis.
*/
static void setDebugOptions(JComponent component, int options) {
info().setDebugOptions(component, options);
}
/** {@collect.stats} Static wrapper method for DebugGraphicsInfo.getDebugOptions().
*/
static int getDebugOptions(JComponent component) {
DebugGraphicsInfo debugGraphicsInfo = info();
if (debugGraphicsInfo == null) {
return 0;
} else {
return debugGraphicsInfo.getDebugOptions(component);
}
}
/** {@collect.stats} Returns non-zero if <b>component</b> should display with DebugGraphics,
* zero otherwise. Walks the JComponent's parent tree to determine if
* any debugging options have been set.
*/
static int shouldComponentDebug(JComponent component) {
DebugGraphicsInfo info = info();
if (info == null) {
return 0;
} else {
Container container = (Container)component;
int debugOptions = 0;
while (container != null && (container instanceof JComponent)) {
debugOptions |= info.getDebugOptions((JComponent)container);
container = container.getParent();
}
return debugOptions;
}
}
/** {@collect.stats} Returns the number of JComponents that have debugging options turned
* on.
*/
static int debugComponentCount() {
DebugGraphicsInfo debugGraphicsInfo = info();
if (debugGraphicsInfo != null &&
debugGraphicsInfo.componentToDebug != null) {
return debugGraphicsInfo.componentToDebug.size();
} else {
return 0;
}
}
boolean debugLog() {
return (debugOptions & LOG_OPTION) == LOG_OPTION;
}
boolean debugFlash() {
return (debugOptions & FLASH_OPTION) == FLASH_OPTION;
}
boolean debugBuffered() {
return (debugOptions & BUFFERED_OPTION) == BUFFERED_OPTION;
}
/** {@collect.stats} Returns a DebugGraphics for use in buffering window.
*/
private Graphics debugGraphics() {
DebugGraphics debugGraphics;
DebugGraphicsInfo info = info();
JFrame debugFrame;
if (info.debugFrame == null) {
info.debugFrame = new JFrame();
info.debugFrame.setSize(500, 500);
}
debugFrame = info.debugFrame;
debugFrame.show();
debugGraphics = new DebugGraphics(debugFrame.getGraphics());
debugGraphics.setFont(getFont());
debugGraphics.setColor(getColor());
debugGraphics.translate(xOffset, yOffset);
debugGraphics.setClip(getClipBounds());
if (debugFlash()) {
debugGraphics.setDebugOptions(FLASH_OPTION);
}
return debugGraphics;
}
/** {@collect.stats} Returns DebugGraphicsInfo, or creates one if none exists.
*/
static DebugGraphicsInfo info() {
DebugGraphicsInfo debugGraphicsInfo = (DebugGraphicsInfo)
SwingUtilities.appContextGet(debugGraphicsInfoKey);
if (debugGraphicsInfo == null) {
debugGraphicsInfo = new DebugGraphicsInfo();
SwingUtilities.appContextPut(debugGraphicsInfoKey,
debugGraphicsInfo);
}
return debugGraphicsInfo;
}
private static final Class debugGraphicsInfoKey = DebugGraphicsInfo.class;
}
|
Java
|
/*
* Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
/** {@collect.stats}
* Constants used to control the window-closing operation.
* The <code>setDefaultCloseOperation</code> and
* <code>getDefaultCloseOperation</code> methods
* provided by <code>JFrame</code>,
* <code>JInternalFrame</code>, and
* <code>JDialog</code>
* use these constants.
* For examples of setting the default window-closing operation, see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/frame.html#windowevents">Responding to Window-Closing Events</a>,
* a section in <em>The Java Tutorial</em>.
* @see JFrame#setDefaultCloseOperation(int)
* @see JDialog#setDefaultCloseOperation(int)
* @see JInternalFrame#setDefaultCloseOperation(int)
*
*
* @author Amy Fowler
*/
public interface WindowConstants
{
/** {@collect.stats}
* The do-nothing default window close operation.
*/
public static final int DO_NOTHING_ON_CLOSE = 0;
/** {@collect.stats}
* The hide-window default window close operation
*/
public static final int HIDE_ON_CLOSE = 1;
/** {@collect.stats}
* The dispose-window default window close operation.
* <p>
* <b>Note</b>: When the last displayable window
* within the Java virtual machine (VM) is disposed of, the VM may
* terminate. See <a href="../../java/awt/doc-files/AWTThreadIssues.html">
* AWT Threading Issues</a> for more information.
* @see java.awt.Window#dispose()
* @see JInternalFrame#dispose()
*/
public static final int DISPOSE_ON_CLOSE = 2;
/** {@collect.stats}
* The exit application default window close operation. Attempting
* to set this on Windows that support this, such as
* <code>JFrame</code>, may throw a <code>SecurityException</code> based
* on the <code>SecurityManager</code>.
* It is recommended you only use this in an application.
*
* @since 1.4
* @see JFrame#setDefaultCloseOperation
*/
public static final int EXIT_ON_CLOSE = 3;
}
|
Java
|
/*
* Copyright (c) 2002, 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.swing.plaf.synth;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.UIResource;
import javax.swing.plaf.basic.BasicLookAndFeel;
import javax.swing.text.DefaultEditorKit;
import java.util.HashMap;
import java.util.Map;
import javax.swing.text.JTextComponent;
import sun.swing.plaf.synth.SynthUI;
/** {@collect.stats}
* <code>SynthStyle</code> is a set of style properties.
* Each <code>SynthUI</code> references at least one
* <code>SynthStyle</code> that is obtained using a
* <code>SynthStyleFactory</code>. You typically don't need to interact with
* this class directly, rather you will load a
* <a href="doc-files/synthFileFormat.html">Synth File Format file</a> into
* <code>SynthLookAndFeel</code> that will create a set of SynthStyles.
*
* @see SynthLookAndFeel
* @see SynthStyleFactory
*
* @since 1.5
* @author Scott Violet
*/
public abstract class SynthStyle {
/** {@collect.stats}
* Contains the default values for certain properties.
*/
private static Map DEFAULT_VALUES;
/** {@collect.stats}
* Shared SynthGraphics.
*/
private static final SynthGraphicsUtils SYNTH_GRAPHICS =
new SynthGraphicsUtils();
/** {@collect.stats}
* Adds the default values that we know about to DEFAULT_VALUES.
*/
private static void populateDefaultValues() {
Object buttonMap = new UIDefaults.LazyInputMap(new Object[] {
"SPACE", "pressed",
"released SPACE", "released"
});
DEFAULT_VALUES.put("Button.focusInputMap", buttonMap);
DEFAULT_VALUES.put("CheckBox.focusInputMap", buttonMap);
DEFAULT_VALUES.put("RadioButton.focusInputMap", buttonMap);
DEFAULT_VALUES.put("ToggleButton.focusInputMap", buttonMap);
DEFAULT_VALUES.put("SynthArrowButton.focusInputMap", buttonMap);
DEFAULT_VALUES.put("List.dropLineColor", Color.BLACK);
DEFAULT_VALUES.put("Tree.dropLineColor", Color.BLACK);
DEFAULT_VALUES.put("Table.dropLineColor", Color.BLACK);
DEFAULT_VALUES.put("Table.dropLineShortColor", Color.RED);
Object multilineInputMap = new UIDefaults.LazyInputMap(new Object[] {
"ctrl C", DefaultEditorKit.copyAction,
"ctrl V", DefaultEditorKit.pasteAction,
"ctrl X", DefaultEditorKit.cutAction,
"COPY", DefaultEditorKit.copyAction,
"PASTE", DefaultEditorKit.pasteAction,
"CUT", DefaultEditorKit.cutAction,
"control INSERT", DefaultEditorKit.copyAction,
"shift INSERT", DefaultEditorKit.pasteAction,
"shift DELETE", DefaultEditorKit.cutAction,
"shift LEFT", DefaultEditorKit.selectionBackwardAction,
"shift KP_LEFT", DefaultEditorKit.selectionBackwardAction,
"shift RIGHT", DefaultEditorKit.selectionForwardAction,
"shift KP_RIGHT", DefaultEditorKit.selectionForwardAction,
"ctrl LEFT", DefaultEditorKit.previousWordAction,
"ctrl KP_LEFT", DefaultEditorKit.previousWordAction,
"ctrl RIGHT", DefaultEditorKit.nextWordAction,
"ctrl KP_RIGHT", DefaultEditorKit.nextWordAction,
"ctrl shift LEFT", DefaultEditorKit.selectionPreviousWordAction,
"ctrl shift KP_LEFT", DefaultEditorKit.selectionPreviousWordAction,
"ctrl shift RIGHT", DefaultEditorKit.selectionNextWordAction,
"ctrl shift KP_RIGHT", DefaultEditorKit.selectionNextWordAction,
"ctrl A", DefaultEditorKit.selectAllAction,
"HOME", DefaultEditorKit.beginLineAction,
"END", DefaultEditorKit.endLineAction,
"shift HOME", DefaultEditorKit.selectionBeginLineAction,
"shift END", DefaultEditorKit.selectionEndLineAction,
"UP", DefaultEditorKit.upAction,
"KP_UP", DefaultEditorKit.upAction,
"DOWN", DefaultEditorKit.downAction,
"KP_DOWN", DefaultEditorKit.downAction,
"PAGE_UP", DefaultEditorKit.pageUpAction,
"PAGE_DOWN", DefaultEditorKit.pageDownAction,
"shift PAGE_UP", "selection-page-up",
"shift PAGE_DOWN", "selection-page-down",
"ctrl shift PAGE_UP", "selection-page-left",
"ctrl shift PAGE_DOWN", "selection-page-right",
"shift UP", DefaultEditorKit.selectionUpAction,
"shift KP_UP", DefaultEditorKit.selectionUpAction,
"shift DOWN", DefaultEditorKit.selectionDownAction,
"shift KP_DOWN", DefaultEditorKit.selectionDownAction,
"ENTER", DefaultEditorKit.insertBreakAction,
"BACK_SPACE", DefaultEditorKit.deletePrevCharAction,
"shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction,
"ctrl H", DefaultEditorKit.deletePrevCharAction,
"DELETE", DefaultEditorKit.deleteNextCharAction,
"ctrl DELETE", DefaultEditorKit.deleteNextWordAction,
"ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction,
"RIGHT", DefaultEditorKit.forwardAction,
"LEFT", DefaultEditorKit.backwardAction,
"KP_RIGHT", DefaultEditorKit.forwardAction,
"KP_LEFT", DefaultEditorKit.backwardAction,
"TAB", DefaultEditorKit.insertTabAction,
"ctrl BACK_SLASH", "unselect"/*DefaultEditorKit.unselectAction*/,
"ctrl HOME", DefaultEditorKit.beginAction,
"ctrl END", DefaultEditorKit.endAction,
"ctrl shift HOME", DefaultEditorKit.selectionBeginAction,
"ctrl shift END", DefaultEditorKit.selectionEndAction,
"ctrl T", "next-link-action",
"ctrl shift T", "previous-link-action",
"ctrl SPACE", "activate-link-action",
"control shift O", "toggle-componentOrientation"/*DefaultEditorKit.toggleComponentOrientation*/
});
DEFAULT_VALUES.put("EditorPane.focusInputMap", multilineInputMap);
DEFAULT_VALUES.put("TextArea.focusInputMap", multilineInputMap);
DEFAULT_VALUES.put("TextPane.focusInputMap", multilineInputMap);
Object fieldInputMap = new UIDefaults.LazyInputMap(new Object[] {
"ctrl C", DefaultEditorKit.copyAction,
"ctrl V", DefaultEditorKit.pasteAction,
"ctrl X", DefaultEditorKit.cutAction,
"COPY", DefaultEditorKit.copyAction,
"PASTE", DefaultEditorKit.pasteAction,
"CUT", DefaultEditorKit.cutAction,
"control INSERT", DefaultEditorKit.copyAction,
"shift INSERT", DefaultEditorKit.pasteAction,
"shift DELETE", DefaultEditorKit.cutAction,
"shift LEFT", DefaultEditorKit.selectionBackwardAction,
"shift KP_LEFT", DefaultEditorKit.selectionBackwardAction,
"shift RIGHT", DefaultEditorKit.selectionForwardAction,
"shift KP_RIGHT", DefaultEditorKit.selectionForwardAction,
"ctrl LEFT", DefaultEditorKit.previousWordAction,
"ctrl KP_LEFT", DefaultEditorKit.previousWordAction,
"ctrl RIGHT", DefaultEditorKit.nextWordAction,
"ctrl KP_RIGHT", DefaultEditorKit.nextWordAction,
"ctrl shift LEFT", DefaultEditorKit.selectionPreviousWordAction,
"ctrl shift KP_LEFT", DefaultEditorKit.selectionPreviousWordAction,
"ctrl shift RIGHT", DefaultEditorKit.selectionNextWordAction,
"ctrl shift KP_RIGHT", DefaultEditorKit.selectionNextWordAction,
"ctrl A", DefaultEditorKit.selectAllAction,
"HOME", DefaultEditorKit.beginLineAction,
"END", DefaultEditorKit.endLineAction,
"shift HOME", DefaultEditorKit.selectionBeginLineAction,
"shift END", DefaultEditorKit.selectionEndLineAction,
"BACK_SPACE", DefaultEditorKit.deletePrevCharAction,
"shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction,
"ctrl H", DefaultEditorKit.deletePrevCharAction,
"DELETE", DefaultEditorKit.deleteNextCharAction,
"ctrl DELETE", DefaultEditorKit.deleteNextWordAction,
"ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction,
"RIGHT", DefaultEditorKit.forwardAction,
"LEFT", DefaultEditorKit.backwardAction,
"KP_RIGHT", DefaultEditorKit.forwardAction,
"KP_LEFT", DefaultEditorKit.backwardAction,
"ENTER", JTextField.notifyAction,
"ctrl BACK_SLASH", "unselect"/*DefaultEditorKit.unselectAction*/,
"control shift O", "toggle-componentOrientation"/*DefaultEditorKit.toggleComponentOrientation*/
});
DEFAULT_VALUES.put("TextField.focusInputMap", fieldInputMap);
DEFAULT_VALUES.put("PasswordField.focusInputMap", fieldInputMap);
DEFAULT_VALUES.put("ComboBox.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"ESCAPE", "hidePopup",
"PAGE_UP", "pageUpPassThrough",
"PAGE_DOWN", "pageDownPassThrough",
"HOME", "homePassThrough",
"END", "endPassThrough",
"DOWN", "selectNext",
"KP_DOWN", "selectNext",
"alt DOWN", "togglePopup",
"alt KP_DOWN", "togglePopup",
"alt UP", "togglePopup",
"alt KP_UP", "togglePopup",
"SPACE", "spacePopup",
"ENTER", "enterPressed",
"UP", "selectPrevious",
"KP_UP", "selectPrevious"
}));
DEFAULT_VALUES.put("Desktop.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"ctrl F5", "restore",
"ctrl F4", "close",
"ctrl F7", "move",
"ctrl F8", "resize",
"RIGHT", "right",
"KP_RIGHT", "right",
"shift RIGHT", "shrinkRight",
"shift KP_RIGHT", "shrinkRight",
"LEFT", "left",
"KP_LEFT", "left",
"shift LEFT", "shrinkLeft",
"shift KP_LEFT", "shrinkLeft",
"UP", "up",
"KP_UP", "up",
"shift UP", "shrinkUp",
"shift KP_UP", "shrinkUp",
"DOWN", "down",
"KP_DOWN", "down",
"shift DOWN", "shrinkDown",
"shift KP_DOWN", "shrinkDown",
"ESCAPE", "escape",
"ctrl F9", "minimize",
"ctrl F10", "maximize",
"ctrl F6", "selectNextFrame",
"ctrl TAB", "selectNextFrame",
"ctrl alt F6", "selectNextFrame",
"shift ctrl alt F6", "selectPreviousFrame",
"ctrl F12", "navigateNext",
"shift ctrl F12", "navigatePrevious"
}));
DEFAULT_VALUES.put("FileChooser.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"ESCAPE", "cancelSelection",
"F2", "editFileName",
"F5", "refresh",
"BACK_SPACE", "Go Up",
"ENTER", "approveSelection",
"ctrl ENTER", "approveSelection"
}));
DEFAULT_VALUES.put("FormattedTextField.focusInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"ctrl C", DefaultEditorKit.copyAction,
"ctrl V", DefaultEditorKit.pasteAction,
"ctrl X", DefaultEditorKit.cutAction,
"COPY", DefaultEditorKit.copyAction,
"PASTE", DefaultEditorKit.pasteAction,
"CUT", DefaultEditorKit.cutAction,
"control INSERT", DefaultEditorKit.copyAction,
"shift INSERT", DefaultEditorKit.pasteAction,
"shift DELETE", DefaultEditorKit.cutAction,
"shift LEFT", DefaultEditorKit.selectionBackwardAction,
"shift KP_LEFT", DefaultEditorKit.selectionBackwardAction,
"shift RIGHT", DefaultEditorKit.selectionForwardAction,
"shift KP_RIGHT", DefaultEditorKit.selectionForwardAction,
"ctrl LEFT", DefaultEditorKit.previousWordAction,
"ctrl KP_LEFT", DefaultEditorKit.previousWordAction,
"ctrl RIGHT", DefaultEditorKit.nextWordAction,
"ctrl KP_RIGHT", DefaultEditorKit.nextWordAction,
"ctrl shift LEFT", DefaultEditorKit.selectionPreviousWordAction,
"ctrl shift KP_LEFT", DefaultEditorKit.selectionPreviousWordAction,
"ctrl shift RIGHT", DefaultEditorKit.selectionNextWordAction,
"ctrl shift KP_RIGHT", DefaultEditorKit.selectionNextWordAction,
"ctrl A", DefaultEditorKit.selectAllAction,
"HOME", DefaultEditorKit.beginLineAction,
"END", DefaultEditorKit.endLineAction,
"shift HOME", DefaultEditorKit.selectionBeginLineAction,
"shift END", DefaultEditorKit.selectionEndLineAction,
"BACK_SPACE", DefaultEditorKit.deletePrevCharAction,
"shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction,
"ctrl H", DefaultEditorKit.deletePrevCharAction,
"DELETE", DefaultEditorKit.deleteNextCharAction,
"ctrl DELETE", DefaultEditorKit.deleteNextWordAction,
"ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction,
"RIGHT", DefaultEditorKit.forwardAction,
"LEFT", DefaultEditorKit.backwardAction,
"KP_RIGHT", DefaultEditorKit.forwardAction,
"KP_LEFT", DefaultEditorKit.backwardAction,
"ENTER", JTextField.notifyAction,
"ctrl BACK_SLASH", "unselect",
"control shift O", "toggle-componentOrientation",
"ESCAPE", "reset-field-edit",
"UP", "increment",
"KP_UP", "increment",
"DOWN", "decrement",
"KP_DOWN", "decrement",
}));
DEFAULT_VALUES.put("InternalFrame.icon",
LookAndFeel.makeIcon(BasicLookAndFeel.class,
"icons/JavaCup16.png"));
DEFAULT_VALUES.put("InternalFrame.windowBindings",
new Object[] {
"shift ESCAPE", "showSystemMenu",
"ctrl SPACE", "showSystemMenu",
"ESCAPE", "hideSystemMenu"});
DEFAULT_VALUES.put("List.focusInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"ctrl C", "copy",
"ctrl V", "paste",
"ctrl X", "cut",
"COPY", "copy",
"PASTE", "paste",
"CUT", "cut",
"control INSERT", "copy",
"shift INSERT", "paste",
"shift DELETE", "cut",
"UP", "selectPreviousRow",
"KP_UP", "selectPreviousRow",
"shift UP", "selectPreviousRowExtendSelection",
"shift KP_UP", "selectPreviousRowExtendSelection",
"ctrl shift UP", "selectPreviousRowExtendSelection",
"ctrl shift KP_UP", "selectPreviousRowExtendSelection",
"ctrl UP", "selectPreviousRowChangeLead",
"ctrl KP_UP", "selectPreviousRowChangeLead",
"DOWN", "selectNextRow",
"KP_DOWN", "selectNextRow",
"shift DOWN", "selectNextRowExtendSelection",
"shift KP_DOWN", "selectNextRowExtendSelection",
"ctrl shift DOWN", "selectNextRowExtendSelection",
"ctrl shift KP_DOWN", "selectNextRowExtendSelection",
"ctrl DOWN", "selectNextRowChangeLead",
"ctrl KP_DOWN", "selectNextRowChangeLead",
"LEFT", "selectPreviousColumn",
"KP_LEFT", "selectPreviousColumn",
"shift LEFT", "selectPreviousColumnExtendSelection",
"shift KP_LEFT", "selectPreviousColumnExtendSelection",
"ctrl shift LEFT", "selectPreviousColumnExtendSelection",
"ctrl shift KP_LEFT", "selectPreviousColumnExtendSelection",
"ctrl LEFT", "selectPreviousColumnChangeLead",
"ctrl KP_LEFT", "selectPreviousColumnChangeLead",
"RIGHT", "selectNextColumn",
"KP_RIGHT", "selectNextColumn",
"shift RIGHT", "selectNextColumnExtendSelection",
"shift KP_RIGHT", "selectNextColumnExtendSelection",
"ctrl shift RIGHT", "selectNextColumnExtendSelection",
"ctrl shift KP_RIGHT", "selectNextColumnExtendSelection",
"ctrl RIGHT", "selectNextColumnChangeLead",
"ctrl KP_RIGHT", "selectNextColumnChangeLead",
"HOME", "selectFirstRow",
"shift HOME", "selectFirstRowExtendSelection",
"ctrl shift HOME", "selectFirstRowExtendSelection",
"ctrl HOME", "selectFirstRowChangeLead",
"END", "selectLastRow",
"shift END", "selectLastRowExtendSelection",
"ctrl shift END", "selectLastRowExtendSelection",
"ctrl END", "selectLastRowChangeLead",
"PAGE_UP", "scrollUp",
"shift PAGE_UP", "scrollUpExtendSelection",
"ctrl shift PAGE_UP", "scrollUpExtendSelection",
"ctrl PAGE_UP", "scrollUpChangeLead",
"PAGE_DOWN", "scrollDown",
"shift PAGE_DOWN", "scrollDownExtendSelection",
"ctrl shift PAGE_DOWN", "scrollDownExtendSelection",
"ctrl PAGE_DOWN", "scrollDownChangeLead",
"ctrl A", "selectAll",
"ctrl SLASH", "selectAll",
"ctrl BACK_SLASH", "clearSelection",
"SPACE", "addToSelection",
"ctrl SPACE", "toggleAndAnchor",
"shift SPACE", "extendTo",
"ctrl shift SPACE", "moveSelectionTo"
}));
DEFAULT_VALUES.put("List.focusInputMap.RightToLeft",
new UIDefaults.LazyInputMap(new Object[] {
"LEFT", "selectNextColumn",
"KP_LEFT", "selectNextColumn",
"shift LEFT", "selectNextColumnExtendSelection",
"shift KP_LEFT", "selectNextColumnExtendSelection",
"ctrl shift LEFT", "selectNextColumnExtendSelection",
"ctrl shift KP_LEFT", "selectNextColumnExtendSelection",
"ctrl LEFT", "selectNextColumnChangeLead",
"ctrl KP_LEFT", "selectNextColumnChangeLead",
"RIGHT", "selectPreviousColumn",
"KP_RIGHT", "selectPreviousColumn",
"shift RIGHT", "selectPreviousColumnExtendSelection",
"shift KP_RIGHT", "selectPreviousColumnExtendSelection",
"ctrl shift RIGHT", "selectPreviousColumnExtendSelection",
"ctrl shift KP_RIGHT", "selectPreviousColumnExtendSelection",
"ctrl RIGHT", "selectPreviousColumnChangeLead",
"ctrl KP_RIGHT", "selectPreviousColumnChangeLead",
}));
DEFAULT_VALUES.put("MenuBar.windowBindings",
new Object[] { "F10", "takeFocus" });
DEFAULT_VALUES.put("OptionPane.windowBindings",
new Object[] { "ESCAPE", "close" });
DEFAULT_VALUES.put("RootPane.defaultButtonWindowKeyBindings",
new Object[] {
"ENTER", "press",
"released ENTER", "release",
"ctrl ENTER", "press",
"ctrl released ENTER", "release"
});
DEFAULT_VALUES.put("RootPane.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"shift F10", "postPopup"
}));
DEFAULT_VALUES.put("ScrollBar.anecstorInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"RIGHT", "positiveUnitIncrement",
"KP_RIGHT", "positiveUnitIncrement",
"DOWN", "positiveUnitIncrement",
"KP_DOWN", "positiveUnitIncrement",
"PAGE_DOWN", "positiveBlockIncrement",
"LEFT", "negativeUnitIncrement",
"KP_LEFT", "negativeUnitIncrement",
"UP", "negativeUnitIncrement",
"KP_UP", "negativeUnitIncrement",
"PAGE_UP", "negativeBlockIncrement",
"HOME", "minScroll",
"END", "maxScroll"
}));
DEFAULT_VALUES.put("ScrollBar.ancestorInputMap.RightToLeft",
new UIDefaults.LazyInputMap(new Object[] {
"RIGHT", "negativeUnitIncrement",
"KP_RIGHT", "negativeUnitIncrement",
"LEFT", "positiveUnitIncrement",
"KP_LEFT", "positiveUnitIncrement",
}));
DEFAULT_VALUES.put("ScrollPane.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"RIGHT", "unitScrollRight",
"KP_RIGHT", "unitScrollRight",
"DOWN", "unitScrollDown",
"KP_DOWN", "unitScrollDown",
"LEFT", "unitScrollLeft",
"KP_LEFT", "unitScrollLeft",
"UP", "unitScrollUp",
"KP_UP", "unitScrollUp",
"PAGE_UP", "scrollUp",
"PAGE_DOWN", "scrollDown",
"ctrl PAGE_UP", "scrollLeft",
"ctrl PAGE_DOWN", "scrollRight",
"ctrl HOME", "scrollHome",
"ctrl END", "scrollEnd"
}));
DEFAULT_VALUES.put("ScrollPane.ancestorInputMap.RightToLeft",
new UIDefaults.LazyInputMap(new Object[] {
"ctrl PAGE_UP", "scrollRight",
"ctrl PAGE_DOWN", "scrollLeft",
}));
DEFAULT_VALUES.put("SplitPane.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"UP", "negativeIncrement",
"DOWN", "positiveIncrement",
"LEFT", "negativeIncrement",
"RIGHT", "positiveIncrement",
"KP_UP", "negativeIncrement",
"KP_DOWN", "positiveIncrement",
"KP_LEFT", "negativeIncrement",
"KP_RIGHT", "positiveIncrement",
"HOME", "selectMin",
"END", "selectMax",
"F8", "startResize",
"F6", "toggleFocus",
"ctrl TAB", "focusOutForward",
"ctrl shift TAB", "focusOutBackward"
}));
DEFAULT_VALUES.put("Spinner.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"UP", "increment",
"KP_UP", "increment",
"DOWN", "decrement",
"KP_DOWN", "decrement"
}));
DEFAULT_VALUES.put("Slider.focusInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"RIGHT", "positiveUnitIncrement",
"KP_RIGHT", "positiveUnitIncrement",
"DOWN", "negativeUnitIncrement",
"KP_DOWN", "negativeUnitIncrement",
"PAGE_DOWN", "negativeBlockIncrement",
"ctrl PAGE_DOWN", "negativeBlockIncrement",
"LEFT", "negativeUnitIncrement",
"KP_LEFT", "negativeUnitIncrement",
"UP", "positiveUnitIncrement",
"KP_UP", "positiveUnitIncrement",
"PAGE_UP", "positiveBlockIncrement",
"ctrl PAGE_UP", "positiveBlockIncrement",
"HOME", "minScroll",
"END", "maxScroll"
}));
DEFAULT_VALUES.put("Slider.focusInputMap.RightToLeft",
new UIDefaults.LazyInputMap(new Object[] {
"RIGHT", "negativeUnitIncrement",
"KP_RIGHT", "negativeUnitIncrement",
"LEFT", "positiveUnitIncrement",
"KP_LEFT", "positiveUnitIncrement",
}));
DEFAULT_VALUES.put("TabbedPane.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"ctrl PAGE_DOWN", "navigatePageDown",
"ctrl PAGE_UP", "navigatePageUp",
"ctrl UP", "requestFocus",
"ctrl KP_UP", "requestFocus",
}));
DEFAULT_VALUES.put("TabbedPane.focusInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"RIGHT", "navigateRight",
"KP_RIGHT", "navigateRight",
"LEFT", "navigateLeft",
"KP_LEFT", "navigateLeft",
"UP", "navigateUp",
"KP_UP", "navigateUp",
"DOWN", "navigateDown",
"KP_DOWN", "navigateDown",
"ctrl DOWN", "requestFocusForVisibleComponent",
"ctrl KP_DOWN", "requestFocusForVisibleComponent",
}));
DEFAULT_VALUES.put("Table.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"ctrl C", "copy",
"ctrl V", "paste",
"ctrl X", "cut",
"COPY", "copy",
"PASTE", "paste",
"CUT", "cut",
"control INSERT", "copy",
"shift INSERT", "paste",
"shift DELETE", "cut",
"RIGHT", "selectNextColumn",
"KP_RIGHT", "selectNextColumn",
"shift RIGHT", "selectNextColumnExtendSelection",
"shift KP_RIGHT", "selectNextColumnExtendSelection",
"ctrl shift RIGHT", "selectNextColumnExtendSelection",
"ctrl shift KP_RIGHT", "selectNextColumnExtendSelection",
"ctrl RIGHT", "selectNextColumnChangeLead",
"ctrl KP_RIGHT", "selectNextColumnChangeLead",
"LEFT", "selectPreviousColumn",
"KP_LEFT", "selectPreviousColumn",
"shift LEFT", "selectPreviousColumnExtendSelection",
"shift KP_LEFT", "selectPreviousColumnExtendSelection",
"ctrl shift LEFT", "selectPreviousColumnExtendSelection",
"ctrl shift KP_LEFT", "selectPreviousColumnExtendSelection",
"ctrl LEFT", "selectPreviousColumnChangeLead",
"ctrl KP_LEFT", "selectPreviousColumnChangeLead",
"DOWN", "selectNextRow",
"KP_DOWN", "selectNextRow",
"shift DOWN", "selectNextRowExtendSelection",
"shift KP_DOWN", "selectNextRowExtendSelection",
"ctrl shift DOWN", "selectNextRowExtendSelection",
"ctrl shift KP_DOWN", "selectNextRowExtendSelection",
"ctrl DOWN", "selectNextRowChangeLead",
"ctrl KP_DOWN", "selectNextRowChangeLead",
"UP", "selectPreviousRow",
"KP_UP", "selectPreviousRow",
"shift UP", "selectPreviousRowExtendSelection",
"shift KP_UP", "selectPreviousRowExtendSelection",
"ctrl shift UP", "selectPreviousRowExtendSelection",
"ctrl shift KP_UP", "selectPreviousRowExtendSelection",
"ctrl UP", "selectPreviousRowChangeLead",
"ctrl KP_UP", "selectPreviousRowChangeLead",
"HOME", "selectFirstColumn",
"shift HOME", "selectFirstColumnExtendSelection",
"ctrl shift HOME", "selectFirstRowExtendSelection",
"ctrl HOME", "selectFirstRow",
"END", "selectLastColumn",
"shift END", "selectLastColumnExtendSelection",
"ctrl shift END", "selectLastRowExtendSelection",
"ctrl END", "selectLastRow",
"PAGE_UP", "scrollUpChangeSelection",
"shift PAGE_UP", "scrollUpExtendSelection",
"ctrl shift PAGE_UP", "scrollLeftExtendSelection",
"ctrl PAGE_UP", "scrollLeftChangeSelection",
"PAGE_DOWN", "scrollDownChangeSelection",
"shift PAGE_DOWN", "scrollDownExtendSelection",
"ctrl shift PAGE_DOWN", "scrollRightExtendSelection",
"ctrl PAGE_DOWN", "scrollRightChangeSelection",
"TAB", "selectNextColumnCell",
"shift TAB", "selectPreviousColumnCell",
"ENTER", "selectNextRowCell",
"shift ENTER", "selectPreviousRowCell",
"ctrl A", "selectAll",
"ctrl SLASH", "selectAll",
"ctrl BACK_SLASH", "clearSelection",
"ESCAPE", "cancel",
"F2", "startEditing",
"SPACE", "addToSelection",
"ctrl SPACE", "toggleAndAnchor",
"shift SPACE", "extendTo",
"ctrl shift SPACE", "moveSelectionTo",
"F8", "focusHeader"
}));
DEFAULT_VALUES.put("TableHeader.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"SPACE", "toggleSortOrder",
"LEFT", "selectColumnToLeft",
"KP_LEFT", "selectColumnToLeft",
"RIGHT", "selectColumnToRight",
"KP_RIGHT", "selectColumnToRight",
"alt LEFT", "moveColumnLeft",
"alt KP_LEFT", "moveColumnLeft",
"alt RIGHT", "moveColumnRight",
"alt KP_RIGHT", "moveColumnRight",
"alt shift LEFT", "resizeLeft",
"alt shift KP_LEFT", "resizeLeft",
"alt shift RIGHT", "resizeRight",
"alt shift KP_RIGHT", "resizeRight",
"ESCAPE", "focusTable",
}));
DEFAULT_VALUES.put("Tree.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"ESCAPE", "cancel"
}));
DEFAULT_VALUES.put("Tree.focusInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"ADD", "expand",
"SUBTRACT", "collapse",
"ctrl C", "copy",
"ctrl V", "paste",
"ctrl X", "cut",
"COPY", "copy",
"PASTE", "paste",
"CUT", "cut",
"control INSERT", "copy",
"shift INSERT", "paste",
"shift DELETE", "cut",
"UP", "selectPrevious",
"KP_UP", "selectPrevious",
"shift UP", "selectPreviousExtendSelection",
"shift KP_UP", "selectPreviousExtendSelection",
"ctrl shift UP", "selectPreviousExtendSelection",
"ctrl shift KP_UP", "selectPreviousExtendSelection",
"ctrl UP", "selectPreviousChangeLead",
"ctrl KP_UP", "selectPreviousChangeLead",
"DOWN", "selectNext",
"KP_DOWN", "selectNext",
"shift DOWN", "selectNextExtendSelection",
"shift KP_DOWN", "selectNextExtendSelection",
"ctrl shift DOWN", "selectNextExtendSelection",
"ctrl shift KP_DOWN", "selectNextExtendSelection",
"ctrl DOWN", "selectNextChangeLead",
"ctrl KP_DOWN", "selectNextChangeLead",
"RIGHT", "selectChild",
"KP_RIGHT", "selectChild",
"LEFT", "selectParent",
"KP_LEFT", "selectParent",
"PAGE_UP", "scrollUpChangeSelection",
"shift PAGE_UP", "scrollUpExtendSelection",
"ctrl shift PAGE_UP", "scrollUpExtendSelection",
"ctrl PAGE_UP", "scrollUpChangeLead",
"PAGE_DOWN", "scrollDownChangeSelection",
"shift PAGE_DOWN", "scrollDownExtendSelection",
"ctrl shift PAGE_DOWN", "scrollDownExtendSelection",
"ctrl PAGE_DOWN", "scrollDownChangeLead",
"HOME", "selectFirst",
"shift HOME", "selectFirstExtendSelection",
"ctrl shift HOME", "selectFirstExtendSelection",
"ctrl HOME", "selectFirstChangeLead",
"END", "selectLast",
"shift END", "selectLastExtendSelection",
"ctrl shift END", "selectLastExtendSelection",
"ctrl END", "selectLastChangeLead",
"F2", "startEditing",
"ctrl A", "selectAll",
"ctrl SLASH", "selectAll",
"ctrl BACK_SLASH", "clearSelection",
"ctrl LEFT", "scrollLeft",
"ctrl KP_LEFT", "scrollLeft",
"ctrl RIGHT", "scrollRight",
"ctrl KP_RIGHT", "scrollRight",
"SPACE", "addToSelection",
"ctrl SPACE", "toggleAndAnchor",
"shift SPACE", "extendTo",
"ctrl shift SPACE", "moveSelectionTo"
}));
DEFAULT_VALUES.put("Tree.focusInputMap.RightToLeft",
new UIDefaults.LazyInputMap(new Object[] {
"RIGHT", "selectParent",
"KP_RIGHT", "selectParent",
"LEFT", "selectChild",
"KP_LEFT", "selectChild",
}));
}
/** {@collect.stats}
* Returns the default value for the specified property, or null if there
* is no default for the specified value.
*/
private static Object getDefaultValue(Object key) {
synchronized(SynthStyle.class) {
if (DEFAULT_VALUES == null) {
DEFAULT_VALUES = new HashMap();
populateDefaultValues();
}
Object value = DEFAULT_VALUES.get(key);
if (value instanceof UIDefaults.LazyValue) {
value = ((UIDefaults.LazyValue)value).createValue(null);
DEFAULT_VALUES.put(key, value);
}
return value;
}
}
/** {@collect.stats}
* Constructs a SynthStyle.
*/
public SynthStyle() {
}
/** {@collect.stats}
* Returns the <code>SynthGraphicUtils</code> for the specified context.
*
* @param context SynthContext identifying requester
* @return SynthGraphicsUtils
*/
public SynthGraphicsUtils getGraphicsUtils(SynthContext context) {
return SYNTH_GRAPHICS;
}
/** {@collect.stats}
* Returns the color for the specified state. This gives precedence to
* foreground and background of the <code>JComponent</code>. If the
* <code>Color</code> from the <code>JComponent</code> is not appropriate,
* or not used, this will invoke <code>getColorForState</code>. Subclasses
* should generally not have to override this, instead override
* {@link #getColorForState}.
*
* @param context SynthContext identifying requester
* @param type Type of color being requested.
* @return Color
*/
public Color getColor(SynthContext context, ColorType type) {
JComponent c = context.getComponent();
Region id = context.getRegion();
if ((context.getComponentState() & SynthConstants.DISABLED) != 0) {
//This component is disabled, so return the disabled color.
//In some cases this means ignoring the color specified by the
//developer on the component. In other cases it means using a
//specified disabledTextColor, such as on JTextComponents.
//For example, JLabel doesn't specify a disabled color that the
//developer can set, yet it should have a disabled color to the
//text when the label is disabled. This code allows for that.
if (c instanceof JTextComponent) {
JTextComponent txt = (JTextComponent)c;
Color disabledColor = txt.getDisabledTextColor();
if (disabledColor == null || disabledColor instanceof UIResource) {
return getColorForState(context, type);
}
} else if (c instanceof JLabel &&
(type == ColorType.FOREGROUND ||
type == ColorType.TEXT_FOREGROUND)) {
return getColorForState(context, type);
}
}
// If the developer has specified a color, prefer it. Otherwise, get
// the color for the state.
Color color = null;
if (!id.isSubregion()) {
if (type == ColorType.BACKGROUND) {
color = c.getBackground();
}
else if (type == ColorType.FOREGROUND) {
color = c.getForeground();
}
else if (type == ColorType.TEXT_FOREGROUND) {
color = c.getForeground();
}
}
if (color == null || color instanceof UIResource) {
// Then use what we've locally defined
color = getColorForState(context, type);
}
if (color == null) {
// No color, fallback to that of the widget.
if (type == ColorType.BACKGROUND ||
type == ColorType.TEXT_BACKGROUND) {
return c.getBackground();
}
else if (type == ColorType.FOREGROUND ||
type == ColorType.TEXT_FOREGROUND) {
return c.getForeground();
}
}
return color;
}
/** {@collect.stats}
* Returns the color for the specified state. This should NOT call any
* methods on the <code>JComponent</code>.
*
* @param context SynthContext identifying requester
* @param type Type of color being requested.
* @return Color to render with
*/
protected abstract Color getColorForState(SynthContext context,
ColorType type);
/** {@collect.stats}
* Returns the Font for the specified state. This redirects to the
* <code>JComponent</code> from the <code>context</code> as necessary.
* If this does not redirect
* to the JComponent {@link #getFontForState} is invoked.
*
* @param context SynthContext identifying requester
* @return Font to render with
*/
public Font getFont(SynthContext context) {
JComponent c = context.getComponent();
if (context.getComponentState() == SynthConstants.ENABLED) {
return c.getFont();
}
Font cFont = c.getFont();
if (cFont != null && !(cFont instanceof UIResource)) {
return cFont;
}
return getFontForState(context);
}
/** {@collect.stats}
* Returns the font for the specified state. This should NOT call any
* method on the <code>JComponent</code>.
*
* @param context SynthContext identifying requester
* @return Font to render with
*/
protected abstract Font getFontForState(SynthContext context);
/** {@collect.stats}
* Returns the Insets that are used to calculate sizing information.
*
* @param context SynthContext identifying requester
* @param insets Insets to place return value in.
* @return Sizing Insets.
*/
public Insets getInsets(SynthContext context, Insets insets) {
if (insets == null) {
insets = new Insets(0, 0, 0, 0);
}
insets.top = insets.bottom = insets.left = insets.right = 0;
return insets;
}
/** {@collect.stats}
* Returns the <code>SynthPainter</code> that will be used for painting.
* This may return null.
*
* @param context SynthContext identifying requester
* @return SynthPainter to use
*/
public SynthPainter getPainter(SynthContext context) {
return null;
}
/** {@collect.stats}
* Returns true if the region is opaque.
*
* @param context SynthContext identifying requester
* @return true if region is opaque.
*/
public boolean isOpaque(SynthContext context) {
return true;
}
/** {@collect.stats}
* Getter for a region specific style property.
*
* @param context SynthContext identifying requester
* @param key Property being requested.
* @return Value of the named property
*/
public Object get(SynthContext context, Object key) {
return getDefaultValue(key);
}
void installDefaults(SynthContext context, SynthUI ui) {
// Special case the Border as this will likely change when the LAF
// can have more control over this.
if (!context.isSubregion()) {
JComponent c = context.getComponent();
Border border = c.getBorder();
if (border == null || border instanceof UIResource) {
c.setBorder(new SynthBorder(ui, getInsets(context, null)));
}
}
installDefaults(context);
}
/** {@collect.stats}
* Installs the necessary state from this Style on the
* <code>JComponent</code> from <code>context</code>.
*
* @param context SynthContext identifying component to install properties
* to.
*/
public void installDefaults(SynthContext context) {
if (!context.isSubregion()) {
JComponent c = context.getComponent();
Region region = context.getRegion();
Font font = c.getFont();
if (font == null || (font instanceof UIResource)) {
c.setFont(getFontForState(context));
}
Color background = c.getBackground();
if (background == null || (background instanceof UIResource)) {
c.setBackground(getColorForState(context,
ColorType.BACKGROUND));
}
Color foreground = c.getForeground();
if (foreground == null || (foreground instanceof UIResource)) {
c.setForeground(getColorForState(context,
ColorType.FOREGROUND));
}
LookAndFeel.installProperty(c, "opaque", Boolean.valueOf(isOpaque(context)));
}
}
/** {@collect.stats}
* Uninstalls any state that this style installed on
* the <code>JComponent</code> from <code>context</code>.
* <p>
* Styles should NOT depend upon this being called, in certain cases
* it may never be called.
*
* @param context SynthContext identifying component to install properties
* to.
*/
public void uninstallDefaults(SynthContext context) {
if (!context.isSubregion()) {
// NOTE: because getForeground, getBackground and getFont will look
// at the parent Container, if we set them to null it may
// mean we they return a non-null and non-UIResource value
// preventing install from correctly settings its colors/font. For
// this reason we do not uninstall the fg/bg/font.
JComponent c = context.getComponent();
Border border = c.getBorder();
if (border instanceof UIResource) {
c.setBorder(null);
}
}
}
/** {@collect.stats}
* Convenience method to get a specific style property whose value is
* a <code>Number</code>. If the value is a <code>Number</code>,
* <code>intValue</code> is returned, otherwise <code>defaultValue</code>
* is returned.
*
* @param context SynthContext identifying requester
* @param key Property being requested.
* @param defaultValue Value to return if the property has not been
* specified, or is not a Number
* @return Value of the named property
*/
public int getInt(SynthContext context, Object key, int defaultValue) {
Object value = get(context, key);
if (value instanceof Number) {
return ((Number)value).intValue();
}
return defaultValue;
}
/** {@collect.stats}
* Convenience method to get a specific style property whose value is
* an Boolean.
*
* @param context SynthContext identifying requester
* @param key Property being requested.
* @param defaultValue Value to return if the property has not been
* specified, or is not a Boolean
* @return Value of the named property
*/
public boolean getBoolean(SynthContext context, Object key,
boolean defaultValue) {
Object value = get(context, key);
if (value instanceof Boolean) {
return ((Boolean)value).booleanValue();
}
return defaultValue;
}
/** {@collect.stats}
* Convenience method to get a specific style property whose value is
* an Icon.
*
* @param context SynthContext identifying requester
* @param key Property being requested.
* @return Value of the named property, or null if not specified
*/
public Icon getIcon(SynthContext context, Object key) {
Object value = get(context, key);
if (value instanceof Icon) {
return (Icon)value;
}
return null;
}
/** {@collect.stats}
* Convenience method to get a specific style property whose value is
* a String.
*
* @param context SynthContext identifying requester
* @param key Property being requested.
* @param defaultValue Value to return if the property has not been
* specified, or is not a String
* @return Value of the named property
*/
public String getString(SynthContext context, Object key,
String defaultValue) {
Object value = get(context, key);
if (value instanceof String) {
return (String)value;
}
return defaultValue;
}
}
|
Java
|
/*
* Copyright (c) 2002, 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.swing.plaf.synth;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.border.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
import sun.swing.plaf.synth.SynthUI;
/** {@collect.stats}
* Synth's MenuBarUI.
*
* @author Scott Violet
*/
class SynthMenuBarUI extends BasicMenuBarUI implements PropertyChangeListener,
SynthUI {
private SynthStyle style;
public static ComponentUI createUI(JComponent x) {
return new SynthMenuBarUI();
}
protected void installDefaults() {
if (menuBar.getLayout() == null ||
menuBar.getLayout() instanceof UIResource) {
menuBar.setLayout(new DefaultMenuLayout(menuBar,BoxLayout.LINE_AXIS));
}
updateStyle(menuBar);
}
protected void installListeners() {
super.installListeners();
menuBar.addPropertyChangeListener(this);
}
private void updateStyle(JMenuBar c) {
SynthContext context = getContext(c, ENABLED);
SynthStyle oldStyle = style;
style = SynthLookAndFeel.updateStyle(context, this);
if (style != oldStyle) {
if (oldStyle != null) {
uninstallKeyboardActions();
installKeyboardActions();
}
}
context.dispose();
}
protected void uninstallDefaults() {
SynthContext context = getContext(menuBar, ENABLED);
style.uninstallDefaults(context);
context.dispose();
style = null;
}
protected void uninstallListeners() {
super.uninstallListeners();
menuBar.removePropertyChangeListener(this);
}
public SynthContext getContext(JComponent c) {
return getContext(c, getComponentState(c));
}
private SynthContext getContext(JComponent c, int state) {
return SynthContext.getContext(SynthContext.class, c,
SynthLookAndFeel.getRegion(c), style, state);
}
private Region getRegion(JComponent c) {
return SynthLookAndFeel.getRegion(c);
}
private int getComponentState(JComponent c) {
return SynthLookAndFeel.getComponentState(c);
}
public void update(Graphics g, JComponent c) {
SynthContext context = getContext(c);
SynthLookAndFeel.update(context, g);
context.getPainter().paintMenuBarBackground(context,
g, 0, 0, c.getWidth(), c.getHeight());
paint(context, g);
context.dispose();
}
public void paint(Graphics g, JComponent c) {
SynthContext context = getContext(c);
paint(context, g);
context.dispose();
}
protected void paint(SynthContext context, Graphics g) {
}
public void paintBorder(SynthContext context, Graphics g, int x,
int y, int w, int h) {
context.getPainter().paintMenuBarBorder(context, g, x, y, w, h);
}
public void propertyChange(PropertyChangeEvent e) {
if (SynthLookAndFeel.shouldUpdateStyle(e)) {
updateStyle((JMenuBar)e.getSource());
}
}
}
|
Java
|
/*
* Copyright (c) 2002, 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.swing.plaf.synth;
import java.awt.*;
import java.awt.event.*;
import java.io.Serializable;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.BasicButtonUI;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.text.View;
import sun.swing.plaf.synth.SynthUI;
import sun.swing.plaf.synth.DefaultSynthStyle;
/** {@collect.stats}
* Synth's ButtonUI implementation.
*
* @author Scott Violet
*/
class SynthButtonUI extends BasicButtonUI implements
PropertyChangeListener, SynthUI {
private SynthStyle style;
public static ComponentUI createUI(JComponent c) {
return new SynthButtonUI();
}
protected void installDefaults(AbstractButton b) {
updateStyle(b);
LookAndFeel.installProperty(b, "rolloverEnabled", Boolean.TRUE);
}
protected void installListeners(AbstractButton b) {
super.installListeners(b);
b.addPropertyChangeListener(this);
}
void updateStyle(AbstractButton b) {
SynthContext context = getContext(b, SynthConstants.ENABLED);
SynthStyle oldStyle = style;
style = SynthLookAndFeel.updateStyle(context, this);
if (style != oldStyle) {
if (b.getMargin() == null ||
(b.getMargin() instanceof UIResource)) {
Insets margin = (Insets)style.get(context,getPropertyPrefix() +
"margin");
if (margin == null) {
// Some places assume margins are non-null.
margin = SynthLookAndFeel.EMPTY_UIRESOURCE_INSETS;
}
b.setMargin(margin);
}
Object value = style.get(context, getPropertyPrefix() + "iconTextGap");
if (value != null) {
LookAndFeel.installProperty(b, "iconTextGap", value);
}
value = style.get(context, getPropertyPrefix() + "contentAreaFilled");
LookAndFeel.installProperty(b, "contentAreaFilled",
value != null? value : Boolean.TRUE);
if (oldStyle != null) {
uninstallKeyboardActions(b);
installKeyboardActions(b);
}
}
context.dispose();
}
protected void uninstallListeners(AbstractButton b) {
super.uninstallListeners(b);
b.removePropertyChangeListener(this);
}
protected void uninstallDefaults(AbstractButton b) {
SynthContext context = getContext(b, ENABLED);
style.uninstallDefaults(context);
context.dispose();
style = null;
}
public SynthContext getContext(JComponent c) {
return getContext(c, getComponentState(c));
}
SynthContext getContext(JComponent c, int state) {
Region region = getRegion(c);
return SynthContext.getContext(SynthContext.class, c, region,
style, state);
}
private Region getRegion(JComponent c) {
return SynthLookAndFeel.getRegion(c);
}
/** {@collect.stats}
* Returns the current state of the passed in <code>AbstractButton</code>.
*/
private int getComponentState(JComponent c) {
int state = ENABLED;
if (!c.isEnabled()) {
state = DISABLED;
}
if (SynthLookAndFeel.selectedUI == this) {
return SynthLookAndFeel.selectedUIState | SynthConstants.ENABLED;
}
AbstractButton button = (AbstractButton) c;
ButtonModel model = button.getModel();
if (model.isPressed()) {
if (model.isArmed()) {
state = PRESSED;
}
else {
state = MOUSE_OVER;
}
}
if (model.isRollover()) {
state |= MOUSE_OVER;
}
if (model.isSelected()) {
state |= SELECTED;
}
if (c.isFocusOwner() && button.isFocusPainted()) {
state |= FOCUSED;
}
if ((c instanceof JButton) && ((JButton)c).isDefaultButton()) {
state |= DEFAULT;
}
return state;
}
public int getBaseline(JComponent c, int width, int height) {
if (c == null) {
throw new NullPointerException("Component must be non-null");
}
if (width < 0 || height < 0) {
throw new IllegalArgumentException(
"Width and height must be >= 0");
}
AbstractButton b = (AbstractButton)c;
String text = b.getText();
if (text == null || "".equals(text)) {
return -1;
}
Insets i = b.getInsets();
Rectangle viewRect = new Rectangle();
Rectangle textRect = new Rectangle();
Rectangle iconRect = new Rectangle();
viewRect.x = i.left;
viewRect.y = i.top;
viewRect.width = width - (i.right + viewRect.x);
viewRect.height = height - (i.bottom + viewRect.y);
// layout the text and icon
SynthContext context = getContext(b);
FontMetrics fm = context.getComponent().getFontMetrics(
context.getStyle().getFont(context));
context.getStyle().getGraphicsUtils(context).layoutText(
context, fm, b.getText(), b.getIcon(),
b.getHorizontalAlignment(), b.getVerticalAlignment(),
b.getHorizontalTextPosition(), b.getVerticalTextPosition(),
viewRect, iconRect, textRect, b.getIconTextGap());
View view = (View)b.getClientProperty(BasicHTML.propertyKey);
int baseline;
if (view != null) {
baseline = BasicHTML.getHTMLBaseline(view, textRect.width,
textRect.height);
if (baseline >= 0) {
baseline += textRect.y;
}
}
else {
baseline = textRect.y + fm.getAscent();
}
context.dispose();
return baseline;
}
// ********************************
// Paint Methods
// ********************************
public void update(Graphics g, JComponent c) {
SynthContext context = getContext(c);
SynthLookAndFeel.update(context, g);
paintBackground(context, g, c);
paint(context, g);
context.dispose();
}
public void paint(Graphics g, JComponent c) {
SynthContext context = getContext(c);
paint(context, g);
context.dispose();
}
protected void paint(SynthContext context, Graphics g) {
AbstractButton b = (AbstractButton)context.getComponent();
g.setColor(context.getStyle().getColor(context,
ColorType.TEXT_FOREGROUND));
g.setFont(style.getFont(context));
context.getStyle().getGraphicsUtils(context).paintText(
context, g, b.getText(), getIcon(b),
b.getHorizontalAlignment(), b.getVerticalAlignment(),
b.getHorizontalTextPosition(), b.getVerticalTextPosition(),
b.getIconTextGap(), b.getDisplayedMnemonicIndex(),
getTextShiftOffset(context));
}
void paintBackground(SynthContext context, Graphics g, JComponent c) {
if (((AbstractButton) c).isContentAreaFilled()) {
context.getPainter().paintButtonBackground(context, g, 0, 0,
c.getWidth(),
c.getHeight());
}
}
public void paintBorder(SynthContext context, Graphics g, int x,
int y, int w, int h) {
context.getPainter().paintButtonBorder(context, g, x, y, w, h);
}
/** {@collect.stats}
* Returns the default icon. This should NOT callback
* to the JComponent.
*
* @param b AbstractButton the icon is associated with
* @return default icon
*/
protected Icon getDefaultIcon(AbstractButton b) {
SynthContext context = getContext(b);
Icon icon = context.getStyle().getIcon(context, getPropertyPrefix() + "icon");
context.dispose();
return icon;
}
/** {@collect.stats}
* Returns the Icon to use in painting the button.
*/
protected Icon getIcon(AbstractButton b) {
Icon icon = b.getIcon();
ButtonModel model = b.getModel();
if (!model.isEnabled()) {
icon = getSynthDisabledIcon(b, icon);
} else if (model.isPressed() && model.isArmed()) {
icon = getPressedIcon(b, getSelectedIcon(b, icon));
} else if (b.isRolloverEnabled() && model.isRollover()) {
icon = getRolloverIcon(b, getSelectedIcon(b, icon));
} else if (model.isSelected()) {
icon = getSelectedIcon(b, icon);
} else {
icon = getEnabledIcon(b, icon);
}
if(icon == null) {
return getDefaultIcon(b);
}
return icon;
}
/** {@collect.stats}
* This method will return the icon that should be used for a button. We
* only want to use the synth icon defined by the style if the specific
* icon has not been defined for the button state and the backup icon is a
* UIResource (we set it, not the developer).
*
* @param b button
* @param specificIcon icon returned from the button for the specific state
* @param defaultIcon fallback icon
* @param state the synth state of the button
*/
private Icon getIcon(AbstractButton b, Icon specificIcon, Icon defaultIcon,
int state) {
Icon icon = specificIcon;
if (icon == null) {
if (defaultIcon instanceof UIResource) {
icon = getSynthIcon(b, state);
if (icon == null) {
icon = defaultIcon;
}
} else {
icon = defaultIcon;
}
}
return icon;
}
private Icon getSynthIcon(AbstractButton b, int synthConstant) {
return style.getIcon(getContext(b, synthConstant), getPropertyPrefix() + "icon");
}
private Icon getEnabledIcon(AbstractButton b, Icon defaultIcon) {
if (defaultIcon == null) {
defaultIcon = getSynthIcon(b, SynthConstants.ENABLED);
}
return defaultIcon;
}
private Icon getSelectedIcon(AbstractButton b, Icon defaultIcon) {
return getIcon(b, b.getSelectedIcon(), defaultIcon,
SynthConstants.SELECTED);
}
private Icon getRolloverIcon(AbstractButton b, Icon defaultIcon) {
ButtonModel model = b.getModel();
Icon icon;
if (model.isSelected()) {
icon = getIcon(b, b.getRolloverSelectedIcon(), defaultIcon,
SynthConstants.MOUSE_OVER | SynthConstants.SELECTED);
} else {
icon = getIcon(b, b.getRolloverIcon(), defaultIcon,
SynthConstants.MOUSE_OVER);
}
return icon;
}
private Icon getPressedIcon(AbstractButton b, Icon defaultIcon) {
return getIcon(b, b.getPressedIcon(), defaultIcon,
SynthConstants.PRESSED);
}
private Icon getSynthDisabledIcon(AbstractButton b, Icon defaultIcon) {
ButtonModel model = b.getModel();
Icon icon;
if (model.isSelected()) {
icon = getIcon(b, b.getDisabledSelectedIcon(), defaultIcon,
SynthConstants.DISABLED | SynthConstants.SELECTED);
} else {
icon = getIcon(b, b.getDisabledIcon(), defaultIcon,
SynthConstants.DISABLED);
}
return icon;
}
/** {@collect.stats}
* Returns the amount to shift the text/icon when painting.
*/
protected int getTextShiftOffset(SynthContext state) {
AbstractButton button = (AbstractButton)state.getComponent();
ButtonModel model = button.getModel();
if (model.isArmed() && model.isPressed() &&
button.getPressedIcon() == null) {
return state.getStyle().getInt(state, getPropertyPrefix() +
"textShiftOffset", 0);
}
return 0;
}
// ********************************
// Layout Methods
// ********************************
public Dimension getMinimumSize(JComponent c) {
if (c.getComponentCount() > 0 && c.getLayout() != null) {
return null;
}
AbstractButton b = (AbstractButton)c;
SynthContext ss = getContext(c);
Dimension size = ss.getStyle().getGraphicsUtils(ss).getMinimumSize(
ss, ss.getStyle().getFont(ss), b.getText(), getSizingIcon(b),
b.getHorizontalAlignment(), b.getVerticalAlignment(),
b.getHorizontalTextPosition(),
b.getVerticalTextPosition(), b.getIconTextGap(),
b.getDisplayedMnemonicIndex());
ss.dispose();
return size;
}
public Dimension getPreferredSize(JComponent c) {
if (c.getComponentCount() > 0 && c.getLayout() != null) {
return null;
}
AbstractButton b = (AbstractButton)c;
SynthContext ss = getContext(c);
Dimension size = ss.getStyle().getGraphicsUtils(ss).getPreferredSize(
ss, ss.getStyle().getFont(ss), b.getText(), getSizingIcon(b),
b.getHorizontalAlignment(), b.getVerticalAlignment(),
b.getHorizontalTextPosition(),
b.getVerticalTextPosition(), b.getIconTextGap(),
b.getDisplayedMnemonicIndex());
ss.dispose();
return size;
}
public Dimension getMaximumSize(JComponent c) {
if (c.getComponentCount() > 0 && c.getLayout() != null) {
return null;
}
AbstractButton b = (AbstractButton)c;
SynthContext ss = getContext(c);
Dimension size = ss.getStyle().getGraphicsUtils(ss).getMaximumSize(
ss, ss.getStyle().getFont(ss), b.getText(), getSizingIcon(b),
b.getHorizontalAlignment(), b.getVerticalAlignment(),
b.getHorizontalTextPosition(),
b.getVerticalTextPosition(), b.getIconTextGap(),
b.getDisplayedMnemonicIndex());
ss.dispose();
return size;
}
/** {@collect.stats}
* Returns the Icon used in calculating the pref/min/max size.
*/
protected Icon getSizingIcon(AbstractButton b) {
Icon icon = getEnabledIcon(b, b.getIcon());
if (icon == null) {
icon = getDefaultIcon(b);
}
return icon;
}
public void propertyChange(PropertyChangeEvent e) {
if (SynthLookAndFeel.shouldUpdateStyle(e)) {
updateStyle((AbstractButton)e.getSource());
}
}
}
|
Java
|
/*
* Copyright (c) 2002, 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.swing.plaf.synth;
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;
import javax.swing.*;
import javax.swing.plaf.*;
import javax.swing.event.*;
import javax.swing.plaf.basic.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import sun.swing.plaf.synth.SynthUI;
/** {@collect.stats}
* Synth's ComboBoxUI.
*
* @author Scott Violet
*/
class SynthComboBoxUI extends BasicComboBoxUI implements
PropertyChangeListener, SynthUI {
private SynthStyle style;
private boolean useListColors;
/** {@collect.stats}
* Used to adjust the location and size of the popup. Very useful for
* situations such as we find in Nimbus where part of the border is used
* to paint the focus. In such cases, the border is empty space, and not
* part of the "visual" border, and in these cases, you'd like the popup
* to be adjusted such that it looks as if it were next to the visual border.
* You may want to use negative insets to get the right look.
*/
Insets popupInsets;
/** {@collect.stats}
* This flag may be set via UIDefaults. By default, it is false, to
* preserve backwards compatibility. If true, then the combo will
* "act as a button" when it is not editable.
*/
private boolean buttonWhenNotEditable;
/** {@collect.stats}
* A flag to indicate that the combo box and combo box button should
* remain in the PRESSED state while the combo popup is visible.
*/
private boolean pressedWhenPopupVisible;
/** {@collect.stats}
* When buttonWhenNotEditable is true, this field is used to help make
* the combo box appear and function as a button when the combo box is
* not editable. In such a state, you can click anywhere on the button
* to get it to open the popup. Also, anywhere you hover over the combo
* will cause the entire combo to go into "rollover" state, and anywhere
* you press will go into "pressed" state. This also keeps in sync the
* state of the combo and the arrowButton.
*/
private ButtonHandler buttonHandler;
/** {@collect.stats}
* Handler for repainting combo when editor component gains/looses focus
*/
private EditorFocusHandler editorFocusHandler;
/** {@collect.stats}
* If true, then the cell renderer will be forced to be non-opaque when
* used for rendering the selected item in the combo box (not in the list),
* and forced to opaque after rendering the selected value.
*/
private boolean forceOpaque = false;
/** {@collect.stats}
* NOTE: This serves the same purpose as the same field in BasicComboBoxUI.
* It is here because I could not give the padding field in
* BasicComboBoxUI protected access in an update release.
*/
private Insets padding;
public static ComponentUI createUI(JComponent c) {
return new SynthComboBoxUI();
}
/** {@collect.stats}
* @inheritDoc
*
* Overridden to ensure that ButtonHandler is created prior to any of
* the other installXXX methods, since several of them reference
* buttonHandler.
*/
@Override
public void installUI(JComponent c) {
buttonHandler = new ButtonHandler();
super.installUI(c);
}
@Override
protected void installDefaults() {
//NOTE: This next line of code was added because, since squareButton in
//BasicComboBoxUI is private, I need to have some way of reading it from UIManager.
//This is an incomplete solution (since it implies that squareButons,
//once set, cannot be reset per state. Probably ok, but not always ok).
//This line of code should be removed at the same time that squareButton
//is made protected in the super class.
super.installDefaults();
//This is here instead of in updateStyle because the value for padding
//needs to remain consistent with the value for padding in
//BasicComboBoxUI. I wouldn't have this value here at all if not
//for the fact that I cannot make "padding" protected in any way
//for an update release. This *should* be fixed in Java 7
padding = UIManager.getInsets("ComboBox.padding");
updateStyle(comboBox);
}
private void updateStyle(JComboBox comboBox) {
SynthStyle oldStyle = style;
SynthContext context = getContext(comboBox, ENABLED);
style = SynthLookAndFeel.updateStyle(context, this);
if (style != oldStyle) {
popupInsets = (Insets)style.get(context, "ComboBox.popupInsets");
useListColors = style.getBoolean(context,
"ComboBox.rendererUseListColors", true);
buttonWhenNotEditable = style.getBoolean(context,
"ComboBox.buttonWhenNotEditable", false);
pressedWhenPopupVisible = style.getBoolean(context,
"ComboBox.pressedWhenPopupVisible", false);
if (oldStyle != null) {
uninstallKeyboardActions();
installKeyboardActions();
}
forceOpaque = style.getBoolean(context,
"ComboBox.forceOpaque", false);
}
context.dispose();
if(listBox != null) {
SynthLookAndFeel.updateStyles(listBox);
}
}
@Override
protected void installListeners() {
comboBox.addPropertyChangeListener(this);
comboBox.addMouseListener(buttonHandler);
editorFocusHandler = new EditorFocusHandler(comboBox);
super.installListeners();
}
@Override
public void uninstallUI(JComponent c) {
if (popup instanceof SynthComboPopup) {
((SynthComboPopup)popup).removePopupMenuListener(buttonHandler);
}
super.uninstallUI(c);
buttonHandler = null;
}
@Override
protected void uninstallDefaults() {
SynthContext context = getContext(comboBox, ENABLED);
style.uninstallDefaults(context);
context.dispose();
style = null;
}
@Override
protected void uninstallListeners() {
editorFocusHandler.unregister();
comboBox.removePropertyChangeListener(this);
comboBox.removeMouseListener(buttonHandler);
buttonHandler.pressed = false;
buttonHandler.over = false;
super.uninstallListeners();
}
@Override
public SynthContext getContext(JComponent c) {
return getContext(c, getComponentState(c));
}
private SynthContext getContext(JComponent c, int state) {
return SynthContext.getContext(SynthContext.class, c,
SynthLookAndFeel.getRegion(c), style, state);
}
private Region getRegion(JComponent c) {
return SynthLookAndFeel.getRegion(c);
}
private int getComponentState(JComponent c) {
// currently we have a broken situation where if a developer
// takes the border from a JComboBox and sets it on a JTextField
// then the codepath will eventually lead back to this method
// but pass in a JTextField instead of JComboBox! In case this
// happens, we just return the normal synth state for the component
// instead of doing anything special
if (!(c instanceof JComboBox)) return SynthLookAndFeel.getComponentState(c);
JComboBox box = (JComboBox)c;
if (shouldActLikeButton()) {
int state = ENABLED;
if ((!c.isEnabled())) {
state = DISABLED;
}
if (buttonHandler.isPressed()) {
state |= PRESSED;
}
if (buttonHandler.isRollover()) {
state |= MOUSE_OVER;
}
if (box.isFocusOwner()) {
state |= FOCUSED;
}
return state;
} else {
// for editable combos the editor component has the focus not the
// combo box its self, so we should make the combo paint focused
// when its editor has focus
int basicState = SynthLookAndFeel.getComponentState(c);
if (box.isEditable() &&
box.getEditor().getEditorComponent().isFocusOwner()) {
basicState |= FOCUSED;
}
return basicState;
}
}
@Override
protected ComboPopup createPopup() {
SynthComboPopup p = new SynthComboPopup(comboBox);
p.addPopupMenuListener(buttonHandler);
return p;
}
@Override
protected ListCellRenderer createRenderer() {
return new SynthComboBoxRenderer();
}
@Override
protected ComboBoxEditor createEditor() {
return new SynthComboBoxEditor();
}
//
// end UI Initialization
//======================
@Override
public void propertyChange(PropertyChangeEvent e) {
if (SynthLookAndFeel.shouldUpdateStyle(e)) {
updateStyle(comboBox);
}
}
@Override
protected JButton createArrowButton() {
SynthArrowButton button = new SynthArrowButton(SwingConstants.SOUTH);
button.setName("ComboBox.arrowButton");
button.setModel(buttonHandler);
return button;
}
//=================================
// begin ComponentUI Implementation
@Override
public void update(Graphics g, JComponent c) {
SynthContext context = getContext(c);
SynthLookAndFeel.update(context, g);
context.getPainter().paintComboBoxBackground(context, g, 0, 0,
c.getWidth(), c.getHeight());
paint(context, g);
context.dispose();
}
@Override
public void paint(Graphics g, JComponent c) {
SynthContext context = getContext(c);
paint(context, g);
context.dispose();
}
protected void paint(SynthContext context, Graphics g) {
hasFocus = comboBox.hasFocus();
if ( !comboBox.isEditable() ) {
Rectangle r = rectangleForCurrentValue();
paintCurrentValue(g,r,hasFocus);
}
}
@Override
public void paintBorder(SynthContext context, Graphics g, int x,
int y, int w, int h) {
context.getPainter().paintComboBoxBorder(context, g, x, y, w, h);
}
/** {@collect.stats}
* Paints the currently selected item.
*/
@Override
public void paintCurrentValue(Graphics g,Rectangle bounds,boolean hasFocus) {
ListCellRenderer renderer = comboBox.getRenderer();
Component c;
c = renderer.getListCellRendererComponent(
listBox, comboBox.getSelectedItem(), -1, false, false );
// Fix for 4238829: should lay out the JPanel.
boolean shouldValidate = false;
if (c instanceof JPanel) {
shouldValidate = true;
}
if (c instanceof UIResource) {
c.setName("ComboBox.renderer");
}
boolean force = forceOpaque && c instanceof JComponent;
if (force) {
((JComponent)c).setOpaque(false);
}
int x = bounds.x, y = bounds.y, w = bounds.width, h = bounds.height;
if (padding != null) {
x = bounds.x + padding.left;
y = bounds.y + padding.top;
w = bounds.width - (padding.left + padding.right);
h = bounds.height - (padding.top + padding.bottom);
}
currentValuePane.paintComponent(g, c, comboBox, x, y, w, h, shouldValidate);
if (force) {
((JComponent)c).setOpaque(true);
}
}
/** {@collect.stats}
* @return true if this combo box should act as one big button. Typically
* only happens when buttonWhenNotEditable is true, and comboBox.isEditable
* is false.
*/
private boolean shouldActLikeButton() {
return buttonWhenNotEditable && !comboBox.isEditable();
}
/** {@collect.stats}
* Return the default size of an empty display area of the combo box using
* the current renderer and font.
*
* This method was overridden to use SynthComboBoxRenderer instead of
* DefaultListCellRenderer as the default renderer when calculating the
* size of the combo box. This is used in the case of the combo not having
* any data.
*
* @return the size of an empty display area
* @see #getDisplaySize
*/
@Override
protected Dimension getDefaultSize() {
SynthComboBoxRenderer r = new SynthComboBoxRenderer();
Dimension d = getSizeForComponent(r.getListCellRendererComponent(listBox, " ", -1, false, false));
return new Dimension(d.width, d.height);
}
/** {@collect.stats}
* This has been refactored out in hopes that it may be investigated and
* simplified for the next major release. adding/removing
* the component to the currentValuePane and changing the font may be
* redundant operations.
*
* NOTE: This method was copied in its entirety from BasicComboBoxUI. Might
* want to make it protected in BasicComboBoxUI in Java 7
*/
private Dimension getSizeForComponent(Component comp) {
currentValuePane.add(comp);
comp.setFont(comboBox.getFont());
Dimension d = comp.getPreferredSize();
currentValuePane.remove(comp);
return d;
}
/** {@collect.stats}
* From BasicComboBoxRenderer v 1.18.
*
* Be aware that SynthFileChooserUIImpl relies on the fact that the default
* renderer installed on a Synth combo box is a JLabel. If this is changed,
* then an assert will fail in SynthFileChooserUIImpl
*/
private class SynthComboBoxRenderer extends JLabel implements ListCellRenderer, UIResource {
public SynthComboBoxRenderer() {
super();
setName("ComboBox.renderer");
setText(" ");
}
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
setName("ComboBox.listRenderer");
SynthLookAndFeel.resetSelectedUI();
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
if (!useListColors) {
SynthLookAndFeel.setSelectedUI(
(SynthLabelUI)SynthLookAndFeel.getUIOfType(getUI(),
SynthLabelUI.class), isSelected, cellHasFocus,
list.isEnabled(), false);
}
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
setFont(list.getFont());
if (value instanceof Icon) {
setIcon((Icon)value);
setText("");
} else {
String text = (value == null) ? " " : value.toString();
if ("".equals(text)) {
text = " ";
}
setText(text);
}
// The renderer component should inherit the enabled and
// orientation state of its parent combobox. This is
// especially needed for GTK comboboxes, where the
// ListCellRenderer's state determines the visual state
// of the combobox.
if (comboBox != null){
setEnabled(comboBox.isEnabled());
setComponentOrientation(comboBox.getComponentOrientation());
}
return this;
}
@Override
public void paint(Graphics g) {
super.paint(g);
SynthLookAndFeel.resetSelectedUI();
}
}
/** {@collect.stats}
* From BasicCombBoxEditor v 1.24.
*/
private static class SynthComboBoxEditor implements
ComboBoxEditor, UIResource {
protected JTextField editor;
private Object oldValue;
public SynthComboBoxEditor() {
editor = new JTextField("",9);
editor.setName("ComboBox.textField");
}
@Override
public Component getEditorComponent() {
return editor;
}
/** {@collect.stats}
* Sets the item that should be edited.
*
* @param anObject the displayed value of the editor
*/
@Override
public void setItem(Object anObject) {
String text;
if ( anObject != null ) {
text = anObject.toString();
oldValue = anObject;
} else {
text = "";
}
// workaround for 4530952
if (!text.equals(editor.getText())) {
editor.setText(text);
}
}
@Override
public Object getItem() {
Object newValue = editor.getText();
if (oldValue != null && !(oldValue instanceof String)) {
// The original value is not a string. Should return the value in it's
// original type.
if (newValue.equals(oldValue.toString())) {
return oldValue;
} else {
// Must take the value from the editor and get the value and cast it to the new type.
Class cls = oldValue.getClass();
try {
Method method = cls.getMethod("valueOf", new Class[]{String.class});
newValue = method.invoke(oldValue, new Object[] { editor.getText()});
} catch (Exception ex) {
// Fail silently and return the newValue (a String object)
}
}
}
return newValue;
}
@Override
public void selectAll() {
editor.selectAll();
editor.requestFocus();
}
@Override
public void addActionListener(ActionListener l) {
editor.addActionListener(l);
}
@Override
public void removeActionListener(ActionListener l) {
editor.removeActionListener(l);
}
}
/** {@collect.stats}
* Handles all the logic for treating the combo as a button when it is
* not editable, and when shouldActLikeButton() is true. This class is a
* special ButtonModel, and installed on the arrowButton when appropriate.
* It also is installed as a mouse listener and mouse motion listener on
* the combo box. In this way, the state between the button and combo
* are in sync. Whenever one is "over" both are. Whenever one is pressed,
* both are.
*/
private final class ButtonHandler extends DefaultButtonModel
implements MouseListener, PopupMenuListener {
/** {@collect.stats}
* Indicates that the mouse is over the combo or the arrow button.
* This field only has meaning if buttonWhenNotEnabled is true.
*/
private boolean over;
/** {@collect.stats}
* Indicates that the combo or arrow button has been pressed. This
* field only has meaning if buttonWhenNotEnabled is true.
*/
private boolean pressed;
//------------------------------------------------------------------
// State Methods
//------------------------------------------------------------------
/** {@collect.stats}
* <p>Updates the internal "pressed" state. If shouldActLikeButton()
* is true, and if this method call will change the internal state,
* then the combo and button will be repainted.</p>
*
* <p>Note that this method is called either when a press event
* occurs on the combo box, or on the arrow button.</p>
*/
private void updatePressed(boolean p) {
this.pressed = p && isEnabled();
if (shouldActLikeButton()) {
comboBox.repaint();
}
}
/** {@collect.stats}
* <p>Updates the internal "over" state. If shouldActLikeButton()
* is true, and if this method call will change the internal state,
* then the combo and button will be repainted.</p>
*
* <p>Note that this method is called either when a mouseover/mouseoff event
* occurs on the combo box, or on the arrow button.</p>
*/
private void updateOver(boolean o) {
boolean old = isRollover();
this.over = o && isEnabled();
boolean newo = isRollover();
if (shouldActLikeButton() && old != newo) {
comboBox.repaint();
}
}
//------------------------------------------------------------------
// DefaultButtonModel Methods
//------------------------------------------------------------------
/** {@collect.stats}
* {@inheritDoc}
*
* Ensures that isPressed() will return true if the combo is pressed,
* or the arrowButton is pressed, <em>or</em> if the combo popup is
* visible. This is the case because a combo box looks pressed when
* the popup is visible, and so should the arrow button.
*/
@Override
public boolean isPressed() {
boolean b = shouldActLikeButton() ? pressed : super.isPressed();
return b || (pressedWhenPopupVisible && comboBox.isPopupVisible());
}
/** {@collect.stats}
* {@inheritDoc}
*
* Ensures that the armed state is in sync with the pressed state
* if shouldActLikeButton is true. Without this method, the arrow
* button will not look pressed when the popup is open, regardless
* of the result of isPressed() alone.
*/
@Override
public boolean isArmed() {
boolean b = shouldActLikeButton() ||
(pressedWhenPopupVisible && comboBox.isPopupVisible());
return b ? isPressed() : super.isArmed();
}
/** {@collect.stats}
* {@inheritDoc}
*
* Ensures that isRollover() will return true if the combo is
* rolled over, or the arrowButton is rolled over.
*/
@Override
public boolean isRollover() {
return shouldActLikeButton() ? over : super.isRollover();
}
/** {@collect.stats}
* {@inheritDoc}
*
* Forwards pressed states to the internal "pressed" field
*/
@Override
public void setPressed(boolean b) {
super.setPressed(b);
updatePressed(b);
}
/** {@collect.stats}
* {@inheritDoc}
*
* Forwards rollover states to the internal "over" field
*/
@Override
public void setRollover(boolean b) {
super.setRollover(b);
updateOver(b);
}
//------------------------------------------------------------------
// MouseListener/MouseMotionListener Methods
//------------------------------------------------------------------
@Override
public void mouseEntered(MouseEvent mouseEvent) {
updateOver(true);
}
@Override
public void mouseExited(MouseEvent mouseEvent) {
updateOver(false);
}
@Override
public void mousePressed(MouseEvent mouseEvent) {
updatePressed(true);
}
@Override
public void mouseReleased(MouseEvent mouseEvent) {
updatePressed(false);
}
@Override
public void mouseClicked(MouseEvent e) {}
//------------------------------------------------------------------
// PopupMenuListener Methods
//------------------------------------------------------------------
/** {@collect.stats}
* @inheritDoc
*
* Ensures that the combo box is repainted when the popup is closed.
* This avoids a bug where clicking off the combo wasn't causing a repaint,
* and thus the combo box still looked pressed even when it was not.
*
* This bug was only noticed when acting as a button, but may be generally
* present. If so, remove the if() block
*/
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
if (shouldActLikeButton() || pressedWhenPopupVisible) {
comboBox.repaint();
}
}
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
}
/** {@collect.stats}
* Handler for repainting combo when editor component gains/looses focus
*/
private static class EditorFocusHandler implements FocusListener,
PropertyChangeListener {
private JComboBox comboBox;
private ComboBoxEditor editor = null;
private Component editorComponent = null;
private EditorFocusHandler(JComboBox comboBox) {
this.comboBox = comboBox;
editor = comboBox.getEditor();
if (editor != null){
editorComponent = editor.getEditorComponent();
if (editorComponent != null){
editorComponent.addFocusListener(this);
}
}
comboBox.addPropertyChangeListener("editor",this);
}
public void unregister(){
comboBox.removePropertyChangeListener(this);
if (editorComponent!=null){
editorComponent.removeFocusListener(this);
}
}
/** {@collect.stats} Invoked when a component gains the keyboard focus. */
public void focusGained(FocusEvent e) {
// repaint whole combo on focus gain
comboBox.repaint();
}
/** {@collect.stats} Invoked when a component loses the keyboard focus. */
public void focusLost(FocusEvent e) {
// repaint whole combo on focus loss
comboBox.repaint();
}
/** {@collect.stats}
* Called when the combos editor changes
*
* @param evt A PropertyChangeEvent object describing the event source and
* the property that has changed.
*/
public void propertyChange(PropertyChangeEvent evt) {
ComboBoxEditor newEditor = comboBox.getEditor();
if (editor != newEditor){
if (editorComponent!=null){
editorComponent.removeFocusListener(this);
}
editor = newEditor;
if (editor != null){
editorComponent = editor.getEditorComponent();
if (editorComponent != null){
editorComponent.addFocusListener(this);
}
}
}
}
}
}
|
Java
|
/*
* Copyright (c) 2002, 2010, 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.swing.plaf.synth;
import com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel;
import java.awt.*;
import java.beans.*;
import java.io.*;
import java.lang.ref.*;
import java.net.*;
import java.security.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
import sun.awt.*;
import sun.security.action.*;
import sun.swing.*;
import sun.swing.plaf.synth.*;
/** {@collect.stats}
* SynthLookAndFeel provides the basis for creating a customized look and
* feel. SynthLookAndFeel does not directly provide a look, all painting is
* delegated.
* You need to either provide a configuration file, by way of the
* {@link #load} method, or provide your own {@link SynthStyleFactory}
* to {@link #setStyleFactory}. Refer to the
* <a href="package-summary.html">package summary</a> for an example of
* loading a file, and {@link javax.swing.plaf.synth.SynthStyleFactory} for
* an example of providing your own <code>SynthStyleFactory</code> to
* <code>setStyleFactory</code>.
* <p>
* <strong>Warning:</strong>
* This class implements {@link Serializable} as a side effect of it
* extending {@link BasicLookAndFeel}. It is not intended to be serialized.
* An attempt to serialize it will
* result in {@link NotSerializableException}.
*
* @serial exclude
* @since 1.5
* @author Scott Violet
*/
public class SynthLookAndFeel extends BasicLookAndFeel {
/** {@collect.stats}
* Used in a handful of places where we need an empty Insets.
*/
static final Insets EMPTY_UIRESOURCE_INSETS = new InsetsUIResource(
0, 0, 0, 0);
/** {@collect.stats}
* AppContext key to get the current SynthStyleFactory.
*/
private static final Object STYLE_FACTORY_KEY = new Object(); // com.sun.java.swing.plaf.gtk.StyleCache
/** {@collect.stats}
* The last SynthStyleFactory that was asked for from AppContext
* <code>lastContext</code>.
*/
private static SynthStyleFactory lastFactory;
/** {@collect.stats}
* If this is true it indicates there is more than one AppContext active
* and that we need to make sure in getStyleCache the requesting
* AppContext matches that of <code>lastContext</code> before returning
* it.
*/
private static boolean multipleApps;
/** {@collect.stats}
* AppContext lastLAF came from.
*/
private static AppContext lastContext;
// Refer to setSelectedUI
static ComponentUI selectedUI;
// Refer to setSelectedUI
static int selectedUIState;
/** {@collect.stats}
* SynthStyleFactory for the this SynthLookAndFeel.
*/
private SynthStyleFactory factory;
/** {@collect.stats}
* Map of defaults table entries. This is populated via the load
* method.
*/
private Map defaultsMap;
private Handler _handler;
/** {@collect.stats}
* Used by the renderers. For the most part the renderers are implemented
* as Labels, which is problematic in so far as they are never selected.
* To accomodate this SynthLabelUI checks if the current
* UI matches that of <code>selectedUI</code> (which this methods sets), if
* it does, then a state as set by this method is returned. This provides
* a way for labels to have a state other than selected.
*/
static void setSelectedUI(ComponentUI uix, boolean selected,
boolean focused, boolean enabled,
boolean rollover) {
selectedUI = uix;
selectedUIState = 0;
if (selected) {
selectedUIState = SynthConstants.SELECTED;
if (focused) {
selectedUIState |= SynthConstants.FOCUSED;
}
}
else if (rollover && enabled) {
selectedUIState |=
SynthConstants.MOUSE_OVER | SynthConstants.ENABLED;
if (focused) {
selectedUIState |= SynthConstants.FOCUSED;
}
}
else {
if (enabled) {
selectedUIState |= SynthConstants.ENABLED;
selectedUIState = SynthConstants.FOCUSED;
}
else {
selectedUIState |= SynthConstants.DISABLED;
}
}
}
/** {@collect.stats}
* Clears out the selected UI that was last set in setSelectedUI.
*/
static void resetSelectedUI() {
selectedUI = null;
}
/** {@collect.stats}
* Sets the SynthStyleFactory that the UI classes provided by
* synth will use to obtain a SynthStyle.
*
* @param cache SynthStyleFactory the UIs should use.
*/
public static void setStyleFactory(SynthStyleFactory cache) {
// We assume the setter is called BEFORE the getter has been invoked
// for a particular AppContext.
synchronized(SynthLookAndFeel.class) {
AppContext context = AppContext.getAppContext();
if (!multipleApps && context != lastContext &&
lastContext != null) {
multipleApps = true;
}
lastFactory = cache;
lastContext = context;
context.put(STYLE_FACTORY_KEY, cache);
}
}
/** {@collect.stats}
* Returns the current SynthStyleFactory.
*
* @return SynthStyleFactory
*/
public static SynthStyleFactory getStyleFactory() {
synchronized(SynthLookAndFeel.class) {
if (!multipleApps) {
return lastFactory;
}
AppContext context = AppContext.getAppContext();
if (lastContext == context) {
return lastFactory;
}
lastContext = context;
lastFactory = (SynthStyleFactory)AppContext.getAppContext().get
(STYLE_FACTORY_KEY);
return lastFactory;
}
}
/** {@collect.stats}
* Returns the component state for the specified component. This should
* only be used for Components that don't have any special state beyond
* that of ENABLED, DISABLED or FOCUSED. For example, buttons shouldn't
* call into this method.
*/
static int getComponentState(Component c) {
if (c.isEnabled()) {
if (c.isFocusOwner()) {
return SynthUI.ENABLED | SynthUI.FOCUSED;
}
return SynthUI.ENABLED;
}
return SynthUI.DISABLED;
}
/** {@collect.stats}
* Gets a SynthStyle for the specified region of the specified component.
* This is not for general consumption, only custom UIs should call this
* method.
*
* @param c JComponent to get the SynthStyle for
* @param region Identifies the region of the specified component
* @return SynthStyle to use.
*/
public static SynthStyle getStyle(JComponent c, Region region) {
return getStyleFactory().getStyle(c, region);
}
/** {@collect.stats}
* Returns true if the Style should be updated in response to the
* specified PropertyChangeEvent. This forwards to
* <code>shouldUpdateStyleOnAncestorChanged</code> as necessary.
*/
static boolean shouldUpdateStyle(PropertyChangeEvent event) {
// Note: The following Nimbus-specific call should be refactored
// to be in the Nimbus LAF. Due to constraints in an update release,
// we couldn't actually provide the public API necessary to allow
// NimbusLookAndFeel (a subclass of SynthLookAndFeel) to provide its
// own rules for shouldUpdateStyle.
LookAndFeel laf = UIManager.getLookAndFeel();
if (laf instanceof NimbusLookAndFeel &&
((NimbusLookAndFeel) laf).shouldUpdateStyleOnEvent(event)) {
return true;
}
String eName = event.getPropertyName();
if ("name" == eName) {
// Always update on a name change
return true;
}
else if ("componentOrientation" == eName) {
// Always update on a component orientation change
return true;
}
else if ("ancestor" == eName && event.getNewValue() != null) {
// Only update on an ancestor change when getting a valid
// parent and the LookAndFeel wants this.
return (laf instanceof SynthLookAndFeel &&
((SynthLookAndFeel)laf).
shouldUpdateStyleOnAncestorChanged());
}
return false;
}
/** {@collect.stats}
* A convience method that will reset the Style of StyleContext if
* necessary.
*
* @return newStyle
*/
static SynthStyle updateStyle(SynthContext context, SynthUI ui) {
SynthStyle newStyle = getStyle(context.getComponent(),
context.getRegion());
SynthStyle oldStyle = context.getStyle();
if (newStyle != oldStyle) {
if (oldStyle != null) {
oldStyle.uninstallDefaults(context);
}
context.setStyle(newStyle);
newStyle.installDefaults(context, ui);
}
return newStyle;
}
/** {@collect.stats}
* Updates the style associated with <code>c</code>, and all its children.
* This is a lighter version of
* <code>SwingUtilities.updateComponentTreeUI</code>.
*
* @param c Component to update style for.
*/
public static void updateStyles(Component c) {
_updateStyles(c);
c.repaint();
}
// Implementation for updateStyles
private static void _updateStyles(Component c) {
if (c instanceof JComponent) {
// Yes, this is hacky. A better solution is to get the UI
// and cast, but JComponent doesn't expose a getter for the UI
// (each of the UIs do), making that approach impractical.
String name = c.getName();
c.setName(null);
if (name != null) {
c.setName(name);
}
((JComponent)c).revalidate();
}
Component[] children = null;
if (c instanceof JMenu) {
children = ((JMenu)c).getMenuComponents();
}
else if (c instanceof Container) {
children = ((Container)c).getComponents();
}
if (children != null) {
for(int i = 0; i < children.length; i++) {
updateStyles(children[i]);
}
}
}
/** {@collect.stats}
* Returns the Region for the JComponent <code>c</code>.
*
* @param c JComponent to fetch the Region for
* @return Region corresponding to <code>c</code>
*/
public static Region getRegion(JComponent c) {
return Region.getRegion(c);
}
/** {@collect.stats}
* A convenience method to return where the foreground should be
* painted for the Component identified by the passed in
* AbstractSynthContext.
*/
static Insets getPaintingInsets(SynthContext state, Insets insets) {
if (state.isSubregion()) {
insets = state.getStyle().getInsets(state, insets);
}
else {
insets = state.getComponent().getInsets(insets);
}
return insets;
}
/** {@collect.stats}
* A convenience method that handles painting of the background.
* All SynthUI implementations should override update and invoke
* this method.
*/
static void update(SynthContext state, Graphics g) {
paintRegion(state, g, null);
}
/** {@collect.stats}
* A convenience method that handles painting of the background for
* subregions. All SynthUI's that have subregions should invoke
* this method, than paint the foreground.
*/
static void updateSubregion(SynthContext state, Graphics g,
Rectangle bounds) {
paintRegion(state, g, bounds);
}
private static void paintRegion(SynthContext state, Graphics g,
Rectangle bounds) {
JComponent c = state.getComponent();
SynthStyle style = state.getStyle();
int x, y, width, height;
if (bounds == null) {
x = 0;
y = 0;
width = c.getWidth();
height = c.getHeight();
}
else {
x = bounds.x;
y = bounds.y;
width = bounds.width;
height = bounds.height;
}
// Fill in the background, if necessary.
boolean subregion = state.isSubregion();
if ((subregion && style.isOpaque(state)) ||
(!subregion && c.isOpaque())) {
g.setColor(style.getColor(state, ColorType.BACKGROUND));
g.fillRect(x, y, width, height);
}
}
static boolean isLeftToRight(Component c) {
return c.getComponentOrientation().isLeftToRight();
}
/** {@collect.stats}
* Returns the ui that is of type <code>klass</code>, or null if
* one can not be found.
*/
static Object getUIOfType(ComponentUI ui, Class klass) {
if (klass.isInstance(ui)) {
return ui;
}
return null;
}
/** {@collect.stats}
* Creates the Synth look and feel <code>ComponentUI</code> for
* the passed in <code>JComponent</code>.
*
* @param c JComponent to create the <code>ComponentUI</code> for
* @return ComponentUI to use for <code>c</code>
*/
public static ComponentUI createUI(JComponent c) {
String key = c.getUIClassID().intern();
if (key == "ButtonUI") {
return SynthButtonUI.createUI(c);
}
else if (key == "CheckBoxUI") {
return SynthCheckBoxUI.createUI(c);
}
else if (key == "CheckBoxMenuItemUI") {
return SynthCheckBoxMenuItemUI.createUI(c);
}
else if (key == "ColorChooserUI") {
return SynthColorChooserUI.createUI(c);
}
else if (key == "ComboBoxUI") {
return SynthComboBoxUI.createUI(c);
}
else if (key == "DesktopPaneUI") {
return SynthDesktopPaneUI.createUI(c);
}
else if (key == "DesktopIconUI") {
return SynthDesktopIconUI.createUI(c);
}
else if (key == "EditorPaneUI") {
return SynthEditorPaneUI.createUI(c);
}
else if (key == "FileChooserUI") {
return SynthFileChooserUI.createUI(c);
}
else if (key == "FormattedTextFieldUI") {
return SynthFormattedTextFieldUI.createUI(c);
}
else if (key == "InternalFrameUI") {
return SynthInternalFrameUI.createUI(c);
}
else if (key == "LabelUI") {
return SynthLabelUI.createUI(c);
}
else if (key == "ListUI") {
return SynthListUI.createUI(c);
}
else if (key == "MenuBarUI") {
return SynthMenuBarUI.createUI(c);
}
else if (key == "MenuUI") {
return SynthMenuUI.createUI(c);
}
else if (key == "MenuItemUI") {
return SynthMenuItemUI.createUI(c);
}
else if (key == "OptionPaneUI") {
return SynthOptionPaneUI.createUI(c);
}
else if (key == "PanelUI") {
return SynthPanelUI.createUI(c);
}
else if (key == "PasswordFieldUI") {
return SynthPasswordFieldUI.createUI(c);
}
else if (key == "PopupMenuSeparatorUI") {
return SynthSeparatorUI.createUI(c);
}
else if (key == "PopupMenuUI") {
return SynthPopupMenuUI.createUI(c);
}
else if (key == "ProgressBarUI") {
return SynthProgressBarUI.createUI(c);
}
else if (key == "RadioButtonUI") {
return SynthRadioButtonUI.createUI(c);
}
else if (key == "RadioButtonMenuItemUI") {
return SynthRadioButtonMenuItemUI.createUI(c);
}
else if (key == "RootPaneUI") {
return SynthRootPaneUI.createUI(c);
}
else if (key == "ScrollBarUI") {
return SynthScrollBarUI.createUI(c);
}
else if (key == "ScrollPaneUI") {
return SynthScrollPaneUI.createUI(c);
}
else if (key == "SeparatorUI") {
return SynthSeparatorUI.createUI(c);
}
else if (key == "SliderUI") {
return SynthSliderUI.createUI(c);
}
else if (key == "SpinnerUI") {
return SynthSpinnerUI.createUI(c);
}
else if (key == "SplitPaneUI") {
return SynthSplitPaneUI.createUI(c);
}
else if (key == "TabbedPaneUI") {
return SynthTabbedPaneUI.createUI(c);
}
else if (key == "TableUI") {
return SynthTableUI.createUI(c);
}
else if (key == "TableHeaderUI") {
return SynthTableHeaderUI.createUI(c);
}
else if (key == "TextAreaUI") {
return SynthTextAreaUI.createUI(c);
}
else if (key == "TextFieldUI") {
return SynthTextFieldUI.createUI(c);
}
else if (key == "TextPaneUI") {
return SynthTextPaneUI.createUI(c);
}
else if (key == "ToggleButtonUI") {
return SynthToggleButtonUI.createUI(c);
}
else if (key == "ToolBarSeparatorUI") {
return SynthSeparatorUI.createUI(c);
}
else if (key == "ToolBarUI") {
return SynthToolBarUI.createUI(c);
}
else if (key == "ToolTipUI") {
return SynthToolTipUI.createUI(c);
}
else if (key == "TreeUI") {
return SynthTreeUI.createUI(c);
}
else if (key == "ViewportUI") {
return SynthViewportUI.createUI(c);
}
return null;
}
/** {@collect.stats}
* Creates a SynthLookAndFeel.
* <p>
* For the returned <code>SynthLookAndFeel</code> to be useful you need to
* invoke <code>load</code> to specify the set of
* <code>SynthStyle</code>s, or invoke <code>setStyleFactory</code>.
*
* @see #load
* @see #setStyleFactory
*/
public SynthLookAndFeel() {
factory = new DefaultSynthStyleFactory();
_handler = new Handler();
}
/** {@collect.stats}
* Loads the set of <code>SynthStyle</code>s that will be used by
* this <code>SynthLookAndFeel</code>. <code>resourceBase</code> is
* used to resolve any path based resources, for example an
* <code>Image</code> would be resolved by
* <code>resourceBase.getResource(path)</code>. Refer to
* <a href="doc-files/synthFileFormat.html">Synth File Format</a>
* for more information.
*
* @param input InputStream to load from
* @param resourceBase used to resolve any images or other resources
* @throws ParseException if there is an error in parsing
* @throws IllegalArgumentException if input or resourceBase is <code>null</code>
*/
public void load(InputStream input, Class<?> resourceBase) throws
ParseException {
if (resourceBase == null) {
throw new IllegalArgumentException(
"You must supply a valid resource base Class");
}
if (defaultsMap == null) {
defaultsMap = new HashMap();
}
new SynthParser().parse(input, (DefaultSynthStyleFactory) factory,
null, resourceBase, defaultsMap);
}
/** {@collect.stats}
* Loads the set of <code>SynthStyle</code>s that will be used by
* this <code>SynthLookAndFeel</code>. Path based resources are resolved
* relatively to the specified <code>URL</code> of the style. For example
* an <code>Image</code> would be resolved by
* <code>new URL(synthFile, path)</code>. Refer to
* <a href="doc-files/synthFileFormat.html">Synth File Format</a> for more
* information.
*
* @param url the <code>URL</code> to load the set of
* <code>SynthStyle</code> from
* @throws ParseException if there is an error in parsing
* @throws IllegalArgumentException if synthSet is <code>null</code>
* @throws IOException if synthSet cannot be opened as an <code>InputStream</code>
* @since 1.6
*/
public void load(URL url) throws ParseException, IOException {
if (url == null) {
throw new IllegalArgumentException(
"You must supply a valid Synth set URL");
}
if (defaultsMap == null) {
defaultsMap = new HashMap();
}
InputStream input = url.openStream();
new SynthParser().parse(input, (DefaultSynthStyleFactory) factory,
url, null, defaultsMap);
}
/** {@collect.stats}
* Called by UIManager when this look and feel is installed.
*/
@Override
public void initialize() {
super.initialize();
DefaultLookup.setDefaultLookup(new SynthDefaultLookup());
setStyleFactory(factory);
KeyboardFocusManager.getCurrentKeyboardFocusManager().
addPropertyChangeListener(_handler);
}
/** {@collect.stats}
* Called by UIManager when this look and feel is uninstalled.
*/
@Override
public void uninitialize() {
KeyboardFocusManager.getCurrentKeyboardFocusManager().
removePropertyChangeListener(_handler);
// We should uninstall the StyleFactory here, but unfortunately
// there are a handful of things that retain references to the
// LookAndFeel and expect things to work
super.uninitialize();
}
/** {@collect.stats}
* Returns the defaults for this SynthLookAndFeel.
*
* @return Defaults table.
*/
@Override
public UIDefaults getDefaults() {
UIDefaults table = new UIDefaults(60, 0.75f);
Region.registerUIs(table);
table.setDefaultLocale(Locale.getDefault());
table.addResourceBundle(
"com.sun.swing.internal.plaf.basic.resources.basic" );
table.addResourceBundle("com.sun.swing.internal.plaf.synth.resources.synth");
// SynthTabbedPaneUI supports rollover on tabs, GTK does not
table.put("TabbedPane.isTabRollover", Boolean.TRUE);
// These need to be defined for JColorChooser to work.
table.put("ColorChooser.swatchesRecentSwatchSize",
new Dimension(10, 10));
table.put("ColorChooser.swatchesDefaultRecentColor", Color.RED);
table.put("ColorChooser.swatchesSwatchSize", new Dimension(10, 10));
// These need to be defined for ImageView.
table.put("html.pendingImage", SwingUtilities2.makeIcon(getClass(),
BasicLookAndFeel.class,
"icons/image-delayed.png"));
table.put("html.missingImage", SwingUtilities2.makeIcon(getClass(),
BasicLookAndFeel.class,
"icons/image-failed.png"));
// These are needed for PopupMenu.
table.put("PopupMenu.selectedWindowInputMapBindings", new Object[] {
"ESCAPE", "cancel",
"DOWN", "selectNext",
"KP_DOWN", "selectNext",
"UP", "selectPrevious",
"KP_UP", "selectPrevious",
"LEFT", "selectParent",
"KP_LEFT", "selectParent",
"RIGHT", "selectChild",
"KP_RIGHT", "selectChild",
"ENTER", "return",
"SPACE", "return"
});
table.put("PopupMenu.selectedWindowInputMapBindings.RightToLeft",
new Object[] {
"LEFT", "selectChild",
"KP_LEFT", "selectChild",
"RIGHT", "selectParent",
"KP_RIGHT", "selectParent",
});
// enabled antialiasing depending on desktop settings
flushUnreferenced();
Object aaTextInfo = getAATextInfo();
table.put(SwingUtilities2.AA_TEXT_PROPERTY_KEY, aaTextInfo);
new AATextListener(this);
if (defaultsMap != null) {
table.putAll(defaultsMap);
}
return table;
}
/** {@collect.stats}
* Returns true, SynthLookAndFeel is always supported.
*
* @return true.
*/
@Override
public boolean isSupportedLookAndFeel() {
return true;
}
/** {@collect.stats}
* Returns false, SynthLookAndFeel is not a native look and feel.
*
* @return false
*/
@Override
public boolean isNativeLookAndFeel() {
return false;
}
/** {@collect.stats}
* Returns a textual description of SynthLookAndFeel.
*
* @return textual description of synth.
*/
@Override
public String getDescription() {
return "Synth look and feel";
}
/** {@collect.stats}
* Return a short string that identifies this look and feel.
*
* @return a short string identifying this look and feel.
*/
@Override
public String getName() {
return "Synth look and feel";
}
/** {@collect.stats}
* Return a string that identifies this look and feel.
*
* @return a short string identifying this look and feel.
*/
@Override
public String getID() {
return "Synth";
}
/** {@collect.stats}
* Returns whether or not the UIs should update their
* <code>SynthStyles</code> from the <code>SynthStyleFactory</code>
* when the ancestor of the <code>JComponent</code> changes. A subclass
* that provided a <code>SynthStyleFactory</code> that based the
* return value from <code>getStyle</code> off the containment hierarchy
* would override this method to return true.
*
* @return whether or not the UIs should update their
* <code>SynthStyles</code> from the <code>SynthStyleFactory</code>
* when the ancestor changed.
*/
public boolean shouldUpdateStyleOnAncestorChanged() {
return false;
}
/** {@collect.stats}
* Returns the antialiasing information as specified by the host desktop.
* Antialiasing might be forced off if the desktop is GNOME and the user
* has set his locale to Chinese, Japanese or Korean. This is consistent
* with what GTK does. See com.sun.java.swing.plaf.gtk.GtkLookAndFeel
* for more information about CJK and antialiased fonts.
*
* @return the text antialiasing information associated to the desktop
*/
private static Object getAATextInfo() {
String language = Locale.getDefault().getLanguage();
String desktop = (String)
AccessController.doPrivileged(new GetPropertyAction("sun.desktop"));
boolean isCjkLocale = (Locale.CHINESE.getLanguage().equals(language) ||
Locale.JAPANESE.getLanguage().equals(language) ||
Locale.KOREAN.getLanguage().equals(language));
boolean isGnome = "gnome".equals(desktop);
boolean isLocal = SwingUtilities2.isLocalDisplay();
boolean setAA = isLocal && (!isGnome || !isCjkLocale);
Object aaTextInfo = SwingUtilities2.AATextInfo.getAATextInfo(setAA);
return aaTextInfo;
}
private static ReferenceQueue queue = new ReferenceQueue();
private static void flushUnreferenced() {
AATextListener aatl;
while ((aatl = (AATextListener) queue.poll()) != null) {
aatl.dispose();
}
}
private static class AATextListener
extends WeakReference implements PropertyChangeListener {
private String key = SunToolkit.DESKTOPFONTHINTS;
AATextListener(LookAndFeel laf) {
super(laf, queue);
Toolkit tk = Toolkit.getDefaultToolkit();
tk.addPropertyChangeListener(key, this);
}
@Override
public void propertyChange(PropertyChangeEvent pce) {
UIDefaults defaults = UIManager.getLookAndFeelDefaults();
if (defaults.getBoolean("Synth.doNotSetTextAA")) {
dispose();
return;
}
LookAndFeel laf = (LookAndFeel) get();
if (laf == null || laf != UIManager.getLookAndFeel()) {
dispose();
return;
}
Object aaTextInfo = getAATextInfo();
defaults.put(SwingUtilities2.AA_TEXT_PROPERTY_KEY, aaTextInfo);
updateUI();
}
void dispose() {
Toolkit tk = Toolkit.getDefaultToolkit();
tk.removePropertyChangeListener(key, this);
}
/** {@collect.stats}
* Updates the UI of the passed in window and all its children.
*/
private static void updateWindowUI(Window window) {
updateStyles(window);
Window ownedWins[] = window.getOwnedWindows();
for (int i = 0; i < ownedWins.length; i++) {
updateWindowUI(ownedWins[i]);
}
}
/** {@collect.stats}
* Updates the UIs of all the known Frames.
*/
private static void updateAllUIs() {
Frame appFrames[] = Frame.getFrames();
for (int i = 0; i < appFrames.length; i++) {
updateWindowUI(appFrames[i]);
}
}
/** {@collect.stats}
* Indicates if an updateUI call is pending.
*/
private static boolean updatePending;
/** {@collect.stats}
* Sets whether or not an updateUI call is pending.
*/
private static synchronized void setUpdatePending(boolean update) {
updatePending = update;
}
/** {@collect.stats}
* Returns true if a UI update is pending.
*/
private static synchronized boolean isUpdatePending() {
return updatePending;
}
protected void updateUI() {
if (!isUpdatePending()) {
setUpdatePending(true);
Runnable uiUpdater = new Runnable() {
@Override
public void run() {
updateAllUIs();
setUpdatePending(false);
}
};
SwingUtilities.invokeLater(uiUpdater);
}
}
}
private void writeObject(java.io.ObjectOutputStream out)
throws IOException {
throw new NotSerializableException(this.getClass().getName());
}
private class Handler implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
Object newValue = evt.getNewValue();
Object oldValue = evt.getOldValue();
if ("focusOwner" == propertyName) {
if (oldValue instanceof JComponent) {
repaintIfBackgroundsDiffer((JComponent)oldValue);
}
if (newValue instanceof JComponent) {
repaintIfBackgroundsDiffer((JComponent)newValue);
}
}
else if ("managingFocus" == propertyName) {
// De-register listener on old keyboard focus manager and
// register it on the new one.
KeyboardFocusManager manager =
(KeyboardFocusManager)evt.getSource();
if (((Boolean)newValue).equals(Boolean.FALSE)) {
manager.removePropertyChangeListener(_handler);
}
else {
manager.addPropertyChangeListener(_handler);
}
}
}
/** {@collect.stats}
* This is a support method that will check if the background colors of
* the specified component differ between focused and unfocused states.
* If the color differ the component will then repaint itself.
*
* @comp the component to check
*/
private void repaintIfBackgroundsDiffer(JComponent comp) {
ComponentUI ui = (ComponentUI)comp.getClientProperty(
SwingUtilities2.COMPONENT_UI_PROPERTY_KEY);
if (ui instanceof SynthUI) {
SynthUI synthUI = (SynthUI)ui;
SynthContext context = synthUI.getContext(comp);
SynthStyle style = context.getStyle();
int state = context.getComponentState();
// Get the current background color.
Color currBG = style.getColor(context, ColorType.BACKGROUND);
// Get the last background color.
state ^= SynthConstants.FOCUSED;
context.setComponentState(state);
Color lastBG = style.getColor(context, ColorType.BACKGROUND);
// Reset the component state back to original.
state ^= SynthConstants.FOCUSED;
context.setComponentState(state);
// Repaint the component if the backgrounds differed.
if (currBG != null && !currBG.equals(lastBG)) {
comp.repaint();
}
context.dispose();
}
}
}
}
|
Java
|
/*
* Copyright (c) 2002, 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.swing.plaf.synth;
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.UIResource;
/** {@collect.stats}
* JButton object that draws a scaled Arrow in one of the cardinal directions.
*
* @author Scott Violet
*/
class SynthArrowButton extends JButton implements SwingConstants, UIResource {
private int direction;
public SynthArrowButton(int direction) {
super();
super.setFocusable(false);
setDirection(direction);
setDefaultCapable(false);
}
public String getUIClassID() {
return "ArrowButtonUI";
}
public void updateUI() {
setUI(new SynthArrowButtonUI());
}
public void setDirection(int dir) {
direction = dir;
putClientProperty("__arrow_direction__", new Integer(dir));
repaint();
}
public int getDirection() {
return direction;
}
public void setFocusable(boolean focusable) {}
private static class SynthArrowButtonUI extends SynthButtonUI {
protected void installDefaults(AbstractButton b) {
super.installDefaults(b);
updateStyle(b);
}
protected void paint(SynthContext context, Graphics g) {
SynthArrowButton button = (SynthArrowButton)context.
getComponent();
context.getPainter().paintArrowButtonForeground(
context, g, 0, 0, button.getWidth(), button.getHeight(),
button.getDirection());
}
void paintBackground(SynthContext context, Graphics g, JComponent c) {
context.getPainter().paintArrowButtonBackground(context, g, 0, 0,
c.getWidth(), c.getHeight());
}
public void paintBorder(SynthContext context, Graphics g, int x,
int y, int w, int h) {
context.getPainter().paintArrowButtonBorder(context, g, x, y, w,h);
}
public Dimension getMinimumSize() {
return new Dimension(5, 5);
}
public Dimension getMaximumSize() {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
public Dimension getPreferredSize(JComponent c) {
SynthContext context = getContext(c);
Dimension dim = null;
if (context.getComponent().getName() == "ScrollBar.button") {
// ScrollBar arrow buttons can be non-square when
// the ScrollBar.squareButtons property is set to FALSE
// and the ScrollBar.buttonSize property is non-null
dim = (Dimension)
context.getStyle().get(context, "ScrollBar.buttonSize");
}
if (dim == null) {
// For all other cases (including Spinner, ComboBox), we will
// fall back on the single ArrowButton.size value to create
// a square return value
int size =
context.getStyle().getInt(context, "ArrowButton.size", 16);
dim = new Dimension(size, size);
}
// handle scaling for sizeVarients for special case components. The
// key "JComponent.sizeVariant" scales for large/small/mini
// components are based on Apples LAF
Container parent = context.getComponent().getParent();
if (parent instanceof JComponent && !(parent instanceof JComboBox)) {
Object scaleKey = ((JComponent)parent).
getClientProperty("JComponent.sizeVariant");
if (scaleKey != null){
if ("large".equals(scaleKey)){
dim = new Dimension(
(int)(dim.width * 1.15),
(int)(dim.height * 1.15));
} else if ("small".equals(scaleKey)){
dim = new Dimension(
(int)(dim.width * 0.857),
(int)(dim.height * 0.857));
} else if ("mini".equals(scaleKey)){
dim = new Dimension(
(int)(dim.width * 0.714),
(int)(dim.height * 0.714));
}
}
}
context.dispose();
return dim;
}
}
}
|
Java
|
/*
* Copyright (c) 2002, 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.swing.plaf.synth;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import javax.swing.text.View;
/** {@collect.stats}
* Synth's RadioButtonUI.
*
* @author Jeff Dinkins
*/
class SynthRadioButtonUI extends SynthToggleButtonUI {
// ********************************
// Create PLAF
// ********************************
public static ComponentUI createUI(JComponent b) {
return new SynthRadioButtonUI();
}
protected String getPropertyPrefix() {
return "RadioButton.";
}
/** {@collect.stats}
* Returns the Icon used in calculating the pref/min/max size.
*/
protected Icon getSizingIcon(AbstractButton b) {
return getIcon(b);
}
void paintBackground(SynthContext context, Graphics g, JComponent c) {
context.getPainter().paintRadioButtonBackground(context, g, 0, 0,
c.getWidth(), c.getHeight());
}
public void paintBorder(SynthContext context, Graphics g, int x,
int y, int w, int h) {
context.getPainter().paintRadioButtonBorder(context, g, x, y, w, h);
}
}
|
Java
|
/*
* Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.synth;
import java.awt.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
import sun.swing.DefaultLookup;
/** {@collect.stats}
* Synth's SplitPaneDivider.
*
* @author Scott Violet
*/
class SynthSplitPaneDivider extends BasicSplitPaneDivider {
public SynthSplitPaneDivider(BasicSplitPaneUI ui) {
super(ui);
}
protected void setMouseOver(boolean mouseOver) {
if (isMouseOver() != mouseOver) {
repaint();
}
super.setMouseOver(mouseOver);
}
public void propertyChange(PropertyChangeEvent e) {
super.propertyChange(e);
if (e.getSource() == splitPane) {
if (e.getPropertyName() == JSplitPane.ORIENTATION_PROPERTY) {
if (leftButton instanceof SynthArrowButton) {
((SynthArrowButton)leftButton).setDirection(
mapDirection(true));
}
if (rightButton instanceof SynthArrowButton) {
((SynthArrowButton)rightButton).setDirection(
mapDirection(false));
}
}
}
}
public void paint(Graphics g) {
Graphics g2 = g.create();
SynthContext context = ((SynthSplitPaneUI)splitPaneUI).getContext(
splitPane, Region.SPLIT_PANE_DIVIDER);
Rectangle bounds = getBounds();
bounds.x = bounds.y = 0;
SynthLookAndFeel.updateSubregion(context, g, bounds);
context.getPainter().paintSplitPaneDividerBackground(context,
g, 0, 0, bounds.width, bounds.height,
splitPane.getOrientation());
SynthPainter foreground = null;
context.getPainter().paintSplitPaneDividerForeground(context, g, 0, 0,
getWidth(), getHeight(), splitPane.getOrientation());
context.dispose();
// super.paint(g2);
for (int counter = 0; counter < getComponentCount(); counter++) {
Component child = getComponent(counter);
Rectangle childBounds = child.getBounds();
Graphics childG = g.create(childBounds.x, childBounds.y,
childBounds.width, childBounds.height);
child.paint(childG);
childG.dispose();
}
g2.dispose();
}
private int mapDirection(boolean isLeft) {
if (isLeft) {
if (splitPane.getOrientation() == JSplitPane.HORIZONTAL_SPLIT){
return SwingConstants.WEST;
}
return SwingConstants.NORTH;
}
if (splitPane.getOrientation() == JSplitPane.HORIZONTAL_SPLIT){
return SwingConstants.EAST;
}
return SwingConstants.SOUTH;
}
/** {@collect.stats}
* Creates and return an instance of JButton that can be used to
* collapse the left component in the split pane.
*/
protected JButton createLeftOneTouchButton() {
SynthArrowButton b = new SynthArrowButton(SwingConstants.NORTH);
int oneTouchSize = lookupOneTouchSize();
b.setName("SplitPaneDivider.leftOneTouchButton");
b.setMinimumSize(new Dimension(oneTouchSize, oneTouchSize));
b.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
b.setFocusPainted(false);
b.setBorderPainted(false);
b.setRequestFocusEnabled(false);
b.setDirection(mapDirection(true));
return b;
}
private int lookupOneTouchSize() {
return DefaultLookup.getInt(splitPaneUI.getSplitPane(), splitPaneUI,
"SplitPaneDivider.oneTouchButtonSize", ONE_TOUCH_SIZE);
}
/** {@collect.stats}
* Creates and return an instance of JButton that can be used to
* collapse the right component in the split pane.
*/
protected JButton createRightOneTouchButton() {
SynthArrowButton b = new SynthArrowButton(SwingConstants.NORTH);
int oneTouchSize = lookupOneTouchSize();
b.setName("SplitPaneDivider.rightOneTouchButton");
b.setMinimumSize(new Dimension(oneTouchSize, oneTouchSize));
b.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
b.setFocusPainted(false);
b.setBorderPainted(false);
b.setRequestFocusEnabled(false);
b.setDirection(mapDirection(false));
return b;
}
}
|
Java
|
/*
* Copyright (c) 2002, 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.swing.plaf.synth;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.BasicEditorPaneUI;
import java.beans.PropertyChangeEvent;
import sun.swing.plaf.synth.SynthUI;
/** {@collect.stats}
* Provides the look and feel for a JEditorPane in the
* Synth look and feel.
*
* @author Shannon Hickey
*/
class SynthEditorPaneUI extends BasicEditorPaneUI implements SynthUI {
private SynthStyle style;
/*
* I would prefer to use UIResource instad of this.
* Unfortunately Boolean is a final class
*/
private Boolean localTrue = new Boolean(true);
private Boolean localFalse = new Boolean(false);
/** {@collect.stats}
* Creates a UI for the JTextPane.
*
* @param c the JTextPane component
* @return the UI
*/
public static ComponentUI createUI(JComponent c) {
return new SynthEditorPaneUI();
}
protected void installDefaults() {
// Installs the text cursor on the component
super.installDefaults();
JComponent c = getComponent();
Object clientProperty =
c.getClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES);
if (clientProperty == null
|| clientProperty == localFalse) {
c.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES,
localTrue);
}
updateStyle((JTextComponent)getComponent());
}
protected void uninstallDefaults() {
SynthContext context = getContext(getComponent(), ENABLED);
JComponent c = getComponent();
c.putClientProperty("caretAspectRatio", null);
style.uninstallDefaults(context);
context.dispose();
style = null;
Object clientProperty =
c.getClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES);
if (clientProperty == localTrue) {
getComponent().putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES,
Boolean.FALSE);
}
super.uninstallDefaults();
}
/** {@collect.stats}
* This method gets called when a bound property is changed
* on the associated JTextComponent. This is a hook
* which UI implementations may change to reflect how the
* UI displays bound properties of JTextComponent subclasses.
* This is implemented to rebuild the ActionMap based upon an
* EditorKit change.
*
* @param evt the property change event
*/
protected void propertyChange(PropertyChangeEvent evt) {
if (SynthLookAndFeel.shouldUpdateStyle(evt)) {
updateStyle((JTextComponent)evt.getSource());
}
super.propertyChange(evt);
}
private void updateStyle(JTextComponent comp) {
SynthContext context = getContext(comp, ENABLED);
SynthStyle oldStyle = style;
style = SynthLookAndFeel.updateStyle(context, this);
if (style != oldStyle) {
SynthTextFieldUI.updateStyle(comp, context, getPropertyPrefix());
if (oldStyle != null) {
uninstallKeyboardActions();
installKeyboardActions();
}
}
context.dispose();
}
public SynthContext getContext(JComponent c) {
return getContext(c, getComponentState(c));
}
private SynthContext getContext(JComponent c, int state) {
return SynthContext.getContext(SynthContext.class, c,
SynthLookAndFeel.getRegion(c), style, state);
}
private int getComponentState(JComponent c) {
return SynthLookAndFeel.getComponentState(c);
}
public void update(Graphics g, JComponent c) {
SynthContext context = getContext(c);
SynthLookAndFeel.update(context, g);
paintBackground(context, g, c);
paint(context, g);
context.dispose();
}
protected void paint(SynthContext context, Graphics g) {
super.paint(g, getComponent());
}
protected void paintBackground(Graphics g) {
// Overriden to do nothing, all our painting is done from update/paint.
}
void paintBackground(SynthContext context, Graphics g, JComponent c) {
context.getPainter().paintEditorPaneBackground(context, g, 0, 0,
c.getWidth(), c.getHeight());
}
public void paintBorder(SynthContext context, Graphics g, int x,
int y, int w, int h) {
context.getPainter().paintEditorPaneBorder(context, g, x, y, w, h);
}
}
|
Java
|
/*
* Copyright (c) 2002, 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.swing.plaf.synth;
import java.awt.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
import javax.swing.table.*;
import sun.swing.DefaultLookup;
import sun.swing.plaf.synth.*;
import sun.swing.table.*;
/** {@collect.stats}
* SynthTableHeaderUI implementation
*
* @author Alan Chung
* @author Philip Milne
*/
class SynthTableHeaderUI extends BasicTableHeaderUI implements
PropertyChangeListener, SynthUI {
//
// Instance Variables
//
private TableCellRenderer prevRenderer = null;
private SynthStyle style;
public static ComponentUI createUI(JComponent h) {
return new SynthTableHeaderUI();
}
protected void installDefaults() {
prevRenderer = header.getDefaultRenderer();
if (prevRenderer instanceof UIResource) {
header.setDefaultRenderer(new HeaderRenderer());
}
updateStyle(header);
}
private void updateStyle(JTableHeader c) {
SynthContext context = getContext(c, ENABLED);
SynthStyle oldStyle = style;
style = SynthLookAndFeel.updateStyle(context, this);
if (style != oldStyle) {
if (oldStyle != null) {
uninstallKeyboardActions();
installKeyboardActions();
}
}
context.dispose();
}
protected void installListeners() {
super.installListeners();
header.addPropertyChangeListener(this);
}
protected void uninstallDefaults() {
if (header.getDefaultRenderer() instanceof HeaderRenderer) {
header.setDefaultRenderer(prevRenderer);
}
SynthContext context = getContext(header, ENABLED);
style.uninstallDefaults(context);
context.dispose();
style = null;
}
protected void uninstallListeners() {
header.removePropertyChangeListener(this);
super.uninstallListeners();
}
public void update(Graphics g, JComponent c) {
SynthContext context = getContext(c);
SynthLookAndFeel.update(context, g);
context.getPainter().paintTableHeaderBackground(context,
g, 0, 0, c.getWidth(), c.getHeight());
paint(context, g);
context.dispose();
}
public void paint(Graphics g, JComponent c) {
SynthContext context = getContext(c);
paint(context, g);
context.dispose();
}
protected void paint(SynthContext context, Graphics g) {
super.paint(g, context.getComponent());
}
public void paintBorder(SynthContext context, Graphics g, int x,
int y, int w, int h) {
context.getPainter().paintTableHeaderBorder(context, g, x, y, w, h);
}
//
// SynthUI
//
public SynthContext getContext(JComponent c) {
return getContext(c, getComponentState(c));
}
private SynthContext getContext(JComponent c, int state) {
return SynthContext.getContext(SynthContext.class, c,
SynthLookAndFeel.getRegion(c), style, state);
}
private Region getRegion(JComponent c) {
return SynthLookAndFeel.getRegion(c);
}
private int getComponentState(JComponent c) {
return SynthLookAndFeel.getComponentState(c);
}
public void propertyChange(PropertyChangeEvent evt) {
if (SynthLookAndFeel.shouldUpdateStyle(evt)) {
updateStyle((JTableHeader)evt.getSource());
}
}
@Override
protected void rolloverColumnUpdated(int oldColumn, int newColumn) {
header.repaint(header.getHeaderRect(oldColumn));
header.repaint(header.getHeaderRect(newColumn));
}
private class HeaderRenderer extends DefaultTableCellHeaderRenderer {
HeaderRenderer() {
setHorizontalAlignment(JLabel.LEADING);
setName("TableHeader.renderer");
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected,
boolean hasFocus,
int row, int column) {
boolean hasRollover = (column == getRolloverColumn());
if (isSelected || hasRollover || hasFocus) {
SynthLookAndFeel.setSelectedUI((SynthLabelUI)SynthLookAndFeel.
getUIOfType(getUI(), SynthLabelUI.class),
isSelected, hasFocus, table.isEnabled(),
hasRollover);
} else {
SynthLookAndFeel.resetSelectedUI();
}
//stuff a variable into the client property of this renderer indicating the sort order,
//so that different rendering can be done for the header based on sorted state.
RowSorter rs = table == null ? null : table.getRowSorter();
java.util.List<? extends RowSorter.SortKey> sortKeys = rs == null ? null : rs.getSortKeys();
if (sortKeys != null && sortKeys.size() > 0 && sortKeys.get(0).getColumn() ==
table.convertColumnIndexToModel(column)) {
switch(sortKeys.get(0).getSortOrder()) {
case ASCENDING:
putClientProperty("Table.sortOrder", "ASCENDING");
break;
case DESCENDING:
putClientProperty("Table.sortOrder", "DESCENDING");
break;
case UNSORTED:
putClientProperty("Table.sortOrder", "UNSORTED");
break;
default:
throw new AssertionError("Cannot happen");
}
} else {
putClientProperty("Table.sortOrder", "UNSORTED");
}
super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
return this;
}
@Override
public void setBorder(Border border) {
if (border instanceof SynthBorder) {
super.setBorder(border);
}
}
}
}
|
Java
|
/*
* Copyright (c) 2002, 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.swing.plaf.synth;
import java.awt.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import java.awt.*;
import java.awt.event.*;
import sun.swing.plaf.synth.SynthUI;
/** {@collect.stats}
* Synth's ViewportUI.
*
*/
class SynthViewportUI extends ViewportUI implements
PropertyChangeListener, SynthUI {
private SynthStyle style;
public static ComponentUI createUI(JComponent c) {
return new SynthViewportUI();
}
public void installUI(JComponent c) {
super.installUI(c);
installDefaults(c);
installListeners(c);
}
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
uninstallListeners(c);
uninstallDefaults(c);
}
protected void installDefaults(JComponent c) {
updateStyle(c);
}
private void updateStyle(JComponent c) {
SynthContext context = getContext(c, ENABLED);
// Note: JViewport is special cased as it does not allow for
// a border to be set. JViewport.setBorder is overriden to throw
// an IllegalArgumentException. Refer to SynthScrollPaneUI for
// details of this.
SynthStyle newStyle = SynthLookAndFeel.getStyle(context.getComponent(),
context.getRegion());
SynthStyle oldStyle = context.getStyle();
if (newStyle != oldStyle) {
if (oldStyle != null) {
oldStyle.uninstallDefaults(context);
}
context.setStyle(newStyle);
newStyle.installDefaults(context);
}
this.style = newStyle;
context.dispose();
}
protected void installListeners(JComponent c) {
c.addPropertyChangeListener(this);
}
protected void uninstallListeners(JComponent c) {
c.removePropertyChangeListener(this);
}
protected void uninstallDefaults(JComponent c) {
SynthContext context = getContext(c, ENABLED);
style.uninstallDefaults(context);
context.dispose();
style = null;
}
public SynthContext getContext(JComponent c) {
return getContext(c, getComponentState(c));
}
private SynthContext getContext(JComponent c, int state) {
return SynthContext.getContext(SynthContext.class, c,
getRegion(c), style, state);
}
private Region getRegion(JComponent c) {
return SynthLookAndFeel.getRegion(c);
}
private int getComponentState(JComponent c) {
return SynthLookAndFeel.getComponentState(c);
}
public void update(Graphics g, JComponent c) {
SynthContext context = getContext(c);
SynthLookAndFeel.update(context, g);
context.getPainter().paintViewportBackground(context,
g, 0, 0, c.getWidth(), c.getHeight());
paint(context, g);
context.dispose();
}
public void paintBorder(SynthContext context, Graphics g, int x,
int y, int w, int h) {
// This does nothing on purpose, JViewport doesn't allow a border
// and therefor this will NEVER be called.
}
public void paint(Graphics g, JComponent c) {
SynthContext context = getContext(c);
paint(context, g);
context.dispose();
}
protected void paint(SynthContext context, Graphics g) {
}
public void propertyChange(PropertyChangeEvent e) {
if (SynthLookAndFeel.shouldUpdateStyle(e)) {
updateStyle((JComponent)e.getSource());
}
}
}
|
Java
|
/*
* Copyright (c) 2002, 2008, 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.swing.plaf.synth;
import sun.swing.StringUIClientPropertyKey;
import sun.swing.MenuItemLayoutHelper;
import sun.swing.plaf.synth.SynthIcon;
import javax.swing.*;
import javax.swing.text.View;
import java.awt.*;
/** {@collect.stats}
* Calculates preferred size and layouts synth menu items.
*
* All JMenuItems (and JMenus) include enough space for the insets
* plus one or more elements. When we say "label" below, we mean
* "icon and/or text."
*
* Cases to consider for SynthMenuItemUI (visualized here in a
* LTR orientation; the RTL case would be reversed):
* label
* check icon + label
* check icon + label + accelerator
* label + accelerator
*
* Cases to consider for SynthMenuUI (again visualized here in a
* LTR orientation):
* label + arrow
*
* Note that in the above scenarios, accelerator and arrow icon are
* mutually exclusive. This means that if a popup menu contains a mix
* of JMenus and JMenuItems, we only need to allow enough space for
* max(maxAccelerator, maxArrow), and both accelerators and arrow icons
* can occupy the same "column" of space in the menu.
*/
class SynthMenuItemLayoutHelper extends MenuItemLayoutHelper {
public static final StringUIClientPropertyKey MAX_ACC_OR_ARROW_WIDTH =
new StringUIClientPropertyKey("maxAccOrArrowWidth");
public static final ColumnAlignment LTR_ALIGNMENT_1 =
new ColumnAlignment(
SwingConstants.LEFT,
SwingConstants.LEFT,
SwingConstants.LEFT,
SwingConstants.RIGHT,
SwingConstants.RIGHT
);
public static final ColumnAlignment LTR_ALIGNMENT_2 =
new ColumnAlignment(
SwingConstants.LEFT,
SwingConstants.LEFT,
SwingConstants.LEFT,
SwingConstants.LEFT,
SwingConstants.RIGHT
);
public static final ColumnAlignment RTL_ALIGNMENT_1 =
new ColumnAlignment(
SwingConstants.RIGHT,
SwingConstants.RIGHT,
SwingConstants.RIGHT,
SwingConstants.LEFT,
SwingConstants.LEFT
);
public static final ColumnAlignment RTL_ALIGNMENT_2 =
new ColumnAlignment(
SwingConstants.RIGHT,
SwingConstants.RIGHT,
SwingConstants.RIGHT,
SwingConstants.RIGHT,
SwingConstants.LEFT
);
private SynthContext context;
private SynthContext accContext;
private SynthStyle style;
private SynthStyle accStyle;
private SynthGraphicsUtils gu;
private SynthGraphicsUtils accGu;
private boolean alignAcceleratorText;
private int maxAccOrArrowWidth;
public SynthMenuItemLayoutHelper(SynthContext context, SynthContext accContext,
JMenuItem mi, Icon checkIcon, Icon arrowIcon,
Rectangle viewRect, int gap, String accDelimiter,
boolean isLeftToRight, boolean useCheckAndArrow,
String propertyPrefix) {
this.context = context;
this.accContext = accContext;
this.style = context.getStyle();
this.accStyle = accContext.getStyle();
this.gu = style.getGraphicsUtils(context);
this.accGu = accStyle.getGraphicsUtils(accContext);
this.alignAcceleratorText = getAlignAcceleratorText(propertyPrefix);
reset(mi, checkIcon, arrowIcon, viewRect, gap, accDelimiter,
isLeftToRight, style.getFont(context), accStyle.getFont(accContext),
useCheckAndArrow, propertyPrefix);
setLeadingGap(0);
}
private boolean getAlignAcceleratorText(String propertyPrefix) {
return style.getBoolean(context,
propertyPrefix + ".alignAcceleratorText", true);
}
protected void calcWidthsAndHeights() {
// iconRect
if (getIcon() != null) {
getIconSize().setWidth(SynthIcon.getIconWidth(getIcon(), context));
getIconSize().setHeight(SynthIcon.getIconHeight(getIcon(), context));
}
// accRect
if (!getAccText().equals("")) {
getAccSize().setWidth(accGu.computeStringWidth(getAccContext(),
getAccFontMetrics().getFont(), getAccFontMetrics(),
getAccText()));
getAccSize().setHeight(getAccFontMetrics().getHeight());
}
// textRect
if (getText() == null) {
setText("");
} else if (!getText().equals("")) {
if (getHtmlView() != null) {
// Text is HTML
getTextSize().setWidth(
(int) getHtmlView().getPreferredSpan(View.X_AXIS));
getTextSize().setHeight(
(int) getHtmlView().getPreferredSpan(View.Y_AXIS));
} else {
// Text isn't HTML
getTextSize().setWidth(gu.computeStringWidth(context,
getFontMetrics().getFont(), getFontMetrics(),
getText()));
getTextSize().setHeight(getFontMetrics().getHeight());
}
}
if (useCheckAndArrow()) {
// checkIcon
if (getCheckIcon() != null) {
getCheckSize().setWidth(
SynthIcon.getIconWidth(getCheckIcon(), context));
getCheckSize().setHeight(
SynthIcon.getIconHeight(getCheckIcon(), context));
}
// arrowRect
if (getArrowIcon() != null) {
getArrowSize().setWidth(
SynthIcon.getIconWidth(getArrowIcon(), context));
getArrowSize().setHeight(
SynthIcon.getIconHeight(getArrowIcon(), context));
}
}
// labelRect
if (isColumnLayout()) {
getLabelSize().setWidth(getIconSize().getWidth()
+ getTextSize().getWidth() + getGap());
getLabelSize().setHeight(MenuItemLayoutHelper.max(
getCheckSize().getHeight(),
getIconSize().getHeight(),
getTextSize().getHeight(),
getAccSize().getHeight(),
getArrowSize().getHeight()));
} else {
Rectangle textRect = new Rectangle();
Rectangle iconRect = new Rectangle();
gu.layoutText(context, getFontMetrics(), getText(), getIcon(),
getHorizontalAlignment(), getVerticalAlignment(),
getHorizontalTextPosition(), getVerticalTextPosition(),
getViewRect(), iconRect, textRect, getGap());
Rectangle labelRect = iconRect.union(textRect);
getLabelSize().setHeight(labelRect.height);
getLabelSize().setWidth(labelRect.width);
}
}
protected void calcMaxWidths() {
calcMaxWidth(getCheckSize(), MAX_CHECK_WIDTH);
maxAccOrArrowWidth =
calcMaxValue(MAX_ACC_OR_ARROW_WIDTH, getArrowSize().getWidth());
maxAccOrArrowWidth =
calcMaxValue(MAX_ACC_OR_ARROW_WIDTH, getAccSize().getWidth());
if (isColumnLayout()) {
calcMaxWidth(getIconSize(), MAX_ICON_WIDTH);
calcMaxWidth(getTextSize(), MAX_TEXT_WIDTH);
int curGap = getGap();
if ((getIconSize().getMaxWidth() == 0)
|| (getTextSize().getMaxWidth() == 0)) {
curGap = 0;
}
getLabelSize().setMaxWidth(
calcMaxValue(MAX_LABEL_WIDTH, getIconSize().getMaxWidth()
+ getTextSize().getMaxWidth() + curGap));
} else {
// We shouldn't use current icon and text widths
// in maximal widths calculation for complex layout.
getIconSize().setMaxWidth(getParentIntProperty(
MAX_ICON_WIDTH));
calcMaxWidth(getLabelSize(), MAX_LABEL_WIDTH);
// If maxLabelWidth is wider
// than the widest icon + the widest text + gap,
// we should update the maximal text witdh
int candidateTextWidth = getLabelSize().getMaxWidth() -
getIconSize().getMaxWidth();
if (getIconSize().getMaxWidth() > 0) {
candidateTextWidth -= getGap();
}
getTextSize().setMaxWidth(calcMaxValue(
MAX_TEXT_WIDTH, candidateTextWidth));
}
}
public SynthContext getContext() {
return context;
}
public SynthContext getAccContext() {
return accContext;
}
public SynthStyle getStyle() {
return style;
}
public SynthStyle getAccStyle() {
return accStyle;
}
public SynthGraphicsUtils getGraphicsUtils() {
return gu;
}
public SynthGraphicsUtils getAccGraphicsUtils() {
return accGu;
}
public boolean alignAcceleratorText() {
return alignAcceleratorText;
}
public int getMaxAccOrArrowWidth() {
return maxAccOrArrowWidth;
}
protected void prepareForLayout(LayoutResult lr) {
lr.getCheckRect().width = getCheckSize().getMaxWidth();
// An item can have an arrow or a check icon at once
if (useCheckAndArrow() && (!"".equals(getAccText()))) {
lr.getAccRect().width = maxAccOrArrowWidth;
} else {
lr.getArrowRect().width = maxAccOrArrowWidth;
}
}
public ColumnAlignment getLTRColumnAlignment() {
if (alignAcceleratorText()) {
return LTR_ALIGNMENT_2;
} else {
return LTR_ALIGNMENT_1;
}
}
public ColumnAlignment getRTLColumnAlignment() {
if (alignAcceleratorText()) {
return RTL_ALIGNMENT_2;
} else {
return RTL_ALIGNMENT_1;
}
}
protected void layoutIconAndTextInLabelRect(LayoutResult lr) {
lr.setTextRect(new Rectangle());
lr.setIconRect(new Rectangle());
gu.layoutText(context, getFontMetrics(), getText(), getIcon(),
getHorizontalAlignment(), getVerticalAlignment(),
getHorizontalTextPosition(), getVerticalTextPosition(),
lr.getLabelRect(), lr.getIconRect(), lr.getTextRect(), getGap());
}
}
|
Java
|
/*
* Copyright (c) 2002, 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.swing.plaf.synth;
import javax.swing.*;
import javax.swing.colorchooser.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.BasicColorChooserUI;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import sun.swing.plaf.synth.SynthUI;
/** {@collect.stats}
* Synth's ColorChooserUI.
*
* @author Tom Santos
* @author Steve Wilson
*/
class SynthColorChooserUI extends BasicColorChooserUI implements
PropertyChangeListener, SynthUI {
private SynthStyle style;
public static ComponentUI createUI(JComponent c) {
return new SynthColorChooserUI();
}
protected AbstractColorChooserPanel[] createDefaultChoosers() {
SynthContext context = getContext(chooser, ENABLED);
AbstractColorChooserPanel[] panels = (AbstractColorChooserPanel[])
context.getStyle().get(context, "ColorChooser.panels");
context.dispose();
if (panels == null) {
panels = ColorChooserComponentFactory.getDefaultChooserPanels();
}
return panels;
}
protected void installDefaults() {
super.installDefaults();
updateStyle(chooser);
}
private void updateStyle(JComponent c) {
SynthContext context = getContext(c, ENABLED);
style = SynthLookAndFeel.updateStyle(context, this);
context.dispose();
}
protected void uninstallDefaults() {
SynthContext context = getContext(chooser, ENABLED);
style.uninstallDefaults(context);
context.dispose();
style = null;
super.uninstallDefaults();
}
protected void installListeners() {
super.installListeners();
chooser.addPropertyChangeListener(this);
}
protected void uninstallListeners() {
chooser.removePropertyChangeListener(this);
super.uninstallListeners();
}
public SynthContext getContext(JComponent c) {
return getContext(c, getComponentState(c));
}
private SynthContext getContext(JComponent c, int state) {
return SynthContext.getContext(SynthContext.class, c,
SynthLookAndFeel.getRegion(c), style, state);
}
private Region getRegion(JComponent c) {
return SynthLookAndFeel.getRegion(c);
}
private int getComponentState(JComponent c) {
return SynthLookAndFeel.getComponentState(c);
}
public void update(Graphics g, JComponent c) {
SynthContext context = getContext(c);
SynthLookAndFeel.update(context, g);
context.getPainter().paintColorChooserBackground(context, g, 0, 0,
c.getWidth(), c.getHeight());
paint(context, g);
context.dispose();
}
public void paint(Graphics g, JComponent c) {
SynthContext context = getContext(c);
paint(context, g);
context.dispose();
}
protected void paint(SynthContext context, Graphics g) {
}
public void paintBorder(SynthContext context, Graphics g, int x,
int y, int w, int h) {
context.getPainter().paintColorChooserBorder(context, g, x, y,w,h);
}
public void propertyChange(PropertyChangeEvent e) {
if (SynthLookAndFeel.shouldUpdateStyle(e)) {
updateStyle((JColorChooser)e.getSource());
}
}
}
|
Java
|
/*
* Copyright (c) 2002, 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.swing.plaf.synth;
import java.awt.Graphics;
import javax.swing.AbstractButton;
import javax.swing.JComponent;
import javax.swing.plaf.ComponentUI;
/** {@collect.stats}
* Synth's ToggleButtonUI.
* <p>
* @author Jeff Dinkins
*/
class SynthToggleButtonUI extends SynthButtonUI {
// ********************************
// Create PLAF
// ********************************
public static ComponentUI createUI(JComponent b) {
return new SynthToggleButtonUI();
}
@Override
protected String getPropertyPrefix() {
return "ToggleButton.";
}
@Override
void paintBackground(SynthContext context, Graphics g, JComponent c) {
if (((AbstractButton) c).isContentAreaFilled()) {
int x = 0, y = 0, w = c.getWidth(), h = c.getHeight();
SynthPainter painter = context.getPainter();
painter.paintToggleButtonBackground(context, g, x, y, w, h);
}
}
@Override
public void paintBorder(SynthContext context, Graphics g, int x,
int y, int w, int h) {
context.getPainter().paintToggleButtonBorder(context, g, x, y, w, h);
}
}
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.