code
stringlengths 3
1.18M
| language
stringclasses 1
value |
|---|---|
/*
* Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth;
/** {@collect.stats}
* This class is for authentication permissions.
* An AuthPermission contains a name
* (also referred to as a "target name")
* but no actions list; you either have the named permission
* or you don't.
*
* <p> The target name is the name of a security configuration parameter
* (see below). Currently the AuthPermission object is used to
* guard access to the Policy, Subject, LoginContext,
* and Configuration objects.
*
* <p> The possible target names for an Authentication Permission are:
*
* <pre>
* doAs - allow the caller to invoke the
* <code>Subject.doAs</code> methods.
*
* doAsPrivileged - allow the caller to invoke the
* <code>Subject.doAsPrivileged</code> methods.
*
* getSubject - allow for the retrieval of the
* Subject(s) associated with the
* current Thread.
*
* getSubjectFromDomainCombiner - allow for the retrieval of the
* Subject associated with the
* a <code>SubjectDomainCombiner</code>.
*
* setReadOnly - allow the caller to set a Subject
* to be read-only.
*
* modifyPrincipals - allow the caller to modify the <code>Set</code>
* of Principals associated with a
* <code>Subject</code>
*
* modifyPublicCredentials - allow the caller to modify the
* <code>Set</code> of public credentials
* associated with a <code>Subject</code>
*
* modifyPrivateCredentials - allow the caller to modify the
* <code>Set</code> of private credentials
* associated with a <code>Subject</code>
*
* refreshCredential - allow code to invoke the <code>refresh</code>
* method on a credential which implements
* the <code>Refreshable</code> interface.
*
* destroyCredential - allow code to invoke the <code>destroy</code>
* method on a credential <code>object</code>
* which implements the <code>Destroyable</code>
* interface.
*
* createLoginContext.{name} - allow code to instantiate a
* <code>LoginContext</code> with the
* specified <i>name</i>. <i>name</i>
* is used as the index into the installed login
* <code>Configuration</code>
* (that returned by
* <code>Configuration.getConfiguration()</code>).
* <i>name</i> can be wildcarded (set to '*')
* to allow for any name.
*
* getLoginConfiguration - allow for the retrieval of the system-wide
* login Configuration.
*
* createLoginConfiguration.{type} - allow code to obtain a Configuration
* object via
* <code>Configuration.getInstance</code>.
*
* setLoginConfiguration - allow for the setting of the system-wide
* login Configuration.
*
* refreshLoginConfiguration - allow for the refreshing of the system-wide
* login Configuration.
* </pre>
*
* <p> The following target name has been deprecated in favor of
* <code>createLoginContext.{name}</code>.
*
* <pre>
* createLoginContext - allow code to instantiate a
* <code>LoginContext</code>.
* </pre>
*
* <p> <code>javax.security.auth.Policy</code> has been
* deprecated in favor of <code>java.security.Policy</code>.
* Therefore, the following target names have also been deprecated:
*
* <pre>
* getPolicy - allow the caller to retrieve the system-wide
* Subject-based access control policy.
*
* setPolicy - allow the caller to set the system-wide
* Subject-based access control policy.
*
* refreshPolicy - allow the caller to refresh the system-wide
* Subject-based access control policy.
* </pre>
*
*/
public final class AuthPermission extends
java.security.BasicPermission {
private static final long serialVersionUID = 5806031445061587174L;
/** {@collect.stats}
* Creates a new AuthPermission with the specified name.
* The name is the symbolic name of the AuthPermission.
*
* <p>
*
* @param name the name of the AuthPermission
*
* @throws NullPointerException if <code>name</code> is <code>null</code>.
* @throws IllegalArgumentException if <code>name</code> is empty.
*/
public AuthPermission(String name) {
// for backwards compatibility --
// createLoginContext is deprecated in favor of createLoginContext.*
super("createLoginContext".equals(name) ?
"createLoginContext.*" : name);
}
/** {@collect.stats}
* Creates a new AuthPermission object with the specified name.
* The name is the symbolic name of the AuthPermission, and the
* actions String is currently unused and should be null.
*
* <p>
*
* @param name the name of the AuthPermission <p>
*
* @param actions should be null.
*
* @throws NullPointerException if <code>name</code> is <code>null</code>.
* @throws IllegalArgumentException if <code>name</code> is empty.
*/
public AuthPermission(String name, String actions) {
// for backwards compatibility --
// createLoginContext is deprecated in favor of createLoginContext.*
super("createLoginContext".equals(name) ?
"createLoginContext.*" : name, actions);
}
}
|
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.security.auth;
/** {@collect.stats}
* Objects such as credentials may optionally implement this
* interface to provide the capability to refresh itself.
* For example, a credential with a particular time-restricted lifespan
* may implement this interface to allow callers to refresh the time period
* for which it is valid.
*
* @see javax.security.auth.Subject
*/
public interface Refreshable {
/** {@collect.stats}
* Determine if this <code>Object</code> is current.
*
* <p>
*
* @return true if this <code>Object</code> is currently current,
* false otherwise.
*/
boolean isCurrent();
/** {@collect.stats}
* Update or extend the validity period for this
* <code>Object</code>.
*
* <p>
*
* @exception SecurityException if the caller does not have permission
* to update or extend the validity period for this
* <code>Object</code>. <p>
*
* @exception RefreshFailedException if the refresh attempt failed.
*/
void refresh() throws RefreshFailedException;
}
|
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.security.auth;
/** {@collect.stats}
* Signals that a <code>refresh</code> operation failed.
*
* <p> This exception is thrown by credentials implementing
* the <code>Refreshable</code> interface when the <code>refresh</code>
* method fails.
*
*/
public class RefreshFailedException extends Exception {
private static final long serialVersionUID = 5058444488565265840L;
/** {@collect.stats}
* Constructs a RefreshFailedException with no detail message. A detail
* message is a String that describes this particular exception.
*/
public RefreshFailedException() {
super();
}
/** {@collect.stats}
* Constructs a RefreshFailedException with the specified detail
* message. A detail message is a String that describes this particular
* exception.
*
* <p>
*
* @param msg the detail message.
*/
public RefreshFailedException(String msg) {
super(msg);
}
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth;
import java.security.AccessController;
import java.security.AccessControlContext;
import java.security.AllPermission;
import java.security.Permission;
import java.security.Permissions;
import java.security.PermissionCollection;
import java.security.Policy;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.lang.ClassLoader;
import java.security.Security;
import java.util.Set;
import java.util.Iterator;
import java.util.WeakHashMap;
import java.lang.ref.WeakReference;
/** {@collect.stats}
* A <code>SubjectDomainCombiner</code> updates ProtectionDomains
* with Principals from the <code>Subject</code> associated with this
* <code>SubjectDomainCombiner</code>.
*
*/
public class SubjectDomainCombiner implements java.security.DomainCombiner {
private Subject subject;
private WeakKeyValueMap<ProtectionDomain, ProtectionDomain> cachedPDs =
new WeakKeyValueMap<ProtectionDomain, ProtectionDomain>();
private Set<Principal> principalSet;
private Principal[] principals;
private static final sun.security.util.Debug debug =
sun.security.util.Debug.getInstance("combiner",
"\t[SubjectDomainCombiner]");
// Note: check only at classloading time, not dynamically during combine()
private static final boolean useJavaxPolicy = compatPolicy();
// Relevant only when useJavaxPolicy is true
private static final boolean allowCaching =
(useJavaxPolicy && cachePolicy());
/** {@collect.stats}
* Associate the provided <code>Subject</code> with this
* <code>SubjectDomainCombiner</code>.
*
* <p>
*
* @param subject the <code>Subject</code> to be associated with
* with this <code>SubjectDomainCombiner</code>.
*/
public SubjectDomainCombiner(Subject subject) {
this.subject = subject;
if (subject.isReadOnly()) {
principalSet = subject.getPrincipals();
principals = principalSet.toArray
(new Principal[principalSet.size()]);
}
}
/** {@collect.stats}
* Get the <code>Subject</code> associated with this
* <code>SubjectDomainCombiner</code>.
*
* <p>
*
* @return the <code>Subject</code> associated with this
* <code>SubjectDomainCombiner</code>, or <code>null</code>
* if no <code>Subject</code> is associated with this
* <code>SubjectDomainCombiner</code>.
*
* @exception SecurityException if the caller does not have permission
* to get the <code>Subject</code> associated with this
* <code>SubjectDomainCombiner</code>.
*/
public Subject getSubject() {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new AuthPermission
("getSubjectFromDomainCombiner"));
}
return subject;
}
/** {@collect.stats}
* Update the relevant ProtectionDomains with the Principals
* from the <code>Subject</code> associated with this
* <code>SubjectDomainCombiner</code>.
*
* <p> A new <code>ProtectionDomain</code> instance is created
* for each <code>ProtectionDomain</code> in the
* <i>currentDomains</i> array. Each new <code>ProtectionDomain</code>
* instance is created using the <code>CodeSource</code>,
* <code>Permission</code>s and <code>ClassLoader</code>
* from the corresponding <code>ProtectionDomain</code> in
* <i>currentDomains</i>, as well as with the Principals from
* the <code>Subject</code> associated with this
* <code>SubjectDomainCombiner</code>.
*
* <p> All of the newly instantiated ProtectionDomains are
* combined into a new array. The ProtectionDomains from the
* <i>assignedDomains</i> array are appended to this new array,
* and the result is returned.
*
* <p> Note that optimizations such as the removal of duplicate
* ProtectionDomains may have occurred.
* In addition, caching of ProtectionDomains may be permitted.
*
* <p>
*
* @param currentDomains the ProtectionDomains associated with the
* current execution Thread, up to the most recent
* privileged <code>ProtectionDomain</code>.
* The ProtectionDomains are are listed in order of execution,
* with the most recently executing <code>ProtectionDomain</code>
* residing at the beginning of the array. This parameter may
* be <code>null</code> if the current execution Thread
* has no associated ProtectionDomains.<p>
*
* @param assignedDomains the ProtectionDomains inherited from the
* parent Thread, or the ProtectionDomains from the
* privileged <i>context</i>, if a call to
* AccessController.doPrivileged(..., <i>context</i>)
* had occurred This parameter may be <code>null</code>
* if there were no ProtectionDomains inherited from the
* parent Thread, or from the privileged <i>context</i>.
*
* @return a new array consisting of the updated ProtectionDomains,
* or <code>null</code>.
*/
public ProtectionDomain[] combine(ProtectionDomain[] currentDomains,
ProtectionDomain[] assignedDomains) {
if (debug != null) {
if (subject == null) {
debug.println("null subject");
} else {
final Subject s = subject;
AccessController.doPrivileged
(new java.security.PrivilegedAction<Void>() {
public Void run() {
debug.println(s.toString());
return null;
}
});
}
printInputDomains(currentDomains, assignedDomains);
}
if (currentDomains == null || currentDomains.length == 0) {
// No need to optimize assignedDomains because it should
// have been previously optimized (when it was set).
// Note that we are returning a direct reference
// to the input array - since ACC does not clone
// the arrays when it calls combiner.combine,
// multiple ACC instances may share the same
// array instance in this case
return assignedDomains;
}
// optimize currentDomains
//
// No need to optimize assignedDomains because it should
// have been previously optimized (when it was set).
currentDomains = optimize(currentDomains);
if (debug != null) {
debug.println("after optimize");
printInputDomains(currentDomains, assignedDomains);
}
if (currentDomains == null && assignedDomains == null) {
return null;
}
// maintain backwards compatibility for people who provide
// their own javax.security.auth.Policy implementations
if (useJavaxPolicy) {
return combineJavaxPolicy(currentDomains, assignedDomains);
}
int cLen = (currentDomains == null ? 0 : currentDomains.length);
int aLen = (assignedDomains == null ? 0 : assignedDomains.length);
// the ProtectionDomains for the new AccessControlContext
// that we will return
ProtectionDomain[] newDomains = new ProtectionDomain[cLen + aLen];
boolean allNew = true;
synchronized(cachedPDs) {
if (!subject.isReadOnly() &&
!subject.getPrincipals().equals(principalSet)) {
// if the Subject was mutated, clear the PD cache
Set<Principal> newSet = subject.getPrincipals();
synchronized(newSet) {
principalSet = new java.util.HashSet<Principal>(newSet);
}
principals = principalSet.toArray
(new Principal[principalSet.size()]);
cachedPDs.clear();
if (debug != null) {
debug.println("Subject mutated - clearing cache");
}
}
ProtectionDomain subjectPd;
for (int i = 0; i < cLen; i++) {
ProtectionDomain pd = currentDomains[i];
subjectPd = cachedPDs.getValue(pd);
if (subjectPd == null) {
subjectPd = new ProtectionDomain(pd.getCodeSource(),
pd.getPermissions(),
pd.getClassLoader(),
principals);
cachedPDs.putValue(pd, subjectPd);
} else {
allNew = false;
}
newDomains[i] = subjectPd;
}
}
if (debug != null) {
debug.println("updated current: ");
for (int i = 0; i < cLen; i++) {
debug.println("\tupdated[" + i + "] = " +
printDomain(newDomains[i]));
}
}
// now add on the assigned domains
if (aLen > 0) {
System.arraycopy(assignedDomains, 0, newDomains, cLen, aLen);
// optimize the result (cached PDs might exist in assignedDomains)
if (!allNew) {
newDomains = optimize(newDomains);
}
}
// if aLen == 0 || allNew, no need to further optimize newDomains
if (debug != null) {
if (newDomains == null || newDomains.length == 0) {
debug.println("returning null");
} else {
debug.println("combinedDomains: ");
for (int i = 0; i < newDomains.length; i++) {
debug.println("newDomain " + i + ": " +
printDomain(newDomains[i]));
}
}
}
// return the new ProtectionDomains
if (newDomains == null || newDomains.length == 0) {
return null;
} else {
return newDomains;
}
}
/** {@collect.stats}
* Use the javax.security.auth.Policy implementation
*/
private ProtectionDomain[] combineJavaxPolicy(
ProtectionDomain[] currentDomains,
ProtectionDomain[] assignedDomains) {
if (!allowCaching) {
java.security.AccessController.doPrivileged
(new PrivilegedAction<Void>() {
public Void run() {
// Call refresh only caching is disallowed
javax.security.auth.Policy.getPolicy().refresh();
return null;
}
});
}
int cLen = (currentDomains == null ? 0 : currentDomains.length);
int aLen = (assignedDomains == null ? 0 : assignedDomains.length);
// the ProtectionDomains for the new AccessControlContext
// that we will return
ProtectionDomain[] newDomains = new ProtectionDomain[cLen + aLen];
synchronized(cachedPDs) {
if (!subject.isReadOnly() &&
!subject.getPrincipals().equals(principalSet)) {
// if the Subject was mutated, clear the PD cache
Set<Principal> newSet = subject.getPrincipals();
synchronized(newSet) {
principalSet = new java.util.HashSet<Principal>(newSet);
}
principals = principalSet.toArray
(new Principal[principalSet.size()]);
cachedPDs.clear();
if (debug != null) {
debug.println("Subject mutated - clearing cache");
}
}
for (int i = 0; i < cLen; i++) {
ProtectionDomain pd = currentDomains[i];
ProtectionDomain subjectPd = cachedPDs.getValue(pd);
if (subjectPd == null) {
// XXX
// we must first add the original permissions.
// that way when we later add the new JAAS permissions,
// any unresolved JAAS-related permissions will
// automatically get resolved.
// get the original perms
Permissions perms = new Permissions();
PermissionCollection coll = pd.getPermissions();
java.util.Enumeration e;
if (coll != null) {
synchronized (coll) {
e = coll.elements();
while (e.hasMoreElements()) {
Permission newPerm =
(Permission)e.nextElement();
perms.add(newPerm);
}
}
}
// get perms from the policy
final java.security.CodeSource finalCs = pd.getCodeSource();
final Subject finalS = subject;
PermissionCollection newPerms =
java.security.AccessController.doPrivileged
(new PrivilegedAction<PermissionCollection>() {
public PermissionCollection run() {
return
javax.security.auth.Policy.getPolicy().getPermissions
(finalS, finalCs);
}
});
// add the newly granted perms,
// avoiding duplicates
synchronized (newPerms) {
e = newPerms.elements();
while (e.hasMoreElements()) {
Permission newPerm = (Permission)e.nextElement();
if (!perms.implies(newPerm)) {
perms.add(newPerm);
if (debug != null)
debug.println (
"Adding perm " + newPerm + "\n");
}
}
}
subjectPd = new ProtectionDomain
(finalCs, perms, pd.getClassLoader(), principals);
if (allowCaching)
cachedPDs.putValue(pd, subjectPd);
}
newDomains[i] = subjectPd;
}
}
if (debug != null) {
debug.println("updated current: ");
for (int i = 0; i < cLen; i++) {
debug.println("\tupdated[" + i + "] = " + newDomains[i]);
}
}
// now add on the assigned domains
if (aLen > 0) {
System.arraycopy(assignedDomains, 0, newDomains, cLen, aLen);
}
if (debug != null) {
if (newDomains == null || newDomains.length == 0) {
debug.println("returning null");
} else {
debug.println("combinedDomains: ");
for (int i = 0; i < newDomains.length; i++) {
debug.println("newDomain " + i + ": " +
newDomains[i].toString());
}
}
}
// return the new ProtectionDomains
if (newDomains == null || newDomains.length == 0) {
return null;
} else {
return newDomains;
}
}
private static ProtectionDomain[] optimize(ProtectionDomain[] domains) {
if (domains == null || domains.length == 0)
return null;
ProtectionDomain[] optimized = new ProtectionDomain[domains.length];
ProtectionDomain pd;
int num = 0;
for (int i = 0; i < domains.length; i++) {
// skip domains with AllPermission
// XXX
//
// if (domains[i].implies(ALL_PERMISSION))
// continue;
// skip System Domains
if ((pd = domains[i]) != null) {
// remove duplicates
boolean found = false;
for (int j = 0; j < num && !found; j++) {
found = (optimized[j] == pd);
}
if (!found) {
optimized[num++] = pd;
}
}
}
// resize the array if necessary
if (num > 0 && num < domains.length) {
ProtectionDomain[] downSize = new ProtectionDomain[num];
System.arraycopy(optimized, 0, downSize, 0, downSize.length);
optimized = downSize;
}
return ((num == 0 || optimized.length == 0) ? null : optimized);
}
private static boolean cachePolicy() {
String s = AccessController.doPrivileged
(new PrivilegedAction<String>() {
public String run() {
return java.security.Security.getProperty
("cache.auth.policy");
}
});
if (s != null) {
return Boolean.parseBoolean(s);
}
// cache by default
return true;
}
// maintain backwards compatibility for people who provide
// their own javax.security.auth.Policy implementations
private static boolean compatPolicy() {
javax.security.auth.Policy javaxPolicy = AccessController.doPrivileged
(new PrivilegedAction<javax.security.auth.Policy>() {
public javax.security.auth.Policy run() {
return javax.security.auth.Policy.getPolicy();
}
});
if (!(javaxPolicy instanceof com.sun.security.auth.PolicyFile)) {
if (debug != null) {
debug.println("Providing backwards compatibility for " +
"javax.security.auth.policy implementation: " +
javaxPolicy.toString());
}
return true;
} else {
return false;
}
}
private static void printInputDomains(ProtectionDomain[] currentDomains,
ProtectionDomain[] assignedDomains) {
if (currentDomains == null || currentDomains.length == 0) {
debug.println("currentDomains null or 0 length");
} else {
for (int i = 0; currentDomains != null &&
i < currentDomains.length; i++) {
if (currentDomains[i] == null) {
debug.println("currentDomain " + i + ": SystemDomain");
} else {
debug.println("currentDomain " + i + ": " +
printDomain(currentDomains[i]));
}
}
}
if (assignedDomains == null || assignedDomains.length == 0) {
debug.println("assignedDomains null or 0 length");
} else {
debug.println("assignedDomains = ");
for (int i = 0; assignedDomains != null &&
i < assignedDomains.length; i++) {
if (assignedDomains[i] == null) {
debug.println("assignedDomain " + i + ": SystemDomain");
} else {
debug.println("assignedDomain " + i + ": " +
printDomain(assignedDomains[i]));
}
}
}
}
private static String printDomain(final ProtectionDomain pd) {
if (pd == null) {
return "null";
}
return AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return pd.toString();
}
});
}
/** {@collect.stats}
* A HashMap that has weak keys and values.
*
* Key objects in this map are the "current" ProtectionDomain instances
* received via the combine method. Each "current" PD is mapped to a
* new PD instance that holds both the contents of the "current" PD,
* as well as the principals from the Subject associated with this combiner.
*
* The newly created "principal-based" PD values must be stored as
* WeakReferences since they contain strong references to the
* corresponding key object (the "current" non-principal-based PD),
* which will prevent the key from being GC'd. Specifically,
* a "principal-based" PD contains strong references to the CodeSource,
* signer certs, PermissionCollection and ClassLoader objects
* in the "current PD".
*/
private static class WeakKeyValueMap<K,V> extends
WeakHashMap<K,WeakReference<V>> {
public V getValue(K key) {
WeakReference<V> wr = super.get(key);
if (wr != null) {
return wr.get();
}
return null;
}
public V putValue(K key, V value) {
WeakReference<V> wr = super.put(key, new WeakReference<V>(value));
if (wr != null) {
return wr.get();
}
return null;
}
}
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth;
import java.util.*;
import java.io.*;
import java.lang.reflect.*;
import java.text.MessageFormat;
import java.security.AccessController;
import java.security.AccessControlContext;
import java.security.DomainCombiner;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;
import java.security.ProtectionDomain;
import sun.security.util.ResourcesMgr;
import sun.security.util.SecurityConstants;
/** {@collect.stats}
* <p> A <code>Subject</code> represents a grouping of related information
* for a single entity, such as a person.
* Such information includes the Subject's identities as well as
* its security-related attributes
* (passwords and cryptographic keys, for example).
*
* <p> Subjects may potentially have multiple identities.
* Each identity is represented as a <code>Principal</code>
* within the <code>Subject</code>. Principals simply bind names to a
* <code>Subject</code>. For example, a <code>Subject</code> that happens
* to be a person, Alice, might have two Principals:
* one which binds "Alice Bar", the name on her driver license,
* to the <code>Subject</code>, and another which binds,
* "999-99-9999", the number on her student identification card,
* to the <code>Subject</code>. Both Principals refer to the same
* <code>Subject</code> even though each has a different name.
*
* <p> A <code>Subject</code> may also own security-related attributes,
* which are referred to as credentials.
* Sensitive credentials that require special protection, such as
* private cryptographic keys, are stored within a private credential
* <code>Set</code>. Credentials intended to be shared, such as
* public key certificates or Kerberos server tickets are stored
* within a public credential <code>Set</code>. Different permissions
* are required to access and modify the different credential Sets.
*
* <p> To retrieve all the Principals associated with a <code>Subject</code>,
* invoke the <code>getPrincipals</code> method. To retrieve
* all the public or private credentials belonging to a <code>Subject</code>,
* invoke the <code>getPublicCredentials</code> method or
* <code>getPrivateCredentials</code> method, respectively.
* To modify the returned <code>Set</code> of Principals and credentials,
* use the methods defined in the <code>Set</code> class.
* For example:
* <pre>
* Subject subject;
* Principal principal;
* Object credential;
*
* // add a Principal and credential to the Subject
* subject.getPrincipals().add(principal);
* subject.getPublicCredentials().add(credential);
* </pre>
*
* <p> This <code>Subject</code> class implements <code>Serializable</code>.
* While the Principals associated with the <code>Subject</code> are serialized,
* the credentials associated with the <code>Subject</code> are not.
* Note that the <code>java.security.Principal</code> class
* does not implement <code>Serializable</code>. Therefore all concrete
* <code>Principal</code> implementations associated with Subjects
* must implement <code>Serializable</code>.
*
* @see java.security.Principal
* @see java.security.DomainCombiner
*/
public final class Subject implements java.io.Serializable {
private static final long serialVersionUID = -8308522755600156056L;
/** {@collect.stats}
* A <code>Set</code> that provides a view of all of this
* Subject's Principals
*
* <p>
*
* @serial Each element in this set is a
* <code>java.security.Principal</code>.
* The set is a <code>Subject.SecureSet</code>.
*/
Set<Principal> principals;
/** {@collect.stats}
* Sets that provide a view of all of this
* Subject's Credentials
*/
transient Set<Object> pubCredentials;
transient Set<Object> privCredentials;
/** {@collect.stats}
* Whether this Subject is read-only
*
* @serial
*/
private volatile boolean readOnly = false;
private static final int PRINCIPAL_SET = 1;
private static final int PUB_CREDENTIAL_SET = 2;
private static final int PRIV_CREDENTIAL_SET = 3;
private static final ProtectionDomain[] NULL_PD_ARRAY
= new ProtectionDomain[0];
/** {@collect.stats}
* Create an instance of a <code>Subject</code>
* with an empty <code>Set</code> of Principals and empty
* Sets of public and private credentials.
*
* <p> The newly constructed Sets check whether this <code>Subject</code>
* has been set read-only before permitting subsequent modifications.
* The newly created Sets also prevent illegal modifications
* by ensuring that callers have sufficient permissions.
*
* <p> To modify the Principals Set, the caller must have
* <code>AuthPermission("modifyPrincipals")</code>.
* To modify the public credential Set, the caller must have
* <code>AuthPermission("modifyPublicCredentials")</code>.
* To modify the private credential Set, the caller must have
* <code>AuthPermission("modifyPrivateCredentials")</code>.
*/
public Subject() {
this.principals = Collections.synchronizedSet
(new SecureSet<Principal>(this, PRINCIPAL_SET));
this.pubCredentials = Collections.synchronizedSet
(new SecureSet<Object>(this, PUB_CREDENTIAL_SET));
this.privCredentials = Collections.synchronizedSet
(new SecureSet<Object>(this, PRIV_CREDENTIAL_SET));
}
/** {@collect.stats}
* Create an instance of a <code>Subject</code> with
* Principals and credentials.
*
* <p> The Principals and credentials from the specified Sets
* are copied into newly constructed Sets.
* These newly created Sets check whether this <code>Subject</code>
* has been set read-only before permitting subsequent modifications.
* The newly created Sets also prevent illegal modifications
* by ensuring that callers have sufficient permissions.
*
* <p> To modify the Principals Set, the caller must have
* <code>AuthPermission("modifyPrincipals")</code>.
* To modify the public credential Set, the caller must have
* <code>AuthPermission("modifyPublicCredentials")</code>.
* To modify the private credential Set, the caller must have
* <code>AuthPermission("modifyPrivateCredentials")</code>.
* <p>
*
* @param readOnly true if the <code>Subject</code> is to be read-only,
* and false otherwise. <p>
*
* @param principals the <code>Set</code> of Principals
* to be associated with this <code>Subject</code>. <p>
*
* @param pubCredentials the <code>Set</code> of public credentials
* to be associated with this <code>Subject</code>. <p>
*
* @param privCredentials the <code>Set</code> of private credentials
* to be associated with this <code>Subject</code>.
*
* @exception NullPointerException if the specified
* <code>principals</code>, <code>pubCredentials</code>,
* or <code>privCredentials</code> are <code>null</code>.
*/
public Subject(boolean readOnly, Set<? extends Principal> principals,
Set<?> pubCredentials, Set<?> privCredentials)
{
if (principals == null ||
pubCredentials == null ||
privCredentials == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid null input(s)"));
this.principals = Collections.synchronizedSet(new SecureSet<Principal>
(this, PRINCIPAL_SET, principals));
this.pubCredentials = Collections.synchronizedSet(new SecureSet<Object>
(this, PUB_CREDENTIAL_SET, pubCredentials));
this.privCredentials = Collections.synchronizedSet(new SecureSet<Object>
(this, PRIV_CREDENTIAL_SET, privCredentials));
this.readOnly = readOnly;
}
/** {@collect.stats}
* Set this <code>Subject</code> to be read-only.
*
* <p> Modifications (additions and removals) to this Subject's
* <code>Principal</code> <code>Set</code> and
* credential Sets will be disallowed.
* The <code>destroy</code> operation on this Subject's credentials will
* still be permitted.
*
* <p> Subsequent attempts to modify the Subject's <code>Principal</code>
* and credential Sets will result in an
* <code>IllegalStateException</code> being thrown.
* Also, once a <code>Subject</code> is read-only,
* it can not be reset to being writable again.
*
* <p>
*
* @exception SecurityException if the caller does not have permission
* to set this <code>Subject</code> to be read-only.
*/
public void setReadOnly() {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new AuthPermission("setReadOnly"));
}
this.readOnly = true;
}
/** {@collect.stats}
* Query whether this <code>Subject</code> is read-only.
*
* <p>
*
* @return true if this <code>Subject</code> is read-only, false otherwise.
*/
public boolean isReadOnly() {
return this.readOnly;
}
/** {@collect.stats}
* Get the <code>Subject</code> associated with the provided
* <code>AccessControlContext</code>.
*
* <p> The <code>AccessControlContext</code> may contain many
* Subjects (from nested <code>doAs</code> calls).
* In this situation, the most recent <code>Subject</code> associated
* with the <code>AccessControlContext</code> is returned.
*
* <p>
*
* @param acc the <code>AccessControlContext</code> from which to retrieve
* the <code>Subject</code>.
*
* @return the <code>Subject</code> associated with the provided
* <code>AccessControlContext</code>, or <code>null</code>
* if no <code>Subject</code> is associated
* with the provided <code>AccessControlContext</code>.
*
* @exception SecurityException if the caller does not have permission
* to get the <code>Subject</code>. <p>
*
* @exception NullPointerException if the provided
* <code>AccessControlContext</code> is <code>null</code>.
*/
public static Subject getSubject(final AccessControlContext acc) {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new AuthPermission("getSubject"));
}
if (acc == null) {
throw new NullPointerException(ResourcesMgr.getString
("invalid null AccessControlContext provided"));
}
// return the Subject from the DomainCombiner of the provided context
return AccessController.doPrivileged
(new java.security.PrivilegedAction<Subject>() {
public Subject run() {
DomainCombiner dc = acc.getDomainCombiner();
if (!(dc instanceof SubjectDomainCombiner))
return null;
SubjectDomainCombiner sdc = (SubjectDomainCombiner)dc;
return sdc.getSubject();
}
});
}
/** {@collect.stats}
* Perform work as a particular <code>Subject</code>.
*
* <p> This method first retrieves the current Thread's
* <code>AccessControlContext</code> via
* <code>AccessController.getContext</code>,
* and then instantiates a new <code>AccessControlContext</code>
* using the retrieved context along with a new
* <code>SubjectDomainCombiner</code> (constructed using
* the provided <code>Subject</code>).
* Finally, this method invokes <code>AccessController.doPrivileged</code>,
* passing it the provided <code>PrivilegedAction</code>,
* as well as the newly constructed <code>AccessControlContext</code>.
*
* <p>
*
* @param subject the <code>Subject</code> that the specified
* <code>action</code> will run as. This parameter
* may be <code>null</code>. <p>
*
* @param action the code to be run as the specified
* <code>Subject</code>. <p>
*
* @return the value returned by the PrivilegedAction's
* <code>run</code> method.
*
* @exception NullPointerException if the <code>PrivilegedAction</code>
* is <code>null</code>. <p>
*
* @exception SecurityException if the caller does not have permission
* to invoke this method.
*/
public static <T> T doAs(final Subject subject,
final java.security.PrivilegedAction<T> action) {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(SecurityConstants.DO_AS_PERMISSION);
}
if (action == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid null action provided"));
// set up the new Subject-based AccessControlContext
// for doPrivileged
final AccessControlContext currentAcc = AccessController.getContext();
// call doPrivileged and push this new context on the stack
return java.security.AccessController.doPrivileged
(action,
createContext(subject, currentAcc));
}
/** {@collect.stats}
* Perform work as a particular <code>Subject</code>.
*
* <p> This method first retrieves the current Thread's
* <code>AccessControlContext</code> via
* <code>AccessController.getContext</code>,
* and then instantiates a new <code>AccessControlContext</code>
* using the retrieved context along with a new
* <code>SubjectDomainCombiner</code> (constructed using
* the provided <code>Subject</code>).
* Finally, this method invokes <code>AccessController.doPrivileged</code>,
* passing it the provided <code>PrivilegedExceptionAction</code>,
* as well as the newly constructed <code>AccessControlContext</code>.
*
* <p>
*
* @param subject the <code>Subject</code> that the specified
* <code>action</code> will run as. This parameter
* may be <code>null</code>. <p>
*
* @param action the code to be run as the specified
* <code>Subject</code>. <p>
*
* @return the value returned by the
* PrivilegedExceptionAction's <code>run</code> method.
*
* @exception PrivilegedActionException if the
* <code>PrivilegedExceptionAction.run</code>
* method throws a checked exception. <p>
*
* @exception NullPointerException if the specified
* <code>PrivilegedExceptionAction</code> is
* <code>null</code>. <p>
*
* @exception SecurityException if the caller does not have permission
* to invoke this method.
*/
public static <T> T doAs(final Subject subject,
final java.security.PrivilegedExceptionAction<T> action)
throws java.security.PrivilegedActionException {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(SecurityConstants.DO_AS_PERMISSION);
}
if (action == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid null action provided"));
// set up the new Subject-based AccessControlContext for doPrivileged
final AccessControlContext currentAcc = AccessController.getContext();
// call doPrivileged and push this new context on the stack
return java.security.AccessController.doPrivileged
(action,
createContext(subject, currentAcc));
}
/** {@collect.stats}
* Perform privileged work as a particular <code>Subject</code>.
*
* <p> This method behaves exactly as <code>Subject.doAs</code>,
* except that instead of retrieving the current Thread's
* <code>AccessControlContext</code>, it uses the provided
* <code>AccessControlContext</code>. If the provided
* <code>AccessControlContext</code> is <code>null</code>,
* this method instantiates a new <code>AccessControlContext</code>
* with an empty collection of ProtectionDomains.
*
* <p>
*
* @param subject the <code>Subject</code> that the specified
* <code>action</code> will run as. This parameter
* may be <code>null</code>. <p>
*
* @param action the code to be run as the specified
* <code>Subject</code>. <p>
*
* @param acc the <code>AccessControlContext</code> to be tied to the
* specified <i>subject</i> and <i>action</i>. <p>
*
* @return the value returned by the PrivilegedAction's
* <code>run</code> method.
*
* @exception NullPointerException if the <code>PrivilegedAction</code>
* is <code>null</code>. <p>
*
* @exception SecurityException if the caller does not have permission
* to invoke this method.
*/
public static <T> T doAsPrivileged(final Subject subject,
final java.security.PrivilegedAction<T> action,
final java.security.AccessControlContext acc) {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(SecurityConstants.DO_AS_PRIVILEGED_PERMISSION);
}
if (action == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid null action provided"));
// set up the new Subject-based AccessControlContext
// for doPrivileged
final AccessControlContext callerAcc =
(acc == null ?
new AccessControlContext(NULL_PD_ARRAY) :
acc);
// call doPrivileged and push this new context on the stack
return java.security.AccessController.doPrivileged
(action,
createContext(subject, callerAcc));
}
/** {@collect.stats}
* Perform privileged work as a particular <code>Subject</code>.
*
* <p> This method behaves exactly as <code>Subject.doAs</code>,
* except that instead of retrieving the current Thread's
* <code>AccessControlContext</code>, it uses the provided
* <code>AccessControlContext</code>. If the provided
* <code>AccessControlContext</code> is <code>null</code>,
* this method instantiates a new <code>AccessControlContext</code>
* with an empty collection of ProtectionDomains.
*
* <p>
*
* @param subject the <code>Subject</code> that the specified
* <code>action</code> will run as. This parameter
* may be <code>null</code>. <p>
*
* @param action the code to be run as the specified
* <code>Subject</code>. <p>
*
* @param acc the <code>AccessControlContext</code> to be tied to the
* specified <i>subject</i> and <i>action</i>. <p>
*
* @return the value returned by the
* PrivilegedExceptionAction's <code>run</code> method.
*
* @exception PrivilegedActionException if the
* <code>PrivilegedExceptionAction.run</code>
* method throws a checked exception. <p>
*
* @exception NullPointerException if the specified
* <code>PrivilegedExceptionAction</code> is
* <code>null</code>. <p>
*
* @exception SecurityException if the caller does not have permission
* to invoke this method.
*/
public static <T> T doAsPrivileged(final Subject subject,
final java.security.PrivilegedExceptionAction<T> action,
final java.security.AccessControlContext acc)
throws java.security.PrivilegedActionException {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(SecurityConstants.DO_AS_PRIVILEGED_PERMISSION);
}
if (action == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid null action provided"));
// set up the new Subject-based AccessControlContext for doPrivileged
final AccessControlContext callerAcc =
(acc == null ?
new AccessControlContext(NULL_PD_ARRAY) :
acc);
// call doPrivileged and push this new context on the stack
return java.security.AccessController.doPrivileged
(action,
createContext(subject, callerAcc));
}
private static AccessControlContext createContext(final Subject subject,
final AccessControlContext acc) {
return java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<AccessControlContext>() {
public AccessControlContext run() {
if (subject == null)
return new AccessControlContext(acc, null);
else
return new AccessControlContext
(acc,
new SubjectDomainCombiner(subject));
}
});
}
/** {@collect.stats}
* Return the <code>Set</code> of Principals associated with this
* <code>Subject</code>. Each <code>Principal</code> represents
* an identity for this <code>Subject</code>.
*
* <p> The returned <code>Set</code> is backed by this Subject's
* internal <code>Principal</code> <code>Set</code>. Any modification
* to the returned <code>Set</code> affects the internal
* <code>Principal</code> <code>Set</code> as well.
*
* <p>
*
* @return The <code>Set</code> of Principals associated with this
* <code>Subject</code>.
*/
public Set<Principal> getPrincipals() {
// always return an empty Set instead of null
// so LoginModules can add to the Set if necessary
return principals;
}
/** {@collect.stats}
* Return a <code>Set</code> of Principals associated with this
* <code>Subject</code> that are instances or subclasses of the specified
* <code>Class</code>.
*
* <p> The returned <code>Set</code> is not backed by this Subject's
* internal <code>Principal</code> <code>Set</code>. A new
* <code>Set</code> is created and returned for each method invocation.
* Modifications to the returned <code>Set</code>
* will not affect the internal <code>Principal</code> <code>Set</code>.
*
* <p>
*
* @param c the returned <code>Set</code> of Principals will all be
* instances of this class.
*
* @return a <code>Set</code> of Principals that are instances of the
* specified <code>Class</code>.
*
* @exception NullPointerException if the specified <code>Class</code>
* is <code>null</code>.
*/
public <T extends Principal> Set<T> getPrincipals(Class<T> c) {
if (c == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid null Class provided"));
// always return an empty Set instead of null
// so LoginModules can add to the Set if necessary
return new ClassSet<T>(PRINCIPAL_SET, c);
}
/** {@collect.stats}
* Return the <code>Set</code> of public credentials held by this
* <code>Subject</code>.
*
* <p> The returned <code>Set</code> is backed by this Subject's
* internal public Credential <code>Set</code>. Any modification
* to the returned <code>Set</code> affects the internal public
* Credential <code>Set</code> as well.
*
* <p>
*
* @return A <code>Set</code> of public credentials held by this
* <code>Subject</code>.
*/
public Set<Object> getPublicCredentials() {
// always return an empty Set instead of null
// so LoginModules can add to the Set if necessary
return pubCredentials;
}
/** {@collect.stats}
* Return the <code>Set</code> of private credentials held by this
* <code>Subject</code>.
*
* <p> The returned <code>Set</code> is backed by this Subject's
* internal private Credential <code>Set</code>. Any modification
* to the returned <code>Set</code> affects the internal private
* Credential <code>Set</code> as well.
*
* <p> A caller requires permissions to access the Credentials
* in the returned <code>Set</code>, or to modify the
* <code>Set</code> itself. A <code>SecurityException</code>
* is thrown if the caller does not have the proper permissions.
*
* <p> While iterating through the <code>Set</code>,
* a <code>SecurityException</code> is thrown
* if the caller does not have permission to access a
* particular Credential. The <code>Iterator</code>
* is nevertheless advanced to next element in the <code>Set</code>.
*
* <p>
*
* @return A <code>Set</code> of private credentials held by this
* <code>Subject</code>.
*/
public Set<Object> getPrivateCredentials() {
// XXX
// we do not need a security check for
// AuthPermission(getPrivateCredentials)
// because we already restrict access to private credentials
// via the PrivateCredentialPermission. all the extra AuthPermission
// would do is protect the set operations themselves
// (like size()), which don't seem security-sensitive.
// always return an empty Set instead of null
// so LoginModules can add to the Set if necessary
return privCredentials;
}
/** {@collect.stats}
* Return a <code>Set</code> of public credentials associated with this
* <code>Subject</code> that are instances or subclasses of the specified
* <code>Class</code>.
*
* <p> The returned <code>Set</code> is not backed by this Subject's
* internal public Credential <code>Set</code>. A new
* <code>Set</code> is created and returned for each method invocation.
* Modifications to the returned <code>Set</code>
* will not affect the internal public Credential <code>Set</code>.
*
* <p>
*
* @param c the returned <code>Set</code> of public credentials will all be
* instances of this class.
*
* @return a <code>Set</code> of public credentials that are instances
* of the specified <code>Class</code>.
*
* @exception NullPointerException if the specified <code>Class</code>
* is <code>null</code>.
*/
public <T> Set<T> getPublicCredentials(Class<T> c) {
if (c == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid null Class provided"));
// always return an empty Set instead of null
// so LoginModules can add to the Set if necessary
return new ClassSet<T>(PUB_CREDENTIAL_SET, c);
}
/** {@collect.stats}
* Return a <code>Set</code> of private credentials associated with this
* <code>Subject</code> that are instances or subclasses of the specified
* <code>Class</code>.
*
* <p> The caller must have permission to access all of the
* requested Credentials, or a <code>SecurityException</code>
* will be thrown.
*
* <p> The returned <code>Set</code> is not backed by this Subject's
* internal private Credential <code>Set</code>. A new
* <code>Set</code> is created and returned for each method invocation.
* Modifications to the returned <code>Set</code>
* will not affect the internal private Credential <code>Set</code>.
*
* <p>
*
* @param c the returned <code>Set</code> of private credentials will all be
* instances of this class.
*
* @return a <code>Set</code> of private credentials that are instances
* of the specified <code>Class</code>.
*
* @exception NullPointerException if the specified <code>Class</code>
* is <code>null</code>.
*/
public <T> Set<T> getPrivateCredentials(Class<T> c) {
// XXX
// we do not need a security check for
// AuthPermission(getPrivateCredentials)
// because we already restrict access to private credentials
// via the PrivateCredentialPermission. all the extra AuthPermission
// would do is protect the set operations themselves
// (like size()), which don't seem security-sensitive.
if (c == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid null Class provided"));
// always return an empty Set instead of null
// so LoginModules can add to the Set if necessary
return new ClassSet<T>(PRIV_CREDENTIAL_SET, c);
}
/** {@collect.stats}
* Compares the specified Object with this <code>Subject</code>
* for equality. Returns true if the given object is also a Subject
* and the two <code>Subject</code> instances are equivalent.
* More formally, two <code>Subject</code> instances are
* equal if their <code>Principal</code> and <code>Credential</code>
* Sets are equal.
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>Subject</code>.
*
* @return true if the specified Object is equal to this
* <code>Subject</code>.
*
* @exception SecurityException if the caller does not have permission
* to access the private credentials for this <code>Subject</code>,
* or if the caller does not have permission to access the
* private credentials for the provided <code>Subject</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (o instanceof Subject) {
final Subject that = (Subject)o;
// check the principal and credential sets
Set<Principal> thatPrincipals;
synchronized(that.principals) {
// avoid deadlock from dual locks
thatPrincipals = new HashSet<Principal>(that.principals);
}
if (!principals.equals(thatPrincipals)) {
return false;
}
Set<Object> thatPubCredentials;
synchronized(that.pubCredentials) {
// avoid deadlock from dual locks
thatPubCredentials = new HashSet<Object>(that.pubCredentials);
}
if (!pubCredentials.equals(thatPubCredentials)) {
return false;
}
Set<Object> thatPrivCredentials;
synchronized(that.privCredentials) {
// avoid deadlock from dual locks
thatPrivCredentials = new HashSet<Object>(that.privCredentials);
}
if (!privCredentials.equals(thatPrivCredentials)) {
return false;
}
return true;
}
return false;
}
/** {@collect.stats}
* Return the String representation of this <code>Subject</code>.
*
* <p>
*
* @return the String representation of this <code>Subject</code>.
*/
public String toString() {
return toString(true);
}
/** {@collect.stats}
* package private convenience method to print out the Subject
* without firing off a security check when trying to access
* the Private Credentials
*/
String toString(boolean includePrivateCredentials) {
String s = ResourcesMgr.getString("Subject:\n");
String suffix = "";
synchronized(principals) {
Iterator<Principal> pI = principals.iterator();
while (pI.hasNext()) {
Principal p = pI.next();
suffix = suffix + ResourcesMgr.getString("\tPrincipal: ") +
p.toString() + ResourcesMgr.getString("\n");
}
}
synchronized(pubCredentials) {
Iterator<Object> pI = pubCredentials.iterator();
while (pI.hasNext()) {
Object o = pI.next();
suffix = suffix +
ResourcesMgr.getString("\tPublic Credential: ") +
o.toString() + ResourcesMgr.getString("\n");
}
}
if (includePrivateCredentials) {
synchronized(privCredentials) {
Iterator<Object> pI = privCredentials.iterator();
while (pI.hasNext()) {
try {
Object o = pI.next();
suffix += ResourcesMgr.getString
("\tPrivate Credential: ") +
o.toString() +
ResourcesMgr.getString("\n");
} catch (SecurityException se) {
suffix += ResourcesMgr.getString
("\tPrivate Credential inaccessible\n");
break;
}
}
}
}
return s + suffix;
}
/** {@collect.stats}
* Returns a hashcode for this <code>Subject</code>.
*
* <p>
*
* @return a hashcode for this <code>Subject</code>.
*
* @exception SecurityException if the caller does not have permission
* to access this Subject's private credentials.
*/
public int hashCode() {
/** {@collect.stats}
* The hashcode is derived exclusive or-ing the
* hashcodes of this Subject's Principals and credentials.
*
* If a particular credential was destroyed
* (<code>credential.hashCode()</code> throws an
* <code>IllegalStateException</code>),
* the hashcode for that credential is derived via:
* <code>credential.getClass().toString().hashCode()</code>.
*/
int hashCode = 0;
synchronized(principals) {
Iterator<Principal> pIterator = principals.iterator();
while (pIterator.hasNext()) {
Principal p = pIterator.next();
hashCode ^= p.hashCode();
}
}
synchronized(pubCredentials) {
Iterator<Object> pubCIterator = pubCredentials.iterator();
while (pubCIterator.hasNext()) {
hashCode ^= getCredHashCode(pubCIterator.next());
}
}
return hashCode;
}
/** {@collect.stats}
* get a credential's hashcode
*/
private int getCredHashCode(Object o) {
try {
return o.hashCode();
} catch (IllegalStateException ise) {
return o.getClass().toString().hashCode();
}
}
/** {@collect.stats}
* Writes this object out to a stream (i.e., serializes it).
*/
private void writeObject(java.io.ObjectOutputStream oos)
throws java.io.IOException {
synchronized(principals) {
oos.defaultWriteObject();
}
}
/** {@collect.stats}
* Reads this object from a stream (i.e., deserializes it)
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
// The Credential <code>Set</code> is not serialized, but we do not
// want the default deserialization routine to set it to null.
this.pubCredentials = Collections.synchronizedSet
(new SecureSet<Object>(this, PUB_CREDENTIAL_SET));
this.privCredentials = Collections.synchronizedSet
(new SecureSet<Object>(this, PRIV_CREDENTIAL_SET));
}
/** {@collect.stats}
* Prevent modifications unless caller has permission.
*
* @serial include
*/
private static class SecureSet<E>
extends AbstractSet<E>
implements java.io.Serializable {
private static final long serialVersionUID = 7911754171111800359L;
/** {@collect.stats}
* @serialField this$0 Subject The outer Subject instance.
* @serialField elements LinkedList The elements in this set.
*/
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("this$0", Subject.class),
new ObjectStreamField("elements", LinkedList.class),
new ObjectStreamField("which", int.class)
};
Subject subject;
LinkedList<E> elements;
/** {@collect.stats}
* @serial An integer identifying the type of objects contained
* in this set. If <code>which == 1</code>,
* this is a Principal set and all the elements are
* of type <code>java.security.Principal</code>.
* If <code>which == 2</code>, this is a public credential
* set and all the elements are of type <code>Object</code>.
* If <code>which == 3</code>, this is a private credential
* set and all the elements are of type <code>Object</code>.
*/
private int which;
SecureSet(Subject subject, int which) {
this.subject = subject;
this.which = which;
this.elements = new LinkedList<E>();
}
SecureSet(Subject subject, int which, Set<? extends E> set) {
this.subject = subject;
this.which = which;
this.elements = new LinkedList<E>(set);
}
public int size() {
return elements.size();
}
public Iterator<E> iterator() {
final LinkedList<E> list = elements;
return new Iterator<E>() {
ListIterator<E> i = list.listIterator(0);
public boolean hasNext() {return i.hasNext();}
public E next() {
if (which != Subject.PRIV_CREDENTIAL_SET) {
return i.next();
}
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
try {
sm.checkPermission(new PrivateCredentialPermission
(list.get(i.nextIndex()).getClass().getName(),
subject.getPrincipals()));
} catch (SecurityException se) {
i.next();
throw (se);
}
}
return i.next();
}
public void remove() {
if (subject.isReadOnly()) {
throw new IllegalStateException(ResourcesMgr.getString
("Subject is read-only"));
}
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
switch (which) {
case Subject.PRINCIPAL_SET:
sm.checkPermission(new AuthPermission
("modifyPrincipals"));
break;
case Subject.PUB_CREDENTIAL_SET:
sm.checkPermission(new AuthPermission
("modifyPublicCredentials"));
break;
default:
sm.checkPermission(new AuthPermission
("modifyPrivateCredentials"));
break;
}
}
i.remove();
}
};
}
public boolean add(E o) {
if (subject.isReadOnly()) {
throw new IllegalStateException
(ResourcesMgr.getString("Subject is read-only"));
}
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
switch (which) {
case Subject.PRINCIPAL_SET:
sm.checkPermission
(new AuthPermission("modifyPrincipals"));
break;
case Subject.PUB_CREDENTIAL_SET:
sm.checkPermission
(new AuthPermission("modifyPublicCredentials"));
break;
default:
sm.checkPermission
(new AuthPermission("modifyPrivateCredentials"));
break;
}
}
switch (which) {
case Subject.PRINCIPAL_SET:
if (!(o instanceof Principal)) {
throw new SecurityException(ResourcesMgr.getString
("attempting to add an object which is not an " +
"instance of java.security.Principal to a " +
"Subject's Principal Set"));
}
break;
default:
// ok to add Objects of any kind to credential sets
break;
}
// check for duplicates
if (!elements.contains(o))
return elements.add(o);
else
return false;
}
public boolean remove(Object o) {
final Iterator<E> e = iterator();
while (e.hasNext()) {
E next;
if (which != Subject.PRIV_CREDENTIAL_SET) {
next = e.next();
} else {
next = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<E>() {
public E run() {
return e.next();
}
});
}
if (next == null) {
if (o == null) {
e.remove();
return true;
}
} else if (next.equals(o)) {
e.remove();
return true;
}
}
return false;
}
public boolean contains(Object o) {
final Iterator<E> e = iterator();
while (e.hasNext()) {
E next;
if (which != Subject.PRIV_CREDENTIAL_SET) {
next = e.next();
} else {
// For private credentials:
// If the caller does not have read permission for
// for o.getClass(), we throw a SecurityException.
// Otherwise we check the private cred set to see whether
// it contains the Object
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new PrivateCredentialPermission
(o.getClass().getName(),
subject.getPrincipals()));
}
next = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<E>() {
public E run() {
return e.next();
}
});
}
if (next == null) {
if (o == null) {
return true;
}
} else if (next.equals(o)) {
return true;
}
}
return false;
}
public boolean removeAll(Collection<?> c) {
boolean modified = false;
final Iterator<E> e = iterator();
while (e.hasNext()) {
E next;
if (which != Subject.PRIV_CREDENTIAL_SET) {
next = e.next();
} else {
next = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<E>() {
public E run() {
return e.next();
}
});
}
Iterator<?> ce = c.iterator();
while (ce.hasNext()) {
Object o = ce.next();
if (next == null) {
if (o == null) {
e.remove();
modified = true;
break;
}
} else if (next.equals(o)) {
e.remove();
modified = true;
break;
}
}
}
return modified;
}
public boolean retainAll(Collection<?> c) {
boolean modified = false;
boolean retain = false;
final Iterator<E> e = iterator();
while (e.hasNext()) {
retain = false;
E next;
if (which != Subject.PRIV_CREDENTIAL_SET) {
next = e.next();
} else {
next = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<E>() {
public E run() {
return e.next();
}
});
}
Iterator<?> ce = c.iterator();
while (ce.hasNext()) {
Object o = ce.next();
if (next == null) {
if (o == null) {
retain = true;
break;
}
} else if (next.equals(o)) {
retain = true;
break;
}
}
if (!retain) {
e.remove();
retain = false;
modified = true;
}
}
return modified;
}
public void clear() {
final Iterator<E> e = iterator();
while (e.hasNext()) {
E next;
if (which != Subject.PRIV_CREDENTIAL_SET) {
next = e.next();
} else {
next = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<E>() {
public E run() {
return e.next();
}
});
}
e.remove();
}
}
/** {@collect.stats}
* Writes this object out to a stream (i.e., serializes it).
*
* <p>
*
* @serialData If this is a private credential set,
* a security check is performed to ensure that
* the caller has permission to access each credential
* in the set. If the security check passes,
* the set is serialized.
*/
private void writeObject(java.io.ObjectOutputStream oos)
throws java.io.IOException {
if (which == Subject.PRIV_CREDENTIAL_SET) {
// check permissions before serializing
Iterator<E> i = iterator();
while (i.hasNext()) {
i.next();
}
}
ObjectOutputStream.PutField fields = oos.putFields();
fields.put("this$0", subject);
fields.put("elements", elements);
fields.put("which", which);
oos.writeFields();
}
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException
{
ObjectInputStream.GetField fields = ois.readFields();
subject = (Subject) fields.get("this$0", null);
elements = (LinkedList<E>) fields.get("elements", null);
which = fields.get("which", 0);
}
}
/** {@collect.stats}
* This class implements a <code>Set</code> which returns only
* members that are an instance of a specified Class.
*/
private class ClassSet<T> extends AbstractSet<T> {
private int which;
private Class<T> c;
private Set<T> set;
ClassSet(int which, Class<T> c) {
this.which = which;
this.c = c;
set = new HashSet<T>();
switch (which) {
case Subject.PRINCIPAL_SET:
synchronized(principals) { populateSet(); }
break;
case Subject.PUB_CREDENTIAL_SET:
synchronized(pubCredentials) { populateSet(); }
break;
default:
synchronized(privCredentials) { populateSet(); }
break;
}
}
private void populateSet() {
final Iterator<?> iterator;
switch(which) {
case Subject.PRINCIPAL_SET:
iterator = Subject.this.principals.iterator();
break;
case Subject.PUB_CREDENTIAL_SET:
iterator = Subject.this.pubCredentials.iterator();
break;
default:
iterator = Subject.this.privCredentials.iterator();
break;
}
// Check whether the caller has permisson to get
// credentials of Class c
while (iterator.hasNext()) {
Object next;
if (which == Subject.PRIV_CREDENTIAL_SET) {
next = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<Object>() {
public Object run() {
return iterator.next();
}
});
} else {
next = iterator.next();
}
if (c.isAssignableFrom(next.getClass())) {
if (which != Subject.PRIV_CREDENTIAL_SET) {
set.add((T)next);
} else {
// Check permission for private creds
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new PrivateCredentialPermission
(next.getClass().getName(),
Subject.this.getPrincipals()));
}
set.add((T)next);
}
}
}
}
public int size() {
return set.size();
}
public Iterator<T> iterator() {
return set.iterator();
}
public boolean add(T o) {
if (!o.getClass().isAssignableFrom(c)) {
MessageFormat form = new MessageFormat(ResourcesMgr.getString
("attempting to add an object which is not an " +
"instance of class"));
Object[] source = {c.toString()};
throw new SecurityException(form.format(source));
}
return set.add(o);
}
}
}
|
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.security.auth.callback;
/** {@collect.stats}
* <p> Underlying security services instantiate and pass a
* <code>ConfirmationCallback</code> to the <code>handle</code>
* method of a <code>CallbackHandler</code> to ask for YES/NO,
* OK/CANCEL, YES/NO/CANCEL or other similar confirmations.
*
* @see javax.security.auth.callback.CallbackHandler
*/
public class ConfirmationCallback implements Callback, java.io.Serializable {
private static final long serialVersionUID = -9095656433782481624L;
/** {@collect.stats}
* Unspecified option type.
*
* <p> The <code>getOptionType</code> method returns this
* value if this <code>ConfirmationCallback</code> was instantiated
* with <code>options</code> instead of an <code>optionType</code>.
*/
public static final int UNSPECIFIED_OPTION = -1;
/** {@collect.stats}
* YES/NO confirmation option.
*
* <p> An underlying security service specifies this as the
* <code>optionType</code> to a <code>ConfirmationCallback</code>
* constructor if it requires a confirmation which can be answered
* with either <code>YES</code> or <code>NO</code>.
*/
public static final int YES_NO_OPTION = 0;
/** {@collect.stats}
* YES/NO/CANCEL confirmation confirmation option.
*
* <p> An underlying security service specifies this as the
* <code>optionType</code> to a <code>ConfirmationCallback</code>
* constructor if it requires a confirmation which can be answered
* with either <code>YES</code>, <code>NO</code> or <code>CANCEL</code>.
*/
public static final int YES_NO_CANCEL_OPTION = 1;
/** {@collect.stats}
* OK/CANCEL confirmation confirmation option.
*
* <p> An underlying security service specifies this as the
* <code>optionType</code> to a <code>ConfirmationCallback</code>
* constructor if it requires a confirmation which can be answered
* with either <code>OK</code> or <code>CANCEL</code>.
*/
public static final int OK_CANCEL_OPTION = 2;
/** {@collect.stats}
* YES option.
*
* <p> If an <code>optionType</code> was specified to this
* <code>ConfirmationCallback</code>, this option may be specified as a
* <code>defaultOption</code> or returned as the selected index.
*/
public static final int YES = 0;
/** {@collect.stats}
* NO option.
*
* <p> If an <code>optionType</code> was specified to this
* <code>ConfirmationCallback</code>, this option may be specified as a
* <code>defaultOption</code> or returned as the selected index.
*/
public static final int NO = 1;
/** {@collect.stats}
* CANCEL option.
*
* <p> If an <code>optionType</code> was specified to this
* <code>ConfirmationCallback</code>, this option may be specified as a
* <code>defaultOption</code> or returned as the selected index.
*/
public static final int CANCEL = 2;
/** {@collect.stats}
* OK option.
*
* <p> If an <code>optionType</code> was specified to this
* <code>ConfirmationCallback</code>, this option may be specified as a
* <code>defaultOption</code> or returned as the selected index.
*/
public static final int OK = 3;
/** {@collect.stats} INFORMATION message type. */
public static final int INFORMATION = 0;
/** {@collect.stats} WARNING message type. */
public static final int WARNING = 1;
/** {@collect.stats} ERROR message type. */
public static final int ERROR = 2;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private String prompt;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private int messageType;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private int optionType = UNSPECIFIED_OPTION;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private int defaultOption;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private String[] options;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private int selection;
/** {@collect.stats}
* Construct a <code>ConfirmationCallback</code> with a
* message type, an option type and a default option.
*
* <p> Underlying security services use this constructor if
* they require either a YES/NO, YES/NO/CANCEL or OK/CANCEL
* confirmation.
*
* <p>
*
* @param messageType the message type (<code>INFORMATION</code>,
* <code>WARNING</code> or <code>ERROR</code>). <p>
*
* @param optionType the option type (<code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code> or
* <code>OK_CANCEL_OPTION</code>). <p>
*
* @param defaultOption the default option
* from the provided optionType (<code>YES</code>,
* <code>NO</code>, <code>CANCEL</code> or
* <code>OK</code>).
*
* @exception IllegalArgumentException if messageType is not either
* <code>INFORMATION</code>, <code>WARNING</code>,
* or <code>ERROR</code>, if optionType is not either
* <code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code>, or
* <code>OK_CANCEL_OPTION</code>,
* or if <code>defaultOption</code>
* does not correspond to one of the options in
* <code>optionType</code>.
*/
public ConfirmationCallback(int messageType,
int optionType, int defaultOption) {
if (messageType < INFORMATION || messageType > ERROR ||
optionType < YES_NO_OPTION || optionType > OK_CANCEL_OPTION)
throw new IllegalArgumentException();
switch (optionType) {
case YES_NO_OPTION:
if (defaultOption != YES && defaultOption != NO)
throw new IllegalArgumentException();
break;
case YES_NO_CANCEL_OPTION:
if (defaultOption != YES && defaultOption != NO &&
defaultOption != CANCEL)
throw new IllegalArgumentException();
break;
case OK_CANCEL_OPTION:
if (defaultOption != OK && defaultOption != CANCEL)
throw new IllegalArgumentException();
break;
}
this.messageType = messageType;
this.optionType = optionType;
this.defaultOption = defaultOption;
}
/** {@collect.stats}
* Construct a <code>ConfirmationCallback</code> with a
* message type, a list of options and a default option.
*
* <p> Underlying security services use this constructor if
* they require a confirmation different from the available preset
* confirmations provided (for example, CONTINUE/ABORT or STOP/GO).
* The confirmation options are listed in the <code>options</code> array,
* and are displayed by the <code>CallbackHandler</code> implementation
* in a manner consistent with the way preset options are displayed.
*
* <p>
*
* @param messageType the message type (<code>INFORMATION</code>,
* <code>WARNING</code> or <code>ERROR</code>). <p>
*
* @param options the list of confirmation options. <p>
*
* @param defaultOption the default option, represented as an index
* into the <code>options</code> array.
*
* @exception IllegalArgumentException if messageType is not either
* <code>INFORMATION</code>, <code>WARNING</code>,
* or <code>ERROR</code>, if <code>options</code> is null,
* if <code>options</code> has a length of 0,
* if any element from <code>options</code> is null,
* if any element from <code>options</code>
* has a length of 0, or if <code>defaultOption</code>
* does not lie within the array boundaries of
* <code>options</code>.
*/
public ConfirmationCallback(int messageType,
String[] options, int defaultOption) {
if (messageType < INFORMATION || messageType > ERROR ||
options == null || options.length == 0 ||
defaultOption < 0 || defaultOption >= options.length)
throw new IllegalArgumentException();
for (int i = 0; i < options.length; i++) {
if (options[i] == null || options[i].length() == 0)
throw new IllegalArgumentException();
}
this.messageType = messageType;
this.options = options;
this.defaultOption = defaultOption;
}
/** {@collect.stats}
* Construct a <code>ConfirmationCallback</code> with a prompt,
* message type, an option type and a default option.
*
* <p> Underlying security services use this constructor if
* they require either a YES/NO, YES/NO/CANCEL or OK/CANCEL
* confirmation.
*
* <p>
*
* @param prompt the prompt used to describe the list of options. <p>
*
* @param messageType the message type (<code>INFORMATION</code>,
* <code>WARNING</code> or <code>ERROR</code>). <p>
*
* @param optionType the option type (<code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code> or
* <code>OK_CANCEL_OPTION</code>). <p>
*
* @param defaultOption the default option
* from the provided optionType (<code>YES</code>,
* <code>NO</code>, <code>CANCEL</code> or
* <code>OK</code>).
*
* @exception IllegalArgumentException if <code>prompt</code> is null,
* if <code>prompt</code> has a length of 0,
* if messageType is not either
* <code>INFORMATION</code>, <code>WARNING</code>,
* or <code>ERROR</code>, if optionType is not either
* <code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code>, or
* <code>OK_CANCEL_OPTION</code>,
* or if <code>defaultOption</code>
* does not correspond to one of the options in
* <code>optionType</code>.
*/
public ConfirmationCallback(String prompt, int messageType,
int optionType, int defaultOption) {
if (prompt == null || prompt.length() == 0 ||
messageType < INFORMATION || messageType > ERROR ||
optionType < YES_NO_OPTION || optionType > OK_CANCEL_OPTION)
throw new IllegalArgumentException();
switch (optionType) {
case YES_NO_OPTION:
if (defaultOption != YES && defaultOption != NO)
throw new IllegalArgumentException();
break;
case YES_NO_CANCEL_OPTION:
if (defaultOption != YES && defaultOption != NO &&
defaultOption != CANCEL)
throw new IllegalArgumentException();
break;
case OK_CANCEL_OPTION:
if (defaultOption != OK && defaultOption != CANCEL)
throw new IllegalArgumentException();
break;
}
this.prompt = prompt;
this.messageType = messageType;
this.optionType = optionType;
this.defaultOption = defaultOption;
}
/** {@collect.stats}
* Construct a <code>ConfirmationCallback</code> with a prompt,
* message type, a list of options and a default option.
*
* <p> Underlying security services use this constructor if
* they require a confirmation different from the available preset
* confirmations provided (for example, CONTINUE/ABORT or STOP/GO).
* The confirmation options are listed in the <code>options</code> array,
* and are displayed by the <code>CallbackHandler</code> implementation
* in a manner consistent with the way preset options are displayed.
*
* <p>
*
* @param prompt the prompt used to describe the list of options. <p>
*
* @param messageType the message type (<code>INFORMATION</code>,
* <code>WARNING</code> or <code>ERROR</code>). <p>
*
* @param options the list of confirmation options. <p>
*
* @param defaultOption the default option, represented as an index
* into the <code>options</code> array.
*
* @exception IllegalArgumentException if <code>prompt</code> is null,
* if <code>prompt</code> has a length of 0,
* if messageType is not either
* <code>INFORMATION</code>, <code>WARNING</code>,
* or <code>ERROR</code>, if <code>options</code> is null,
* if <code>options</code> has a length of 0,
* if any element from <code>options</code> is null,
* if any element from <code>options</code>
* has a length of 0, or if <code>defaultOption</code>
* does not lie within the array boundaries of
* <code>options</code>.
*/
public ConfirmationCallback(String prompt, int messageType,
String[] options, int defaultOption) {
if (prompt == null || prompt.length() == 0 ||
messageType < INFORMATION || messageType > ERROR ||
options == null || options.length == 0 ||
defaultOption < 0 || defaultOption >= options.length)
throw new IllegalArgumentException();
for (int i = 0; i < options.length; i++) {
if (options[i] == null || options[i].length() == 0)
throw new IllegalArgumentException();
}
this.prompt = prompt;
this.messageType = messageType;
this.options = options;
this.defaultOption = defaultOption;
}
/** {@collect.stats}
* Get the prompt.
*
* <p>
*
* @return the prompt, or null if this <code>ConfirmationCallback</code>
* was instantiated without a <code>prompt</code>.
*/
public String getPrompt() {
return prompt;
}
/** {@collect.stats}
* Get the message type.
*
* <p>
*
* @return the message type (<code>INFORMATION</code>,
* <code>WARNING</code> or <code>ERROR</code>).
*/
public int getMessageType() {
return messageType;
}
/** {@collect.stats}
* Get the option type.
*
* <p> If this method returns <code>UNSPECIFIED_OPTION</code>, then this
* <code>ConfirmationCallback</code> was instantiated with
* <code>options</code> instead of an <code>optionType</code>.
* In this case, invoke the <code>getOptions</code> method
* to determine which confirmation options to display.
*
* <p>
*
* @return the option type (<code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code> or
* <code>OK_CANCEL_OPTION</code>), or
* <code>UNSPECIFIED_OPTION</code> if this
* <code>ConfirmationCallback</code> was instantiated with
* <code>options</code> instead of an <code>optionType</code>.
*/
public int getOptionType() {
return optionType;
}
/** {@collect.stats}
* Get the confirmation options.
*
* <p>
*
* @return the list of confirmation options, or null if this
* <code>ConfirmationCallback</code> was instantiated with
* an <code>optionType</code> instead of <code>options</code>.
*/
public String[] getOptions() {
return options;
}
/** {@collect.stats}
* Get the default option.
*
* <p>
*
* @return the default option, represented as
* <code>YES</code>, <code>NO</code>, <code>OK</code> or
* <code>CANCEL</code> if an <code>optionType</code>
* was specified to the constructor of this
* <code>ConfirmationCallback</code>.
* Otherwise, this method returns the default option as
* an index into the
* <code>options</code> array specified to the constructor
* of this <code>ConfirmationCallback</code>.
*/
public int getDefaultOption() {
return defaultOption;
}
/** {@collect.stats}
* Set the selected confirmation option.
*
* <p>
*
* @param selection the selection represented as <code>YES</code>,
* <code>NO</code>, <code>OK</code> or <code>CANCEL</code>
* if an <code>optionType</code> was specified to the constructor
* of this <code>ConfirmationCallback</code>.
* Otherwise, the selection represents the index into the
* <code>options</code> array specified to the constructor
* of this <code>ConfirmationCallback</code>.
*
* @see #getSelectedIndex
*/
public void setSelectedIndex(int selection) {
this.selection = selection;
}
/** {@collect.stats}
* Get the selected confirmation option.
*
* <p>
*
* @return the selected confirmation option represented as
* <code>YES</code>, <code>NO</code>, <code>OK</code> or
* <code>CANCEL</code> if an <code>optionType</code>
* was specified to the constructor of this
* <code>ConfirmationCallback</code>.
* Otherwise, this method returns the selected confirmation
* option as an index into the
* <code>options</code> array specified to the constructor
* of this <code>ConfirmationCallback</code>.
*
* @see #setSelectedIndex
*/
public int getSelectedIndex() {
return selection;
}
}
|
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.security.auth.callback;
/** {@collect.stats}
* <p> An application implements a <code>CallbackHandler</code> and passes
* it to underlying security services so that they may interact with
* the application to retrieve specific authentication data,
* such as usernames and passwords, or to display certain information,
* such as error and warning messages.
*
* <p> CallbackHandlers are implemented in an application-dependent fashion.
* For example, implementations for an application with a graphical user
* interface (GUI) may pop up windows to prompt for requested information
* or to display error messages. An implementation may also choose to obtain
* requested information from an alternate source without asking the end user.
*
* <p> Underlying security services make requests for different types
* of information by passing individual Callbacks to the
* <code>CallbackHandler</code>. The <code>CallbackHandler</code>
* implementation decides how to retrieve and display information
* depending on the Callbacks passed to it. For example,
* if the underlying service needs a username and password to
* authenticate a user, it uses a <code>NameCallback</code> and
* <code>PasswordCallback</code>. The <code>CallbackHandler</code>
* can then choose to prompt for a username and password serially,
* or to prompt for both in a single window.
*
* <p> A default <code>CallbackHandler</code> class implementation
* may be specified in the <i>auth.login.defaultCallbackHandler</i>
* security property. The security property can be set
* in the Java security properties file located in the file named
* <JAVA_HOME>/lib/security/java.security.
* <JAVA_HOME> refers to the value of the java.home system property,
* and specifies the directory where the JRE is installed.
*
* <p> If the security property is set to the fully qualified name of a
* <code>CallbackHandler</code> implementation class,
* then a <code>LoginContext</code> will load the specified
* <code>CallbackHandler</code> and pass it to the underlying LoginModules.
* The <code>LoginContext</code> only loads the default handler
* if it was not provided one.
*
* <p> All default handler implementations must provide a public
* zero-argument constructor.
*
*/
public interface CallbackHandler {
/** {@collect.stats}
* <p> Retrieve or display the information requested in the
* provided Callbacks.
*
* <p> The <code>handle</code> method implementation checks the
* instance(s) of the <code>Callback</code> object(s) passed in
* to retrieve or display the requested information.
* The following example is provided to help demonstrate what an
* <code>handle</code> method implementation might look like.
* This example code is for guidance only. Many details,
* including proper error handling, are left out for simplicity.
*
* <pre>
* public void handle(Callback[] callbacks)
* throws IOException, UnsupportedCallbackException {
*
* for (int i = 0; i < callbacks.length; i++) {
* if (callbacks[i] instanceof TextOutputCallback) {
*
* // display the message according to the specified type
* TextOutputCallback toc = (TextOutputCallback)callbacks[i];
* switch (toc.getMessageType()) {
* case TextOutputCallback.INFORMATION:
* System.out.println(toc.getMessage());
* break;
* case TextOutputCallback.ERROR:
* System.out.println("ERROR: " + toc.getMessage());
* break;
* case TextOutputCallback.WARNING:
* System.out.println("WARNING: " + toc.getMessage());
* break;
* default:
* throw new IOException("Unsupported message type: " +
* toc.getMessageType());
* }
*
* } else if (callbacks[i] instanceof NameCallback) {
*
* // prompt the user for a username
* NameCallback nc = (NameCallback)callbacks[i];
*
* // ignore the provided defaultName
* System.err.print(nc.getPrompt());
* System.err.flush();
* nc.setName((new BufferedReader
* (new InputStreamReader(System.in))).readLine());
*
* } else if (callbacks[i] instanceof PasswordCallback) {
*
* // prompt the user for sensitive information
* PasswordCallback pc = (PasswordCallback)callbacks[i];
* System.err.print(pc.getPrompt());
* System.err.flush();
* pc.setPassword(readPassword(System.in));
*
* } else {
* throw new UnsupportedCallbackException
* (callbacks[i], "Unrecognized Callback");
* }
* }
* }
*
* // Reads user password from given input stream.
* private char[] readPassword(InputStream in) throws IOException {
* // insert code to read a user password from the input stream
* }
* </pre>
*
* @param callbacks an array of <code>Callback</code> objects provided
* by an underlying security service which contains
* the information requested to be retrieved or displayed.
*
* @exception java.io.IOException if an input or output error occurs. <p>
*
* @exception UnsupportedCallbackException if the implementation of this
* method does not support one or more of the Callbacks
* specified in the <code>callbacks</code> parameter.
*/
void handle(Callback[] callbacks)
throws java.io.IOException, UnsupportedCallbackException;
}
|
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.security.auth.callback;
/** {@collect.stats}
* <p> Underlying security services instantiate and pass a
* <code>NameCallback</code> to the <code>handle</code>
* method of a <code>CallbackHandler</code> to retrieve name information.
*
* @see javax.security.auth.callback.CallbackHandler
*/
public class NameCallback implements Callback, java.io.Serializable {
private static final long serialVersionUID = 3770938795909392253L;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private String prompt;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private String defaultName;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private String inputName;
/** {@collect.stats}
* Construct a <code>NameCallback</code> with a prompt.
*
* <p>
*
* @param prompt the prompt used to request the name.
*
* @exception IllegalArgumentException if <code>prompt</code> is null
* or if <code>prompt</code> has a length of 0.
*/
public NameCallback(String prompt) {
if (prompt == null || prompt.length() == 0)
throw new IllegalArgumentException();
this.prompt = prompt;
}
/** {@collect.stats}
* Construct a <code>NameCallback</code> with a prompt
* and default name.
*
* <p>
*
* @param prompt the prompt used to request the information. <p>
*
* @param defaultName the name to be used as the default name displayed
* with the prompt.
*
* @exception IllegalArgumentException if <code>prompt</code> is null,
* if <code>prompt</code> has a length of 0,
* if <code>defaultName</code> is null,
* or if <code>defaultName</code> has a length of 0.
*/
public NameCallback(String prompt, String defaultName) {
if (prompt == null || prompt.length() == 0 ||
defaultName == null || defaultName.length() == 0)
throw new IllegalArgumentException();
this.prompt = prompt;
this.defaultName = defaultName;
}
/** {@collect.stats}
* Get the prompt.
*
* <p>
*
* @return the prompt.
*/
public String getPrompt() {
return prompt;
}
/** {@collect.stats}
* Get the default name.
*
* <p>
*
* @return the default name, or null if this <code>NameCallback</code>
* was not instantiated with a <code>defaultName</code>.
*/
public String getDefaultName() {
return defaultName;
}
/** {@collect.stats}
* Set the retrieved name.
*
* <p>
*
* @param name the retrieved name (which may be null).
*
* @see #getName
*/
public void setName(String name) {
this.inputName = name;
}
/** {@collect.stats}
* Get the retrieved name.
*
* <p>
*
* @return the retrieved name (which may be null)
*
* @see #setName
*/
public String getName() {
return inputName;
}
}
|
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.security.auth.callback;
/** {@collect.stats}
* Signals that a <code>CallbackHandler</code> does not
* recognize a particular <code>Callback</code>.
*
*/
public class UnsupportedCallbackException extends Exception {
private static final long serialVersionUID = -6873556327655666839L;
/** {@collect.stats}
* @serial
*/
private Callback callback;
/** {@collect.stats}
* Constructs a <code>UnsupportedCallbackException</code>
* with no detail message.
*
* <p>
*
* @param callback the unrecognized <code>Callback</code>.
*/
public UnsupportedCallbackException(Callback callback) {
super();
this.callback = callback;
}
/** {@collect.stats}
* Constructs a UnsupportedCallbackException with the specified detail
* message. A detail message is a String that describes this particular
* exception.
*
* <p>
*
* @param callback the unrecognized <code>Callback</code>. <p>
*
* @param msg the detail message.
*/
public UnsupportedCallbackException(Callback callback, String msg) {
super(msg);
this.callback = callback;
}
/** {@collect.stats}
* Get the unrecognized <code>Callback</code>.
*
* <p>
*
* @return the unrecognized <code>Callback</code>.
*/
public Callback getCallback() {
return callback;
}
}
|
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.security.auth.callback;
/** {@collect.stats}
* <p> Implementations of this interface are passed to a
* <code>CallbackHandler</code>, allowing underlying security services
* the ability to interact with a calling application to retrieve specific
* authentication data such as usernames and passwords, or to display
* certain information, such as error and warning messages.
*
* <p> <code>Callback</code> implementations do not retrieve or
* display the information requested by underlying security services.
* <code>Callback</code> implementations simply provide the means
* to pass such requests to applications, and for applications,
* if appropriate, to return requested information back to the
* underlying security services.
*
* @see javax.security.auth.callback.CallbackHandler
* @see javax.security.auth.callback.ChoiceCallback
* @see javax.security.auth.callback.ConfirmationCallback
* @see javax.security.auth.callback.LanguageCallback
* @see javax.security.auth.callback.NameCallback
* @see javax.security.auth.callback.PasswordCallback
* @see javax.security.auth.callback.TextInputCallback
* @see javax.security.auth.callback.TextOutputCallback
*/
public interface Callback { }
|
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.security.auth.callback;
/** {@collect.stats}
* <p> Underlying security services instantiate and pass a
* <code>ChoiceCallback</code> to the <code>handle</code>
* method of a <code>CallbackHandler</code> to display a list of choices
* and to retrieve the selected choice(s).
*
* @see javax.security.auth.callback.CallbackHandler
*/
public class ChoiceCallback implements Callback, java.io.Serializable {
private static final long serialVersionUID = -3975664071579892167L;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private String prompt;
/** {@collect.stats}
* @serial the list of choices
* @since 1.4
*/
private String[] choices;
/** {@collect.stats}
* @serial the choice to be used as the default choice
* @since 1.4
*/
private int defaultChoice;
/** {@collect.stats}
* @serial whether multiple selections are allowed from the list of
* choices
* @since 1.4
*/
private boolean multipleSelectionsAllowed;
/** {@collect.stats}
* @serial the selected choices, represented as indexes into the
* <code>choices</code> list.
* @since 1.4
*/
private int[] selections;
/** {@collect.stats}
* Construct a <code>ChoiceCallback</code> with a prompt,
* a list of choices, a default choice, and a boolean specifying
* whether or not multiple selections from the list of choices are allowed.
*
* <p>
*
* @param prompt the prompt used to describe the list of choices. <p>
*
* @param choices the list of choices. <p>
*
* @param defaultChoice the choice to be used as the default choice
* when the list of choices are displayed. This value
* is represented as an index into the
* <code>choices</code> array. <p>
*
* @param multipleSelectionsAllowed boolean specifying whether or
* not multiple selections can be made from the
* list of choices.
*
* @exception IllegalArgumentException if <code>prompt</code> is null,
* if <code>prompt</code> has a length of 0,
* if <code>choices</code> is null,
* if <code>choices</code> has a length of 0,
* if any element from <code>choices</code> is null,
* if any element from <code>choices</code>
* has a length of 0 or if <code>defaultChoice</code>
* does not fall within the array boundaries of
* <code>choices</code>.
*/
public ChoiceCallback(String prompt, String[] choices,
int defaultChoice, boolean multipleSelectionsAllowed) {
if (prompt == null || prompt.length() == 0 ||
choices == null || choices.length == 0 ||
defaultChoice < 0 || defaultChoice >= choices.length)
throw new IllegalArgumentException();
for (int i = 0; i < choices.length; i++) {
if (choices[i] == null || choices[i].length() == 0)
throw new IllegalArgumentException();
}
this.prompt = prompt;
this.choices = choices;
this.defaultChoice = defaultChoice;
this.multipleSelectionsAllowed = multipleSelectionsAllowed;
}
/** {@collect.stats}
* Get the prompt.
*
* <p>
*
* @return the prompt.
*/
public String getPrompt() {
return prompt;
}
/** {@collect.stats}
* Get the list of choices.
*
* <p>
*
* @return the list of choices.
*/
public String[] getChoices() {
return choices;
}
/** {@collect.stats}
* Get the defaultChoice.
*
* <p>
*
* @return the defaultChoice, represented as an index into
* the <code>choices</code> list.
*/
public int getDefaultChoice() {
return defaultChoice;
}
/** {@collect.stats}
* Get the boolean determining whether multiple selections from
* the <code>choices</code> list are allowed.
*
* <p>
*
* @return whether multiple selections are allowed.
*/
public boolean allowMultipleSelections() {
return multipleSelectionsAllowed;
}
/** {@collect.stats}
* Set the selected choice.
*
* <p>
*
* @param selection the selection represented as an index into the
* <code>choices</code> list.
*
* @see #getSelectedIndexes
*/
public void setSelectedIndex(int selection) {
this.selections = new int[1];
this.selections[0] = selection;
}
/** {@collect.stats}
* Set the selected choices.
*
* <p>
*
* @param selections the selections represented as indexes into the
* <code>choices</code> list.
*
* @exception UnsupportedOperationException if multiple selections are
* not allowed, as determined by
* <code>allowMultipleSelections</code>.
*
* @see #getSelectedIndexes
*/
public void setSelectedIndexes(int[] selections) {
if (!multipleSelectionsAllowed)
throw new UnsupportedOperationException();
this.selections = selections;
}
/** {@collect.stats}
* Get the selected choices.
*
* <p>
*
* @return the selected choices, represented as indexes into the
* <code>choices</code> list.
*
* @see #setSelectedIndexes
*/
public int[] getSelectedIndexes() {
return selections;
}
}
|
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.security.auth.callback;
/** {@collect.stats}
* <p> Underlying security services instantiate and pass a
* <code>TextOutputCallback</code> to the <code>handle</code>
* method of a <code>CallbackHandler</code> to display information messages,
* warning messages and error messages.
*
* @see javax.security.auth.callback.CallbackHandler
*/
public class TextOutputCallback implements Callback, java.io.Serializable {
private static final long serialVersionUID = 1689502495511663102L;
/** {@collect.stats} Information message. */
public static final int INFORMATION = 0;
/** {@collect.stats} Warning message. */
public static final int WARNING = 1;
/** {@collect.stats} Error message. */
public static final int ERROR = 2;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private int messageType;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private String message;
/** {@collect.stats}
* Construct a TextOutputCallback with a message type and message
* to be displayed.
*
* <p>
*
* @param messageType the message type (<code>INFORMATION</code>,
* <code>WARNING</code> or <code>ERROR</code>). <p>
*
* @param message the message to be displayed. <p>
*
* @exception IllegalArgumentException if <code>messageType</code>
* is not either <code>INFORMATION</code>,
* <code>WARNING</code> or <code>ERROR</code>,
* if <code>message</code> is null,
* or if <code>message</code> has a length of 0.
*/
public TextOutputCallback(int messageType, String message) {
if ((messageType != INFORMATION &&
messageType != WARNING && messageType != ERROR) ||
message == null || message.length() == 0)
throw new IllegalArgumentException();
this.messageType = messageType;
this.message = message;
}
/** {@collect.stats}
* Get the message type.
*
* <p>
*
* @return the message type (<code>INFORMATION</code>,
* <code>WARNING</code> or <code>ERROR</code>).
*/
public int getMessageType() {
return messageType;
}
/** {@collect.stats}
* Get the message to be displayed.
*
* <p>
*
* @return the message to be displayed.
*/
public String getMessage() {
return message;
}
}
|
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.security.auth.callback;
/** {@collect.stats}
* <p> Underlying security services instantiate and pass a
* <code>TextInputCallback</code> to the <code>handle</code>
* method of a <code>CallbackHandler</code> to retrieve generic text
* information.
*
* @see javax.security.auth.callback.CallbackHandler
*/
public class TextInputCallback implements Callback, java.io.Serializable {
private static final long serialVersionUID = -8064222478852811804L;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private String prompt;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private String defaultText;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private String inputText;
/** {@collect.stats}
* Construct a <code>TextInputCallback</code> with a prompt.
*
* <p>
*
* @param prompt the prompt used to request the information.
*
* @exception IllegalArgumentException if <code>prompt</code> is null
* or if <code>prompt</code> has a length of 0.
*/
public TextInputCallback(String prompt) {
if (prompt == null || prompt.length() == 0)
throw new IllegalArgumentException();
this.prompt = prompt;
}
/** {@collect.stats}
* Construct a <code>TextInputCallback</code> with a prompt
* and default input value.
*
* <p>
*
* @param prompt the prompt used to request the information. <p>
*
* @param defaultText the text to be used as the default text displayed
* with the prompt.
*
* @exception IllegalArgumentException if <code>prompt</code> is null,
* if <code>prompt</code> has a length of 0,
* if <code>defaultText</code> is null
* or if <code>defaultText</code> has a length of 0.
*/
public TextInputCallback(String prompt, String defaultText) {
if (prompt == null || prompt.length() == 0 ||
defaultText == null || defaultText.length() == 0)
throw new IllegalArgumentException();
this.prompt = prompt;
this.defaultText = defaultText;
}
/** {@collect.stats}
* Get the prompt.
*
* <p>
*
* @return the prompt.
*/
public String getPrompt() {
return prompt;
}
/** {@collect.stats}
* Get the default text.
*
* <p>
*
* @return the default text, or null if this <code>TextInputCallback</code>
* was not instantiated with <code>defaultText</code>.
*/
public String getDefaultText() {
return defaultText;
}
/** {@collect.stats}
* Set the retrieved text.
*
* <p>
*
* @param text the retrieved text, which may be null.
*
* @see #getText
*/
public void setText(String text) {
this.inputText = text;
}
/** {@collect.stats}
* Get the retrieved text.
*
* <p>
*
* @return the retrieved text, which may be null.
*
* @see #setText
*/
public String getText() {
return inputText;
}
}
|
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.security.auth.callback;
import java.util.Locale;
/** {@collect.stats}
* <p> Underlying security services instantiate and pass a
* <code>LanguageCallback</code> to the <code>handle</code>
* method of a <code>CallbackHandler</code> to retrieve the <code>Locale</code>
* used for localizing text.
*
* @see javax.security.auth.callback.CallbackHandler
*/
public class LanguageCallback implements Callback, java.io.Serializable {
private static final long serialVersionUID = 2019050433478903213L;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private Locale locale;
/** {@collect.stats}
* Construct a <code>LanguageCallback</code>.
*/
public LanguageCallback() { }
/** {@collect.stats}
* Set the retrieved <code>Locale</code>.
*
* <p>
*
* @param locale the retrieved <code>Locale</code>.
*
* @see #getLocale
*/
public void setLocale(Locale locale) {
this.locale = locale;
}
/** {@collect.stats}
* Get the retrieved <code>Locale</code>.
*
* <p>
*
* @return the retrieved <code>Locale</code>, or null
* if no <code>Locale</code> could be retrieved.
*
* @see #setLocale
*/
public Locale getLocale() {
return locale;
}
}
|
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.security.auth.callback;
/** {@collect.stats}
* <p> Underlying security services instantiate and pass a
* <code>PasswordCallback</code> to the <code>handle</code>
* method of a <code>CallbackHandler</code> to retrieve password information.
*
* @see javax.security.auth.callback.CallbackHandler
*/
public class PasswordCallback implements Callback, java.io.Serializable {
private static final long serialVersionUID = 2267422647454909926L;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private String prompt;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private boolean echoOn;
/** {@collect.stats}
* @serial
* @since 1.4
*/
private char[] inputPassword;
/** {@collect.stats}
* Construct a <code>PasswordCallback</code> with a prompt
* and a boolean specifying whether the password should be displayed
* as it is being typed.
*
* <p>
*
* @param prompt the prompt used to request the password. <p>
*
* @param echoOn true if the password should be displayed
* as it is being typed.
*
* @exception IllegalArgumentException if <code>prompt</code> is null or
* if <code>prompt</code> has a length of 0.
*/
public PasswordCallback(String prompt, boolean echoOn) {
if (prompt == null || prompt.length() == 0)
throw new IllegalArgumentException();
this.prompt = prompt;
this.echoOn = echoOn;
}
/** {@collect.stats}
* Get the prompt.
*
* <p>
*
* @return the prompt.
*/
public String getPrompt() {
return prompt;
}
/** {@collect.stats}
* Return whether the password
* should be displayed as it is being typed.
*
* <p>
*
* @return the whether the password
* should be displayed as it is being typed.
*/
public boolean isEchoOn() {
return echoOn;
}
/** {@collect.stats}
* Set the retrieved password.
*
* <p> This method makes a copy of the input <i>password</i>
* before storing it.
*
* <p>
*
* @param password the retrieved password, which may be null.
*
* @see #getPassword
*/
public void setPassword(char[] password) {
this.inputPassword = (password == null ? null : password.clone());
}
/** {@collect.stats}
* Get the retrieved password.
*
* <p> This method returns a copy of the retrieved password.
*
* <p>
*
* @return the retrieved password, which may be null.
*
* @see #setPassword
*/
public char[] getPassword() {
return (inputPassword == null ? null : inputPassword.clone());
}
/** {@collect.stats}
* Clear the retrieved password.
*/
public void clearPassword() {
if (inputPassword != null) {
for (int i = 0; i < inputPassword.length; i++)
inputPassword[i] = ' ';
}
}
}
|
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.security.auth.spi;
import javax.security.auth.Subject;
import javax.security.auth.AuthPermission;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import java.util.Map;
/** {@collect.stats}
* <p> <code>LoginModule</code> describes the interface
* implemented by authentication technology providers. LoginModules
* are plugged in under applications to provide a particular type of
* authentication.
*
* <p> While applications write to the <code>LoginContext</code> API,
* authentication technology providers implement the
* <code>LoginModule</code> interface.
* A <code>Configuration</code> specifies the LoginModule(s)
* to be used with a particular login application. Therefore different
* LoginModules can be plugged in under the application without
* requiring any modifications to the application itself.
*
* <p> The <code>LoginContext</code> is responsible for reading the
* <code>Configuration</code> and instantiating the appropriate
* LoginModules. Each <code>LoginModule</code> is initialized with
* a <code>Subject</code>, a <code>CallbackHandler</code>, shared
* <code>LoginModule</code> state, and LoginModule-specific options.
*
* The <code>Subject</code> represents the
* <code>Subject</code> currently being authenticated and is updated
* with relevant Credentials if authentication succeeds.
* LoginModules use the <code>CallbackHandler</code> to
* communicate with users. The <code>CallbackHandler</code> may be
* used to prompt for usernames and passwords, for example.
* Note that the <code>CallbackHandler</code> may be null. LoginModules
* which absolutely require a <code>CallbackHandler</code> to authenticate
* the <code>Subject</code> may throw a <code>LoginException</code>.
* LoginModules optionally use the shared state to share information
* or data among themselves.
*
* <p> The LoginModule-specific options represent the options
* configured for this <code>LoginModule</code> by an administrator or user
* in the login <code>Configuration</code>.
* The options are defined by the <code>LoginModule</code> itself
* and control the behavior within it. For example, a
* <code>LoginModule</code> may define options to support debugging/testing
* capabilities. Options are defined using a key-value syntax,
* such as <i>debug=true</i>. The <code>LoginModule</code>
* stores the options as a <code>Map</code> so that the values may
* be retrieved using the key. Note that there is no limit to the number
* of options a <code>LoginModule</code> chooses to define.
*
* <p> The calling application sees the authentication process as a single
* operation. However, the authentication process within the
* <code>LoginModule</code> proceeds in two distinct phases.
* In the first phase, the LoginModule's
* <code>login</code> method gets invoked by the LoginContext's
* <code>login</code> method. The <code>login</code>
* method for the <code>LoginModule</code> then performs
* the actual authentication (prompt for and verify a password for example)
* and saves its authentication status as private state
* information. Once finished, the LoginModule's <code>login</code>
* method either returns <code>true</code> (if it succeeded) or
* <code>false</code> (if it should be ignored), or throws a
* <code>LoginException</code> to specify a failure.
* In the failure case, the <code>LoginModule</code> must not retry the
* authentication or introduce delays. The responsibility of such tasks
* belongs to the application. If the application attempts to retry
* the authentication, the LoginModule's <code>login</code> method will be
* called again.
*
* <p> In the second phase, if the LoginContext's overall authentication
* succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL
* LoginModules succeeded), then the <code>commit</code>
* method for the <code>LoginModule</code> gets invoked.
* The <code>commit</code> method for a <code>LoginModule</code> checks its
* privately saved state to see if its own authentication succeeded.
* If the overall <code>LoginContext</code> authentication succeeded
* and the LoginModule's own authentication succeeded, then the
* <code>commit</code> method associates the relevant
* Principals (authenticated identities) and Credentials (authentication data
* such as cryptographic keys) with the <code>Subject</code>
* located within the <code>LoginModule</code>.
*
* <p> If the LoginContext's overall authentication failed (the relevant
* REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules did not succeed),
* then the <code>abort</code> method for each <code>LoginModule</code>
* gets invoked. In this case, the <code>LoginModule</code> removes/destroys
* any authentication state originally saved.
*
* <p> Logging out a <code>Subject</code> involves only one phase.
* The <code>LoginContext</code> invokes the LoginModule's <code>logout</code>
* method. The <code>logout</code> method for the <code>LoginModule</code>
* then performs the logout procedures, such as removing Principals or
* Credentials from the <code>Subject</code> or logging session information.
*
* <p> A <code>LoginModule</code> implementation must have a constructor with
* no arguments. This allows classes which load the <code>LoginModule</code>
* to instantiate it.
*
* @see javax.security.auth.login.LoginContext
* @see javax.security.auth.login.Configuration
*/
public interface LoginModule {
/** {@collect.stats}
* Initialize this LoginModule.
*
* <p> This method is called by the <code>LoginContext</code>
* after this <code>LoginModule</code> has been instantiated.
* The purpose of this method is to initialize this
* <code>LoginModule</code> with the relevant information.
* If this <code>LoginModule</code> does not understand
* any of the data stored in <code>sharedState</code> or
* <code>options</code> parameters, they can be ignored.
*
* <p>
*
* @param subject the <code>Subject</code> to be authenticated. <p>
*
* @param callbackHandler a <code>CallbackHandler</code> for communicating
* with the end user (prompting for usernames and
* passwords, for example). <p>
*
* @param sharedState state shared with other configured LoginModules. <p>
*
* @param options options specified in the login
* <code>Configuration</code> for this particular
* <code>LoginModule</code>.
*/
void initialize(Subject subject, CallbackHandler callbackHandler,
Map<String,?> sharedState,
Map<String,?> options);
/** {@collect.stats}
* Method to authenticate a <code>Subject</code> (phase 1).
*
* <p> The implementation of this method authenticates
* a <code>Subject</code>. For example, it may prompt for
* <code>Subject</code> information such
* as a username and password and then attempt to verify the password.
* This method saves the result of the authentication attempt
* as private state within the LoginModule.
*
* <p>
*
* @exception LoginException if the authentication fails
*
* @return true if the authentication succeeded, or false if this
* <code>LoginModule</code> should be ignored.
*/
boolean login() throws LoginException;
/** {@collect.stats}
* Method to commit the authentication process (phase 2).
*
* <p> This method is called if the LoginContext's
* overall authentication succeeded
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* succeeded).
*
* <p> If this LoginModule's own authentication attempt
* succeeded (checked by retrieving the private state saved by the
* <code>login</code> method), then this method associates relevant
* Principals and Credentials with the <code>Subject</code> located in the
* <code>LoginModule</code>. If this LoginModule's own
* authentication attempted failed, then this method removes/destroys
* any state that was originally saved.
*
* <p>
*
* @exception LoginException if the commit fails
*
* @return true if this method succeeded, or false if this
* <code>LoginModule</code> should be ignored.
*/
boolean commit() throws LoginException;
/** {@collect.stats}
* Method to abort the authentication process (phase 2).
*
* <p> This method is called if the LoginContext's
* overall authentication failed.
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* did not succeed).
*
* <p> If this LoginModule's own authentication attempt
* succeeded (checked by retrieving the private state saved by the
* <code>login</code> method), then this method cleans up any state
* that was originally saved.
*
* <p>
*
* @exception LoginException if the abort fails
*
* @return true if this method succeeded, or false if this
* <code>LoginModule</code> should be ignored.
*/
boolean abort() throws LoginException;
/** {@collect.stats}
* Method which logs out a <code>Subject</code>.
*
* <p>An implementation of this method might remove/destroy a Subject's
* Principals and Credentials.
*
* <p>
*
* @exception LoginException if the logout fails
*
* @return true if this method succeeded, or false if this
* <code>LoginModule</code> should be ignored.
*/
boolean logout() throws LoginException;
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth.login;
import java.util.Map;
import java.util.Collections;
/** {@collect.stats}
* This class represents a single <code>LoginModule</code> entry
* configured for the application specified in the
* <code>getAppConfigurationEntry(String appName)</code>
* method in the <code>Configuration</code> class. Each respective
* <code>AppConfigurationEntry</code> contains a <code>LoginModule</code> name,
* a control flag (specifying whether this <code>LoginModule</code> is
* REQUIRED, REQUISITE, SUFFICIENT, or OPTIONAL), and LoginModule-specific
* options. Please refer to the <code>Configuration</code> class for
* more information on the different control flags and their semantics.
*
* @see javax.security.auth.login.Configuration
*/
public class AppConfigurationEntry {
private String loginModuleName;
private LoginModuleControlFlag controlFlag;
private Map<String,?> options;
/** {@collect.stats}
* Default constructor for this class.
*
* <p> This entry represents a single <code>LoginModule</code>
* entry configured for the application specified in the
* <code>getAppConfigurationEntry(String appName)</code>
* method from the <code>Configuration</code> class.
*
* @param loginModuleName String representing the class name of the
* <code>LoginModule</code> configured for the
* specified application. <p>
*
* @param controlFlag either REQUIRED, REQUISITE, SUFFICIENT,
* or OPTIONAL. <p>
*
* @param options the options configured for this <code>LoginModule</code>.
*
* @exception IllegalArgumentException if <code>loginModuleName</code>
* is null, if <code>LoginModuleName</code>
* has a length of 0, if <code>controlFlag</code>
* is not either REQUIRED, REQUISITE, SUFFICIENT
* or OPTIONAL, or if <code>options</code> is null.
*/
public AppConfigurationEntry(String loginModuleName,
LoginModuleControlFlag controlFlag,
Map<String,?> options)
{
if (loginModuleName == null || loginModuleName.length() == 0 ||
(controlFlag != LoginModuleControlFlag.REQUIRED &&
controlFlag != LoginModuleControlFlag.REQUISITE &&
controlFlag != LoginModuleControlFlag.SUFFICIENT &&
controlFlag != LoginModuleControlFlag.OPTIONAL) ||
options == null)
throw new IllegalArgumentException();
this.loginModuleName = loginModuleName;
this.controlFlag = controlFlag;
this.options = Collections.unmodifiableMap(options);
}
/** {@collect.stats}
* Get the class name of the configured <code>LoginModule</code>.
*
* @return the class name of the configured <code>LoginModule</code> as
* a String.
*/
public String getLoginModuleName() {
return loginModuleName;
}
/** {@collect.stats}
* Return the controlFlag
* (either REQUIRED, REQUISITE, SUFFICIENT, or OPTIONAL)
* for this <code>LoginModule</code>.
*
* @return the controlFlag
* (either REQUIRED, REQUISITE, SUFFICIENT, or OPTIONAL)
* for this <code>LoginModule</code>.
*/
public LoginModuleControlFlag getControlFlag() {
return controlFlag;
}
/** {@collect.stats}
* Get the options configured for this <code>LoginModule</code>.
*
* @return the options configured for this <code>LoginModule</code>
* as an unmodifiable <code>Map</code>.
*/
public Map<String,?> getOptions() {
return options;
}
/** {@collect.stats}
* This class represents whether or not a <code>LoginModule</code>
* is REQUIRED, REQUISITE, SUFFICIENT or OPTIONAL.
*/
public static class LoginModuleControlFlag {
private String controlFlag;
/** {@collect.stats}
* Required <code>LoginModule</code>.
*/
public static final LoginModuleControlFlag REQUIRED =
new LoginModuleControlFlag("required");
/** {@collect.stats}
* Requisite <code>LoginModule</code>.
*/
public static final LoginModuleControlFlag REQUISITE =
new LoginModuleControlFlag("requisite");
/** {@collect.stats}
* Sufficient <code>LoginModule</code>.
*/
public static final LoginModuleControlFlag SUFFICIENT =
new LoginModuleControlFlag("sufficient");
/** {@collect.stats}
* Optional <code>LoginModule</code>.
*/
public static final LoginModuleControlFlag OPTIONAL =
new LoginModuleControlFlag("optional");
private LoginModuleControlFlag(String controlFlag) {
this.controlFlag = controlFlag;
}
/** {@collect.stats}
* Return a String representation of this controlFlag.
*
* <p> The String has the format, "LoginModuleControlFlag: <i>flag</i>",
* where <i>flag</i> is either <i>required</i>, <i>requisite</i>,
* <i>sufficient</i>, or <i>optional</i>.
*
* @return a String representation of this controlFlag.
*/
public String toString() {
return (sun.security.util.ResourcesMgr.getString
("LoginModuleControlFlag: ") + controlFlag);
}
}
}
|
Java
|
/*
* Copyright (c) 1998, 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.security.auth.login;
import javax.security.auth.AuthPermission;
import java.io.*;
import java.util.*;
import java.net.URI;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.Security;
import java.security.SecurityPermission;
import sun.security.jca.GetInstance;
/** {@collect.stats}
* A Configuration object is responsible for specifying which LoginModules
* should be used for a particular application, and in what order the
* LoginModules should be invoked.
*
* <p> A login configuration contains the following information.
* Note that this example only represents the default syntax for the
* <code>Configuration</code>. Subclass implementations of this class
* may implement alternative syntaxes and may retrieve the
* <code>Configuration</code> from any source such as files, databases,
* or servers.
*
* <pre>
* Name {
* ModuleClass Flag ModuleOptions;
* ModuleClass Flag ModuleOptions;
* ModuleClass Flag ModuleOptions;
* };
* Name {
* ModuleClass Flag ModuleOptions;
* ModuleClass Flag ModuleOptions;
* };
* other {
* ModuleClass Flag ModuleOptions;
* ModuleClass Flag ModuleOptions;
* };
* </pre>
*
* <p> Each entry in the <code>Configuration</code> is indexed via an
* application name, <i>Name</i>, and contains a list of
* LoginModules configured for that application. Each <code>LoginModule</code>
* is specified via its fully qualified class name.
* Authentication proceeds down the module list in the exact order specified.
* If an application does not have specific entry,
* it defaults to the specific entry for "<i>other</i>".
*
* <p> The <i>Flag</i> value controls the overall behavior as authentication
* proceeds down the stack. The following represents a description of the
* valid values for <i>Flag</i> and their respective semantics:
*
* <pre>
* 1) Required - The <code>LoginModule</code> is required to succeed.
* If it succeeds or fails, authentication still continues
* to proceed down the <code>LoginModule</code> list.
*
* 2) Requisite - The <code>LoginModule</code> is required to succeed.
* If it succeeds, authentication continues down the
* <code>LoginModule</code> list. If it fails,
* control immediately returns to the application
* (authentication does not proceed down the
* <code>LoginModule</code> list).
*
* 3) Sufficient - The <code>LoginModule</code> is not required to
* succeed. If it does succeed, control immediately
* returns to the application (authentication does not
* proceed down the <code>LoginModule</code> list).
* If it fails, authentication continues down the
* <code>LoginModule</code> list.
*
* 4) Optional - The <code>LoginModule</code> is not required to
* succeed. If it succeeds or fails,
* authentication still continues to proceed down the
* <code>LoginModule</code> list.
* </pre>
*
* <p> The overall authentication succeeds only if all <i>Required</i> and
* <i>Requisite</i> LoginModules succeed. If a <i>Sufficient</i>
* <code>LoginModule</code> is configured and succeeds,
* then only the <i>Required</i> and <i>Requisite</i> LoginModules prior to
* that <i>Sufficient</i> <code>LoginModule</code> need to have succeeded for
* the overall authentication to succeed. If no <i>Required</i> or
* <i>Requisite</i> LoginModules are configured for an application,
* then at least one <i>Sufficient</i> or <i>Optional</i>
* <code>LoginModule</code> must succeed.
*
* <p> <i>ModuleOptions</i> is a space separated list of
* <code>LoginModule</code>-specific values which are passed directly to
* the underlying LoginModules. Options are defined by the
* <code>LoginModule</code> itself, and control the behavior within it.
* For example, a <code>LoginModule</code> may define options to support
* debugging/testing capabilities. The correct way to specify options in the
* <code>Configuration</code> is by using the following key-value pairing:
* <i>debug="true"</i>. The key and value should be separated by an
* 'equals' symbol, and the value should be surrounded by double quotes.
* If a String in the form, ${system.property}, occurs in the value,
* it will be expanded to the value of the system property.
* Note that there is no limit to the number of
* options a <code>LoginModule</code> may define.
*
* <p> The following represents an example <code>Configuration</code> entry
* based on the syntax above:
*
* <pre>
* Login {
* com.sun.security.auth.module.UnixLoginModule required;
* com.sun.security.auth.module.Krb5LoginModule optional
* useTicketCache="true"
* ticketCache="${user.home}${/}tickets";
* };
* </pre>
*
* <p> This <code>Configuration</code> specifies that an application named,
* "Login", requires users to first authenticate to the
* <i>com.sun.security.auth.module.UnixLoginModule</i>, which is
* required to succeed. Even if the <i>UnixLoginModule</i>
* authentication fails, the
* <i>com.sun.security.auth.module.Krb5LoginModule</i>
* still gets invoked. This helps hide the source of failure.
* Since the <i>Krb5LoginModule</i> is <i>Optional</i>, the overall
* authentication succeeds only if the <i>UnixLoginModule</i>
* (<i>Required</i>) succeeds.
*
* <p> Also note that the LoginModule-specific options,
* <i>useTicketCache="true"</i> and
* <i>ticketCache=${user.home}${/}tickets"</i>,
* are passed to the <i>Krb5LoginModule</i>.
* These options instruct the <i>Krb5LoginModule</i> to
* use the ticket cache at the specified location.
* The system properties, <i>user.home</i> and <i>/</i>
* (file.separator), are expanded to their respective values.
*
* <p> There is only one Configuration object installed in the runtime at any
* given time. A Configuration object can be installed by calling the
* <code>setConfiguration</code> method. The installed Configuration object
* can be obtained by calling the <code>getConfiguration</code> method.
*
* <p> If no Configuration object has been installed in the runtime, a call to
* <code>getConfiguration</code> installs an instance of the default
* Configuration implementation (a default subclass implementation of this
* abstract class).
* The default Configuration implementation can be changed by setting the value
* of the "login.configuration.provider" security property (in the Java
* security properties file) to the fully qualified name of the desired
* Configuration subclass implementation. The Java security properties file
* is located in the file named <JAVA_HOME>/lib/security/java.security.
* <JAVA_HOME> refers to the value of the java.home system property,
* and specifies the directory where the JRE is installed.
*
* <p> Application code can directly subclass Configuration to provide a custom
* implementation. In addition, an instance of a Configuration object can be
* constructed by invoking one of the <code>getInstance</code> factory methods
* with a standard type. The default policy type is "JavaLoginConfig".
* See Appendix A in the
* <a href="../../../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture API Specification & Reference </a>
* for a list of standard Configuration types.
*
* @see javax.security.auth.login.LoginContext
*/
public abstract class Configuration {
private static Configuration configuration;
private static ClassLoader contextClassLoader;
static {
contextClassLoader = AccessController.doPrivileged
(new PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return Thread.currentThread().getContextClassLoader();
}
});
};
private static void checkPermission(String type) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new AuthPermission
("createLoginConfiguration." + type));
}
}
/** {@collect.stats}
* Sole constructor. (For invocation by subclass constructors, typically
* implicit.)
*/
protected Configuration() { }
/** {@collect.stats}
* Get the installed login Configuration.
*
* <p>
*
* @return the login Configuration. If a Configuration object was set
* via the <code>Configuration.setConfiguration</code> method,
* then that object is returned. Otherwise, a default
* Configuration object is returned.
*
* @exception SecurityException if the caller does not have permission
* to retrieve the Configuration.
*
* @see #setConfiguration
*/
public static Configuration getConfiguration() {
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkPermission(new AuthPermission("getLoginConfiguration"));
synchronized (Configuration.class) {
if (configuration == null) {
String config_class = null;
config_class = AccessController.doPrivileged
(new PrivilegedAction<String>() {
public String run() {
return java.security.Security.getProperty
("login.configuration.provider");
}
});
if (config_class == null) {
config_class = "com.sun.security.auth.login.ConfigFile";
}
try {
final String finalClass = config_class;
configuration = AccessController.doPrivileged
(new PrivilegedExceptionAction<Configuration>() {
public Configuration run() throws ClassNotFoundException,
InstantiationException,
IllegalAccessException {
return (Configuration)Class.forName
(finalClass,
true,
contextClassLoader).newInstance();
}
});
} catch (PrivilegedActionException e) {
Exception ee = e.getException();
if (ee instanceof InstantiationException) {
throw (SecurityException) new
SecurityException
("Configuration error:" +
ee.getCause().getMessage() +
"\n").initCause(ee.getCause());
} else {
throw (SecurityException) new
SecurityException
("Configuration error: " +
ee.toString() +
"\n").initCause(ee);
}
}
}
return configuration;
}
}
/** {@collect.stats}
* Set the login <code>Configuration</code>.
*
* <p>
*
* @param configuration the new <code>Configuration</code>
*
* @exception SecurityException if the current thread does not have
* Permission to set the <code>Configuration</code>.
*
* @see #getConfiguration
*/
public static void setConfiguration(Configuration configuration) {
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkPermission(new AuthPermission("setLoginConfiguration"));
Configuration.configuration = configuration;
}
/** {@collect.stats}
* Returns a Configuration object of the specified type.
*
* <p> This method traverses the list of registered security providers,
* starting with the most preferred Provider.
* A new Configuration object encapsulating the
* ConfigurationSpi implementation from the first
* Provider that supports the specified type is returned.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param type the specified Configuration type. See Appendix A in the
* <a href="../../../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture API Specification & Reference </a>
* for a list of standard Configuration types.
*
* @param params parameters for the Configuration, which may be null.
*
* @return the new Configuration object.
*
* @exception SecurityException if the caller does not have permission
* to get a Configuration instance for the specified type.
*
* @exception NullPointerException if the specified type is null.
*
* @exception IllegalArgumentException if the specified parameters
* are not understood by the ConfigurationSpi implementation
* from the selected Provider.
*
* @exception NoSuchAlgorithmException if no Provider supports a
* ConfigurationSpi implementation for the specified type.
*
* @see Provider
* @since 1.6
*/
public static Configuration getInstance(String type,
Configuration.Parameters params)
throws NoSuchAlgorithmException {
checkPermission(type);
try {
GetInstance.Instance instance = GetInstance.getInstance
("Configuration",
ConfigurationSpi.class,
type,
params);
return new ConfigDelegate((ConfigurationSpi)instance.impl,
instance.provider,
type,
params);
} catch (NoSuchAlgorithmException nsae) {
return handleException (nsae);
}
}
/** {@collect.stats}
* Returns a Configuration object of the specified type.
*
* <p> A new Configuration object encapsulating the
* ConfigurationSpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the provider list.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param type the specified Configuration type. See Appendix A in the
* <a href="../../../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture API Specification & Reference </a>
* for a list of standard Configuration types.
*
* @param params parameters for the Configuration, which may be null.
*
* @param provider the provider.
*
* @return the new Configuration object.
*
* @exception SecurityException if the caller does not have permission
* to get a Configuration instance for the specified type.
*
* @exception NullPointerException if the specified type is null.
*
* @exception IllegalArgumentException if the specified provider
* is null or empty,
* or if the specified parameters are not understood by
* the ConfigurationSpi implementation from the specified provider.
*
* @exception NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception NoSuchAlgorithmException if the specified provider does not
* support a ConfigurationSpi implementation for the specified
* type.
*
* @see Provider
* @since 1.6
*/
public static Configuration getInstance(String type,
Configuration.Parameters params,
String provider)
throws NoSuchProviderException, NoSuchAlgorithmException {
if (provider == null || provider.length() == 0) {
throw new IllegalArgumentException("missing provider");
}
checkPermission(type);
try {
GetInstance.Instance instance = GetInstance.getInstance
("Configuration",
ConfigurationSpi.class,
type,
params,
provider);
return new ConfigDelegate((ConfigurationSpi)instance.impl,
instance.provider,
type,
params);
} catch (NoSuchAlgorithmException nsae) {
return handleException (nsae);
}
}
/** {@collect.stats}
* Returns a Configuration object of the specified type.
*
* <p> A new Configuration object encapsulating the
* ConfigurationSpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param type the specified Configuration type. See Appendix A in the
* <a href="../../../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture API Specification & Reference </a>
* for a list of standard Configuration types.
*
* @param params parameters for the Configuration, which may be null.
*
* @param provider the Provider.
*
* @return the new Configuration object.
*
* @exception SecurityException if the caller does not have permission
* to get a Configuration instance for the specified type.
*
* @exception NullPointerException if the specified type is null.
*
* @exception IllegalArgumentException if the specified Provider is null,
* or if the specified parameters are not understood by
* the ConfigurationSpi implementation from the specified Provider.
*
* @exception NoSuchAlgorithmException if the specified Provider does not
* support a ConfigurationSpi implementation for the specified
* type.
*
* @see Provider
* @since 1.6
*/
public static Configuration getInstance(String type,
Configuration.Parameters params,
Provider provider)
throws NoSuchAlgorithmException {
if (provider == null) {
throw new IllegalArgumentException("missing provider");
}
checkPermission(type);
try {
GetInstance.Instance instance = GetInstance.getInstance
("Configuration",
ConfigurationSpi.class,
type,
params,
provider);
return new ConfigDelegate((ConfigurationSpi)instance.impl,
instance.provider,
type,
params);
} catch (NoSuchAlgorithmException nsae) {
return handleException (nsae);
}
}
private static Configuration handleException(NoSuchAlgorithmException nsae)
throws NoSuchAlgorithmException {
Throwable cause = nsae.getCause();
if (cause instanceof IllegalArgumentException) {
throw (IllegalArgumentException)cause;
}
throw nsae;
}
/** {@collect.stats}
* Return the Provider of this Configuration.
*
* <p> This Configuration instance will only have a Provider if it
* was obtained via a call to <code>Configuration.getInstance</code>.
* Otherwise this method returns null.
*
* @return the Provider of this Configuration, or null.
*
* @since 1.6
*/
public Provider getProvider() {
return null;
}
/** {@collect.stats}
* Return the type of this Configuration.
*
* <p> This Configuration instance will only have a type if it
* was obtained via a call to <code>Configuration.getInstance</code>.
* Otherwise this method returns null.
*
* @return the type of this Configuration, or null.
*
* @since 1.6
*/
public String getType() {
return null;
}
/** {@collect.stats}
* Return Configuration parameters.
*
* <p> This Configuration instance will only have parameters if it
* was obtained via a call to <code>Configuration.getInstance</code>.
* Otherwise this method returns null.
*
* @return Configuration parameters, or null.
*
* @since 1.6
*/
public Configuration.Parameters getParameters() {
return null;
}
/** {@collect.stats}
* Retrieve the AppConfigurationEntries for the specified <i>name</i>
* from this Configuration.
*
* <p>
*
* @param name the name used to index the Configuration.
*
* @return an array of AppConfigurationEntries for the specified <i>name</i>
* from this Configuration, or null if there are no entries
* for the specified <i>name</i>
*/
public abstract AppConfigurationEntry[] getAppConfigurationEntry
(String name);
/** {@collect.stats}
* Refresh and reload the Configuration.
*
* <p> This method causes this Configuration object to refresh/reload its
* contents in an implementation-dependent manner.
* For example, if this Configuration object stores its entries in a file,
* calling <code>refresh</code> may cause the file to be re-read.
*
* <p> The default implementation of this method does nothing.
* This method should be overridden if a refresh operation is supported
* by the implementation.
*
* @exception SecurityException if the caller does not have permission
* to refresh its Configuration.
*/
public void refresh() { }
/** {@collect.stats}
* This subclass is returned by the getInstance calls. All Configuration
* calls are delegated to the underlying ConfigurationSpi.
*/
private static class ConfigDelegate extends Configuration {
private ConfigurationSpi spi;
private Provider p;
private String type;
private Configuration.Parameters params;
private ConfigDelegate(ConfigurationSpi spi, Provider p,
String type, Configuration.Parameters params) {
this.spi = spi;
this.p = p;
this.type = type;
this.params = params;
}
public String getType() { return type; }
public Configuration.Parameters getParameters() { return params; }
public Provider getProvider() { return p; }
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
return spi.engineGetAppConfigurationEntry(name);
}
public void refresh() {
spi.engineRefresh();
}
}
/** {@collect.stats}
* This represents a marker interface for Configuration parameters.
*
* @since 1.6
*/
public static interface Parameters { }
}
|
Java
|
/*
* Copyright (c) 1998, 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.security.auth.login;
/** {@collect.stats}
* This is the basic login exception.
*
* @see javax.security.auth.login.LoginContext
*/
public class LoginException extends java.security.GeneralSecurityException {
private static final long serialVersionUID = -4679091624035232488L;
/** {@collect.stats}
* Constructs a LoginException with no detail message. A detail
* message is a String that describes this particular exception.
*/
public LoginException() {
super();
}
/** {@collect.stats}
* Constructs a LoginException with the specified detail message.
* A detail message is a String that describes this particular
* exception.
*
* <p>
*
* @param msg the detail message.
*/
public LoginException(String msg) {
super(msg);
}
}
|
Java
|
/*
* Copyright (c) 1998, 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.security.auth.login;
/** {@collect.stats}
* Signals that a user account has expired.
*
* <p> This exception is thrown by LoginModules when they determine
* that an account has expired. For example, a <code>LoginModule</code>,
* after successfully authenticating a user, may determine that the
* user's account has expired. In this case the <code>LoginModule</code>
* throws this exception to notify the application. The application can
* then take the appropriate steps to notify the user.
*
*/
public class AccountExpiredException extends AccountException {
private static final long serialVersionUID = -6064064890162661560L;
/** {@collect.stats}
* Constructs a AccountExpiredException with no detail message. A detail
* message is a String that describes this particular exception.
*/
public AccountExpiredException() {
super();
}
/** {@collect.stats}
* Constructs a AccountExpiredException with the specified detail
* message. A detail message is a String that describes this particular
* exception.
*
* <p>
*
* @param msg the detail message.
*/
public AccountExpiredException(String msg) {
super(msg);
}
}
|
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.security.auth.login;
/** {@collect.stats}
* Signals that an account was locked.
*
* <p> This exception may be thrown by a LoginModule if it
* determines that authentication is being attempted on a
* locked account.
*
* @since 1.5
*/
public class AccountLockedException extends AccountException {
private static final long serialVersionUID = 8280345554014066334L;
/** {@collect.stats}
* Constructs a AccountLockedException with no detail message.
* A detail message is a String that describes this particular exception.
*/
public AccountLockedException() {
super();
}
/** {@collect.stats}
* Constructs a AccountLockedException with the specified
* detail message. A detail message is a String that describes
* this particular exception.
*
* <p>
*
* @param msg the detail message.
*/
public AccountLockedException(String msg) {
super(msg);
}
}
|
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.security.auth.login;
/** {@collect.stats}
* Signals that an account was not found.
*
* <p> This exception may be thrown by a LoginModule if it is unable
* to locate an account necessary to perform authentication.
*
* @since 1.5
*/
public class AccountNotFoundException extends AccountException {
private static final long serialVersionUID = 1498349563916294614L;
/** {@collect.stats}
* Constructs a AccountNotFoundException with no detail message.
* A detail message is a String that describes this particular exception.
*/
public AccountNotFoundException() {
super();
}
/** {@collect.stats}
* Constructs a AccountNotFoundException with the specified
* detail message. A detail message is a String that describes
* this particular exception.
*
* <p>
*
* @param msg the detail message.
*/
public AccountNotFoundException(String msg) {
super(msg);
}
}
|
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.security.auth.login;
/** {@collect.stats}
* A generic credential exception.
*
* @since 1.5
*/
public class CredentialException extends LoginException {
private static final long serialVersionUID = -4772893876810601859L;
/** {@collect.stats}
* Constructs a CredentialException with no detail message. A detail
* message is a String that describes this particular exception.
*/
public CredentialException() {
super();
}
/** {@collect.stats}
* Constructs a CredentialException with the specified detail message.
* A detail message is a String that describes this particular
* exception.
*
* <p>
*
* @param msg the detail message.
*/
public CredentialException(String msg) {
super(msg);
}
}
|
Java
|
/*
* Copyright (c) 1998, 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.security.auth.login;
/** {@collect.stats}
* Signals that user authentication failed.
*
* <p> This exception is thrown by LoginModules if authentication failed.
* For example, a <code>LoginModule</code> throws this exception if
* the user entered an incorrect password.
*
*/
public class FailedLoginException extends LoginException {
private static final long serialVersionUID = 802556922354616286L;
/** {@collect.stats}
* Constructs a FailedLoginException with no detail message. A detail
* message is a String that describes this particular exception.
*/
public FailedLoginException() {
super();
}
/** {@collect.stats}
* Constructs a FailedLoginException with the specified detail
* message. A detail message is a String that describes this particular
* exception.
*
* <p>
*
* @param msg the detail message.
*/
public FailedLoginException(String msg) {
super(msg);
}
}
|
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.security.auth.login;
/** {@collect.stats}
* A generic account exception.
*
* @since 1.5
*/
public class AccountException extends LoginException {
private static final long serialVersionUID = -2112878680072211787L;
/** {@collect.stats}
* Constructs a AccountException with no detail message. A detail
* message is a String that describes this particular exception.
*/
public AccountException() {
super();
}
/** {@collect.stats}
* Constructs a AccountException with the specified detail message.
* A detail message is a String that describes this particular
* exception.
*
* <p>
*
* @param msg the detail message.
*/
public AccountException(String msg) {
super(msg);
}
}
|
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.security.auth.login;
/** {@collect.stats}
* Signals that a credential was not found.
*
* <p> This exception may be thrown by a LoginModule if it is unable
* to locate a credential necessary to perform authentication.
*
* @since 1.5
*/
public class CredentialNotFoundException extends CredentialException {
private static final long serialVersionUID = -7779934467214319475L;
/** {@collect.stats}
* Constructs a CredentialNotFoundException with no detail message.
* A detail message is a String that describes this particular exception.
*/
public CredentialNotFoundException() {
super();
}
/** {@collect.stats}
* Constructs a CredentialNotFoundException with the specified
* detail message. A detail message is a String that describes
* this particular exception.
*
* <p>
*
* @param msg the detail message.
*/
public CredentialNotFoundException(String msg) {
super(msg);
}
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth.login;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.Map;
import java.util.HashMap;
import java.text.MessageFormat;
import javax.security.auth.Subject;
import javax.security.auth.AuthPermission;
import javax.security.auth.callback.*;
import java.security.AccessController;
import java.security.AccessControlContext;
import sun.security.util.PendingException;
import sun.security.util.ResourcesMgr;
/** {@collect.stats}
* <p> The <code>LoginContext</code> class describes the basic methods used
* to authenticate Subjects and provides a way to develop an
* application independent of the underlying authentication technology.
* A <code>Configuration</code> specifies the authentication technology, or
* <code>LoginModule</code>, to be used with a particular application.
* Different LoginModules can be plugged in under an application
* without requiring any modifications to the application itself.
*
* <p> In addition to supporting <i>pluggable</i> authentication, this class
* also supports the notion of <i>stacked</i> authentication.
* Applications may be configured to use more than one
* LoginModule. For example, one could
* configure both a Kerberos LoginModule and a smart card
* LoginModule under an application.
*
* <p> A typical caller instantiates a LoginContext with
* a <i>name</i> and a <code>CallbackHandler</code>.
* LoginContext uses the <i>name</i> as the index into a
* Configuration to determine which LoginModules should be used,
* and which ones must succeed in order for the overall authentication to
* succeed. The <code>CallbackHandler</code> is passed to the underlying
* LoginModules so they may communicate and interact with users
* (prompting for a username and password via a graphical user interface,
* for example).
*
* <p> Once the caller has instantiated a LoginContext,
* it invokes the <code>login</code> method to authenticate
* a <code>Subject</code>. The <code>login</code> method invokes
* the configured modules to perform their respective types of authentication
* (username/password, smart card pin verification, etc.).
* Note that the LoginModules will not attempt authentication retries nor
* introduce delays if the authentication fails.
* Such tasks belong to the LoginContext caller.
*
* <p> If the <code>login</code> method returns without
* throwing an exception, then the overall authentication succeeded.
* The caller can then retrieve
* the newly authenticated Subject by invoking the
* <code>getSubject</code> method. Principals and Credentials associated
* with the Subject may be retrieved by invoking the Subject's
* respective <code>getPrincipals</code>, <code>getPublicCredentials</code>,
* and <code>getPrivateCredentials</code> methods.
*
* <p> To logout the Subject, the caller calls
* the <code>logout</code> method. As with the <code>login</code>
* method, this <code>logout</code> method invokes the <code>logout</code>
* method for the configured modules.
*
* <p> A LoginContext should not be used to authenticate
* more than one Subject. A separate LoginContext
* should be used to authenticate each different Subject.
*
* <p> The following documentation applies to all LoginContext constructors:
* <ol>
*
* <li> <code>Subject</code>
* <ul>
* <li> If the constructor has a Subject
* input parameter, the LoginContext uses the caller-specified
* Subject object.
* <p>
* <li> If the caller specifies a <code>null</code> Subject
* and a <code>null</code> value is permitted,
* the LoginContext instantiates a new Subject.
* <p>
* <li> If the constructor does <b>not</b> have a Subject
* input parameter, the LoginContext instantiates a new Subject.
* <p>
* </ul>
*
* <li> <code>Configuration</code>
* <ul>
* <li> If the constructor has a Configuration
* input parameter and the caller specifies a non-null Configuration,
* the LoginContext uses the caller-specified Configuration.
* <p>
* If the constructor does <b>not</b> have a Configuration
* input parameter, or if the caller specifies a <code>null</code>
* Configuration object, the constructor uses the following call to
* get the installed Configuration:
* <pre>
* config = Configuration.getConfiguration();
* </pre>
* For both cases,
* the <i>name</i> argument given to the constructor is passed to the
* <code>Configuration.getAppConfigurationEntry</code> method.
* If the Configuration has no entries for the specified <i>name</i>,
* then the <code>LoginContext</code> calls
* <code>getAppConfigurationEntry</code> with the name, "<i>other</i>"
* (the default entry name). If there is no entry for "<i>other</i>",
* then a <code>LoginException</code> is thrown.
* <p>
* <li> When LoginContext uses the installed Configuration, the caller
* requires the createLoginContext.<em>name</em> and possibly
* createLoginContext.other AuthPermissions. Furthermore, the
* LoginContext will invoke configured modules from within an
* <code>AccessController.doPrivileged</code> call so that modules that
* perform security-sensitive tasks (such as connecting to remote hosts,
* and updating the Subject) will require the respective permissions, but
* the callers of the LoginContext will not require those permissions.
* <p>
* <li> When LoginContext uses a caller-specified Configuration, the caller
* does not require any createLoginContext AuthPermission. The LoginContext
* saves the <code>AccessControlContext</code> for the caller,
* and invokes the configured modules from within an
* <tt>AccessController.doPrivileged</tt> call constrained by that context.
* This means the caller context (stored when the LoginContext was created)
* must have sufficient permissions to perform any security-sensitive tasks
* that the modules may perform.
* <p>
* </ul>
*
* <li> <code>CallbackHandler</code>
* <ul>
* <li> If the constructor has a CallbackHandler
* input parameter, the LoginContext uses the caller-specified
* CallbackHandler object.
* <p>
* <li> If the constructor does <b>not</b> have a CallbackHandler
* input parameter, or if the caller specifies a <code>null</code>
* CallbackHandler object (and a <code>null</code> value is permitted),
* the LoginContext queries the
* <i>auth.login.defaultCallbackHandler</i> security property
* for the fully qualified class name of a default handler implementation.
* If the security property is not set,
* then the underlying modules will not have a
* CallbackHandler for use in communicating
* with users. The caller thus assumes that the configured
* modules have alternative means for authenticating the user.
*
* <p>
* <li> When the LoginContext uses the installed Configuration (instead of
* a caller-specified Configuration, see above),
* then this LoginContext must wrap any
* caller-specified or default CallbackHandler implementation
* in a new CallbackHandler implementation
* whose <code>handle</code> method implementation invokes the
* specified CallbackHandler's <code>handle</code> method in a
* <code>java.security.AccessController.doPrivileged</code> call
* constrained by the caller's current <code>AccessControlContext</code>.
* </ul>
* </ol>
*
* <p> Note that Security Properties
* (such as <code>auth.login.defaultCallbackHandler</code>)
* can be set programmatically via the
* <code>java.security.Security</code> class,
* or statically in the Java security properties file located in the
* file named <JAVA_HOME>/lib/security/java.security.
* <JAVA_HOME> refers to the value of the java.home system property,
* and specifies the directory where the JRE is installed.
*
* @see java.security.Security
* @see javax.security.auth.AuthPermission
* @see javax.security.auth.Subject
* @see javax.security.auth.callback.CallbackHandler
* @see javax.security.auth.login.Configuration
* @see javax.security.auth.spi.LoginModule
*/
public class LoginContext {
private static final String INIT_METHOD = "initialize";
private static final String LOGIN_METHOD = "login";
private static final String COMMIT_METHOD = "commit";
private static final String ABORT_METHOD = "abort";
private static final String LOGOUT_METHOD = "logout";
private static final String OTHER = "other";
private static final String DEFAULT_HANDLER =
"auth.login.defaultCallbackHandler";
private Subject subject = null;
private boolean subjectProvided = false;
private boolean loginSucceeded = false;
private CallbackHandler callbackHandler;
private Map state = new HashMap();
private Configuration config;
private boolean configProvided = false;
private AccessControlContext creatorAcc = null;
private ModuleInfo[] moduleStack;
private ClassLoader contextClassLoader = null;
private static final Class[] PARAMS = { };
// state saved in the event a user-specified asynchronous exception
// was specified and thrown
private int moduleIndex = 0;
private LoginException firstError = null;
private LoginException firstRequiredError = null;
private boolean success = false;
private static final sun.security.util.Debug debug =
sun.security.util.Debug.getInstance("logincontext", "\t[LoginContext]");
private void init(String name) throws LoginException {
SecurityManager sm = System.getSecurityManager();
if (sm != null && !configProvided) {
sm.checkPermission(new AuthPermission
("createLoginContext." + name));
}
if (name == null)
throw new LoginException
(ResourcesMgr.getString("Invalid null input: name"));
// get the Configuration
if (config == null) {
config = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<Configuration>() {
public Configuration run() {
return Configuration.getConfiguration();
}
});
}
// get the LoginModules configured for this application
AppConfigurationEntry[] entries = config.getAppConfigurationEntry(name);
if (entries == null) {
if (sm != null && !configProvided) {
sm.checkPermission(new AuthPermission
("createLoginContext." + OTHER));
}
entries = config.getAppConfigurationEntry(OTHER);
if (entries == null) {
MessageFormat form = new MessageFormat(ResourcesMgr.getString
("No LoginModules configured for name"));
Object[] source = {name};
throw new LoginException(form.format(source));
}
}
moduleStack = new ModuleInfo[entries.length];
for (int i = 0; i < entries.length; i++) {
// clone returned array
moduleStack[i] = new ModuleInfo
(new AppConfigurationEntry
(entries[i].getLoginModuleName(),
entries[i].getControlFlag(),
entries[i].getOptions()),
null);
}
contextClassLoader = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return Thread.currentThread().getContextClassLoader();
}
});
}
private void loadDefaultCallbackHandler() throws LoginException {
// get the default handler class
try {
final ClassLoader finalLoader = contextClassLoader;
this.callbackHandler = java.security.AccessController.doPrivileged(
new java.security.PrivilegedExceptionAction<CallbackHandler>() {
public CallbackHandler run() throws Exception {
String defaultHandler = java.security.Security.getProperty
(DEFAULT_HANDLER);
if (defaultHandler == null || defaultHandler.length() == 0)
return null;
Class c = Class.forName(defaultHandler,
true,
finalLoader);
return (CallbackHandler)c.newInstance();
}
});
} catch (java.security.PrivilegedActionException pae) {
throw new LoginException(pae.getException().toString());
}
// secure it with the caller's ACC
if (this.callbackHandler != null && !configProvided) {
this.callbackHandler = new SecureCallbackHandler
(java.security.AccessController.getContext(),
this.callbackHandler);
}
}
/** {@collect.stats}
* Instantiate a new <code>LoginContext</code> object with a name.
*
* @param name the name used as the index into the
* <code>Configuration</code>.
*
* @exception LoginException if the caller-specified <code>name</code>
* does not appear in the <code>Configuration</code>
* and there is no <code>Configuration</code> entry
* for "<i>other</i>", or if the
* <i>auth.login.defaultCallbackHandler</i>
* security property was set, but the implementation
* class could not be loaded.
* <p>
* @exception SecurityException if a SecurityManager is set and
* the caller does not have
* AuthPermission("createLoginContext.<i>name</i>"),
* or if a configuration entry for <i>name</i> does not exist and
* the caller does not additionally have
* AuthPermission("createLoginContext.other")
*/
public LoginContext(String name) throws LoginException {
init(name);
loadDefaultCallbackHandler();
}
/** {@collect.stats}
* Instantiate a new <code>LoginContext</code> object with a name
* and a <code>Subject</code> object.
*
* <p>
*
* @param name the name used as the index into the
* <code>Configuration</code>. <p>
*
* @param subject the <code>Subject</code> to authenticate.
*
* @exception LoginException if the caller-specified <code>name</code>
* does not appear in the <code>Configuration</code>
* and there is no <code>Configuration</code> entry
* for "<i>other</i>", if the caller-specified <code>subject</code>
* is <code>null</code>, or if the
* <i>auth.login.defaultCallbackHandler</i>
* security property was set, but the implementation
* class could not be loaded.
* <p>
* @exception SecurityException if a SecurityManager is set and
* the caller does not have
* AuthPermission("createLoginContext.<i>name</i>"),
* or if a configuration entry for <i>name</i> does not exist and
* the caller does not additionally have
* AuthPermission("createLoginContext.other")
*/
public LoginContext(String name, Subject subject)
throws LoginException {
init(name);
if (subject == null)
throw new LoginException
(ResourcesMgr.getString("invalid null Subject provided"));
this.subject = subject;
subjectProvided = true;
loadDefaultCallbackHandler();
}
/** {@collect.stats}
* Instantiate a new <code>LoginContext</code> object with a name
* and a <code>CallbackHandler</code> object.
*
* <p>
*
* @param name the name used as the index into the
* <code>Configuration</code>. <p>
*
* @param callbackHandler the <code>CallbackHandler</code> object used by
* LoginModules to communicate with the user.
*
* @exception LoginException if the caller-specified <code>name</code>
* does not appear in the <code>Configuration</code>
* and there is no <code>Configuration</code> entry
* for "<i>other</i>", or if the caller-specified
* <code>callbackHandler</code> is <code>null</code>.
* <p>
* @exception SecurityException if a SecurityManager is set and
* the caller does not have
* AuthPermission("createLoginContext.<i>name</i>"),
* or if a configuration entry for <i>name</i> does not exist and
* the caller does not additionally have
* AuthPermission("createLoginContext.other")
*/
public LoginContext(String name, CallbackHandler callbackHandler)
throws LoginException {
init(name);
if (callbackHandler == null)
throw new LoginException(ResourcesMgr.getString
("invalid null CallbackHandler provided"));
this.callbackHandler = new SecureCallbackHandler
(java.security.AccessController.getContext(),
callbackHandler);
}
/** {@collect.stats}
* Instantiate a new <code>LoginContext</code> object with a name,
* a <code>Subject</code> to be authenticated, and a
* <code>CallbackHandler</code> object.
*
* <p>
*
* @param name the name used as the index into the
* <code>Configuration</code>. <p>
*
* @param subject the <code>Subject</code> to authenticate. <p>
*
* @param callbackHandler the <code>CallbackHandler</code> object used by
* LoginModules to communicate with the user.
*
* @exception LoginException if the caller-specified <code>name</code>
* does not appear in the <code>Configuration</code>
* and there is no <code>Configuration</code> entry
* for "<i>other</i>", or if the caller-specified
* <code>subject</code> is <code>null</code>,
* or if the caller-specified
* <code>callbackHandler</code> is <code>null</code>.
* <p>
* @exception SecurityException if a SecurityManager is set and
* the caller does not have
* AuthPermission("createLoginContext.<i>name</i>"),
* or if a configuration entry for <i>name</i> does not exist and
* the caller does not additionally have
* AuthPermission("createLoginContext.other")
*/
public LoginContext(String name, Subject subject,
CallbackHandler callbackHandler) throws LoginException {
this(name, subject);
if (callbackHandler == null)
throw new LoginException(ResourcesMgr.getString
("invalid null CallbackHandler provided"));
this.callbackHandler = new SecureCallbackHandler
(java.security.AccessController.getContext(),
callbackHandler);
}
/** {@collect.stats}
* Instantiate a new <code>LoginContext</code> object with a name,
* a <code>Subject</code> to be authenticated,
* a <code>CallbackHandler</code> object, and a login
* <code>Configuration</code>.
*
* <p>
*
* @param name the name used as the index into the caller-specified
* <code>Configuration</code>. <p>
*
* @param subject the <code>Subject</code> to authenticate,
* or <code>null</code>. <p>
*
* @param callbackHandler the <code>CallbackHandler</code> object used by
* LoginModules to communicate with the user, or <code>null</code>.
* <p>
*
* @param config the <code>Configuration</code> that lists the
* login modules to be called to perform the authentication,
* or <code>null</code>.
*
* @exception LoginException if the caller-specified <code>name</code>
* does not appear in the <code>Configuration</code>
* and there is no <code>Configuration</code> entry
* for "<i>other</i>".
* <p>
* @exception SecurityException if a SecurityManager is set,
* <i>config</i> is <code>null</code>,
* and either the caller does not have
* AuthPermission("createLoginContext.<i>name</i>"),
* or if a configuration entry for <i>name</i> does not exist and
* the caller does not additionally have
* AuthPermission("createLoginContext.other")
*
* @since 1.5
*/
public LoginContext(String name, Subject subject,
CallbackHandler callbackHandler,
Configuration config) throws LoginException {
this.config = config;
configProvided = (config != null) ? true : false;
if (configProvided) {
creatorAcc = java.security.AccessController.getContext();
}
init(name);
if (subject != null) {
this.subject = subject;
subjectProvided = true;
}
if (callbackHandler == null) {
loadDefaultCallbackHandler();
} else if (!configProvided) {
this.callbackHandler = new SecureCallbackHandler
(java.security.AccessController.getContext(),
callbackHandler);
} else {
this.callbackHandler = callbackHandler;
}
}
/** {@collect.stats}
* Perform the authentication.
*
* <p> This method invokes the <code>login</code> method for each
* LoginModule configured for the <i>name</i> specified to the
* <code>LoginContext</code> constructor, as determined by the login
* <code>Configuration</code>. Each <code>LoginModule</code>
* then performs its respective type of authentication
* (username/password, smart card pin verification, etc.).
*
* <p> This method completes a 2-phase authentication process by
* calling each configured LoginModule's <code>commit</code> method
* if the overall authentication succeeded (the relevant REQUIRED,
* REQUISITE, SUFFICIENT, and OPTIONAL LoginModules succeeded),
* or by calling each configured LoginModule's <code>abort</code> method
* if the overall authentication failed. If authentication succeeded,
* each successful LoginModule's <code>commit</code> method associates
* the relevant Principals and Credentials with the <code>Subject</code>.
* If authentication failed, each LoginModule's <code>abort</code> method
* removes/destroys any previously stored state.
*
* <p> If the <code>commit</code> phase of the authentication process
* fails, then the overall authentication fails and this method
* invokes the <code>abort</code> method for each configured
* <code>LoginModule</code>.
*
* <p> If the <code>abort</code> phase
* fails for any reason, then this method propagates the
* original exception thrown either during the <code>login</code> phase
* or the <code>commit</code> phase. In either case, the overall
* authentication fails.
*
* <p> In the case where multiple LoginModules fail,
* this method propagates the exception raised by the first
* <code>LoginModule</code> which failed.
*
* <p> Note that if this method enters the <code>abort</code> phase
* (either the <code>login</code> or <code>commit</code> phase failed),
* this method invokes all LoginModules configured for the
* application regardless of their respective <code>Configuration</code>
* flag parameters. Essentially this means that <code>Requisite</code>
* and <code>Sufficient</code> semantics are ignored during the
* <code>abort</code> phase. This guarantees that proper cleanup
* and state restoration can take place.
*
* <p>
*
* @exception LoginException if the authentication fails.
*/
public void login() throws LoginException {
loginSucceeded = false;
if (subject == null) {
subject = new Subject();
}
try {
if (configProvided) {
// module invoked in doPrivileged with creatorAcc
invokeCreatorPriv(LOGIN_METHOD);
invokeCreatorPriv(COMMIT_METHOD);
} else {
// module invoked in doPrivileged
invokePriv(LOGIN_METHOD);
invokePriv(COMMIT_METHOD);
}
loginSucceeded = true;
} catch (LoginException le) {
try {
if (configProvided) {
invokeCreatorPriv(ABORT_METHOD);
} else {
invokePriv(ABORT_METHOD);
}
} catch (LoginException le2) {
throw le;
}
throw le;
}
}
/** {@collect.stats}
* Logout the <code>Subject</code>.
*
* <p> This method invokes the <code>logout</code> method for each
* <code>LoginModule</code> configured for this <code>LoginContext</code>.
* Each <code>LoginModule</code> performs its respective logout procedure
* which may include removing/destroying
* <code>Principal</code> and <code>Credential</code> information
* from the <code>Subject</code> and state cleanup.
*
* <p> Note that this method invokes all LoginModules configured for the
* application regardless of their respective
* <code>Configuration</code> flag parameters. Essentially this means
* that <code>Requisite</code> and <code>Sufficient</code> semantics are
* ignored for this method. This guarantees that proper cleanup
* and state restoration can take place.
*
* <p>
*
* @exception LoginException if the logout fails.
*/
public void logout() throws LoginException {
if (subject == null) {
throw new LoginException(ResourcesMgr.getString
("null subject - logout called before login"));
}
if (configProvided) {
// module invoked in doPrivileged with creatorAcc
invokeCreatorPriv(LOGOUT_METHOD);
} else {
// module invoked in doPrivileged
invokePriv(LOGOUT_METHOD);
}
}
/** {@collect.stats}
* Return the authenticated Subject.
*
* <p>
*
* @return the authenticated Subject. If the caller specified a
* Subject to this LoginContext's constructor,
* this method returns the caller-specified Subject.
* If a Subject was not specified and authentication succeeds,
* this method returns the Subject instantiated and used for
* authentication by this LoginContext.
* If a Subject was not specified, and authentication fails or
* has not been attempted, this method returns null.
*/
public Subject getSubject() {
if (!loginSucceeded && !subjectProvided)
return null;
return subject;
}
private void clearState() {
moduleIndex = 0;
firstError = null;
firstRequiredError = null;
success = false;
}
private void throwException(LoginException originalError, LoginException le)
throws LoginException {
// first clear state
clearState();
// throw the exception
LoginException error = (originalError != null) ? originalError : le;
throw error;
}
/** {@collect.stats}
* Invokes the login, commit, and logout methods
* from a LoginModule inside a doPrivileged block.
*
* This version is called if the caller did not instantiate
* the LoginContext with a Configuration object.
*/
private void invokePriv(final String methodName) throws LoginException {
try {
java.security.AccessController.doPrivileged
(new java.security.PrivilegedExceptionAction<Void>() {
public Void run() throws LoginException {
invoke(methodName);
return null;
}
});
} catch (java.security.PrivilegedActionException pae) {
throw (LoginException)pae.getException();
}
}
/** {@collect.stats}
* Invokes the login, commit, and logout methods
* from a LoginModule inside a doPrivileged block restricted
* by creatorAcc
*
* This version is called if the caller instantiated
* the LoginContext with a Configuration object.
*/
private void invokeCreatorPriv(final String methodName)
throws LoginException {
try {
java.security.AccessController.doPrivileged
(new java.security.PrivilegedExceptionAction<Void>() {
public Void run() throws LoginException {
invoke(methodName);
return null;
}
}, creatorAcc);
} catch (java.security.PrivilegedActionException pae) {
throw (LoginException)pae.getException();
}
}
private void invoke(String methodName) throws LoginException {
// start at moduleIndex
// - this can only be non-zero if methodName is LOGIN_METHOD
for (int i = moduleIndex; i < moduleStack.length; i++, moduleIndex++) {
try {
int mIndex = 0;
Method[] methods = null;
if (moduleStack[i].module != null) {
methods = moduleStack[i].module.getClass().getMethods();
} else {
// instantiate the LoginModule
Class c = Class.forName
(moduleStack[i].entry.getLoginModuleName(),
true,
contextClassLoader);
Constructor constructor = c.getConstructor(PARAMS);
Object[] args = { };
// allow any object to be a LoginModule
// as long as it conforms to the interface
moduleStack[i].module = constructor.newInstance(args);
methods = moduleStack[i].module.getClass().getMethods();
// call the LoginModule's initialize method
for (mIndex = 0; mIndex < methods.length; mIndex++) {
if (methods[mIndex].getName().equals(INIT_METHOD))
break;
}
Object[] initArgs = {subject,
callbackHandler,
state,
moduleStack[i].entry.getOptions() };
// invoke the LoginModule initialize method
methods[mIndex].invoke(moduleStack[i].module, initArgs);
}
// find the requested method in the LoginModule
for (mIndex = 0; mIndex < methods.length; mIndex++) {
if (methods[mIndex].getName().equals(methodName))
break;
}
// set up the arguments to be passed to the LoginModule method
Object[] args = { };
// invoke the LoginModule method
boolean status = ((Boolean)methods[mIndex].invoke
(moduleStack[i].module, args)).booleanValue();
if (status == true) {
// if SUFFICIENT, return if no prior REQUIRED errors
if (!methodName.equals(ABORT_METHOD) &&
!methodName.equals(LOGOUT_METHOD) &&
moduleStack[i].entry.getControlFlag() ==
AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT &&
firstRequiredError == null) {
// clear state
clearState();
if (debug != null)
debug.println(methodName + " SUFFICIENT success");
return;
}
if (debug != null)
debug.println(methodName + " success");
success = true;
} else {
if (debug != null)
debug.println(methodName + " ignored");
}
} catch (NoSuchMethodException nsme) {
MessageFormat form = new MessageFormat(ResourcesMgr.getString
("unable to instantiate LoginModule, module, because " +
"it does not provide a no-argument constructor"));
Object[] source = {moduleStack[i].entry.getLoginModuleName()};
throwException(null, new LoginException(form.format(source)));
} catch (InstantiationException ie) {
throwException(null, new LoginException(ResourcesMgr.getString
("unable to instantiate LoginModule: ") +
ie.getMessage()));
} catch (ClassNotFoundException cnfe) {
throwException(null, new LoginException(ResourcesMgr.getString
("unable to find LoginModule class: ") +
cnfe.getMessage()));
} catch (IllegalAccessException iae) {
throwException(null, new LoginException(ResourcesMgr.getString
("unable to access LoginModule: ") +
iae.getMessage()));
} catch (InvocationTargetException ite) {
// failure cases
LoginException le;
if (ite.getCause() instanceof PendingException &&
methodName.equals(LOGIN_METHOD)) {
// XXX
//
// if a module's LOGIN_METHOD threw a PendingException
// then immediately throw it.
//
// when LoginContext is called again,
// the module that threw the exception is invoked first
// (the module list is not invoked from the start).
// previously thrown exception state is still present.
//
// it is assumed that the module which threw
// the exception can have its
// LOGIN_METHOD invoked twice in a row
// without any commit/abort in between.
//
// in all cases when LoginContext returns
// (either via natural return or by throwing an exception)
// we need to call clearState before returning.
// the only time that is not true is in this case -
// do not call throwException here.
throw (PendingException)ite.getCause();
} else if (ite.getCause() instanceof LoginException) {
le = (LoginException)ite.getCause();
} else if (ite.getCause() instanceof SecurityException) {
// do not want privacy leak
// (e.g., sensitive file path in exception msg)
le = new LoginException("Security Exception");
le.initCause(new SecurityException());
if (debug != null) {
debug.println
("original security exception with detail msg " +
"replaced by new exception with empty detail msg");
debug.println("original security exception: " +
ite.getCause().toString());
}
} else {
// capture an unexpected LoginModule exception
java.io.StringWriter sw = new java.io.StringWriter();
ite.getCause().printStackTrace
(new java.io.PrintWriter(sw));
sw.flush();
le = new LoginException(sw.toString());
}
if (moduleStack[i].entry.getControlFlag() ==
AppConfigurationEntry.LoginModuleControlFlag.REQUISITE) {
if (debug != null)
debug.println(methodName + " REQUISITE failure");
// if REQUISITE, then immediately throw an exception
if (methodName.equals(ABORT_METHOD) ||
methodName.equals(LOGOUT_METHOD)) {
if (firstRequiredError == null)
firstRequiredError = le;
} else {
throwException(firstRequiredError, le);
}
} else if (moduleStack[i].entry.getControlFlag() ==
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED) {
if (debug != null)
debug.println(methodName + " REQUIRED failure");
// mark down that a REQUIRED module failed
if (firstRequiredError == null)
firstRequiredError = le;
} else {
if (debug != null)
debug.println(methodName + " OPTIONAL failure");
// mark down that an OPTIONAL module failed
if (firstError == null)
firstError = le;
}
}
}
// we went thru all the LoginModules.
if (firstRequiredError != null) {
// a REQUIRED module failed -- return the error
throwException(firstRequiredError, null);
} else if (success == false && firstError != null) {
// no module succeeded -- return the first error
throwException(firstError, null);
} else if (success == false) {
// no module succeeded -- all modules were IGNORED
throwException(new LoginException
(ResourcesMgr.getString("Login Failure: all modules ignored")),
null);
} else {
// success
clearState();
return;
}
}
/** {@collect.stats}
* Wrap the caller-specified CallbackHandler in our own
* and invoke it within a privileged block, constrained by
* the caller's AccessControlContext.
*/
private static class SecureCallbackHandler implements CallbackHandler {
private final java.security.AccessControlContext acc;
private final CallbackHandler ch;
SecureCallbackHandler(java.security.AccessControlContext acc,
CallbackHandler ch) {
this.acc = acc;
this.ch = ch;
}
public void handle(final Callback[] callbacks)
throws java.io.IOException, UnsupportedCallbackException {
try {
java.security.AccessController.doPrivileged
(new java.security.PrivilegedExceptionAction<Void>() {
public Void run() throws java.io.IOException,
UnsupportedCallbackException {
ch.handle(callbacks);
return null;
}
}, acc);
} catch (java.security.PrivilegedActionException pae) {
if (pae.getException() instanceof java.io.IOException) {
throw (java.io.IOException)pae.getException();
} else {
throw (UnsupportedCallbackException)pae.getException();
}
}
}
}
/** {@collect.stats}
* LoginModule information -
* incapsulates Configuration info and actual module instances
*/
private static class ModuleInfo {
AppConfigurationEntry entry;
Object module;
ModuleInfo(AppConfigurationEntry newEntry, Object newModule) {
this.entry = newEntry;
this.module = newModule;
}
}
}
|
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.security.auth.login;
/** {@collect.stats}
* This class defines the <i>Service Provider Interface</i> (<b>SPI</b>)
* for the <code>Configuration</code> class.
* All the abstract methods in this class must be implemented by each
* service provider who wishes to supply a Configuration implementation.
*
* <p> Subclass implementations of this abstract class must provide
* a public constructor that takes a <code>Configuration.Parameters</code>
* object as an input parameter. This constructor also must throw
* an IllegalArgumentException if it does not understand the
* <code>Configuration.Parameters</code> input.
*
*
* @since 1.6
*/
public abstract class ConfigurationSpi {
/** {@collect.stats}
* Retrieve the AppConfigurationEntries for the specified <i>name</i>.
*
* <p>
*
* @param name the name used to index the Configuration.
*
* @return an array of AppConfigurationEntries for the specified
* <i>name</i>, or null if there are no entries.
*/
protected abstract AppConfigurationEntry[] engineGetAppConfigurationEntry
(String name);
/** {@collect.stats}
* Refresh and reload the Configuration.
*
* <p> This method causes this Configuration object to refresh/reload its
* contents in an implementation-dependent manner.
* For example, if this Configuration object stores its entries in a file,
* calling <code>refresh</code> may cause the file to be re-read.
*
* <p> The default implementation of this method does nothing.
* This method should be overridden if a refresh operation is supported
* by the implementation.
*
* @exception SecurityException if the caller does not have permission
* to refresh its Configuration.
*/
protected void engineRefresh() { }
}
|
Java
|
/*
* Copyright (c) 1998, 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.security.auth.login;
/** {@collect.stats}
* Signals that a <code>Credential</code> has expired.
*
* <p> This exception is thrown by LoginModules when they determine
* that a <code>Credential</code> has expired.
* For example, a <code>LoginModule</code> authenticating a user
* in its <code>login</code> method may determine that the user's
* password, although entered correctly, has expired. In this case
* the <code>LoginModule</code> throws this exception to notify
* the application. The application can then take the appropriate
* steps to assist the user in updating the password.
*
*/
public class CredentialExpiredException extends CredentialException {
private static final long serialVersionUID = -5344739593859737937L;
/** {@collect.stats}
* Constructs a CredentialExpiredException with no detail message. A detail
* message is a String that describes this particular exception.
*/
public CredentialExpiredException() {
super();
}
/** {@collect.stats}
* Constructs a CredentialExpiredException with the specified detail
* message. A detail message is a String that describes this particular
* exception.
*
* <p>
*
* @param msg the detail message.
*/
public CredentialExpiredException(String msg) {
super(msg);
}
}
|
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.security.auth;
import java.util.*;
import java.text.MessageFormat;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Principal;
import sun.security.util.ResourcesMgr;
/** {@collect.stats}
* This class is used to protect access to private Credentials
* belonging to a particular <code>Subject</code>. The <code>Subject</code>
* is represented by a Set of Principals.
*
* <p> The target name of this <code>Permission</code> specifies
* a Credential class name, and a Set of Principals.
* The only valid value for this Permission's actions is, "read".
* The target name must abide by the following syntax:
*
* <pre>
* CredentialClass {PrincipalClass "PrincipalName"}*
* </pre>
*
* For example, the following permission grants access to the
* com.sun.PrivateCredential owned by Subjects which have
* a com.sun.Principal with the name, "duke". Note that although
* this example, as well as all the examples below, do not contain
* Codebase, SignedBy, or Principal information in the grant statement
* (for simplicity reasons), actual policy configurations should
* specify that information when appropriate.
*
* <pre>
*
* grant {
* permission javax.security.auth.PrivateCredentialPermission
* "com.sun.PrivateCredential com.sun.Principal \"duke\"",
* "read";
* };
* </pre>
*
* If CredentialClass is "*", then access is granted to
* all private Credentials belonging to the specified
* <code>Subject</code>.
* If "PrincipalName" is "*", then access is granted to the
* specified Credential owned by any <code>Subject</code> that has the
* specified <code>Principal</code> (the actual PrincipalName doesn't matter).
* For example, the following grants access to the
* a.b.Credential owned by any <code>Subject</code> that has
* an a.b.Principal.
*
* <pre>
* grant {
* permission javax.security.auth.PrivateCredentialPermission
* "a.b.Credential a.b.Principal "*"",
* "read";
* };
* </pre>
*
* If both the PrincipalClass and "PrincipalName" are "*",
* then access is granted to the specified Credential owned by
* any <code>Subject</code>.
*
* <p> In addition, the PrincipalClass/PrincipalName pairing may be repeated:
*
* <pre>
* grant {
* permission javax.security.auth.PrivateCredentialPermission
* "a.b.Credential a.b.Principal "duke" c.d.Principal "dukette"",
* "read";
* };
* </pre>
*
* The above grants access to the private Credential, "a.b.Credential",
* belonging to a <code>Subject</code> with at least two associated Principals:
* "a.b.Principal" with the name, "duke", and "c.d.Principal", with the name,
* "dukette".
*
*/
public final class PrivateCredentialPermission extends Permission {
private static final long serialVersionUID = 5284372143517237068L;
private static final CredOwner[] EMPTY_PRINCIPALS = new CredOwner[0];
/** {@collect.stats}
* @serial
*/
private String credentialClass;
/** {@collect.stats}
* @serial The Principals associated with this permission.
* The set contains elements of type,
* <code>PrivateCredentialPermission.CredOwner</code>.
*/
private Set principals; // ignored - kept around for compatibility
private transient CredOwner[] credOwners;
/** {@collect.stats}
* @serial
*/
private boolean testing = false;
/** {@collect.stats}
* Create a new <code>PrivateCredentialPermission</code>
* with the specified <code>credentialClass</code> and Principals.
*/
PrivateCredentialPermission(String credentialClass,
Set<Principal> principals) {
super(credentialClass);
this.credentialClass = credentialClass;
synchronized(principals) {
if (principals.size() == 0) {
this.credOwners = EMPTY_PRINCIPALS;
} else {
this.credOwners = new CredOwner[principals.size()];
int index = 0;
Iterator<Principal> i = principals.iterator();
while (i.hasNext()) {
Principal p = i.next();
this.credOwners[index++] = new CredOwner
(p.getClass().getName(),
p.getName());
}
}
}
}
/** {@collect.stats}
* Creates a new <code>PrivateCredentialPermission</code>
* with the specified <code>name</code>. The <code>name</code>
* specifies both a Credential class and a <code>Principal</code> Set.
*
* <p>
*
* @param name the name specifying the Credential class and
* <code>Principal</code> Set. <p>
*
* @param actions the actions specifying that the Credential can be read.
*
* @throws IllegalArgumentException if <code>name</code> does not conform
* to the correct syntax or if <code>actions</code> is not "read".
*/
public PrivateCredentialPermission(String name, String actions) {
super(name);
if (!"read".equalsIgnoreCase(actions))
throw new IllegalArgumentException
(ResourcesMgr.getString("actions can only be 'read'"));
init(name);
}
/** {@collect.stats}
* Returns the Class name of the Credential associated with this
* <code>PrivateCredentialPermission</code>.
*
* <p>
*
* @return the Class name of the Credential associated with this
* <code>PrivateCredentialPermission</code>.
*/
public String getCredentialClass() {
return credentialClass;
}
/** {@collect.stats}
* Returns the <code>Principal</code> classes and names
* associated with this <code>PrivateCredentialPermission</code>.
* The information is returned as a two-dimensional array (array[x][y]).
* The 'x' value corresponds to the number of <code>Principal</code>
* class and name pairs. When (y==0), it corresponds to
* the <code>Principal</code> class value, and when (y==1),
* it corresponds to the <code>Principal</code> name value.
* For example, array[0][0] corresponds to the class name of
* the first <code>Principal</code> in the array. array[0][1]
* corresponds to the <code>Principal</code> name of the
* first <code>Principal</code> in the array.
*
* <p>
*
* @return the <code>Principal</code> class and names associated
* with this <code>PrivateCredentialPermission</code>.
*/
public String[][] getPrincipals() {
if (credOwners == null || credOwners.length == 0) {
return new String[0][0];
}
String[][] pArray = new String[credOwners.length][2];
for (int i = 0; i < credOwners.length; i++) {
pArray[i][0] = credOwners[i].principalClass;
pArray[i][1] = credOwners[i].principalName;
}
return pArray;
}
/** {@collect.stats}
* Checks if this <code>PrivateCredentialPermission</code> implies
* the specified <code>Permission</code>.
*
* <p>
*
* This method returns true if:
* <p><ul>
* <li> <i>p</i> is an instanceof PrivateCredentialPermission and <p>
* <li> the target name for <i>p</i> is implied by this object's
* target name. For example:
* <pre>
* [* P1 "duke"] implies [a.b.Credential P1 "duke"].
* [C1 P1 "duke"] implies [C1 P1 "duke" P2 "dukette"].
* [C1 P2 "dukette"] implies [C1 P1 "duke" P2 "dukette"].
* </pre>
* </ul>
*
* <p>
*
* @param p the <code>Permission</code> to check against.
*
* @return true if this <code>PrivateCredentialPermission</code> implies
* the specified <code>Permission</code>, false if not.
*/
public boolean implies(Permission p) {
if (p == null || !(p instanceof PrivateCredentialPermission))
return false;
PrivateCredentialPermission that = (PrivateCredentialPermission)p;
if (!impliesCredentialClass(credentialClass, that.credentialClass))
return false;
return impliesPrincipalSet(credOwners, that.credOwners);
}
/** {@collect.stats}
* Checks two <code>PrivateCredentialPermission</code> objects for
* equality. Checks that <i>obj</i> is a
* <code>PrivateCredentialPermission</code>,
* and has the same credential class as this object,
* as well as the same Principals as this object.
* The order of the Principals in the respective Permission's
* target names is not relevant.
*
* <p>
*
* @param obj the object we are testing for equality with this object.
*
* @return true if obj is a <code>PrivateCredentialPermission</code>,
* has the same credential class as this object,
* and has the same Principals as this object.
*/
public boolean equals(Object obj) {
if (obj == this)
return true;
if (! (obj instanceof PrivateCredentialPermission))
return false;
PrivateCredentialPermission that = (PrivateCredentialPermission)obj;
return (this.implies(that) && that.implies(this));
}
/** {@collect.stats}
* Returns the hash code value for this object.
*
* @return a hash code value for this object.
*/
public int hashCode() {
return this.credentialClass.hashCode();
}
/** {@collect.stats}
* Returns the "canonical string representation" of the actions.
* This method always returns the String, "read".
*
* <p>
*
* @return the actions (always returns "read").
*/
public String getActions() {
return "read";
}
/** {@collect.stats}
* Return a homogeneous collection of PrivateCredentialPermissions
* in a <code>PermissionCollection</code>.
* No such <code>PermissionCollection</code> is defined,
* so this method always returns <code>null</code>.
*
* <p>
*
* @return null in all cases.
*/
public PermissionCollection newPermissionCollection() {
return null;
}
private void init(String name) {
if (name == null || name.trim().length() == 0) {
throw new IllegalArgumentException("invalid empty name");
}
ArrayList<CredOwner> pList = new ArrayList<CredOwner>();
StringTokenizer tokenizer = new StringTokenizer(name, " ", true);
String principalClass = null;
String principalName = null;
if (testing)
System.out.println("whole name = " + name);
// get the Credential Class
credentialClass = tokenizer.nextToken();
if (testing)
System.out.println("Credential Class = " + credentialClass);
if (tokenizer.hasMoreTokens() == false) {
MessageFormat form = new MessageFormat(ResourcesMgr.getString
("permission name [name] syntax invalid: "));
Object[] source = {name};
throw new IllegalArgumentException
(form.format(source) + ResourcesMgr.getString
("Credential Class not followed by a " +
"Principal Class and Name"));
}
while (tokenizer.hasMoreTokens()) {
// skip delimiter
tokenizer.nextToken();
// get the Principal Class
principalClass = tokenizer.nextToken();
if (testing)
System.out.println(" Principal Class = " + principalClass);
if (tokenizer.hasMoreTokens() == false) {
MessageFormat form = new MessageFormat(ResourcesMgr.getString
("permission name [name] syntax invalid: "));
Object[] source = {name};
throw new IllegalArgumentException
(form.format(source) + ResourcesMgr.getString
("Principal Class not followed by a Principal Name"));
}
// skip delimiter
tokenizer.nextToken();
// get the Principal Name
principalName = tokenizer.nextToken();
if (!principalName.startsWith("\"")) {
MessageFormat form = new MessageFormat(ResourcesMgr.getString
("permission name [name] syntax invalid: "));
Object[] source = {name};
throw new IllegalArgumentException
(form.format(source) + ResourcesMgr.getString
("Principal Name must be surrounded by quotes"));
}
if (!principalName.endsWith("\"")) {
// we have a name with spaces in it --
// keep parsing until we find the end quote,
// and keep the spaces in the name
while (tokenizer.hasMoreTokens()) {
principalName = principalName + tokenizer.nextToken();
if (principalName.endsWith("\""))
break;
}
if (!principalName.endsWith("\"")) {
MessageFormat form = new MessageFormat
(ResourcesMgr.getString
("permission name [name] syntax invalid: "));
Object[] source = {name};
throw new IllegalArgumentException
(form.format(source) + ResourcesMgr.getString
("Principal Name missing end quote"));
}
}
if (testing)
System.out.println("\tprincipalName = '" + principalName + "'");
principalName = principalName.substring
(1, principalName.length() - 1);
if (principalClass.equals("*") &&
!principalName.equals("*")) {
throw new IllegalArgumentException(ResourcesMgr.getString
("PrivateCredentialPermission Principal Class " +
"can not be a wildcard (*) value if Principal Name " +
"is not a wildcard (*) value"));
}
if (testing)
System.out.println("\tprincipalName = '" + principalName + "'");
pList.add(new CredOwner(principalClass, principalName));
}
this.credOwners = new CredOwner[pList.size()];
pList.toArray(this.credOwners);
}
private boolean impliesCredentialClass(String thisC, String thatC) {
// this should never happen
if (thisC == null || thatC == null)
return false;
if (testing)
System.out.println("credential class comparison: " +
thisC + "/" + thatC);
if (thisC.equals("*"))
return true;
/** {@collect.stats}
* XXX let's not enable this for now --
* if people want it, we'll enable it later
*/
/*
if (thisC.endsWith("*")) {
String cClass = thisC.substring(0, thisC.length() - 2);
return thatC.startsWith(cClass);
}
*/
return thisC.equals(thatC);
}
private boolean impliesPrincipalSet(CredOwner[] thisP, CredOwner[] thatP) {
// this should never happen
if (thisP == null || thatP == null)
return false;
if (thatP.length == 0)
return true;
if (thisP.length == 0)
return false;
for (int i = 0; i < thisP.length; i++) {
boolean foundMatch = false;
for (int j = 0; j < thatP.length; j++) {
if (thisP[i].implies(thatP[j])) {
foundMatch = true;
break;
}
}
if (!foundMatch) {
return false;
}
}
return true;
}
/** {@collect.stats}
* Reads this object from a stream (i.e., deserializes it)
*/
private void readObject(java.io.ObjectInputStream s) throws
java.io.IOException,
ClassNotFoundException {
s.defaultReadObject();
// perform new initialization from the permission name
if (getName().indexOf(" ") == -1 && getName().indexOf("\"") == -1) {
// name only has a credential class specified
credentialClass = getName();
credOwners = EMPTY_PRINCIPALS;
} else {
// perform regular initialization
init(getName());
}
}
/** {@collect.stats}
* @serial include
*/
static class CredOwner implements java.io.Serializable {
private static final long serialVersionUID = -5607449830436408266L;
/** {@collect.stats}
* @serial
*/
String principalClass;
/** {@collect.stats}
* @serial
*/
String principalName;
CredOwner(String principalClass, String principalName) {
this.principalClass = principalClass;
this.principalName = principalName;
}
public boolean implies(Object obj) {
if (obj == null || !(obj instanceof CredOwner))
return false;
CredOwner that = (CredOwner)obj;
if (principalClass.equals("*") ||
principalClass.equals(that.principalClass)) {
if (principalName.equals("*") ||
principalName.equals(that.principalName)) {
return true;
}
}
/** {@collect.stats}
* XXX no code yet to support a.b.*
*/
return false;
}
public String toString() {
MessageFormat form = new MessageFormat(ResourcesMgr.getString
("CredOwner:\n\tPrincipal Class = class\n\t" +
"Principal Name = name"));
Object[] source = {principalClass, principalName};
return (form.format(source));
}
}
}
|
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.security.cert;
/** {@collect.stats}
* Certificate Encoding Exception. This is thrown whenever an error
* occurs whilst attempting to encode a certificate.
*
* <p><em>Note: The classes in the package <code>javax.security.cert</code>
* exist for compatibility with earlier versions of the
* Java Secure Sockets Extension (JSSE). New applications should instead
* use the standard Java SE certificate classes located in
* <code>java.security.cert</code>.</em></p>
*
* @since 1.4
* @author Hemma Prafullchandra
*/
public class CertificateEncodingException extends CertificateException {
/** {@collect.stats}
* Constructs a CertificateEncodingException with no detail message. A
* detail message is a String that describes this particular
* exception.
*/
public CertificateEncodingException() {
super();
}
/** {@collect.stats}
* Constructs a CertificateEncodingException with the specified detail
* message. A detail message is a String that describes this
* particular exception.
*
* @param message the detail message.
*/
public CertificateEncodingException(String message) {
super(message);
}
}
|
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.security.cert;
/** {@collect.stats}
* Certificate Parsing Exception. This is thrown whenever
* invalid DER encoded certificate is parsed or unsupported DER features
* are found in the Certificate.
*
* <p><em>Note: The classes in the package <code>javax.security.cert</code>
* exist for compatibility with earlier versions of the
* Java Secure Sockets Extension (JSSE). New applications should instead
* use the standard Java SE certificate classes located in
* <code>java.security.cert</code>.</em></p>
*
* @since 1.4
* @author Hemma Prafullchandra
*/
public class CertificateParsingException extends CertificateException {
/** {@collect.stats}
* Constructs a CertificateParsingException with no detail message. A
* detail message is a String that describes this particular
* exception.
*/
public CertificateParsingException() {
super();
}
/** {@collect.stats}
* Constructs a CertificateParsingException with the specified detail
* message. A detail message is a String that describes this
* particular exception.
*
* @param message the detail message.
*/
public CertificateParsingException(String message) {
super(message);
}
}
|
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.security.cert;
/** {@collect.stats}
* Certificate Expired Exception. This is thrown whenever the current
* <code>Date</code> or the specified <code>Date</code> is after the
* <code>notAfter</code> date/time specified in the validity period
* of the certificate.
*
* <p><em>Note: The classes in the package <code>javax.security.cert</code>
* exist for compatibility with earlier versions of the
* Java Secure Sockets Extension (JSSE). New applications should instead
* use the standard Java SE certificate classes located in
* <code>java.security.cert</code>.</em></p>
*
* @since 1.4
* @author Hemma Prafullchandra
*/
public class CertificateExpiredException extends CertificateException {
/** {@collect.stats}
* Constructs a CertificateExpiredException with no detail message. A
* detail message is a String that describes this particular
* exception.
*/
public CertificateExpiredException() {
super();
}
/** {@collect.stats}
* Constructs a CertificateExpiredException with the specified detail
* message. A detail message is a String that describes this
* particular exception.
*
* @param message the detail message.
*/
public CertificateExpiredException(String message) {
super(message);
}
}
|
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.security.cert;
/** {@collect.stats}
* Certificate is not yet valid exception. This is thrown whenever
* the current <code>Date</code> or the specified <code>Date</code>
* is before the <code>notBefore</code> date/time in the Certificate
* validity period.
*
* <p><em>Note: The classes in the package <code>javax.security.cert</code>
* exist for compatibility with earlier versions of the
* Java Secure Sockets Extension (JSSE). New applications should instead
* use the standard Java SE certificate classes located in
* <code>java.security.cert</code>.</em></p>
*
* @since 1.4
* @author Hemma Prafullchandra
*/
public class CertificateNotYetValidException extends CertificateException {
/** {@collect.stats}
* Constructs a CertificateNotYetValidException with no detail message. A
* detail message is a String that describes this particular
* exception.
*/
public CertificateNotYetValidException() {
super();
}
/** {@collect.stats}
* Constructs a CertificateNotYetValidException with the specified detail
* message. A detail message is a String that describes this
* particular exception.
*
* @param message the detail message.
*/
public CertificateNotYetValidException(String message) {
super(message);
}
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.cert;
/** {@collect.stats}
* This exception indicates one of a variety of certificate problems.
*
* <p><em>Note: The classes in the package <code>javax.security.cert</code>
* exist for compatibility with earlier versions of the
* Java Secure Sockets Extension (JSSE). New applications should instead
* use the standard Java SE certificate classes located in
* <code>java.security.cert</code>.</em></p>
*
* @author Hemma Prafullchandra
* @since 1.4
* @see Certificate
*/
public class CertificateException extends Exception {
/** {@collect.stats}
* Constructs a certificate exception with no detail message. A detail
* message is a String that describes this particular exception.
*/
public CertificateException() {
super();
}
/** {@collect.stats}
* Constructs a certificate exception with the given detail
* message. A detail message is a String that describes this
* particular exception.
*
* @param msg the detail message.
*/
public CertificateException(String msg) {
super(msg);
}
}
|
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.security.cert;
import java.security.PublicKey;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.InvalidKeyException;
import java.security.SignatureException;
/** {@collect.stats}
* <p>Abstract class for managing a variety of identity certificates.
* An identity certificate is a guarantee by a principal that
* a public key is that of another principal. (A principal represents
* an entity such as an individual user, a group, or a corporation.)
*<p>
* This class is an abstraction for certificates that have different
* formats but important common uses. For example, different types of
* certificates, such as X.509 and PGP, share general certificate
* functionality (like encoding and verifying) and
* some types of information (like a public key).
* <p>
* X.509, PGP, and SDSI certificates can all be implemented by
* subclassing the Certificate class, even though they contain different
* sets of information, and they store and retrieve the information in
* different ways.
*
* <p><em>Note: The classes in the package <code>javax.security.cert</code>
* exist for compatibility with earlier versions of the
* Java Secure Sockets Extension (JSSE). New applications should instead
* use the standard Java SE certificate classes located in
* <code>java.security.cert</code>.</em></p>
*
* @since 1.4
* @see X509Certificate
*
* @author Hemma Prafullchandra
*/
public abstract class Certificate {
/** {@collect.stats}
* Compares this certificate for equality with the specified
* object. If the <code>other</code> object is an
* <code>instanceof</code> <code>Certificate</code>, then
* its encoded form is retrieved and compared with the
* encoded form of this certificate.
*
* @param other the object to test for equality with this certificate.
* @return true if the encoded forms of the two certificates
* match, false otherwise.
*/
public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof Certificate))
return false;
try {
byte[] thisCert = this.getEncoded();
byte[] otherCert = ((Certificate)other).getEncoded();
if (thisCert.length != otherCert.length)
return false;
for (int i = 0; i < thisCert.length; i++)
if (thisCert[i] != otherCert[i])
return false;
return true;
} catch (CertificateException e) {
return false;
}
}
/** {@collect.stats}
* Returns a hashcode value for this certificate from its
* encoded form.
*
* @return the hashcode value.
*/
public int hashCode() {
int retval = 0;
try {
byte[] certData = this.getEncoded();
for (int i = 1; i < certData.length; i++) {
retval += certData[i] * i;
}
return (retval);
} catch (CertificateException e) {
return (retval);
}
}
/** {@collect.stats}
* Returns the encoded form of this certificate. It is
* assumed that each certificate type would have only a single
* form of encoding; for example, X.509 certificates would
* be encoded as ASN.1 DER.
*
* @return encoded form of this certificate
* @exception CertificateEncodingException on internal certificate
* encoding failure
*/
public abstract byte[] getEncoded() throws CertificateEncodingException;
/** {@collect.stats}
* Verifies that this certificate was signed using the
* private key that corresponds to the specified public key.
*
* @param key the PublicKey used to carry out the verification.
*
* @exception NoSuchAlgorithmException on unsupported signature
* algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException if there's no default provider.
* @exception SignatureException on signature errors.
* @exception CertificateException on encoding errors.
*/
public abstract void verify(PublicKey key)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException,
SignatureException;
/** {@collect.stats}
* Verifies that this certificate was signed using the
* private key that corresponds to the specified public key.
* This method uses the signature verification engine
* supplied by the specified provider.
*
* @param key the PublicKey used to carry out the verification.
* @param sigProvider the name of the signature provider.
* @exception NoSuchAlgorithmException on unsupported signature algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException on incorrect provider.
* @exception SignatureException on signature errors.
* @exception CertificateException on encoding errors.
*/
public abstract void verify(PublicKey key, String sigProvider)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException,
SignatureException;
/** {@collect.stats}
* Returns a string representation of this certificate.
*
* @return a string representation of this certificate.
*/
public abstract String toString();
/** {@collect.stats}
* Gets the public key from this certificate.
*
* @return the public key.
*/
public abstract PublicKey getPublicKey();
}
|
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.security.cert;
import java.io.InputStream;
import java.lang.Class;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.Security;
import java.math.BigInteger;
import java.security.AccessController;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.PublicKey;
import java.util.BitSet;
import java.util.Date;
/** {@collect.stats}
* Abstract class for X.509 v1 certificates. This provides a standard
* way to access all the version 1 attributes of an X.509 certificate.
* Attributes that are specific to X.509 v2 or v3 are not available
* through this interface. Future API evolution will provide full access to
* complete X.509 v3 attributes.
* <p>
* The basic X.509 format was defined by
* ISO/IEC and ANSI X9 and is described below in ASN.1:
* <pre>
* Certificate ::= SEQUENCE {
* tbsCertificate TBSCertificate,
* signatureAlgorithm AlgorithmIdentifier,
* signature BIT STRING }
* </pre>
* <p>
* These certificates are widely used to support authentication and
* other functionality in Internet security systems. Common applications
* include Privacy Enhanced Mail (PEM), Transport Layer Security (SSL),
* code signing for trusted software distribution, and Secure Electronic
* Transactions (SET).
* <p>
* These certificates are managed and vouched for by <em>Certificate
* Authorities</em> (CAs). CAs are services which create certificates by
* placing data in the X.509 standard format and then digitally signing
* that data. CAs act as trusted third parties, making introductions
* between principals who have no direct knowledge of each other.
* CA certificates are either signed by themselves, or by some other
* CA such as a "root" CA.
* <p>
* The ASN.1 definition of <code>tbsCertificate</code> is:
* <pre>
* TBSCertificate ::= SEQUENCE {
* version [0] EXPLICIT Version DEFAULT v1,
* serialNumber CertificateSerialNumber,
* signature AlgorithmIdentifier,
* issuer Name,
* validity Validity,
* subject Name,
* subjectPublicKeyInfo SubjectPublicKeyInfo,
* }
* </pre>
* <p>
* Here is sample code to instantiate an X.509 certificate:
* <pre>
* InputStream inStream = new FileInputStream("fileName-of-cert");
* X509Certificate cert = X509Certificate.getInstance(inStream);
* inStream.close();
* </pre>
* OR
* <pre>
* byte[] certData = <certificate read from a file, say>
* X509Certificate cert = X509Certificate.getInstance(certData);
* </pre>
* <p>
* In either case, the code that instantiates an X.509 certificate
* consults the Java security properties file to locate the actual
* implementation or instantiates a default implementation.
* <p>
* The Java security properties file is located in the file named
* <JAVA_HOME>/lib/security/java.security.
* <JAVA_HOME> refers to the value of the java.home system property,
* and specifies the directory where the JRE is installed.
* In the Security properties file, a default implementation
* for X.509 v1 may be given such as:
* <pre>
* cert.provider.x509v1=com.sun.security.cert.internal.x509.X509V1CertImpl
* </pre>
* <p>
* The value of this <code>cert.provider.x509v1</code> property has to be
* changed to instatiate another implementation. If this security
* property is not set, a default implementation will be used.
* Currently, due to possible security restrictions on access to
* Security properties, this value is looked up and cached at class
* initialization time and will fallback on a default implementation if
* the Security property is not accessible.
*
* <p><em>Note: The classes in the package <code>javax.security.cert</code>
* exist for compatibility with earlier versions of the
* Java Secure Sockets Extension (JSSE). New applications should instead
* use the standard Java SE certificate classes located in
* <code>java.security.cert</code>.</em></p>
*
* @author Hemma Prafullchandra
* @since 1.4
* @see Certificate
* @see java.security.cert.X509Extension
*/
public abstract class X509Certificate extends Certificate {
/*
* Constant to lookup in the Security properties file.
* In the Security properties file the default implementation
* for X.509 v3 is given as:
* <pre>
* cert.provider.x509v1=com.sun.security.cert.internal.x509.X509V1CertImpl
* </pre>
*/
private static final String X509_PROVIDER = "cert.provider.x509v1";
private static String X509Provider;
static {
X509Provider = AccessController.doPrivileged(
new PrivilegedAction<String>() {
public String run() {
return Security.getProperty(X509_PROVIDER);
}
}
);
}
/** {@collect.stats}
* Instantiates an X509Certificate object, and initializes it with
* the data read from the input stream <code>inStream</code>.
* The implementation (X509Certificate is an abstract class) is
* provided by the class specified as the value of the
* <code>cert.provider.x509v1</code>
* property in the security properties file.
*
* <p>Note: Only one DER-encoded
* certificate is expected to be in the input stream.
* Also, all X509Certificate
* subclasses must provide a constructor of the form:
* <code><pre>
* public <subClass>(InputStream inStream) ...
* </pre></code>
*
* @param inStream an input stream with the data to be read to
* initialize the certificate.
* @return an X509Certificate object initialized with the data
* from the input stream.
* @exception CertificateException if a class initialization
* or certificate parsing error occurs.
*/
public static final X509Certificate getInstance(InputStream inStream)
throws CertificateException {
return getInst((Object)inStream);
}
/** {@collect.stats}
* Instantiates an X509Certificate object, and initializes it with
* the specified byte array.
* The implementation (X509Certificate is an abstract class) is
* provided by the class specified as the value of the
* <code>cert.provider.x509v1</code>
* property in the security properties file.
*
* <p>Note: All X509Certificate
* subclasses must provide a constructor of the form:
* <code><pre>
* public <subClass>(InputStream inStream) ...
* </pre></code>
*
* @param certData a byte array containing the DER-encoded
* certificate.
* @return an X509Certificate object initialized with the data
* from <code>certData</code>.
* @exception CertificateException if a class initialization
* or certificate parsing error occurs.
*/
public static final X509Certificate getInstance(byte[] certData)
throws CertificateException {
return getInst((Object)certData);
}
private static final X509Certificate getInst(Object value)
throws CertificateException {
/*
* This turns out not to work for now. To run under JDK1.2 we would
* need to call beginPrivileged() but we can't do that and run
* under JDK1.1.
*/
String className = X509Provider;
if (className == null || className.length() == 0) {
// shouldn't happen, but assume corrupted properties file
// provide access to sun implementation
className = "com.sun.security.cert.internal.x509.X509V1CertImpl";
}
try {
Class[] params = null;
if (value instanceof InputStream) {
params = new Class[] { InputStream.class };
} else if (value instanceof byte[]) {
params = new Class[] { value.getClass() };
} else
throw new CertificateException("Unsupported argument type");
Class<?> certClass = Class.forName(className);
// get the appropriate constructor and instantiate it
Constructor<?> cons = certClass.getConstructor(params);
// get a new instance
Object obj = cons.newInstance(new Object[] {value});
return (X509Certificate)obj;
} catch (ClassNotFoundException e) {
throw new CertificateException("Could not find class: " + e);
} catch (IllegalAccessException e) {
throw new CertificateException("Could not access class: " + e);
} catch (InstantiationException e) {
throw new CertificateException("Problems instantiating: " + e);
} catch (InvocationTargetException e) {
throw new CertificateException("InvocationTargetException: "
+ e.getTargetException());
} catch (NoSuchMethodException e) {
throw new CertificateException("Could not find class method: "
+ e.getMessage());
}
}
/** {@collect.stats}
* Checks that the certificate is currently valid. It is if
* the current date and time are within the validity period given in the
* certificate.
* <p>
* The validity period consists of two date/time values:
* the first and last dates (and times) on which the certificate
* is valid. It is defined in
* ASN.1 as:
* <pre>
* validity Validity<p>
* Validity ::= SEQUENCE {
* notBefore CertificateValidityDate,
* notAfter CertificateValidityDate }<p>
* CertificateValidityDate ::= CHOICE {
* utcTime UTCTime,
* generalTime GeneralizedTime }
* </pre>
*
* @exception CertificateExpiredException if the certificate has expired.
* @exception CertificateNotYetValidException if the certificate is not
* yet valid.
*/
public abstract void checkValidity()
throws CertificateExpiredException, CertificateNotYetValidException;
/** {@collect.stats}
* Checks that the specified date is within the certificate's
* validity period. In other words, this determines whether the
* certificate would be valid at the specified date/time.
*
* @param date the Date to check against to see if this certificate
* is valid at that date/time.
* @exception CertificateExpiredException if the certificate has expired
* with respect to the <code>date</code> supplied.
* @exception CertificateNotYetValidException if the certificate is not
* yet valid with respect to the <code>date</code> supplied.
* @see #checkValidity()
*/
public abstract void checkValidity(Date date)
throws CertificateExpiredException, CertificateNotYetValidException;
/** {@collect.stats}
* Gets the <code>version</code> (version number) value from the
* certificate. The ASN.1 definition for this is:
* <pre>
* version [0] EXPLICIT Version DEFAULT v1<p>
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
* </pre>
*
* @return the version number from the ASN.1 encoding, i.e. 0, 1 or 2.
*/
public abstract int getVersion();
/** {@collect.stats}
* Gets the <code>serialNumber</code> value from the certificate.
* The serial number is an integer assigned by the certification
* authority to each certificate. It must be unique for each
* certificate issued by a given CA (i.e., the issuer name and
* serial number identify a unique certificate).
* The ASN.1 definition for this is:
* <pre>
* serialNumber CertificateSerialNumber<p>
*
* CertificateSerialNumber ::= INTEGER
* </pre>
*
* @return the serial number.
*/
public abstract BigInteger getSerialNumber();
/** {@collect.stats}
* Gets the <code>issuer</code> (issuer distinguished name) value from
* the certificate. The issuer name identifies the entity that signed (and
* issued) the certificate.
*
* <p>The issuer name field contains an
* X.500 distinguished name (DN).
* The ASN.1 definition for this is:
* <pre>
* issuer Name<p>
*
* Name ::= CHOICE { RDNSequence }
* RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
* RelativeDistinguishedName ::=
* SET OF AttributeValueAssertion
*
* AttributeValueAssertion ::= SEQUENCE {
* AttributeType,
* AttributeValue }
* AttributeType ::= OBJECT IDENTIFIER
* AttributeValue ::= ANY
* </pre>
* The <code>Name</code> describes a hierarchical name composed of
* attributes, such as country name, and corresponding values, such as US.
* The type of the <code>AttributeValue</code> component is determined by
* the <code>AttributeType</code>; in general it will be a
* <code>directoryString</code>. A <code>directoryString</code> is usually
* one of <code>PrintableString</code>,
* <code>TeletexString</code> or <code>UniversalString</code>.
*
* @return a Principal whose name is the issuer distinguished name.
*/
public abstract Principal getIssuerDN();
/** {@collect.stats}
* Gets the <code>subject</code> (subject distinguished name) value
* from the certificate.
* The ASN.1 definition for this is:
* <pre>
* subject Name
* </pre>
*
* <p>See <a href = "#getIssuerDN">getIssuerDN</a> for <code>Name</code>
* and other relevant definitions.
*
* @return a Principal whose name is the subject name.
* @see #getIssuerDN()
*/
public abstract Principal getSubjectDN();
/** {@collect.stats}
* Gets the <code>notBefore</code> date from the validity period of
* the certificate.
* The relevant ASN.1 definitions are:
* <pre>
* validity Validity<p>
*
* Validity ::= SEQUENCE {
* notBefore CertificateValidityDate,
* notAfter CertificateValidityDate }<p>
* CertificateValidityDate ::= CHOICE {
* utcTime UTCTime,
* generalTime GeneralizedTime }
* </pre>
*
* @return the start date of the validity period.
* @see #checkValidity()
*/
public abstract Date getNotBefore();
/** {@collect.stats}
* Gets the <code>notAfter</code> date from the validity period of
* the certificate. See <a href = "#getNotBefore">getNotBefore</a>
* for relevant ASN.1 definitions.
*
* @return the end date of the validity period.
* @see #checkValidity()
*/
public abstract Date getNotAfter();
/** {@collect.stats}
* Gets the signature algorithm name for the certificate
* signature algorithm. An example is the string "SHA-1/DSA".
* The ASN.1 definition for this is:
* <pre>
* signatureAlgorithm AlgorithmIdentifier<p>
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL }
* -- contains a value of the type
* -- registered for use with the
* -- algorithm object identifier value
* </pre>
*
* <p>The algorithm name is determined from the <code>algorithm</code>
* OID string.
*
* @return the signature algorithm name.
*/
public abstract String getSigAlgName();
/** {@collect.stats}
* Gets the signature algorithm OID string from the certificate.
* An OID is represented by a set of positive whole numbers separated
* by periods.
* For example, the string "1.2.840.10040.4.3" identifies the SHA-1
* with DSA signature algorithm, as per the PKIX part I.
*
* <p>See <a href = "#getSigAlgName">getSigAlgName</a> for
* relevant ASN.1 definitions.
*
* @return the signature algorithm OID string.
*/
public abstract String getSigAlgOID();
/** {@collect.stats}
* Gets the DER-encoded signature algorithm parameters from this
* certificate's signature algorithm. In most cases, the signature
* algorithm parameters are null; the parameters are usually
* supplied with the certificate's public key.
*
* <p>See <a href = "#getSigAlgName">getSigAlgName</a> for
* relevant ASN.1 definitions.
*
* @return the DER-encoded signature algorithm parameters, or
* null if no parameters are present.
*/
public abstract byte[] getSigAlgParams();
}
|
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.security.sasl;
import javax.security.auth.callback.CallbackHandler;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
import java.security.Provider;
import java.security.Security;
/** {@collect.stats}
* A static class for creating SASL clients and servers.
*<p>
* This class defines the policy of how to locate, load, and instantiate
* SASL clients and servers.
*<p>
* For example, an application or library gets a SASL client by doing
* something like:
*<blockquote><pre>
* SaslClient sc = Sasl.createSaslClient(mechanisms,
* authorizationId, protocol, serverName, props, callbackHandler);
*</pre></blockquote>
* It can then proceed to use the instance to create an authentication connection.
*<p>
* Similarly, a server gets a SASL server by using code that looks as follows:
*<blockquote><pre>
* SaslServer ss = Sasl.createSaslServer(mechanism,
* protocol, serverName, props, callbackHandler);
*</pre></blockquote>
*
* @since 1.5
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public class Sasl {
// Cannot create one of these
private Sasl() {
}
/** {@collect.stats}
* The name of a property that specifies the quality-of-protection to use.
* The property contains a comma-separated, ordered list
* of quality-of-protection values that the
* client or server is willing to support. A qop value is one of
* <ul>
* <li><tt>"auth"</tt> - authentication only</li>
* <li><tt>"auth-int"</tt> - authentication plus integrity protection</li>
* <li><tt>"auth-conf"</tt> - authentication plus integrity and confidentiality
* protection</li>
* </ul>
*
* The order of the list specifies the preference order of the client or
* server. If this property is absent, the default qop is <tt>"auth"</tt>.
* The value of this constant is <tt>"javax.security.sasl.qop"</tt>.
*/
public static final String QOP = "javax.security.sasl.qop";
/** {@collect.stats}
* The name of a property that specifies the cipher strength to use.
* The property contains a comma-separated, ordered list
* of cipher strength values that
* the client or server is willing to support. A strength value is one of
* <ul>
* <li><tt>"low"</tt></li>
* <li><tt>"medium"</tt></li>
* <li><tt>"high"</tt></li>
* </ul>
* The order of the list specifies the preference order of the client or
* server. An implementation should allow configuration of the meaning
* of these values. An application may use the Java Cryptography
* Extension (JCE) with JCE-aware mechanisms to control the selection of
* cipher suites that match the strength values.
* <BR>
* If this property is absent, the default strength is
* <tt>"high,medium,low"</tt>.
* The value of this constant is <tt>"javax.security.sasl.strength"</tt>.
*/
public static final String STRENGTH = "javax.security.sasl.strength";
/** {@collect.stats}
* The name of a property that specifies whether the
* server must authenticate to the client. The property contains
* <tt>"true"</tt> if the server must
* authenticate the to client; <tt>"false"</tt> otherwise.
* The default is <tt>"false"</tt>.
* <br>The value of this constant is
* <tt>"javax.security.sasl.server.authentication"</tt>.
*/
public static final String SERVER_AUTH =
"javax.security.sasl.server.authentication";
/** {@collect.stats}
* The name of a property that specifies the maximum size of the receive
* buffer in bytes of <tt>SaslClient</tt>/<tt>SaslServer</tt>.
* The property contains the string representation of an integer.
* <br>If this property is absent, the default size
* is defined by the mechanism.
* <br>The value of this constant is <tt>"javax.security.sasl.maxbuffer"</tt>.
*/
public static final String MAX_BUFFER = "javax.security.sasl.maxbuffer";
/** {@collect.stats}
* The name of a property that specifies the maximum size of the raw send
* buffer in bytes of <tt>SaslClient</tt>/<tt>SaslServer</tt>.
* The property contains the string representation of an integer.
* The value of this property is negotiated between the client and server
* during the authentication exchange.
* <br>The value of this constant is <tt>"javax.security.sasl.rawsendsize"</tt>.
*/
public static final String RAW_SEND_SIZE = "javax.security.sasl.rawsendsize";
/** {@collect.stats}
* The name of a property that specifies whether to reuse previously
* authenticated session information. The property contains "true" if the
* mechanism implementation may attempt to reuse previously authenticated
* session information; it contains "false" if the implementation must
* not reuse previously authenticated session information. A setting of
* "true" serves only as a hint: it does not necessarily entail actual
* reuse because reuse might not be possible due to a number of reasons,
* including, but not limited to, lack of mechanism support for reuse,
* expiration of reusable information, and the peer's refusal to support
* reuse.
*
* The property's default value is "false". The value of this constant
* is "javax.security.sasl.reuse".
*
* Note that all other parameters and properties required to create a
* SASL client/server instance must be provided regardless of whether
* this property has been supplied. That is, you cannot supply any less
* information in anticipation of reuse.
*
* Mechanism implementations that support reuse might allow customization
* of its implementation, for factors such as cache size, timeouts, and
* criteria for reuseability. Such customizations are
* implementation-dependent.
*/
public static final String REUSE = "javax.security.sasl.reuse";
/** {@collect.stats}
* The name of a property that specifies
* whether mechanisms susceptible to simple plain passive attacks (e.g.,
* "PLAIN") are not permitted. The property
* contains <tt>"true"</tt> if such mechanisms are not permitted;
* <tt>"false"</tt> if such mechanisms are permitted.
* The default is <tt>"false"</tt>.
* <br>The value of this constant is
* <tt>"javax.security.sasl.policy.noplaintext"</tt>.
*/
public static final String POLICY_NOPLAINTEXT =
"javax.security.sasl.policy.noplaintext";
/** {@collect.stats}
* The name of a property that specifies whether
* mechanisms susceptible to active (non-dictionary) attacks
* are not permitted.
* The property contains <tt>"true"</tt>
* if mechanisms susceptible to active attacks
* are not permitted; <tt>"false"</tt> if such mechanisms are permitted.
* The default is <tt>"false"</tt>.
* <br>The value of this constant is
* <tt>"javax.security.sasl.policy.noactive"</tt>.
*/
public static final String POLICY_NOACTIVE =
"javax.security.sasl.policy.noactive";
/** {@collect.stats}
* The name of a property that specifies whether
* mechanisms susceptible to passive dictionary attacks are not permitted.
* The property contains <tt>"true"</tt>
* if mechanisms susceptible to dictionary attacks are not permitted;
* <tt>"false"</tt> if such mechanisms are permitted.
* The default is <tt>"false"</tt>.
*<br>
* The value of this constant is
* <tt>"javax.security.sasl.policy.nodictionary"</tt>.
*/
public static final String POLICY_NODICTIONARY =
"javax.security.sasl.policy.nodictionary";
/** {@collect.stats}
* The name of a property that specifies whether mechanisms that accept
* anonymous login are not permitted. The property contains <tt>"true"</tt>
* if mechanisms that accept anonymous login are not permitted;
* <tt>"false"</tt>
* if such mechanisms are permitted. The default is <tt>"false"</tt>.
*<br>
* The value of this constant is
* <tt>"javax.security.sasl.policy.noanonymous"</tt>.
*/
public static final String POLICY_NOANONYMOUS =
"javax.security.sasl.policy.noanonymous";
/** {@collect.stats}
* The name of a property that specifies whether mechanisms that implement
* forward secrecy between sessions are required. Forward secrecy
* means that breaking into one session will not automatically
* provide information for breaking into future sessions.
* The property
* contains <tt>"true"</tt> if mechanisms that implement forward secrecy
* between sessions are required; <tt>"false"</tt> if such mechanisms
* are not required. The default is <tt>"false"</tt>.
*<br>
* The value of this constant is
* <tt>"javax.security.sasl.policy.forward"</tt>.
*/
public static final String POLICY_FORWARD_SECRECY =
"javax.security.sasl.policy.forward";
/** {@collect.stats}
* The name of a property that specifies whether
* mechanisms that pass client credentials are required. The property
* contains <tt>"true"</tt> if mechanisms that pass
* client credentials are required; <tt>"false"</tt>
* if such mechanisms are not required. The default is <tt>"false"</tt>.
*<br>
* The value of this constant is
* <tt>"javax.security.sasl.policy.credentials"</tt>.
*/
public static final String POLICY_PASS_CREDENTIALS =
"javax.security.sasl.policy.credentials";
/** {@collect.stats}
* The name of a property that specifies the credentials to use.
* The property contains a mechanism-specific Java credential object.
* Mechanism implementations may examine the value of this property
* to determine whether it is a class that they support.
* The property may be used to supply credentials to a mechanism that
* supports delegated authentication.
*<br>
* The value of this constant is
* <tt>"javax.security.sasl.credentials"</tt>.
*/
public static final String CREDENTIALS = "javax.security.sasl.credentials";
/** {@collect.stats}
* Creates a <tt>SaslClient</tt> using the parameters supplied.
*
* This method uses the
<a href="{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#Provider">JCA Security Provider Framework</a>, described in the
* "Java Cryptography Architecture API Specification & Reference", for
* locating and selecting a <tt>SaslClient</tt> implementation.
*
* First, it
* obtains an ordered list of <tt>SaslClientFactory</tt> instances from
* the registered security providers for the "SaslClientFactory" service
* and the specified SASL mechanism(s). It then invokes
* <tt>createSaslClient()</tt> on each factory instance on the list
* until one produces a non-null <tt>SaslClient</tt> instance. It returns
* the non-null <tt>SaslClient</tt> instance, or null if the search fails
* to produce a non-null <tt>SaslClient</tt> instance.
*<p>
* A security provider for SaslClientFactory registers with the
* JCA Security Provider Framework keys of the form <br>
* <tt>SaslClientFactory.<em>mechanism_name</em></tt>
* <br>
* and values that are class names of implementations of
* <tt>javax.security.sasl.SaslClientFactory</tt>.
*
* For example, a provider that contains a factory class,
* <tt>com.wiz.sasl.digest.ClientFactory</tt>, that supports the
* "DIGEST-MD5" mechanism would register the following entry with the JCA:
* <tt>SaslClientFactory.DIGEST-MD5 com.wiz.sasl.digest.ClientFactory</tt>
*<p>
* See the
* "Java Cryptography Architecture API Specification & Reference"
* for information about how to install and configure security service
* providers.
*
* @param mechanisms The non-null list of mechanism names to try. Each is the
* IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").
* @param authorizationId The possibly null protocol-dependent
* identification to be used for authorization.
* If null or empty, the server derives an authorization
* ID from the client's authentication credentials.
* When the SASL authentication completes successfully,
* the specified entity is granted access.
*
* @param protocol The non-null string name of the protocol for which
* the authentication is being performed (e.g., "ldap").
*
* @param serverName The non-null fully-qualified host name of the server
* to authenticate to.
*
* @param props The possibly null set of properties used to
* select the SASL mechanism and to configure the authentication
* exchange of the selected mechanism.
* For example, if <tt>props</tt> contains the
* <code>Sasl.POLICY_NOPLAINTEXT</code> property with the value
* <tt>"true"</tt>, then the selected
* SASL mechanism must not be susceptible to simple plain passive attacks.
* In addition to the standard properties declared in this class,
* other, possibly mechanism-specific, properties can be included.
* Properties not relevant to the selected mechanism are ignored,
* including any map entries with non-String keys.
*
* @param cbh The possibly null callback handler to used by the SASL
* mechanisms to get further information from the application/library
* to complete the authentication. For example, a SASL mechanism might
* require the authentication ID, password and realm from the caller.
* The authentication ID is requested by using a <tt>NameCallback</tt>.
* The password is requested by using a <tt>PasswordCallback</tt>.
* The realm is requested by using a <tt>RealmChoiceCallback</tt> if there is a list
* of realms to choose from, and by using a <tt>RealmCallback</tt> if
* the realm must be entered.
*
*@return A possibly null <tt>SaslClient</tt> created using the parameters
* supplied. If null, cannot find a <tt>SaslClientFactory</tt>
* that will produce one.
*@exception SaslException If cannot create a <tt>SaslClient</tt> because
* of an error.
*/
public static SaslClient createSaslClient(
String[] mechanisms,
String authorizationId,
String protocol,
String serverName,
Map<String,?> props,
CallbackHandler cbh) throws SaslException {
SaslClient mech = null;
SaslClientFactory fac;
String className;
String mechName;
for (int i = 0; i < mechanisms.length; i++) {
if ((mechName=mechanisms[i]) == null) {
throw new NullPointerException(
"Mechanism name cannot be null");
} else if (mechName.length() == 0) {
continue;
}
String mechFilter = "SaslClientFactory." + mechName;
Provider[] provs = Security.getProviders(mechFilter);
for (int j = 0; provs != null && j < provs.length; j++) {
className = provs[j].getProperty(mechFilter);
if (className == null) {
// Case is ignored
continue;
}
fac = (SaslClientFactory) loadFactory(provs[j], className);
if (fac != null) {
mech = fac.createSaslClient(
new String[]{mechanisms[i]}, authorizationId,
protocol, serverName, props, cbh);
if (mech != null) {
return mech;
}
}
}
}
return null;
}
private static Object loadFactory(Provider p, String className)
throws SaslException {
try {
/*
* Load the implementation class with the same class loader
* that was used to load the provider.
* In order to get the class loader of a class, the
* caller's class loader must be the same as or an ancestor of
* the class loader being returned. Otherwise, the caller must
* have "getClassLoader" permission, or a SecurityException
* will be thrown.
*/
ClassLoader cl = p.getClass().getClassLoader();
Class implClass;
implClass = Class.forName(className, true, cl);
return implClass.newInstance();
} catch (ClassNotFoundException e) {
throw new SaslException("Cannot load class " + className, e);
} catch (InstantiationException e) {
throw new SaslException("Cannot instantiate class " + className, e);
} catch (IllegalAccessException e) {
throw new SaslException("Cannot access class " + className, e);
} catch (SecurityException e) {
throw new SaslException("Cannot access class " + className, e);
}
}
/** {@collect.stats}
* Creates a <tt>SaslServer</tt> for the specified mechanism.
*
* This method uses the
<a href="{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#Provider">JCA Security Provider Framework</a>,
* described in the
* "Java Cryptography Architecture API Specification & Reference", for
* locating and selecting a <tt>SaslServer</tt> implementation.
*
* First, it
* obtains an ordered list of <tt>SaslServerFactory</tt> instances from
* the registered security providers for the "SaslServerFactory" service
* and the specified mechanism. It then invokes
* <tt>createSaslServer()</tt> on each factory instance on the list
* until one produces a non-null <tt>SaslServer</tt> instance. It returns
* the non-null <tt>SaslServer</tt> instance, or null if the search fails
* to produce a non-null <tt>SaslServer</tt> instance.
*<p>
* A security provider for SaslServerFactory registers with the
* JCA Security Provider Framework keys of the form <br>
* <tt>SaslServerFactory.<em>mechanism_name</em></tt>
* <br>
* and values that are class names of implementations of
* <tt>javax.security.sasl.SaslServerFactory</tt>.
*
* For example, a provider that contains a factory class,
* <tt>com.wiz.sasl.digest.ServerFactory</tt>, that supports the
* "DIGEST-MD5" mechanism would register the following entry with the JCA:
* <tt>SaslServerFactory.DIGEST-MD5 com.wiz.sasl.digest.ServerFactory</tt>
*<p>
* See the
* "Java Cryptography Architecture API Specification & Reference"
* for information about how to install and configure security
* service providers.
*
* @param mechanism The non-null mechanism name. It must be an
* IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").
* @param protocol The non-null string name of the protocol for which
* the authentication is being performed (e.g., "ldap").
* @param serverName The non-null fully qualified host name of the server.
* @param props The possibly null set of properties used to
* select the SASL mechanism and to configure the authentication
* exchange of the selected mechanism.
* For example, if <tt>props</tt> contains the
* <code>Sasl.POLICY_NOPLAINTEXT</code> property with the value
* <tt>"true"</tt>, then the selected
* SASL mechanism must not be susceptible to simple plain passive attacks.
* In addition to the standard properties declared in this class,
* other, possibly mechanism-specific, properties can be included.
* Properties not relevant to the selected mechanism are ignored,
* including any map entries with non-String keys.
*
* @param cbh The possibly null callback handler to used by the SASL
* mechanisms to get further information from the application/library
* to complete the authentication. For example, a SASL mechanism might
* require the authentication ID, password and realm from the caller.
* The authentication ID is requested by using a <tt>NameCallback</tt>.
* The password is requested by using a <tt>PasswordCallback</tt>.
* The realm is requested by using a <tt>RealmChoiceCallback</tt> if there is a list
* of realms to choose from, and by using a <tt>RealmCallback</tt> if
* the realm must be entered.
*
*@return A possibly null <tt>SaslServer</tt> created using the parameters
* supplied. If null, cannot find a <tt>SaslServerFactory</tt>
* that will produce one.
*@exception SaslException If cannot create a <tt>SaslServer</tt> because
* of an error.
**/
public static SaslServer
createSaslServer(String mechanism,
String protocol,
String serverName,
Map<String,?> props,
javax.security.auth.callback.CallbackHandler cbh)
throws SaslException {
SaslServer mech = null;
SaslServerFactory fac;
String className;
if (mechanism == null) {
throw new NullPointerException("Mechanism name cannot be null");
} else if (mechanism.length() == 0) {
return null;
}
String mechFilter = "SaslServerFactory." + mechanism;
Provider[] provs = Security.getProviders(mechFilter);
for (int j = 0; provs != null && j < provs.length; j++) {
className = provs[j].getProperty(mechFilter);
if (className == null) {
throw new SaslException("Provider does not support " +
mechFilter);
}
fac = (SaslServerFactory) loadFactory(provs[j], className);
if (fac != null) {
mech = fac.createSaslServer(
mechanism, protocol, serverName, props, cbh);
if (mech != null) {
return mech;
}
}
}
return null;
}
/** {@collect.stats}
* Gets an enumeration of known factories for producing <tt>SaslClient</tt>.
* This method uses the same algorithm for locating factories as
* <tt>createSaslClient()</tt>.
* @return A non-null enumeration of known factories for producing
* <tt>SaslClient</tt>.
* @see #createSaslClient
*/
public static Enumeration<SaslClientFactory> getSaslClientFactories() {
Set<Object> facs = getFactories("SaslClientFactory");
final Iterator<Object> iter = facs.iterator();
return new Enumeration<SaslClientFactory>() {
public boolean hasMoreElements() {
return iter.hasNext();
}
public SaslClientFactory nextElement() {
return (SaslClientFactory)iter.next();
}
};
}
/** {@collect.stats}
* Gets an enumeration of known factories for producing <tt>SaslServer</tt>.
* This method uses the same algorithm for locating factories as
* <tt>createSaslServer()</tt>.
* @return A non-null enumeration of known factories for producing
* <tt>SaslServer</tt>.
* @see #createSaslServer
*/
public static Enumeration<SaslServerFactory> getSaslServerFactories() {
Set<Object> facs = getFactories("SaslServerFactory");
final Iterator<Object> iter = facs.iterator();
return new Enumeration<SaslServerFactory>() {
public boolean hasMoreElements() {
return iter.hasNext();
}
public SaslServerFactory nextElement() {
return (SaslServerFactory)iter.next();
}
};
}
private static Set<Object> getFactories(String serviceName) {
HashSet<Object> result = new HashSet<Object>();
if ((serviceName == null) || (serviceName.length() == 0) ||
(serviceName.endsWith("."))) {
return result;
}
Provider[] providers = Security.getProviders();
HashSet<String> classes = new HashSet<String>();
Object fac;
for (int i = 0; i < providers.length; i++) {
classes.clear();
// Check the keys for each provider.
for (Enumeration e = providers[i].keys(); e.hasMoreElements(); ) {
String currentKey = (String)e.nextElement();
if (currentKey.startsWith(serviceName)) {
// We should skip the currentKey if it contains a
// whitespace. The reason is: such an entry in the
// provider property contains attributes for the
// implementation of an algorithm. We are only interested
// in entries which lead to the implementation
// classes.
if (currentKey.indexOf(" ") < 0) {
String className = providers[i].getProperty(currentKey);
if (!classes.contains(className)) {
classes.add(className);
try {
fac = loadFactory(providers[i], className);
if (fac != null) {
result.add(fac);
}
}catch (Exception ignore) {
}
}
}
}
}
}
return Collections.unmodifiableSet(result);
}
}
|
Java
|
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.sasl;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
/** {@collect.stats}
* An interface for creating instances of <tt>SaslServer</tt>.
* A class that implements this interface
* must be thread-safe and handle multiple simultaneous
* requests. It must also have a public constructor that accepts no
* argument.
*<p>
* This interface is not normally accessed directly by a server, which will use the
* <tt>Sasl</tt> static methods
* instead. However, a particular environment may provide and install a
* new or different <tt>SaslServerFactory</tt>.
*
* @since 1.5
*
* @see SaslServer
* @see Sasl
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public abstract interface SaslServerFactory {
/** {@collect.stats}
* Creates a <tt>SaslServer</tt> using the parameters supplied.
* It returns null
* if no <tt>SaslServer</tt> can be created using the parameters supplied.
* Throws <tt>SaslException</tt> if it cannot create a <tt>SaslServer</tt>
* because of an error.
*
* @param mechanism The non-null
* IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").
* @param protocol The non-null string name of the protocol for which
* the authentication is being performed (e.g., "ldap").
* @param serverName The non-null fully qualified host name of the server
* to authenticate to.
* @param props The possibly null set of properties used to select the SASL
* mechanism and to configure the authentication exchange of the selected
* mechanism. See the <tt>Sasl</tt> class for a list of standard properties.
* Other, possibly mechanism-specific, properties can be included.
* Properties not relevant to the selected mechanism are ignored,
* including any map entries with non-String keys.
*
* @param cbh The possibly null callback handler to used by the SASL
* mechanisms to get further information from the application/library
* to complete the authentication. For example, a SASL mechanism might
* require the authentication ID, password and realm from the caller.
* The authentication ID is requested by using a <tt>NameCallback</tt>.
* The password is requested by using a <tt>PasswordCallback</tt>.
* The realm is requested by using a <tt>RealmChoiceCallback</tt> if there is a list
* of realms to choose from, and by using a <tt>RealmCallback</tt> if
* the realm must be entered.
*
*@return A possibly null <tt>SaslServer</tt> created using the parameters
* supplied. If null, this factory cannot produce a <tt>SaslServer</tt>
* using the parameters supplied.
*@exception SaslException If cannot create a <tt>SaslServer</tt> because
* of an error.
*/
public abstract SaslServer createSaslServer(
String mechanism,
String protocol,
String serverName,
Map<String,?> props,
CallbackHandler cbh) throws SaslException;
/** {@collect.stats}
* Returns an array of names of mechanisms that match the specified
* mechanism selection policies.
* @param props The possibly null set of properties used to specify the
* security policy of the SASL mechanisms. For example, if <tt>props</tt>
* contains the <tt>Sasl.POLICY_NOPLAINTEXT</tt> property with the value
* <tt>"true"</tt>, then the factory must not return any SASL mechanisms
* that are susceptible to simple plain passive attacks.
* See the <tt>Sasl</tt> class for a complete list of policy properties.
* Non-policy related properties, if present in <tt>props</tt>, are ignored,
* including any map entries with non-String keys.
* @return A non-null array containing a IANA-registered SASL mechanism names.
*/
public abstract String[] getMechanismNames(Map<String,?> props);
}
|
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.security.sasl;
/** {@collect.stats}
* Performs SASL authentication as a server.
*<p>
* A server such an LDAP server gets an instance of this
* class in order to perform authentication defined by a specific SASL
* mechanism. Invoking methods on the <tt>SaslServer</tt> instance
* generates challenges according to the SASL
* mechanism implemented by the <tt>SaslServer</tt>.
* As the authentication proceeds, the instance
* encapsulates the state of a SASL server's authentication exchange.
*<p>
* Here's an example of how an LDAP server might use a <tt>SaslServer</tt>.
* It first gets an instance of a <tt>SaslServer</tt> for the SASL mechanism
* requested by the client:
*<blockquote><pre>
* SaslServer ss = Sasl.createSaslServer(mechanism,
* "ldap", myFQDN, props, callbackHandler);
*</pre></blockquote>
* It can then proceed to use the server for authentication.
* For example, suppose the LDAP server received an LDAP BIND request
* containing the name of the SASL mechanism and an (optional) initial
* response. It then might use the server as follows:
*<blockquote><pre>
* while (!ss.isComplete()) {
* try {
* byte[] challenge = ss.evaluateResponse(response);
* if (ss.isComplete()) {
* status = ldap.sendBindResponse(mechanism, challenge, SUCCESS);
* } else {
* status = ldap.sendBindResponse(mechanism, challenge,
SASL_BIND_IN_PROGRESS);
* response = ldap.readBindRequest();
* }
* } catch (SaslException e) {
* status = ldap.sendErrorResponse(e);
* break;
* }
* }
* if (ss.isComplete() && status == SUCCESS) {
* String qop = (String) sc.getNegotiatedProperty(Sasl.QOP);
* if (qop != null
* && (qop.equalsIgnoreCase("auth-int")
* || qop.equalsIgnoreCase("auth-conf"))) {
*
* // Use SaslServer.wrap() and SaslServer.unwrap() for future
* // communication with client
* ldap.in = new SecureInputStream(ss, ldap.in);
* ldap.out = new SecureOutputStream(ss, ldap.out);
* }
* }
*</pre></blockquote>
*
* @since 1.5
*
* @see Sasl
* @see SaslServerFactory
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public abstract interface SaslServer {
/** {@collect.stats}
* Returns the IANA-registered mechanism name of this SASL server.
* (e.g. "CRAM-MD5", "GSSAPI").
* @return A non-null string representing the IANA-registered mechanism name.
*/
public abstract String getMechanismName();
/** {@collect.stats}
* Evaluates the response data and generates a challenge.
*
* If a response is received from the client during the authentication
* process, this method is called to prepare an appropriate next
* challenge to submit to the client. The challenge is null if the
* authentication has succeeded and no more challenge data is to be sent
* to the client. It is non-null if the authentication must be continued
* by sending a challenge to the client, or if the authentication has
* succeeded but challenge data needs to be processed by the client.
* <tt>isComplete()</tt> should be called
* after each call to <tt>evaluateResponse()</tt>,to determine if any further
* response is needed from the client.
*
* @param response The non-null (but possibly empty) response sent
* by the client.
*
* @return The possibly null challenge to send to the client.
* It is null if the authentication has succeeded and there is
* no more challenge data to be sent to the client.
* @exception SaslException If an error occurred while processing
* the response or generating a challenge.
*/
public abstract byte[] evaluateResponse(byte[] response)
throws SaslException;
/** {@collect.stats}
* Determines whether the authentication exchange has completed.
* This method is typically called after each invocation of
* <tt>evaluateResponse()</tt> to determine whether the
* authentication has completed successfully or should be continued.
* @return true if the authentication exchange has completed; false otherwise.
*/
public abstract boolean isComplete();
/** {@collect.stats}
* Reports the authorization ID in effect for the client of this
* session.
* This method can only be called if isComplete() returns true.
* @return The authorization ID of the client.
* @exception IllegalStateException if this authentication session has not completed
*/
public String getAuthorizationID();
/** {@collect.stats}
* Unwraps a byte array received from the client.
* This method can be called only after the authentication exchange has
* completed (i.e., when <tt>isComplete()</tt> returns true) and only if
* the authentication exchange has negotiated integrity and/or privacy
* as the quality of protection; otherwise,
* an <tt>IllegalStateException</tt> is thrown.
*<p>
* <tt>incoming</tt> is the contents of the SASL buffer as defined in RFC 2222
* without the leading four octet field that represents the length.
* <tt>offset</tt> and <tt>len</tt> specify the portion of <tt>incoming</tt>
* to use.
*
* @param incoming A non-null byte array containing the encoded bytes
* from the client.
* @param offset The starting position at <tt>incoming</tt> of the bytes to use.
* @param len The number of bytes from <tt>incoming</tt> to use.
* @return A non-null byte array containing the decoded bytes.
* @exception SaslException if <tt>incoming</tt> cannot be successfully
* unwrapped.
* @exception IllegalStateException if the authentication exchange has
* not completed, or if the negotiated quality of protection
* has neither integrity nor privacy
*/
public abstract byte[] unwrap(byte[] incoming, int offset, int len)
throws SaslException;
/** {@collect.stats}
* Wraps a byte array to be sent to the client.
* This method can be called only after the authentication exchange has
* completed (i.e., when <tt>isComplete()</tt> returns true) and only if
* the authentication exchange has negotiated integrity and/or privacy
* as the quality of protection; otherwise, a <tt>SaslException</tt> is thrown.
*<p>
* The result of this method
* will make up the contents of the SASL buffer as defined in RFC 2222
* without the leading four octet field that represents the length.
* <tt>offset</tt> and <tt>len</tt> specify the portion of <tt>outgoing</tt>
* to use.
*
* @param outgoing A non-null byte array containing the bytes to encode.
* @param offset The starting position at <tt>outgoing</tt> of the bytes to use.
* @param len The number of bytes from <tt>outgoing</tt> to use.
* @return A non-null byte array containing the encoded bytes.
* @exception SaslException if <tt>outgoing</tt> cannot be successfully
* wrapped.
* @exception IllegalStateException if the authentication exchange has
* not completed, or if the negotiated quality of protection has
* neither integrity nor privacy.
*/
public abstract byte[] wrap(byte[] outgoing, int offset, int len)
throws SaslException;
/** {@collect.stats}
* Retrieves the negotiated property.
* This method can be called only after the authentication exchange has
* completed (i.e., when <tt>isComplete()</tt> returns true); otherwise, an
* <tt>IllegalStateException</tt> is thrown.
*
* @param propName the property
* @return The value of the negotiated property. If null, the property was
* not negotiated or is not applicable to this mechanism.
* @exception IllegalStateException if this authentication exchange has not completed
*/
public abstract Object getNegotiatedProperty(String propName);
/** {@collect.stats}
* Disposes of any system resources or security-sensitive information
* the SaslServer might be using. Invoking this method invalidates
* the SaslServer instance. This method is idempotent.
* @throws SaslException If a problem was encountered while disposing
* the resources.
*/
public abstract void dispose() throws SaslException;
}
|
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.security.sasl;
/** {@collect.stats}
* This exception is thrown by a SASL mechanism implementation
* to indicate that the SASL
* exchange has failed due to reasons related to authentication, such as
* an invalid identity, passphrase, or key.
* <p>
* Note that the lack of an AuthenticationException does not mean that
* the failure was not due to an authentication error. A SASL mechanism
* implementation might throw the more general SaslException instead of
* AuthenticationException if it is unable to determine the nature
* of the failure, or if does not want to disclose the nature of
* the failure, for example, due to security reasons.
*
* @since 1.5
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public class AuthenticationException extends SaslException {
/** {@collect.stats}
* Constructs a new instance of <tt>AuthenticationException</tt>.
* The root exception and the detailed message are null.
*/
public AuthenticationException () {
super();
}
/** {@collect.stats}
* Constructs a new instance of <tt>AuthenticationException</tt>
* with a detailed message.
* The root exception is null.
* @param detail A possibly null string containing details of the exception.
*
* @see java.lang.Throwable#getMessage
*/
public AuthenticationException (String detail) {
super(detail);
}
/** {@collect.stats}
* Constructs a new instance of <tt>AuthenticationException</tt> with a detailed message
* and a root exception.
*
* @param detail A possibly null string containing details of the exception.
* @param ex A possibly null root exception that caused this exception.
*
* @see java.lang.Throwable#getMessage
* @see #getCause
*/
public AuthenticationException (String detail, Throwable ex) {
super(detail, ex);
}
/** {@collect.stats} Use serialVersionUID from JSR 28 RI for interoperability */
private static final long serialVersionUID = -3579708765071815007L;
}
|
Java
|
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.sasl;
import javax.security.auth.callback.ChoiceCallback;
/** {@collect.stats}
* This callback is used by <tt>SaslClient</tt> and <tt>SaslServer</tt>
* to obtain a realm given a list of realm choices.
*
* @since 1.5
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public class RealmChoiceCallback extends ChoiceCallback {
/** {@collect.stats}
* Constructs a <tt>RealmChoiceCallback</tt> with a prompt, a list of
* choices and a default choice.
*
* @param prompt the non-null prompt to use to request the realm.
* @param choices the non-null list of realms to choose from.
* @param defaultChoice the choice to be used as the default choice
* when the list of choices is displayed. It is an index into
* the <tt>choices</tt> arary.
* @param multiple true if multiple choices allowed; false otherwise
* @throws IllegalArgumentException If <tt>prompt</tt> is null or the empty string,
* if <tt>choices</tt> has a length of 0, if any element from
* <tt>choices</tt> is null or empty, or if <tt>defaultChoice</tt>
* does not fall within the array boundary of <tt>choices</tt>
*/
public RealmChoiceCallback(String prompt, String[]choices,
int defaultChoice, boolean multiple) {
super(prompt, choices, defaultChoice, multiple);
}
private static final long serialVersionUID = -8588141348846281332L;
}
|
Java
|
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.sasl;
import javax.security.auth.callback.TextInputCallback;
/** {@collect.stats}
* This callback is used by <tt>SaslClient</tt> and <tt>SaslServer</tt>
* to retrieve realm information.
*
* @since 1.5
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public class RealmCallback extends TextInputCallback {
/** {@collect.stats}
* Constructs a <tt>RealmCallback</tt> with a prompt.
*
* @param prompt The non-null prompt to use to request the realm information.
* @throws IllegalArgumentException If <tt>prompt</tt> is null or
* the empty string.
*/
public RealmCallback(String prompt) {
super(prompt);
}
/** {@collect.stats}
* Constructs a <tt>RealmCallback</tt> with a prompt and default
* realm information.
*
* @param prompt The non-null prompt to use to request the realm information.
* @param defaultRealmInfo The non-null default realm information to use.
* @throws IllegalArgumentException If <tt>prompt</tt> is null or
* the empty string,
* or if <tt>defaultRealm</tt> is empty or null.
*/
public RealmCallback(String prompt, String defaultRealmInfo) {
super(prompt, defaultRealmInfo);
}
private static final long serialVersionUID = -4342673378785456908L;
}
|
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.security.sasl;
import java.io.IOException;
/** {@collect.stats}
* This class represents an error that has occurred when using SASL.
*
* @since 1.5
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public class SaslException extends IOException {
/** {@collect.stats}
* The possibly null root cause exception.
* @serial
*/
// Required for serialization interoperability with JSR 28
private Throwable _exception;
/** {@collect.stats}
* Constructs a new instance of <tt>SaslException</tt>.
* The root exception and the detailed message are null.
*/
public SaslException () {
super();
}
/** {@collect.stats}
* Constructs a new instance of <tt>SaslException</tt> with a detailed message.
* The root exception is null.
* @param detail A possibly null string containing details of the exception.
*
* @see java.lang.Throwable#getMessage
*/
public SaslException (String detail) {
super(detail);
}
/** {@collect.stats}
* Constructs a new instance of <tt>SaslException</tt> with a detailed message
* and a root exception.
* For example, a SaslException might result from a problem with
* the callback handler, which might throw a NoSuchCallbackException if
* it does not support the requested callback, or throw an IOException
* if it had problems obtaining data for the callback. The
* SaslException's root exception would be then be the exception thrown
* by the callback handler.
*
* @param detail A possibly null string containing details of the exception.
* @param ex A possibly null root exception that caused this exception.
*
* @see java.lang.Throwable#getMessage
* @see #getCause
*/
public SaslException (String detail, Throwable ex) {
super(detail);
if (ex != null) {
initCause(ex);
}
}
/*
* Override Throwable.getCause() to ensure deserialized object from
* JSR 28 would return same value for getCause() (i.e., _exception).
*/
public Throwable getCause() {
return _exception;
}
/*
* Override Throwable.initCause() to match getCause() by updating
* _exception as well.
*/
public Throwable initCause(Throwable cause) {
super.initCause(cause);
_exception = cause;
return this;
}
/** {@collect.stats}
* Returns the string representation of this exception.
* The string representation contains
* this exception's class name, its detailed messsage, and if
* it has a root exception, the string representation of the root
* exception. This string representation
* is meant for debugging and not meant to be interpreted
* programmatically.
* @return The non-null string representation of this exception.
* @see java.lang.Throwable#getMessage
*/
// Override Throwable.toString() to conform to JSR 28
public String toString() {
String answer = super.toString();
if (_exception != null && _exception != this) {
answer += " [Caused by " + _exception.toString() + "]";
}
return answer;
}
/** {@collect.stats} Use serialVersionUID from JSR 28 RI for interoperability */
private static final long serialVersionUID = 4579784287983423626L;
}
|
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.security.sasl;
/** {@collect.stats}
* Performs SASL authentication as a client.
*<p>
* A protocol library such as one for LDAP gets an instance of this
* class in order to perform authentication defined by a specific SASL
* mechanism. Invoking methods on the <tt>SaslClient</tt> instance
* process challenges and create responses according to the SASL
* mechanism implemented by the <tt>SaslClient</tt>.
* As the authentication proceeds, the instance
* encapsulates the state of a SASL client's authentication exchange.
*<p>
* Here's an example of how an LDAP library might use a <tt>SaslClient</tt>.
* It first gets an instance of a <tt>SaslClient</tt>:
*<blockquote><pre>
* SaslClient sc = Sasl.createSaslClient(mechanisms,
* authorizationId, protocol, serverName, props, callbackHandler);
*</pre></blockquote>
* It can then proceed to use the client for authentication.
* For example, an LDAP library might use the client as follows:
*<blockquote><pre>
* // Get initial response and send to server
* byte[] response = (sc.hasInitialResponse() ? sc.evaluateChallenge(new byte[0]) :
* null);
* LdapResult res = ldap.sendBindRequest(dn, sc.getName(), response);
* while (!sc.isComplete() &&
* (res.status == SASL_BIND_IN_PROGRESS || res.status == SUCCESS)) {
* response = sc.evaluateChallenge(res.getBytes());
* if (res.status == SUCCESS) {
* // we're done; don't expect to send another BIND
* if (response != null) {
* throw new SaslException(
* "Protocol error: attempting to send response after completion");
* }
* break;
* }
* res = ldap.sendBindRequest(dn, sc.getName(), response);
* }
* if (sc.isComplete() && res.status == SUCCESS) {
* String qop = (String) sc.getNegotiatedProperty(Sasl.QOP);
* if (qop != null
* && (qop.equalsIgnoreCase("auth-int")
* || qop.equalsIgnoreCase("auth-conf"))) {
*
* // Use SaslClient.wrap() and SaslClient.unwrap() for future
* // communication with server
* ldap.in = new SecureInputStream(sc, ldap.in);
* ldap.out = new SecureOutputStream(sc, ldap.out);
* }
* }
*</pre></blockquote>
*
* If the mechanism has an initial response, the library invokes
* <tt>evaluateChallenge()</tt> with an empty
* challenge and to get initial response.
* Protocols such as IMAP4, which do not include an initial response with
* their first authentication command to the server, initiates the
* authentication without first calling <tt>hasInitialResponse()</tt>
* or <tt>evaluateChallenge()</tt>.
* When the server responds to the command, it sends an initial challenge.
* For a SASL mechanism in which the client sends data first, the server should
* have issued a challenge with no data. This will then result in a call
* (on the client) to <tt>evaluateChallenge()</tt> with an empty challenge.
*
* @since 1.5
*
* @see Sasl
* @see SaslClientFactory
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public abstract interface SaslClient {
/** {@collect.stats}
* Returns the IANA-registered mechanism name of this SASL client.
* (e.g. "CRAM-MD5", "GSSAPI").
* @return A non-null string representing the IANA-registered mechanism name.
*/
public abstract String getMechanismName();
/** {@collect.stats}
* Determines whether this mechanism has an optional initial response.
* If true, caller should call <tt>evaluateChallenge()</tt> with an
* empty array to get the initial response.
*
* @return true if this mechanism has an initial response.
*/
public abstract boolean hasInitialResponse();
/** {@collect.stats}
* Evaluates the challenge data and generates a response.
* If a challenge is received from the server during the authentication
* process, this method is called to prepare an appropriate next
* response to submit to the server.
*
* @param challenge The non-null challenge sent from the server.
* The challenge array may have zero length.
*
* @return The possibly null reponse to send to the server.
* It is null if the challenge accompanied a "SUCCESS" status and the challenge
* only contains data for the client to update its state and no response
* needs to be sent to the server. The response is a zero-length byte
* array if the client is to send a response with no data.
* @exception SaslException If an error occurred while processing
* the challenge or generating a response.
*/
public abstract byte[] evaluateChallenge(byte[] challenge)
throws SaslException;
/** {@collect.stats}
* Determines whether the authentication exchange has completed.
* This method may be called at any time, but typically, it
* will not be called until the caller has received indication
* from the server
* (in a protocol-specific manner) that the exchange has completed.
*
* @return true if the authentication exchange has completed; false otherwise.
*/
public abstract boolean isComplete();
/** {@collect.stats}
* Unwraps a byte array received from the server.
* This method can be called only after the authentication exchange has
* completed (i.e., when <tt>isComplete()</tt> returns true) and only if
* the authentication exchange has negotiated integrity and/or privacy
* as the quality of protection; otherwise, an
* <tt>IllegalStateException</tt> is thrown.
*<p>
* <tt>incoming</tt> is the contents of the SASL buffer as defined in RFC 2222
* without the leading four octet field that represents the length.
* <tt>offset</tt> and <tt>len</tt> specify the portion of <tt>incoming</tt>
* to use.
*
* @param incoming A non-null byte array containing the encoded bytes
* from the server.
* @param offset The starting position at <tt>incoming</tt> of the bytes to use.
* @param len The number of bytes from <tt>incoming</tt> to use.
* @return A non-null byte array containing the decoded bytes.
* @exception SaslException if <tt>incoming</tt> cannot be successfully
* unwrapped.
* @exception IllegalStateException if the authentication exchange has
* not completed, or if the negotiated quality of protection
* has neither integrity nor privacy.
*/
public abstract byte[] unwrap(byte[] incoming, int offset, int len)
throws SaslException;
/** {@collect.stats}
* Wraps a byte array to be sent to the server.
* This method can be called only after the authentication exchange has
* completed (i.e., when <tt>isComplete()</tt> returns true) and only if
* the authentication exchange has negotiated integrity and/or privacy
* as the quality of protection; otherwise, an
* <tt>IllegalStateException</tt> is thrown.
*<p>
* The result of this method will make up the contents of the SASL buffer
* as defined in RFC 2222 without the leading four octet field that
* represents the length.
* <tt>offset</tt> and <tt>len</tt> specify the portion of <tt>outgoing</tt>
* to use.
*
* @param outgoing A non-null byte array containing the bytes to encode.
* @param offset The starting position at <tt>outgoing</tt> of the bytes to use.
* @param len The number of bytes from <tt>outgoing</tt> to use.
* @return A non-null byte array containing the encoded bytes.
* @exception SaslException if <tt>outgoing</tt> cannot be successfully
* wrapped.
* @exception IllegalStateException if the authentication exchange has
* not completed, or if the negotiated quality of protection
* has neither integrity nor privacy.
*/
public abstract byte[] wrap(byte[] outgoing, int offset, int len)
throws SaslException;
/** {@collect.stats}
* Retrieves the negotiated property.
* This method can be called only after the authentication exchange has
* completed (i.e., when <tt>isComplete()</tt> returns true); otherwise, an
* <tt>IllegalStateException</tt> is thrown.
*
* @param propName The non-null property name.
* @return The value of the negotiated property. If null, the property was
* not negotiated or is not applicable to this mechanism.
* @exception IllegalStateException if this authentication exchange
* has not completed
*/
public abstract Object getNegotiatedProperty(String propName);
/** {@collect.stats}
* Disposes of any system resources or security-sensitive information
* the SaslClient might be using. Invoking this method invalidates
* the SaslClient instance. This method is idempotent.
* @throws SaslException If a problem was encountered while disposing
* the resources.
*/
public abstract void dispose() throws SaslException;
}
|
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.security.sasl;
import javax.security.auth.callback.Callback;
/** {@collect.stats}
* This callback is used by <tt>SaslServer</tt> to determine whether
* one entity (identified by an authenticated authentication id)
* can act on
* behalf of another entity (identified by an authorization id).
*
* @since 1.5
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public class AuthorizeCallback implements Callback, java.io.Serializable {
/** {@collect.stats}
* The (authenticated) authentication id to check.
* @serial
*/
private String authenticationID;
/** {@collect.stats}
* The authorization id to check.
* @serial
*/
private String authorizationID;
/** {@collect.stats}
* The id of the authorized entity. If null, the id of
* the authorized entity is authorizationID.
* @serial
*/
private String authorizedID;
/** {@collect.stats}
* A flag indicating whether the authentication id is allowed to
* act on behalf of the authorization id.
* @serial
*/
private boolean authorized;
/** {@collect.stats}
* Constructs an instance of <tt>AuthorizeCallback</tt>.
*
* @param authnID The (authenticated) authentication id.
* @param authzID The authorization id.
*/
public AuthorizeCallback(String authnID, String authzID) {
authenticationID = authnID;
authorizationID = authzID;
}
/** {@collect.stats}
* Returns the authentication id to check.
* @return The authentication id to check.
*/
public String getAuthenticationID() {
return authenticationID;
}
/** {@collect.stats}
* Returns the authorization id to check.
* @return The authentication id to check.
*/
public String getAuthorizationID() {
return authorizationID;
}
/** {@collect.stats}
* Determines whether the authentication id is allowed to
* act on behalf of the authorization id.
*
* @return <tt>true</tt> if authorization is allowed; <tt>false</tt> otherwise
* @see #setAuthorized(boolean)
* @see #getAuthorizedID()
*/
public boolean isAuthorized() {
return authorized;
}
/** {@collect.stats}
* Sets whether the authorization is allowed.
* @param ok <tt>true</tt> if authorization is allowed; <tt>false</tt> otherwise
* @see #isAuthorized
* @see #setAuthorizedID(java.lang.String)
*/
public void setAuthorized(boolean ok) {
authorized = ok;
}
/** {@collect.stats}
* Returns the id of the authorized user.
* @return The id of the authorized user. <tt>null</tt> means the
* authorization failed.
* @see #setAuthorized(boolean)
* @see #setAuthorizedID(java.lang.String)
*/
public String getAuthorizedID() {
if (!authorized) {
return null;
}
return (authorizedID == null) ? authorizationID : authorizedID;
}
/** {@collect.stats}
* Sets the id of the authorized entity. Called by handler only when the id
* is different from getAuthorizationID(). For example, the id
* might need to be canonicalized for the environment in which it
* will be used.
* @param id The id of the authorized user.
* @see #setAuthorized(boolean)
* @see #getAuthorizedID
*/
public void setAuthorizedID(String id) {
authorizedID = id;
}
private static final long serialVersionUID = -2353344186490470805L;
}
|
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.security.sasl;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
/** {@collect.stats}
* An interface for creating instances of <tt>SaslClient</tt>.
* A class that implements this interface
* must be thread-safe and handle multiple simultaneous
* requests. It must also have a public constructor that accepts no
* argument.
*<p>
* This interface is not normally accessed directly by a client, which will use the
* <tt>Sasl</tt> static methods
* instead. However, a particular environment may provide and install a
* new or different <tt>SaslClientFactory</tt>.
*
* @since 1.5
*
* @see SaslClient
* @see Sasl
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public abstract interface SaslClientFactory {
/** {@collect.stats}
* Creates a SaslClient using the parameters supplied.
*
* @param mechanisms The non-null list of mechanism names to try. Each is the
* IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").
* @param authorizationId The possibly null protocol-dependent
* identification to be used for authorization.
* If null or empty, the server derives an authorization
* ID from the client's authentication credentials.
* When the SASL authentication completes successfully,
* the specified entity is granted access.
* @param protocol The non-null string name of the protocol for which
* the authentication is being performed (e.g., "ldap").
* @param serverName The non-null fully qualified host name
* of the server to authenticate to.
* @param props The possibly null set of properties used to select the SASL
* mechanism and to configure the authentication exchange of the selected
* mechanism. See the <tt>Sasl</tt> class for a list of standard properties.
* Other, possibly mechanism-specific, properties can be included.
* Properties not relevant to the selected mechanism are ignored,
* including any map entries with non-String keys.
*
* @param cbh The possibly null callback handler to used by the SASL
* mechanisms to get further information from the application/library
* to complete the authentication. For example, a SASL mechanism might
* require the authentication ID, password and realm from the caller.
* The authentication ID is requested by using a <tt>NameCallback</tt>.
* The password is requested by using a <tt>PasswordCallback</tt>.
* The realm is requested by using a <tt>RealmChoiceCallback</tt> if there is a list
* of realms to choose from, and by using a <tt>RealmCallback</tt> if
* the realm must be entered.
*
*@return A possibly null <tt>SaslClient</tt> created using the parameters
* supplied. If null, this factory cannot produce a <tt>SaslClient</tt>
* using the parameters supplied.
*@exception SaslException If cannot create a <tt>SaslClient</tt> because
* of an error.
*/
public abstract SaslClient createSaslClient(
String[] mechanisms,
String authorizationId,
String protocol,
String serverName,
Map<String,?> props,
CallbackHandler cbh) throws SaslException;
/** {@collect.stats}
* Returns an array of names of mechanisms that match the specified
* mechanism selection policies.
* @param props The possibly null set of properties used to specify the
* security policy of the SASL mechanisms. For example, if <tt>props</tt>
* contains the <tt>Sasl.POLICY_NOPLAINTEXT</tt> property with the value
* <tt>"true"</tt>, then the factory must not return any SASL mechanisms
* that are susceptible to simple plain passive attacks.
* See the <tt>Sasl</tt> class for a complete list of policy properties.
* Non-policy related properties, if present in <tt>props</tt>, are ignored,
* including any map entries with non-String keys.
* @return A non-null array containing a IANA-registered SASL mechanism names.
*/
public abstract String[] getMechanismNames(Map<String,?> props);
}
|
Java
|
/*
* Copyright (c) 1997, 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.net;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
/** {@collect.stats}
* This class creates sockets. It may be subclassed by other factories,
* which create particular subclasses of sockets and thus provide a general
* framework for the addition of public socket-level functionality.
*
* <P> Socket factories are a simple way to capture a variety of policies
* related to the sockets being constructed, producing such sockets in
* a way which does not require special configuration of the code which
* asks for the sockets: <UL>
*
* <LI> Due to polymorphism of both factories and sockets, different
* kinds of sockets can be used by the same application code just
* by passing it different kinds of factories.
*
* <LI> Factories can themselves be customized with parameters used
* in socket construction. So for example, factories could be
* customized to return sockets with different networking timeouts
* or security parameters already configured.
*
* <LI> The sockets returned to the application can be subclasses
* of java.net.Socket, so that they can directly expose new APIs
* for features such as compression, security, record marking,
* statistics collection, or firewall tunneling.
*
* </UL>
*
* <P> Factory classes are specified by environment-specific configuration
* mechanisms. For example, the <em>getDefault</em> method could return
* a factory that was appropriate for a particular user or applet, and a
* framework could use a factory customized to its own purposes.
*
* @since 1.4
* @see ServerSocketFactory
*
* @author David Brownell
*/
public abstract class SocketFactory
{
//
// NOTE: JDK 1.1 bug in class GC, this can get collected
// even though it's always accessible via getDefault().
//
private static SocketFactory theFactory;
/** {@collect.stats}
* Creates a <code>SocketFactory</code>.
*/
protected SocketFactory() { /* NOTHING */ }
/** {@collect.stats}
* Returns a copy of the environment's default socket factory.
*
* @return the default <code>SocketFactory</code>
*/
public static SocketFactory getDefault()
{
synchronized (SocketFactory.class) {
if (theFactory == null) {
//
// Different implementations of this method SHOULD
// work rather differently. For example, driving
// this from a system property, or using a different
// implementation than JavaSoft's.
//
theFactory = new DefaultSocketFactory();
}
}
return theFactory;
}
/** {@collect.stats}
* Creates an unconnected socket.
*
* @return the unconnected socket
* @throws IOException if the socket cannot be created
* @see java.net.Socket#connect(java.net.SocketAddress)
* @see java.net.Socket#connect(java.net.SocketAddress, int)
* @see java.net.Socket#Socket()
*/
public Socket createSocket() throws IOException {
//
// bug 6771432:
// The Exception is used by HttpsClient to signal that
// unconnected sockets have not been implemented.
//
UnsupportedOperationException uop = new
UnsupportedOperationException();
SocketException se = new SocketException(
"Unconnected sockets not implemented");
se.initCause(uop);
throw se;
}
/** {@collect.stats}
* Creates a socket and connects it to the specified remote host
* at the specified remote port. This socket is configured using
* the socket options established for this factory.
*
* @param host the server host
* @param port the server port
* @return the <code>Socket</code>
* @throws IOException if an I/O error occurs when creating the socket
* @throws UnknownHostException if the host is not known
* @see java.net.Socket#Socket(String, int)
*/
public abstract Socket createSocket(String host, int port)
throws IOException, UnknownHostException;
/** {@collect.stats}
* Creates a socket and connects it to the specified remote host
* on the specified remote port.
* The socket will also be bound to the local address and port supplied.
* This socket is configured using
* the socket options established for this factory.
*
* @param host the server host
* @param port the server port
* @param localHost the local address the socket is bound to
* @param localPort the local port the socket is bound to
* @return the <code>Socket</code>
* @throws IOException if an I/O error occurs when creating the socket
* @throws UnknownHostException if the host is not known
* @see java.net.Socket#Socket(String, int, java.net.InetAddress, int)
*/
public abstract Socket
createSocket(String host, int port, InetAddress localHost, int localPort)
throws IOException, UnknownHostException;
/** {@collect.stats}
* Creates a socket and connects it to the specified port number
* at the specified address. This socket is configured using
* the socket options established for this factory.
*
* @param host the server host
* @param port the server port
* @return the <code>Socket</code>
* @throws IOException if an I/O error occurs when creating the socket
* @see java.net.Socket#Socket(java.net.InetAddress, int)
*/
public abstract Socket createSocket(InetAddress host, int port)
throws IOException;
/** {@collect.stats}
* Creates a socket and connect it to the specified remote address
* on the specified remote port. The socket will also be bound
* to the local address and port suplied. The socket is configured using
* the socket options established for this factory.
*
* @param address the server network address
* @param port the server port
* @param localAddress the client network address
* @param localPort the client port
* @return the <code>Socket</code>
* @throws IOException if an I/O error occurs when creating the socket
* @see java.net.Socket#Socket(java.net.InetAddress, int,
* java.net.InetAddress, int)
*/
public abstract Socket
createSocket(InetAddress address, int port,
InetAddress localAddress, int localPort)
throws IOException;
}
//
// The default factory has NO intelligence about policies like tunneling
// out through firewalls (e.g. SOCKS V4 or V5) or in through them
// (e.g. using SSL), or that some ports are reserved for use with SSL.
//
// Note that at least JDK 1.1 has a low level "plainSocketImpl" that
// knows about SOCKS V4 tunneling, so this isn't a totally bogus default.
//
// ALSO: we may want to expose this class somewhere so other folk
// can reuse it, particularly if we start to add highly useful features
// such as ability to set connect timeouts.
//
class DefaultSocketFactory extends SocketFactory {
public Socket createSocket() {
return new Socket();
}
public Socket createSocket(String host, int port)
throws IOException, UnknownHostException
{
return new Socket(host, port);
}
public Socket createSocket(InetAddress address, int port)
throws IOException
{
return new Socket(address, port);
}
public Socket createSocket(String host, int port,
InetAddress clientAddress, int clientPort)
throws IOException, UnknownHostException
{
return new Socket(host, port, clientAddress, clientPort);
}
public Socket createSocket(InetAddress address, int port,
InetAddress clientAddress, int clientPort)
throws IOException
{
return new Socket(address, port, clientAddress, clientPort);
}
}
|
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.net;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.SocketException;
/** {@collect.stats}
* This class creates server sockets. It may be subclassed by other
* factories, which create particular types of server sockets. This
* provides a general framework for the addition of public socket-level
* functionality. It is the server side analogue of a socket factory,
* and similarly provides a way to capture a variety of policies related
* to the sockets being constructed.
*
* <P> Like socket factories, server Socket factory instances have
* methods used to create sockets. There is also an environment
* specific default server socket factory; frameworks will often use
* their own customized factory.
*
* @since 1.4
* @see SocketFactory
*
* @author David Brownell
*/
public abstract class ServerSocketFactory
{
//
// NOTE: JDK 1.1 bug in class GC, this can get collected
// even though it's always accessible via getDefault().
//
private static ServerSocketFactory theFactory;
/** {@collect.stats}
* Creates a server socket factory.
*/
protected ServerSocketFactory() { /* NOTHING */ }
/** {@collect.stats}
* Returns a copy of the environment's default socket factory.
*
* @return the <code>ServerSocketFactory</code>
*/
public static ServerSocketFactory getDefault()
{
synchronized (ServerSocketFactory.class) {
if (theFactory == null) {
//
// Different implementations of this method could
// work rather differently. For example, driving
// this from a system property, or using a different
// implementation than JavaSoft's.
//
theFactory = new DefaultServerSocketFactory();
}
}
return theFactory;
}
/** {@collect.stats}
* Returns an unbound server socket. The socket is configured with
* the socket options (such as accept timeout) given to this factory.
*
* @return the unbound socket
* @throws IOException if the socket cannot be created
* @see java.net.ServerSocket#bind(java.net.SocketAddress)
* @see java.net.ServerSocket#bind(java.net.SocketAddress, int)
* @see java.net.ServerSocket#ServerSocket()
*/
public ServerSocket createServerSocket() throws IOException {
throw new SocketException("Unbound server sockets not implemented");
}
/** {@collect.stats}
* Returns a server socket bound to the specified port.
* The socket is configured with the socket options
* (such as accept timeout) given to this factory.
*
* @param port the port to listen to
* @return the <code>ServerSocket</code>
* @exception IOException for networking errors
* @see java.net.ServerSocket#ServerSocket(int)
*/
public abstract ServerSocket createServerSocket(int port)
throws IOException;
/** {@collect.stats}
* Returns a server socket bound to the specified port, and uses the
* specified connection backlog. The socket is configured with
* the socket options (such as accept timeout) given to this factory.
*
* @param port the port to listen to
* @param backlog how many connections are queued
* @return the <code>ServerSocket</code>
* @exception IOException for networking errors
* @see java.net.ServerSocket#ServerSocket(int, int)
*/
public abstract ServerSocket
createServerSocket(int port, int backlog)
throws IOException;
/** {@collect.stats}
* Returns a server socket bound to the specified port,
* with a specified listen backlog and local IP.
* The <code>ifAddress</code> argument can be used on a multi-homed
* host for a <code>ServerSocket</code> that will only accept connect
* requests to one of its addresses. If <code>ifAddress</code> is null,
* it will accept connections on all local addresses. The socket is
* configured with the socket options (such as accept timeout) given
* to this factory.
*
* @param port the port to listen to
* @param backlog how many connections are queued
* @param ifAddress the network interface address to use
* @return the <code>ServerSocket</code>
* @exception IOException for networking errors
* @see java.net.ServerSocket#ServerSocket(int, int, java.net.InetAddress)
*/
public abstract ServerSocket
createServerSocket(int port, int backlog, InetAddress ifAddress)
throws IOException;
}
//
// The default factory has NO intelligence. In fact it's not clear
// what sort of intelligence servers need; the onus is on clients,
// who have to know how to tunnel etc.
//
class DefaultServerSocketFactory extends ServerSocketFactory {
DefaultServerSocketFactory()
{
/* NOTHING */
}
public ServerSocket createServerSocket()
throws IOException
{
return new ServerSocket();
}
public ServerSocket createServerSocket(int port)
throws IOException
{
return new ServerSocket(port);
}
public ServerSocket createServerSocket(int port, int backlog)
throws IOException
{
return new ServerSocket(port, backlog);
}
public ServerSocket
createServerSocket(int port, int backlog, InetAddress ifAddress)
throws IOException
{
return new ServerSocket(port, backlog, ifAddress);
}
}
|
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.net.ssl;
import java.security.KeyManagementException;
import java.security.PrivateKey;
import java.security.Principal;
import java.security.cert.X509Certificate;
import java.net.Socket;
/** {@collect.stats}
* Instances of this interface manage which X509 certificate-based
* key pairs are used to authenticate the local side of a secure
* socket.
* <P>
* During secure socket negotiations, implentations
* call methods in this interface to:
* <UL>
* <LI> determine the set of aliases that are available for negotiations
* based on the criteria presented,
* <LI> select the <ITALIC> best alias </ITALIC> based on
* the criteria presented, and
* <LI> obtain the corresponding key material for given aliases.
* </UL>
* <P>
* Note: the X509ExtendedKeyManager should be used in favor of this
* class.
*
* @since 1.4
*/
public interface X509KeyManager extends KeyManager {
/** {@collect.stats}
* Get the matching aliases for authenticating the client side of a secure
* socket given the public key type and the list of
* certificate issuer authorities recognized by the peer (if any).
*
* @param keyType the key algorithm type name
* @param issuers the list of acceptable CA issuer subject names,
* or null if it does not matter which issuers are used.
* @return an array of the matching alias names, or null if there
* were no matches.
*/
public String[] getClientAliases(String keyType, Principal[] issuers);
/** {@collect.stats}
* Choose an alias to authenticate the client side of a secure
* socket given the public key type and the list of
* certificate issuer authorities recognized by the peer (if any).
*
* @param keyType the key algorithm type name(s), ordered
* with the most-preferred key type first.
* @param issuers the list of acceptable CA issuer subject names
* or null if it does not matter which issuers are used.
* @param socket the socket to be used for this connection. This
* parameter can be null, which indicates that
* implementations are free to select an alias applicable
* to any socket.
* @return the alias name for the desired key, or null if there
* are no matches.
*/
public String chooseClientAlias(String[] keyType, Principal[] issuers,
Socket socket);
/** {@collect.stats}
* Get the matching aliases for authenticating the server side of a secure
* socket given the public key type and the list of
* certificate issuer authorities recognized by the peer (if any).
*
* @param keyType the key algorithm type name
* @param issuers the list of acceptable CA issuer subject names
* or null if it does not matter which issuers are used.
* @return an array of the matching alias names, or null
* if there were no matches.
*/
public String[] getServerAliases(String keyType, Principal[] issuers);
/** {@collect.stats}
* Choose an alias to authenticate the server side of a secure
* socket given the public key type and the list of
* certificate issuer authorities recognized by the peer (if any).
*
* @param keyType the key algorithm type name.
* @param issuers the list of acceptable CA issuer subject names
* or null if it does not matter which issuers are used.
* @param socket the socket to be used for this connection. This
* parameter can be null, which indicates that
* implementations are free to select an alias applicable
* to any socket.
* @return the alias name for the desired key, or null if there
* are no matches.
*/
public String chooseServerAlias(String keyType, Principal[] issuers,
Socket socket);
/** {@collect.stats}
* Returns the certificate chain associated with the given alias.
*
* @param alias the alias name
* @return the certificate chain (ordered with the user's certificate first
* and the root certificate authority last), or null
* if the alias can't be found.
*/
public X509Certificate[] getCertificateChain(String alias);
/** {@collect.stats}
* Returns the key associated with the given alias.
*
* @param alias the alias name
* @return the requested key, or null if the alias can't be found.
*/
public PrivateKey getPrivateKey(String alias);
}
|
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.net.ssl;
import java.security.Security;
import java.security.*;
import sun.security.jca.GetInstance;
/** {@collect.stats}
* This class acts as a factory for trust managers based on a
* source of trust material. Each trust manager manages a specific
* type of trust material for use by secure sockets. The trust
* material is based on a KeyStore and/or provider specific sources.
*
* @since 1.4
* @see TrustManager
*/
public class TrustManagerFactory {
// The provider
private Provider provider;
// The provider implementation (delegate)
private TrustManagerFactorySpi factorySpi;
// The name of the trust management algorithm.
private String algorithm;
/** {@collect.stats}
* Obtains the default TrustManagerFactory algorithm name.
*
* <p>The default TrustManager can be changed at runtime by setting
* the value of the "ssl.TrustManagerFactory.algorithm" security
* property (set in the Java security properties file or by calling
* {@link java.security.Security#setProperty(String, String) })
* to the desired algorithm name.
*
* @return the default algorithm name as specified in the
* Java security properties, or an implementation-specific default
* if no such property exists.
*/
public final static String getDefaultAlgorithm() {
String type;
type = AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return Security.getProperty(
"ssl.TrustManagerFactory.algorithm");
}
});
if (type == null) {
type = "SunX509";
}
return type;
}
/** {@collect.stats}
* Creates a TrustManagerFactory object.
*
* @param factorySpi the delegate
* @param provider the provider
* @param algorithm the algorithm
*/
protected TrustManagerFactory(TrustManagerFactorySpi factorySpi,
Provider provider, String algorithm) {
this.factorySpi = factorySpi;
this.provider = provider;
this.algorithm = algorithm;
}
/** {@collect.stats}
* Returns the algorithm name of this <code>TrustManagerFactory</code>
* object.
*
* <p>This is the same name that was specified in one of the
* <code>getInstance</code> calls that created this
* <code>TrustManagerFactory</code> object.
*
* @return the algorithm name of this <code>TrustManagerFactory</code>
* object
*/
public final String getAlgorithm() {
return this.algorithm;
}
/** {@collect.stats}
* Returns a <code>TrustManagerFactory</code> object that acts as a
* factory for trust managers.
*
* <p> This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new TrustManagerFactory object encapsulating the
* TrustManagerFactorySpi implementation from the first
* Provider that supports the specified algorithm is returned.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the standard name of the requested trust management
* algorithm. See the <a href=
* "{@docRoot}/../technotes/guides/security/jsse/JSSERefGuide.html">
* Java Secure Socket Extension Reference Guide </a>
* for information about standard algorithm names.
*
* @return the new <code>TrustManagerFactory</code> object.
*
* @exception NoSuchAlgorithmException if no Provider supports a
* TrustManagerFactorySpi implementation for the
* specified algorithm.
*
* @see java.security.Provider
*/
public static final TrustManagerFactory getInstance(String algorithm)
throws NoSuchAlgorithmException {
GetInstance.Instance instance = GetInstance.getInstance
("TrustManagerFactory", TrustManagerFactorySpi.class,
algorithm);
return new TrustManagerFactory((TrustManagerFactorySpi)instance.impl,
instance.provider, algorithm);
}
/** {@collect.stats}
* Returns a <code>TrustManagerFactory</code> object that acts as a
* factory for trust managers.
*
* <p> A new KeyManagerFactory object encapsulating the
* KeyManagerFactorySpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the standard name of the requested trust management
* algorithm. See the <a href=
* "{@docRoot}/../technotes/guides/security/jsse/JSSERefGuide.html">
* Java Secure Socket Extension Reference Guide </a>
* for information about standard algorithm names.
*
* @param provider the name of the provider.
*
* @return the new <code>TrustManagerFactory</code> object
*
* @throws NoSuchAlgorithmException if a TrustManagerFactorySpi
* implementation for the specified algorithm is not
* available from the specified provider.
*
* @throws NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @throws IllegalArgumentException if the provider name is null or empty.
*
* @see java.security.Provider
*/
public static final TrustManagerFactory getInstance(String algorithm,
String provider) throws NoSuchAlgorithmException,
NoSuchProviderException {
GetInstance.Instance instance = GetInstance.getInstance
("TrustManagerFactory", TrustManagerFactorySpi.class,
algorithm, provider);
return new TrustManagerFactory((TrustManagerFactorySpi)instance.impl,
instance.provider, algorithm);
}
/** {@collect.stats}
* Returns a <code>TrustManagerFactory</code> object that acts as a
* factory for trust managers.
*
* <p> A new TrustManagerFactory object encapsulating the
* TrustManagerFactorySpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param algorithm the standard name of the requested trust management
* algorithm. See the <a href=
* "{@docRoot}/../technotes/guides/security/jsse/JSSERefGuide.html">
* Java Secure Socket Extension Reference Guide </a>
* for information about standard algorithm names.
*
* @param provider an instance of the provider.
*
* @return the new <code>TrustManagerFactory</code> object.
*
* @throws NoSuchAlgorithmException if a TrustManagerFactorySpi
* implementation for the specified algorithm is not available
* from the specified Provider object.
*
* @throws IllegalArgumentException if the provider is null.
*
* @see java.security.Provider
*/
public static final TrustManagerFactory getInstance(String algorithm,
Provider provider) throws NoSuchAlgorithmException {
GetInstance.Instance instance = GetInstance.getInstance
("TrustManagerFactory", TrustManagerFactorySpi.class,
algorithm, provider);
return new TrustManagerFactory((TrustManagerFactorySpi)instance.impl,
instance.provider, algorithm);
}
/** {@collect.stats}
* Returns the provider of this <code>TrustManagerFactory</code> object.
*
* @return the provider of this <code>TrustManagerFactory</code> object
*/
public final Provider getProvider() {
return this.provider;
}
/** {@collect.stats}
* Initializes this factory with a source of certificate
* authorities and related trust material.
* <P>
* The provider typically uses a KeyStore as a basis for making
* trust decisions.
* <P>
* For more flexible initialization, please see
* {@link #init(ManagerFactoryParameters)}.
*
* @param ks the key store, or null
* @throws KeyStoreException if this operation fails
*/
public final void init(KeyStore ks) throws KeyStoreException {
factorySpi.engineInit(ks);
}
/** {@collect.stats}
* Initializes this factory with a source of provider-specific
* trust material.
* <P>
* In some cases, initialization parameters other than a keystore
* may be needed by a provider. Users of that particular provider
* are expected to pass an implementation of the appropriate
* <CODE>ManagerFactoryParameters</CODE> as defined by the
* provider. The provider can then call the specified methods in
* the <CODE>ManagerFactoryParameters</CODE> implementation to obtain the
* needed information.
*
* @param spec an implementation of a provider-specific parameter
* specification
* @throws InvalidAlgorithmParameterException if an error is
* encountered
*/
public final void init(ManagerFactoryParameters spec) throws
InvalidAlgorithmParameterException {
factorySpi.engineInit(spec);
}
/** {@collect.stats}
* Returns one trust manager for each type of trust material.
*
* @return the trust managers
*/
public final TrustManager[] getTrustManagers() {
return factorySpi.engineGetTrustManagers();
}
}
|
Java
|
/*
* Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.net.ssl;
/** {@collect.stats}
* Indicates that the peer's identity has not been verified.
* <P>
* When the peer was not able to
* identify itself (for example; no certificate, the particular
* cipher suite being used does not support authentication, or no
* peer authentication was established during SSL handshaking) this
* exception is thrown.
*
* @since 1.4
* @author David Brownell
*/
public
class SSLPeerUnverifiedException extends SSLException
{
private static final long serialVersionUID = -8919512675000600547L;
/** {@collect.stats}
* Constructs an exception reporting that the SSL peer's
* identity has not been verifiied.
*
* @param reason describes the problem.
*/
public SSLPeerUnverifiedException(String reason)
{
super(reason);
}
}
|
Java
|
/*
* Copyright (c) 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.net.ssl;
/** {@collect.stats}
* This class is the base interface for providing
* algorithm-specific information to a KeyManagerFactory or
* TrustManagerFactory.
* <P>
* In some cases, initialization parameters other than keystores
* may be needed by a provider. Users of that particular provider
* are expected to pass an implementation of the appropriate
* sub-interface of this class as defined by the
* provider. The provider can then call the specified methods in
* the <CODE>ManagerFactoryParameters</CODE> implementation to obtain the
* needed information.
*
* @author Brad R. Wetmore
* @since 1.4
*/
public interface ManagerFactoryParameters {
}
|
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.net.ssl;
import java.security.cert.CertPathParameters;
/** {@collect.stats}
* A wrapper for CertPathParameters. This class is used to pass validation
* settings to CertPath based {@link TrustManager}s using the
* {@link TrustManagerFactory#init(ManagerFactoryParameters)
* TrustManagerFactory.init()} method.
*
* <p>Instances of this class are immutable.
*
* @see X509TrustManager
* @see TrustManagerFactory
* @see java.security.cert.CertPathParameters
*
* @since 1.5
* @author Andreas Sterbenz
*/
public class CertPathTrustManagerParameters implements ManagerFactoryParameters {
private final CertPathParameters parameters;
/** {@collect.stats}
* Construct new CertPathTrustManagerParameters from the specified
* parameters. The parameters are cloned to protect against subsequent
* modification.
*
* @param parameters the CertPathParameters to be used
*
* @throws NullPointerException if parameters is null
*/
public CertPathTrustManagerParameters(CertPathParameters parameters) {
this.parameters = (CertPathParameters)parameters.clone();
}
/** {@collect.stats}
* Return a clone of the CertPathParameters encapsulated by this class.
*
* @return a clone of the CertPathParameters encapsulated by this class.
*/
public CertPathParameters getParameters() {
return (CertPathParameters)parameters.clone();
}
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.net.ssl;
import java.io.IOException;
import java.net.*;
import java.util.Enumeration;
import java.util.Vector;
/** {@collect.stats}
* This class extends <code>Socket</code>s and provides secure
* socket using protocols such as the "Secure
* Sockets Layer" (SSL) or IETF "Transport Layer Security" (TLS) protocols.
* <P>
* Such sockets are normal stream sockets, but they
* add a layer of security protections over the underlying network transport
* protocol, such as TCP. Those protections include: <UL>
*
* <LI> <em>Integrity Protection</em>. SSL protects against
* modification of messages by an active wiretapper.
*
* <LI> <em>Authentication</em>. In most modes, SSL provides
* peer authentication. Servers are usually authenticated,
* and clients may be authenticated as requested by servers.
*
* <LI> <em>Confidentiality (Privacy Protection)</em>. In most
* modes, SSL encrypts data being sent between client and server.
* This protects the confidentiality of data, so that passive
* wiretappers won't see sensitive data such as financial
* information or personal information of many kinds.
*
* </UL>
*
* <P>These kinds of protection are specified by a "cipher suite", which
* is a combination of cryptographic algorithms used by a given SSL connection.
* During the negotiation process, the two endpoints must agree on
* a ciphersuite that is available in both environments.
* If there is no such suite in common, no SSL connection can
* be established, and no data can be exchanged.
*
* <P> The cipher suite used is established by a negotiation process
* called "handshaking". The goal of this
* process is to create or rejoin a "session", which may protect many
* connections over time. After handshaking has completed, you can access
* session attributes by using the <em>getSession</em> method.
* The initial handshake on this connection can be initiated in
* one of three ways: <UL>
*
* <LI> calling <code>startHandshake</code> which explicitly
* begins handshakes, or
* <LI> any attempt to read or write application data on
* this socket causes an implicit handshake, or
* <LI> a call to <code>getSession</code> tries to set up a session
* if there is no currently valid session, and
* an implicit handshake is done.
* </UL>
*
* <P>If handshaking fails for any reason, the <code>SSLSocket</code>
* is closed, and no futher communications can be done.
*
* <P>There are two groups of cipher suites which you will need to know
* about when managing cipher suites: <UL>
*
* <LI> <em>Supported</em> cipher suites: all the suites which are
* supported by the SSL implementation. This list is reported
* using <em>getSupportedCipherSuites</em>.
*
* <LI> <em>Enabled</em> cipher suites, which may be fewer
* than the full set of supported suites. This group is
* set using the <em>setEnabledCipherSuites</em> method, and
* queried using the <em>getEnabledCipherSuites</em> method.
* Initially, a default set of cipher suites will be enabled on
* a new socket that represents the minimum suggested configuration.
*
* </UL>
*
* <P> Implementation defaults require that only cipher
* suites which authenticate servers and provide confidentiality
* be enabled by default.
* Only if both sides explicitly agree to unauthenticated and/or
* non-private (unencrypted) communications will such a ciphersuite be
* selected.
*
* <P>When <code>SSLSocket</code>s are first created, no handshaking
* is done so that applications may first set their communication
* preferences: what cipher suites to use, whether the socket should be
* in client or server mode, etc.
* However, security is always provided by the time that application data
* is sent over the connection.
*
* <P> You may register to receive event notification of handshake
* completion. This involves
* the use of two additional classes. <em>HandshakeCompletedEvent</em>
* objects are passed to <em>HandshakeCompletedListener</em> instances,
* which are registered by users of this API.
*
* <code>SSLSocket</code>s are created by <code>SSLSocketFactory</code>s,
* or by <code>accept</code>ing a connection from a
* <code>SSLServerSocket</code>.
*
* <P>A SSL socket must choose to operate in the client or server mode.
* This will determine who begins the handshaking process, as well
* as which messages should be sent by each party. Each
* connection must have one client and one server, or handshaking
* will not progress properly. Once the initial handshaking has started, a
* socket can not switch between client and server modes, even when
* performing renegotiations.
*
* @see java.net.Socket
* @see SSLServerSocket
* @see SSLSocketFactory
*
* @since 1.4
* @author David Brownell
*/
public abstract class SSLSocket extends Socket
{
/** {@collect.stats}
* Used only by subclasses.
* Constructs an uninitialized, unconnected TCP socket.
*/
protected SSLSocket()
{ super(); }
/** {@collect.stats}
* Used only by subclasses.
* Constructs a TCP connection to a named host at a specified port.
* This acts as the SSL client.
*
* @param host name of the host with which to connect
* @param port number of the server's port
* @throws IOException if an I/O error occurs when creating the socket
* @throws UnknownHostException if the host is not known
*/
protected SSLSocket(String host, int port)
throws IOException, UnknownHostException
{ super(host, port); }
/** {@collect.stats}
* Used only by subclasses.
* Constructs a TCP connection to a server at a specified address
* and port. This acts as the SSL client.
*
* @param address the server's host
* @param port its port
* @throws IOException if an I/O error occurs when creating the socket
*/
protected SSLSocket(InetAddress address, int port)
throws IOException
{ super(address, port); }
/** {@collect.stats}
* Used only by subclasses.
* Constructs an SSL connection to a named host at a specified port,
* binding the client side of the connection a given address and port.
* This acts as the SSL client.
*
* @param host name of the host with which to connect
* @param port number of the server's port
* @param clientAddress the client's host
* @param clientPort number of the client's port
* @throws IOException if an I/O error occurs when creating the socket
* @throws UnknownHostException if the host is not known
*/
protected SSLSocket(String host, int port,
InetAddress clientAddress, int clientPort)
throws IOException, UnknownHostException
{ super(host, port, clientAddress, clientPort); }
/** {@collect.stats}
* Used only by subclasses.
* Constructs an SSL connection to a server at a specified address
* and TCP port, binding the client side of the connection a given
* address and port. This acts as the SSL client.
*
* @param address the server's host
* @param port its port
* @param clientAddress the client's host
* @param clientPort number of the client's port
* @throws IOException if an I/O error occurs when creating the socket
*/
protected SSLSocket(InetAddress address, int port,
InetAddress clientAddress, int clientPort)
throws IOException
{ super(address, port, clientAddress, clientPort); }
/** {@collect.stats}
* Returns the names of the cipher suites which could be enabled for use
* on this connection. Normally, only a subset of these will actually
* be enabled by default, since this list may include cipher suites which
* do not meet quality of service requirements for those defaults. Such
* cipher suites might be useful in specialized applications.
*
* @return an array of cipher suite names
* @see #getEnabledCipherSuites()
* @see #setEnabledCipherSuites(String [])
*/
public abstract String [] getSupportedCipherSuites();
/** {@collect.stats}
* Returns the names of the SSL cipher suites which are currently
* enabled for use on this connection. When an SSLSocket is first
* created, all enabled cipher suites support a minimum quality of
* service. Thus, in some environments this value might be empty.
* <P>
* Even if a suite has been enabled, it might never be used. (For
* example, the peer does not support it, the requisite certificates
* (and private keys) for the suite are not available, or an
* anonymous suite is enabled but authentication is required.
*
* @return an array of cipher suite names
* @see #getSupportedCipherSuites()
* @see #setEnabledCipherSuites(String [])
*/
public abstract String [] getEnabledCipherSuites();
/** {@collect.stats}
* Sets the cipher suites enabled for use on this connection.
* <P>
* Each cipher suite in the <code>suites</code> parameter must have
* been listed by getSupportedCipherSuites(), or the method will
* fail. Following a successful call to this method, only suites
* listed in the <code>suites</code> parameter are enabled for use.
* <P>
* See {@link #getEnabledCipherSuites()} for more information
* on why a specific ciphersuite may never be used on a connection.
*
* @param suites Names of all the cipher suites to enable
* @throws IllegalArgumentException when one or more of the ciphers
* named by the parameter is not supported, or when the
* parameter is null.
* @see #getSupportedCipherSuites()
* @see #getEnabledCipherSuites()
*/
public abstract void setEnabledCipherSuites(String suites []);
/** {@collect.stats}
* Returns the names of the protocols which could be enabled for use
* on an SSL connection.
*
* @return an array of protocols supported
*/
public abstract String [] getSupportedProtocols();
/** {@collect.stats}
* Returns the names of the protocol versions which are currently
* enabled for use on this connection.
* @see #setEnabledProtocols(String [])
* @return an array of protocols
*/
public abstract String [] getEnabledProtocols();
/** {@collect.stats}
* Sets the protocol versions enabled for use on this connection.
* <P>
* The protocols must have been listed by
* <code>getSupportedProtocols()</code> as being supported.
* Following a successful call to this method, only protocols listed
* in the <code>protocols</code> parameter are enabled for use.
*
* @param protocols Names of all the protocols to enable.
* @throws IllegalArgumentException when one or more of
* the protocols named by the parameter is not supported or
* when the protocols parameter is null.
* @see #getEnabledProtocols()
*/
public abstract void setEnabledProtocols(String protocols[]);
/** {@collect.stats}
* Returns the SSL Session in use by this connection. These can
* be long lived, and frequently correspond to an entire login session
* for some user. The session specifies a particular cipher suite
* which is being actively used by all connections in that session,
* as well as the identities of the session's client and server.
* <P>
* This method will initiate the initial handshake if
* necessary and then block until the handshake has been
* established.
* <P>
* If an error occurs during the initial handshake, this method
* returns an invalid session object which reports an invalid
* cipher suite of "SSL_NULL_WITH_NULL_NULL".
*
* @return the <code>SSLSession</code>
*/
public abstract SSLSession getSession();
/** {@collect.stats}
* Registers an event listener to receive notifications that an
* SSL handshake has completed on this connection.
*
* @param listener the HandShake Completed event listener
* @see #startHandshake()
* @see #removeHandshakeCompletedListener(HandshakeCompletedListener)
* @throws IllegalArgumentException if the argument is null.
*/
public abstract void addHandshakeCompletedListener(
HandshakeCompletedListener listener);
/** {@collect.stats}
* Removes a previously registered handshake completion listener.
*
* @param listener the HandShake Completed event listener
* @throws IllegalArgumentException if the listener is not registered,
* or the argument is null.
* @see #addHandshakeCompletedListener(HandshakeCompletedListener)
*/
public abstract void removeHandshakeCompletedListener(
HandshakeCompletedListener listener);
/** {@collect.stats}
* Starts an SSL handshake on this connection. Common reasons include
* a need to use new encryption keys, to change cipher suites, or to
* initiate a new session. To force complete reauthentication, the
* current session could be invalidated before starting this handshake.
*
* <P> If data has already been sent on the connection, it continues
* to flow during this handshake. When the handshake completes, this
* will be signaled with an event.
*
* This method is synchronous for the initial handshake on a connection
* and returns when the negotiated handshake is complete. Some
* protocols may not support multiple handshakes on an existing socket
* and may throw an IOException.
*
* @throws IOException on a network level error
* @see #addHandshakeCompletedListener(HandshakeCompletedListener)
*/
public abstract void startHandshake() throws IOException;
/** {@collect.stats}
* Configures the socket to use client (or server) mode when
* handshaking.
* <P>
* This method must be called before any handshaking occurs.
* Once handshaking has begun, the mode can not be reset for the
* life of this socket.
* <P>
* Servers normally authenticate themselves, and clients
* are not required to do so.
*
* @param mode true if the socket should start its handshaking
* in "client" mode
* @throws IllegalArgumentException if a mode change is attempted
* after the initial handshake has begun.
* @see #getUseClientMode()
*/
public abstract void setUseClientMode(boolean mode);
/** {@collect.stats}
* Returns true if the socket is set to use client mode when
* handshaking.
*
* @return true if the socket should do handshaking
* in "client" mode
* @see #setUseClientMode(boolean)
*/
public abstract boolean getUseClientMode();
/** {@collect.stats}
* Configures the socket to <i>require</i> client authentication. This
* option is only useful for sockets in the server mode.
* <P>
* A socket's client authentication setting is one of the following:
* <ul>
* <li> client authentication required
* <li> client authentication requested
* <li> no client authentication desired
* </ul>
* <P>
* Unlike {@link #setWantClientAuth(boolean)}, if this option is set and
* the client chooses not to provide authentication information
* about itself, <i>the negotiations will stop and the connection
* will be dropped</i>.
* <P>
* Calling this method overrides any previous setting made by
* this method or {@link #setWantClientAuth(boolean)}.
*
* @param need set to true if client authentication is required,
* or false if no client authentication is desired.
* @see #getNeedClientAuth()
* @see #setWantClientAuth(boolean)
* @see #getWantClientAuth()
* @see #setUseClientMode(boolean)
*/
public abstract void setNeedClientAuth(boolean need);
/** {@collect.stats}
* Returns true if the socket will <i>require</i> client authentication.
* This option is only useful to sockets in the server mode.
*
* @return true if client authentication is required,
* or false if no client authentication is desired.
* @see #setNeedClientAuth(boolean)
* @see #setWantClientAuth(boolean)
* @see #getWantClientAuth()
* @see #setUseClientMode(boolean)
*/
public abstract boolean getNeedClientAuth();
/** {@collect.stats}
* Configures the socket to <i>request</i> client authentication.
* This option is only useful for sockets in the server mode.
* <P>
* A socket's client authentication setting is one of the following:
* <ul>
* <li> client authentication required
* <li> client authentication requested
* <li> no client authentication desired
* </ul>
* <P>
* Unlike {@link #setNeedClientAuth(boolean)}, if this option is set and
* the client chooses not to provide authentication information
* about itself, <i>the negotiations will continue</i>.
* <P>
* Calling this method overrides any previous setting made by
* this method or {@link #setNeedClientAuth(boolean)}.
*
* @param want set to true if client authentication is requested,
* or false if no client authentication is desired.
* @see #getWantClientAuth()
* @see #setNeedClientAuth(boolean)
* @see #getNeedClientAuth()
* @see #setUseClientMode(boolean)
*/
public abstract void setWantClientAuth(boolean want);
/** {@collect.stats}
* Returns true if the socket will <i>request</i> client authentication.
* This option is only useful for sockets in the server mode.
*
* @return true if client authentication is requested,
* or false if no client authentication is desired.
* @see #setNeedClientAuth(boolean)
* @see #getNeedClientAuth()
* @see #setWantClientAuth(boolean)
* @see #setUseClientMode(boolean)
*/
public abstract boolean getWantClientAuth();
/** {@collect.stats}
* Controls whether new SSL sessions may be established by this socket.
* If session creations are not allowed, and there are no
* existing sessions to resume, there will be no successful
* handshaking.
*
* @param flag true indicates that sessions may be created; this
* is the default. false indicates that an existing session
* must be resumed
* @see #getEnableSessionCreation()
*/
public abstract void setEnableSessionCreation(boolean flag);
/** {@collect.stats}
* Returns true if new SSL sessions may be established by this socket.
*
* @return true indicates that sessions may be created; this
* is the default. false indicates that an existing session
* must be resumed
* @see #setEnableSessionCreation(boolean)
*/
public abstract boolean getEnableSessionCreation();
/** {@collect.stats}
* Returns the SSLParameters in effect for this SSLSocket.
* The ciphersuites and protocols of the returned SSLParameters
* are always non-null.
*
* @return the SSLParameters in effect for this SSLSocket.
* @since 1.6
*/
public SSLParameters getSSLParameters() {
SSLParameters params = new SSLParameters();
params.setCipherSuites(getEnabledCipherSuites());
params.setProtocols(getEnabledProtocols());
if (getNeedClientAuth()) {
params.setNeedClientAuth(true);
} else if (getWantClientAuth()) {
params.setWantClientAuth(true);
}
return params;
}
/** {@collect.stats}
* Applies SSLParameters to this socket.
*
* <p>This means:
* <ul>
* <li>if <code>params.getCipherSuites()</code> is non-null,
* <code>setEnabledCipherSuites()</code> is called with that value
* <li>if <code>params.getProtocols()</code> is non-null,
* <code>setEnabledProtocols()</code> is called with that value
* <li>if <code>params.getNeedClientAuth()</code> or
* <code>params.getWantClientAuth()</code> return <code>true</code>,
* <code>setNeedClientAuth(true)</code> and
* <code>setWantClientAuth(true)</code> are called, respectively;
* otherwise <code>setWantClientAuth(false)</code> is called.
* </ul>
*
* @param params the parameters
* @throws IllegalArgumentException if the setEnabledCipherSuites() or
* the setEnabledProtocols() call fails
* @since 1.6
*/
public void setSSLParameters(SSLParameters params) {
String[] s;
s = params.getCipherSuites();
if (s != null) {
setEnabledCipherSuites(s);
}
s = params.getProtocols();
if (s != null) {
setEnabledProtocols(s);
}
if (params.getNeedClientAuth()) {
setNeedClientAuth(true);
} else if (params.getWantClientAuth()) {
setWantClientAuth(true);
} else {
setWantClientAuth(false);
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 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.net.ssl;
import java.util.EventListener;
/** {@collect.stats}
* This interface is implemented by any class which wants to receive
* notifications about the completion of an SSL protocol handshake
* on a given SSL connection.
*
* <P> When an SSL handshake completes, new security parameters will
* have been established. Those parameters always include the security
* keys used to protect messages. They may also include parameters
* associated with a new <em>session</em> such as authenticated
* peer identity and a new SSL cipher suite.
*
* @since 1.4
* @author David Brownell
*/
public interface HandshakeCompletedListener extends EventListener
{
/** {@collect.stats}
* This method is invoked on registered objects
* when a SSL handshake is completed.
*
* @param event the event identifying when the SSL Handshake
* completed on a given SSL connection
*/
void handshakeCompleted(HandshakeCompletedEvent event);
}
|
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.net.ssl;
import java.util.*;
import java.security.*;
/** {@collect.stats}
* This class defines the <i>Service Provider Interface</i> (<b>SPI</b>)
* for the <code>SSLContext</code> class.
*
* <p> All the abstract methods in this class must be implemented by each
* cryptographic service provider who wishes to supply the implementation
* of a particular SSL context.
*
* @since 1.4
* @see SSLContext
*/
public abstract class SSLContextSpi {
/** {@collect.stats}
* Initializes this context.
*
* @param km the sources of authentication keys
* @param tm the sources of peer authentication trust decisions
* @param sr the source of randomness
* @throws KeyManagementException if this operation fails
* @see SSLContext#init(KeyManager [], TrustManager [], SecureRandom)
*/
protected abstract void engineInit(KeyManager[] km, TrustManager[] tm,
SecureRandom sr) throws KeyManagementException;
/** {@collect.stats}
* Returns a <code>SocketFactory</code> object for this
* context.
*
* @return the <code>SocketFactory</code> object
* @throws IllegalStateException if the SSLContextImpl requires
* initialization and the <code>engineInit()</code>
* has not been called
* @see javax.net.ssl.SSLContext#getSocketFactory()
*/
protected abstract SSLSocketFactory engineGetSocketFactory();
/** {@collect.stats}
* Returns a <code>ServerSocketFactory</code> object for
* this context.
*
* @return the <code>ServerSocketFactory</code> object
* @throws IllegalStateException if the SSLContextImpl requires
* initialization and the <code>engineInit()</code>
* has not been called
* @see javax.net.ssl.SSLContext#getServerSocketFactory()
*/
protected abstract SSLServerSocketFactory engineGetServerSocketFactory();
/** {@collect.stats}
* Creates a new <code>SSLEngine</code> using this context.
* <P>
* Applications using this factory method are providing no hints
* for an internal session reuse strategy. If hints are desired,
* {@link #engineCreateSSLEngine(String, int)} should be used
* instead.
* <P>
* Some cipher suites (such as Kerberos) require remote hostname
* information, in which case this factory method should not be used.
*
* @return the <code>SSLEngine</code> Object
* @throws IllegalStateException if the SSLContextImpl requires
* initialization and the <code>engineInit()</code>
* has not been called
*
* @see SSLContext#createSSLEngine()
*
* @since 1.5
*/
protected abstract SSLEngine engineCreateSSLEngine();
/** {@collect.stats}
* Creates a <code>SSLEngine</code> using this context.
* <P>
* Applications using this factory method are providing hints
* for an internal session reuse strategy.
* <P>
* Some cipher suites (such as Kerberos) require remote hostname
* information, in which case peerHost needs to be specified.
*
* @param host the non-authoritative name of the host
* @param port the non-authoritative port
* @return the <code>SSLEngine</code> Object
* @throws IllegalStateException if the SSLContextImpl requires
* initialization and the <code>engineInit()</code>
* has not been called
*
* @see SSLContext#createSSLEngine(String, int)
*
* @since 1.5
*/
protected abstract SSLEngine engineCreateSSLEngine(String host, int port);
/** {@collect.stats}
* Returns a server <code>SSLSessionContext</code> object for
* this context.
*
* @return the <code>SSLSessionContext</code> object
* @see javax.net.ssl.SSLContext#getServerSessionContext()
*/
protected abstract SSLSessionContext engineGetServerSessionContext();
/** {@collect.stats}
* Returns a client <code>SSLSessionContext</code> object for
* this context.
*
* @return the <code>SSLSessionContext</code> object
* @see javax.net.ssl.SSLContext#getClientSessionContext()
*/
protected abstract SSLSessionContext engineGetClientSessionContext();
private SSLSocket getDefaultSocket() {
try {
SSLSocketFactory factory = engineGetSocketFactory();
return (SSLSocket)factory.createSocket();
} catch (java.io.IOException e) {
throw new UnsupportedOperationException("Could not obtain parameters", e);
}
}
/** {@collect.stats}
* Returns a copy of the SSLParameters indicating the default
* settings for this SSL context.
*
* <p>The parameters will always have the ciphersuite and protocols
* arrays set to non-null values.
*
* <p>The default implementation obtains the parameters from an
* SSLSocket created by calling the
* {@linkplain javax.net.SocketFactory#createSocket
* SocketFactory.createSocket()} method of this context's SocketFactory.
*
* @return a copy of the SSLParameters object with the default settings
* @throws UnsupportedOperationException if the default SSL parameters
* could not be obtained.
*
* @since 1.6
*/
protected SSLParameters engineGetDefaultSSLParameters() {
SSLSocket socket = getDefaultSocket();
return socket.getSSLParameters();
}
/** {@collect.stats}
* Returns a copy of the SSLParameters indicating the maximum supported
* settings for this SSL context.
*
* <p>The parameters will always have the ciphersuite and protocols
* arrays set to non-null values.
*
* <p>The default implementation obtains the parameters from an
* SSLSocket created by calling the
* {@linkplain javax.net.SocketFactory#createSocket
* SocketFactory.createSocket()} method of this context's SocketFactory.
*
* @return a copy of the SSLParameters object with the maximum supported
* settings
* @throws UnsupportedOperationException if the supported SSL parameters
* could not be obtained.
*
* @since 1.6
*/
protected SSLParameters engineGetSupportedSSLParameters() {
SSLSocket socket = getDefaultSocket();
SSLParameters params = new SSLParameters();
params.setCipherSuites(socket.getSupportedCipherSuites());
params.setProtocols(socket.getSupportedProtocols());
return params;
}
}
|
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.net.ssl;
import java.util.*;
import java.security.KeyStore.*;
/** {@collect.stats}
* A parameters object for X509KeyManagers that encapsulates a List
* of KeyStore.Builders.
*
* @see java.security.KeyStore.Builder
* @see X509KeyManager
*
* @author Andreas Sterbenz
* @since 1.5
*/
public class KeyStoreBuilderParameters implements ManagerFactoryParameters {
private final List<Builder> parameters;
/** {@collect.stats}
* Construct new KeyStoreBuilderParameters from the specified
* {@linkplain java.security.KeyStore.Builder}.
*
* @param builder the Builder object
* @exception NullPointerException if builder is null
*/
public KeyStoreBuilderParameters(Builder builder) {
parameters = Collections.singletonList(builder);
}
/** {@collect.stats}
* Construct new KeyStoreBuilderParameters from a List
* of {@linkplain java.security.KeyStore.Builder}s. Note that the list
* is cloned to protect against subsequent modification.
*
* @param parameters the List of Builder objects
* @exception NullPointerException if parameters is null
* @exception IllegalArgumentException if parameters is an empty list
*/
public KeyStoreBuilderParameters(List<Builder> parameters) {
this.parameters = Collections.unmodifiableList(
new ArrayList<Builder>(parameters));
if (this.parameters.isEmpty()) {
throw new IllegalArgumentException();
}
}
/** {@collect.stats}
* Return the unmodifiable List of the
* {@linkplain java.security.KeyStore.Builder}s
* encapsulated by this object.
*
* @return the unmodifiable List of the
* {@linkplain java.security.KeyStore.Builder}s
* encapsulated by this object.
*/
public List<Builder> getParameters() {
return parameters;
}
}
|
Java
|
/*
* Copyright (c) 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.net.ssl;
import java.security.Principal;
/** {@collect.stats}
* Abstract class that provides for extension of the X509KeyManager
* interface.
* <P>
* Methods in this class should be overriden to provide actual
* implementations.
*
* @since 1.5
* @author Brad R. Wetmore
*/
public abstract class X509ExtendedKeyManager implements X509KeyManager {
/** {@collect.stats}
* Constructor used by subclasses only.
*/
protected X509ExtendedKeyManager() {
}
/** {@collect.stats}
* Choose an alias to authenticate the client side of an
* <code>SSLEngine</code> connection given the public key type
* and the list of certificate issuer authorities recognized by
* the peer (if any).
* <P>
* The default implementation returns null.
*
* @param keyType the key algorithm type name(s), ordered
* with the most-preferred key type first.
* @param issuers the list of acceptable CA issuer subject names
* or null if it does not matter which issuers are used.
* @param engine the <code>SSLEngine</code> to be used for this
* connection. This parameter can be null, which indicates
* that implementations of this interface are free to
* select an alias applicable to any engine.
* @return the alias name for the desired key, or null if there
* are no matches.
*/
public String chooseEngineClientAlias(String[] keyType,
Principal[] issuers, SSLEngine engine) {
return null;
}
/** {@collect.stats}
* Choose an alias to authenticate the server side of an
* <code>SSLEngine</code> connection given the public key type
* and the list of certificate issuer authorities recognized by
* the peer (if any).
* <P>
* The default implementation returns null.
*
* @param keyType the key algorithm type name.
* @param issuers the list of acceptable CA issuer subject names
* or null if it does not matter which issuers are used.
* @param engine the <code>SSLEngine</code> to be used for this
* connection. This parameter can be null, which indicates
* that implementations of this interface are free to
* select an alias applicable to any engine.
* @return the alias name for the desired key, or null if there
* are no matches.
*/
public String chooseEngineServerAlias(String keyType,
Principal[] issuers, SSLEngine engine) {
return null;
}
}
|
Java
|
/*
* Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.net.ssl;
/** {@collect.stats}
* Reports an error in the operation of the SSL protocol. Normally
* this indicates a flaw in one of the protocol implementations.
*
* @since 1.4
* @author David Brownell
*/
public
class SSLProtocolException extends SSLException
{
private static final long serialVersionUID = 5445067063799134928L;
/** {@collect.stats}
* Constructs an exception reporting an SSL protocol error
* detected by an SSL subsystem.
*
* @param reason describes the problem.
*/
public SSLProtocolException(String reason)
{
super(reason);
}
}
|
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.net.ssl;
import java.security.*;
import java.util.*;
import sun.security.jca.GetInstance;
/** {@collect.stats}
* Instances of this class represent a secure socket protocol
* implementation which acts as a factory for secure socket
* factories or <code>SSLEngine</code>s. This class is initialized
* with an optional set of key and trust managers and source of
* secure random bytes.
*
* @since 1.4
*/
public class SSLContext {
private final Provider provider;
private final SSLContextSpi contextSpi;
private final String protocol;
/** {@collect.stats}
* Creates an SSLContext object.
*
* @param contextSpi the delegate
* @param provider the provider
* @param protocol the protocol
*/
protected SSLContext(SSLContextSpi contextSpi, Provider provider,
String protocol) {
this.contextSpi = contextSpi;
this.provider = provider;
this.protocol = protocol;
}
private static SSLContext defaultContext;
/** {@collect.stats}
* Returns the default SSL context.
*
* <p>If a default context was set using the {@link #setDefault
* SSLContext.setDefault()} method, it is returned. Otherwise, the first
* call of this method triggers the call
* <code>SSLContext.getInstance("Default")</code>.
* If successful, that object is made the default SSL context and returned.
*
* <p>The default context is immediately
* usable and does not require {@linkplain #init initialization}.
*
* @return the default SSL context
* @throws NoSuchAlgorithmException if the
* {@link SSLContext#getInstance SSLContext.getInstance()} call fails
* @since 1.6
*/
public static synchronized SSLContext getDefault()
throws NoSuchAlgorithmException {
if (defaultContext == null) {
defaultContext = SSLContext.getInstance("Default");
}
return defaultContext;
}
/** {@collect.stats}
* Sets the default SSL context. It will be returned by subsequent calls
* to {@link #getDefault}. The default context must be immediately usable
* and not require {@linkplain #init initialization}.
*
* @param context the SSLContext
* @throws NullPointerException if context is null
* @throws SecurityException if a security manager exists and its
* <code>checkPermission</code> method does not allow
* <code>SSLPermission("setDefaultSSLContext")</code>
* @since 1.6
*/
public static synchronized void setDefault(SSLContext context) {
if (context == null) {
throw new NullPointerException();
}
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new SSLPermission("setDefaultSSLContext"));
}
defaultContext = context;
}
/** {@collect.stats}
* Returns a <code>SSLContext</code> object that implements the
* specified secure socket protocol.
*
* <p> This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new SSLContext object encapsulating the
* SSLContextSpi implementation from the first
* Provider that supports the specified protocol is returned.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param protocol the standard name of the requested protocol.
* See Appendix A in the <a href=
* "{@docRoot}/../technotes/guides/security/jsse/JSSERefGuide.html#AppA">
* Java Secure Socket Extension Reference Guide </a>
* for information about standard protocol names.
*
* @return the new <code>SSLContext</code> object.
*
* @exception NoSuchAlgorithmException if no Provider supports a
* TrustManagerFactorySpi implementation for the
* specified protocol.
*
* @see java.security.Provider
*/
public static SSLContext getInstance(String protocol)
throws NoSuchAlgorithmException {
GetInstance.Instance instance = GetInstance.getInstance
("SSLContext", SSLContextSpi.class, protocol);
return new SSLContext((SSLContextSpi)instance.impl, instance.provider,
protocol);
}
/** {@collect.stats}
* Returns a <code>SSLContext</code> object that implements the
* specified secure socket protocol.
*
* <p> A new SSLContext object encapsulating the
* SSLContextSpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param protocol the standard name of the requested protocol.
* See Appendix A in the <a href=
* "{@docRoot}/../technotes/guides//security/jsse/JSSERefGuide.html#AppA">
* Java Secure Socket Extension Reference Guide </a>
* for information about standard protocol names.
*
* @param provider the name of the provider.
*
* @return the new <code>SSLContext</code> object.
*
* @throws NoSuchAlgorithmException if a SSLContextSpi
* implementation for the specified protocol is not
* available from the specified provider.
*
* @throws NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @throws IllegalArgumentException if the provider name is null or empty.
*
* @see java.security.Provider
*/
public static SSLContext getInstance(String protocol, String provider)
throws NoSuchAlgorithmException, NoSuchProviderException {
GetInstance.Instance instance = GetInstance.getInstance
("SSLContext", SSLContextSpi.class, protocol, provider);
return new SSLContext((SSLContextSpi)instance.impl, instance.provider,
protocol);
}
/** {@collect.stats}
* Returns a <code>SSLContext</code> object that implements the
* specified secure socket protocol.
*
* <p> A new SSLContext object encapsulating the
* SSLContextSpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param protocol the standard name of the requested protocol.
* See Appendix A in the <a href=
* "{@docRoot}/../technotes/guides/security/jsse/JSSERefGuide.html#AppA">
* Java Secure Socket Extension Reference Guide </a>
* for information about standard protocol names.
*
* @param provider an instance of the provider.
*
* @return the new <code>SSLContext</code> object.
*
* @throws NoSuchAlgorithmException if a KeyManagerFactorySpi
* implementation for the specified protocol is not available
* from the specified Provider object.
*
* @throws IllegalArgumentException if the provider name is null.
*
* @see java.security.Provider
*/
public static SSLContext getInstance(String protocol, Provider provider)
throws NoSuchAlgorithmException {
GetInstance.Instance instance = GetInstance.getInstance
("SSLContext", SSLContextSpi.class, protocol, provider);
return new SSLContext((SSLContextSpi)instance.impl, instance.provider,
protocol);
}
/** {@collect.stats}
* Returns the protocol name of this <code>SSLContext</code> object.
*
* <p>This is the same name that was specified in one of the
* <code>getInstance</code> calls that created this
* <code>SSLContext</code> object.
*
* @return the protocol name of this <code>SSLContext</code> object.
*/
public final String getProtocol() {
return this.protocol;
}
/** {@collect.stats}
* Returns the provider of this <code>SSLContext</code> object.
*
* @return the provider of this <code>SSLContext</code> object
*/
public final Provider getProvider() {
return this.provider;
}
/** {@collect.stats}
* Initializes this context. Either of the first two parameters
* may be null in which case the installed security providers will
* be searched for the highest priority implementation of the
* appropriate factory. Likewise, the secure random parameter may
* be null in which case the default implementation will be used.
* <P>
* Only the first instance of a particular key and/or trust manager
* implementation type in the array is used. (For example, only
* the first javax.net.ssl.X509KeyManager in the array will be used.)
*
* @param km the sources of authentication keys or null
* @param tm the sources of peer authentication trust decisions or null
* @param random the source of randomness for this generator or null
* @throws KeyManagementException if this operation fails
*/
public final void init(KeyManager[] km, TrustManager[] tm,
SecureRandom random)
throws KeyManagementException {
contextSpi.engineInit(km, tm, random);
}
/** {@collect.stats}
* Returns a <code>SocketFactory</code> object for this
* context.
*
* @return the <code>SocketFactory</code> object
* @throws IllegalStateException if the SSLContextImpl requires
* initialization and the <code>init()</code> has not been called
*/
public final SSLSocketFactory getSocketFactory() {
return contextSpi.engineGetSocketFactory();
}
/** {@collect.stats}
* Returns a <code>ServerSocketFactory</code> object for
* this context.
*
* @return the <code>ServerSocketFactory</code> object
* @throws IllegalStateException if the SSLContextImpl requires
* initialization and the <code>init()</code> has not been called
*/
public final SSLServerSocketFactory getServerSocketFactory() {
return contextSpi.engineGetServerSocketFactory();
}
/** {@collect.stats}
* Creates a new <code>SSLEngine</code> using this context.
* <P>
* Applications using this factory method are providing no hints
* for an internal session reuse strategy. If hints are desired,
* {@link #createSSLEngine(String, int)} should be used
* instead.
* <P>
* Some cipher suites (such as Kerberos) require remote hostname
* information, in which case this factory method should not be used.
*
* @return the <code>SSLEngine</code> object
* @throws UnsupportedOperationException if the underlying provider
* does not implement the operation.
* @throws IllegalStateException if the SSLContextImpl requires
* initialization and the <code>init()</code> has not been called
* @since 1.5
*/
public final SSLEngine createSSLEngine() {
try {
return contextSpi.engineCreateSSLEngine();
} catch (AbstractMethodError e) {
UnsupportedOperationException unsup =
new UnsupportedOperationException(
"Provider: " + getProvider() +
" doesn't support this operation");
unsup.initCause(e);
throw unsup;
}
}
/** {@collect.stats}
* Creates a new <code>SSLEngine</code> using this context using
* advisory peer information.
* <P>
* Applications using this factory method are providing hints
* for an internal session reuse strategy.
* <P>
* Some cipher suites (such as Kerberos) require remote hostname
* information, in which case peerHost needs to be specified.
*
* @param peerHost the non-authoritative name of the host
* @param peerPort the non-authoritative port
* @return the new <code>SSLEngine</code> object
* @throws UnsupportedOperationException if the underlying provider
* does not implement the operation.
* @throws IllegalStateException if the SSLContextImpl requires
* initialization and the <code>init()</code> has not been called
* @since 1.5
*/
public final SSLEngine createSSLEngine(String peerHost, int peerPort) {
try {
return contextSpi.engineCreateSSLEngine(peerHost, peerPort);
} catch (AbstractMethodError e) {
UnsupportedOperationException unsup =
new UnsupportedOperationException(
"Provider: " + getProvider() +
" does not support this operation");
unsup.initCause(e);
throw unsup;
}
}
/** {@collect.stats}
* Returns the server session context, which represents the set of
* SSL sessions available for use during the handshake phase of
* server-side SSL sockets.
* <P>
* This context may be unavailable in some environments, in which
* case this method returns null. For example, when the underlying
* SSL provider does not provide an implementation of SSLSessionContext
* interface, this method returns null. A non-null session context
* is returned otherwise.
*
* @return server session context bound to this SSL context
*/
public final SSLSessionContext getServerSessionContext() {
return contextSpi.engineGetServerSessionContext();
}
/** {@collect.stats}
* Returns the client session context, which represents the set of
* SSL sessions available for use during the handshake phase of
* client-side SSL sockets.
* <P>
* This context may be unavailable in some environments, in which
* case this method returns null. For example, when the underlying
* SSL provider does not provide an implementation of SSLSessionContext
* interface, this method returns null. A non-null session context
* is returned otherwise.
*
* @return client session context bound to this SSL context
*/
public final SSLSessionContext getClientSessionContext() {
return contextSpi.engineGetClientSessionContext();
}
/** {@collect.stats}
* Returns a copy of the SSLParameters indicating the default
* settings for this SSL context.
*
* <p>The parameters will always have the ciphersuites and protocols
* arrays set to non-null values.
*
* @return a copy of the SSLParameters object with the default settings
* @throws UnsupportedOperationException if the default SSL parameters
* could not be obtained.
* @since 1.6
*/
public final SSLParameters getDefaultSSLParameters() {
return contextSpi.engineGetDefaultSSLParameters();
}
/** {@collect.stats}
* Returns a copy of the SSLParameters indicating the supported
* settings for this SSL context.
*
* <p>The parameters will always have the ciphersuites and protocols
* arrays set to non-null values.
*
* @return a copy of the SSLParameters object with the supported
* settings
* @throws UnsupportedOperationException if the supported SSL parameters
* could not be obtained.
* @since 1.6
*/
public final SSLParameters getSupportedSSLParameters() {
return contextSpi.engineGetSupportedSSLParameters();
}
}
|
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.net.ssl;
import java.util.EventObject;
import java.security.cert.Certificate;
import java.security.Principal;
import java.security.cert.X509Certificate;
import javax.security.auth.x500.X500Principal;
/** {@collect.stats}
* This event indicates that an SSL handshake completed on a given
* SSL connection. All of the core information about that handshake's
* result is captured through an "SSLSession" object. As a convenience,
* this event class provides direct access to some important session
* attributes.
*
* <P> The source of this event is the SSLSocket on which handshaking
* just completed.
*
* @see SSLSocket
* @see HandshakeCompletedListener
* @see SSLSession
*
* @since 1.4
* @author David Brownell
*/
public class HandshakeCompletedEvent extends EventObject
{
private static final long serialVersionUID = 7914963744257769778L;
private transient SSLSession session;
/** {@collect.stats}
* Constructs a new HandshakeCompletedEvent.
*
* @param sock the SSLSocket acting as the source of the event
* @param s the SSLSession this event is associated with
*/
public HandshakeCompletedEvent(SSLSocket sock, SSLSession s)
{
super(sock);
session = s;
}
/** {@collect.stats}
* Returns the session that triggered this event.
*
* @return the <code>SSLSession</code> for this handshake
*/
public SSLSession getSession()
{
return session;
}
/** {@collect.stats}
* Returns the cipher suite in use by the session which was produced
* by the handshake. (This is a convenience method for
* getting the ciphersuite from the SSLsession.)
*
* @return the name of the cipher suite negotiated during this session.
*/
public String getCipherSuite()
{
return session.getCipherSuite();
}
/** {@collect.stats}
* Returns the certificate(s) that were sent to the peer during
* handshaking.
* Note: This method is useful only when using certificate-based
* cipher suites.
*
* When multiple certificates are available for use in a
* handshake, the implementation chooses what it considers the
* "best" certificate chain available, and transmits that to
* the other side. This method allows the caller to know
* which certificate chain was actually used.
*
* @return an ordered array of certificates, with the local
* certificate first followed by any
* certificate authorities. If no certificates were sent,
* then null is returned.
* @see #getLocalPrincipal()
*/
public java.security.cert.Certificate [] getLocalCertificates()
{
return session.getLocalCertificates();
}
/** {@collect.stats}
* Returns the identity of the peer which was established as part
* of defining the session.
* Note: This method can be used only when using certificate-based
* cipher suites; using it with non-certificate-based cipher suites,
* such as Kerberos, will throw an SSLPeerUnverifiedException.
*
* @return an ordered array of the peer certificates,
* with the peer's own certificate first followed by
* any certificate authorities.
* @exception SSLPeerUnverifiedException if the peer is not verified.
* @see #getPeerPrincipal()
*/
public java.security.cert.Certificate [] getPeerCertificates()
throws SSLPeerUnverifiedException
{
return session.getPeerCertificates();
}
/** {@collect.stats}
* Returns the identity of the peer which was identified as part
* of defining the session.
* Note: This method can be used only when using certificate-based
* cipher suites; using it with non-certificate-based cipher suites,
* such as Kerberos, will throw an SSLPeerUnverifiedException.
*
* <p><em>Note: this method exists for compatibility with previous
* releases. New applications should use
* {@link #getPeerCertificates} instead.</em></p>
*
* @return an ordered array of peer X.509 certificates,
* with the peer's own certificate first followed by any
* certificate authorities. (The certificates are in
* the original JSSE
* {@link javax.security.cert.X509Certificate} format).
* @exception SSLPeerUnverifiedException if the peer is not verified.
* @see #getPeerPrincipal()
*/
public javax.security.cert.X509Certificate [] getPeerCertificateChain()
throws SSLPeerUnverifiedException
{
return session.getPeerCertificateChain();
}
/** {@collect.stats}
* Returns the identity of the peer which was established as part of
* defining the session.
*
* @return the peer's principal. Returns an X500Principal of the
* end-entity certiticate for X509-based cipher suites, and
* KerberosPrincipal for Kerberos cipher suites.
*
* @throws SSLPeerUnverifiedException if the peer's identity has not
* been verified
*
* @see #getPeerCertificates()
* @see #getLocalPrincipal()
*
* @since 1.5
*/
public Principal getPeerPrincipal()
throws SSLPeerUnverifiedException
{
Principal principal;
try {
principal = session.getPeerPrincipal();
} catch (AbstractMethodError e) {
// if the provider does not support it, fallback to peer certs.
// return the X500Principal of the end-entity cert.
Certificate[] certs = getPeerCertificates();
principal = (X500Principal)
((X509Certificate)certs[0]).getSubjectX500Principal();
}
return principal;
}
/** {@collect.stats}
* Returns the principal that was sent to the peer during handshaking.
*
* @return the principal sent to the peer. Returns an X500Principal
* of the end-entity certificate for X509-based cipher suites, and
* KerberosPrincipal for Kerberos cipher suites. If no principal was
* sent, then null is returned.
*
* @see #getLocalCertificates()
* @see #getPeerPrincipal()
*
* @since 1.5
*/
public Principal getLocalPrincipal()
{
Principal principal;
try {
principal = session.getLocalPrincipal();
} catch (AbstractMethodError e) {
principal = null;
// if the provider does not support it, fallback to local certs.
// return the X500Principal of the end-entity cert.
Certificate[] certs = getLocalCertificates();
if (certs != null) {
principal = (X500Principal)
((X509Certificate)certs[0]).getSubjectX500Principal();
}
}
return principal;
}
/** {@collect.stats}
* Returns the socket which is the source of this event.
* (This is a convenience function, to let applications
* write code without type casts.)
*
* @return the socket on which the connection was made.
*/
public SSLSocket getSocket()
{
return (SSLSocket) getSource();
}
}
|
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.net.ssl;
import java.net.URL;
import java.net.HttpURLConnection;
import java.security.Principal;
import java.security.cert.X509Certificate;
import javax.security.auth.x500.X500Principal;
/** {@collect.stats}
* <code>HttpsURLConnection</code> extends <code>HttpURLConnection</code>
* with support for https-specific features.
* <P>
* See <A HREF="http://www.w3.org/pub/WWW/Protocols/">
* http://www.w3.org/pub/WWW/Protocols/</A> and
* <A HREF="http://www.ietf.org/"> RFC 2818 </A>
* for more details on the
* https specification.
* <P>
* This class uses <code>HostnameVerifier</code> and
* <code>SSLSocketFactory</code>.
* There are default implementations defined for both classes.
* However, the implementations can be replaced on a per-class (static) or
* per-instance basis. All new <code>HttpsURLConnection</code>s instances
* will be assigned
* the "default" static values at instance creation, but they can be overriden
* by calling the appropriate per-instance set method(s) before
* <code>connect</code>ing.
*
* @since 1.4
*/
abstract public
class HttpsURLConnection extends HttpURLConnection
{
/** {@collect.stats}
* Creates an <code>HttpsURLConnection</code> using the
* URL specified.
*
* @param url the URL
*/
protected HttpsURLConnection(URL url) {
super(url);
}
/** {@collect.stats}
* Returns the cipher suite in use on this connection.
*
* @return the cipher suite
* @throws IllegalStateException if this method is called before
* the connection has been established.
*/
public abstract String getCipherSuite();
/** {@collect.stats}
* Returns the certificate(s) that were sent to the server during
* handshaking.
* <P>
* Note: This method is useful only when using certificate-based
* cipher suites.
* <P>
* When multiple certificates are available for use in a
* handshake, the implementation chooses what it considers the
* "best" certificate chain available, and transmits that to
* the other side. This method allows the caller to know
* which certificate chain was actually sent.
*
* @return an ordered array of certificates,
* with the client's own certificate first followed by any
* certificate authorities. If no certificates were sent,
* then null is returned.
* @throws IllegalStateException if this method is called before
* the connection has been established.
* @see #getLocalPrincipal()
*/
public abstract java.security.cert.Certificate [] getLocalCertificates();
/** {@collect.stats}
* Returns the server's certificate chain which was established
* as part of defining the session.
* <P>
* Note: This method can be used only when using certificate-based
* cipher suites; using it with non-certificate-based cipher suites,
* such as Kerberos, will throw an SSLPeerUnverifiedException.
*
* @return an ordered array of server certificates,
* with the peer's own certificate first followed by
* any certificate authorities.
* @throws SSLPeerUnverifiedException if the peer is not verified.
* @throws IllegalStateException if this method is called before
* the connection has been established.
* @see #getPeerPrincipal()
*/
public abstract java.security.cert.Certificate [] getServerCertificates()
throws SSLPeerUnverifiedException;
/** {@collect.stats}
* Returns the server's principal which was established as part of
* defining the session.
* <P>
* Note: Subclasses should override this method. If not overridden, it
* will default to returning the X500Principal of the server's end-entity
* certificate for certificate-based ciphersuites, or throw an
* SSLPeerUnverifiedException for non-certificate based ciphersuites,
* such as Kerberos.
*
* @return the server's principal. Returns an X500Principal of the
* end-entity certiticate for X509-based cipher suites, and
* KerberosPrincipal for Kerberos cipher suites.
*
* @throws SSLPeerUnverifiedException if the peer was not verified
* @throws IllegalStateException if this method is called before
* the connection has been established.
*
* @see #getServerCertificates()
* @see #getLocalPrincipal()
*
* @since 1.5
*/
public Principal getPeerPrincipal()
throws SSLPeerUnverifiedException {
java.security.cert.Certificate[] certs = getServerCertificates();
return ((X500Principal)
((X509Certificate)certs[0]).getSubjectX500Principal());
}
/** {@collect.stats}
* Returns the principal that was sent to the server during handshaking.
* <P>
* Note: Subclasses should override this method. If not overridden, it
* will default to returning the X500Principal of the end-entity certificate
* that was sent to the server for certificate-based ciphersuites or,
* return null for non-certificate based ciphersuites, such as Kerberos.
*
* @return the principal sent to the server. Returns an X500Principal
* of the end-entity certificate for X509-based cipher suites, and
* KerberosPrincipal for Kerberos cipher suites. If no principal was
* sent, then null is returned.
*
* @throws IllegalStateException if this method is called before
* the connection has been established.
*
* @see #getLocalCertificates()
* @see #getPeerPrincipal()
*
* @since 1.5
*/
public Principal getLocalPrincipal() {
java.security.cert.Certificate[] certs = getLocalCertificates();
if (certs != null) {
return ((X500Principal)
((X509Certificate)certs[0]).getSubjectX500Principal());
} else {
return null;
}
}
/** {@collect.stats}
* <code>HostnameVerifier</code> provides a callback mechanism so that
* implementers of this interface can supply a policy for
* handling the case where the host to connect to and
* the server name from the certificate mismatch.
* <p>
* The default implementation will deny such connections.
*/
private static HostnameVerifier defaultHostnameVerifier;
/** {@collect.stats}
* Initialize the default <code>HostnameVerifier</code>.
*/
static {
try {
defaultHostnameVerifier =
new sun.net.www.protocol.https.DefaultHostnameVerifier();
} catch (NoClassDefFoundError e) {
defaultHostnameVerifier = new DefaultHostnameVerifier();
}
}
/*
* The initial default <code>HostnameVerifier</code>. Should be
* updated for another other type of <code>HostnameVerifier</code>
* that are created.
*/
private static class DefaultHostnameVerifier
implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return false;
}
}
/** {@collect.stats}
* The <code>hostnameVerifier</code> for this object.
*/
protected HostnameVerifier hostnameVerifier = defaultHostnameVerifier;
/** {@collect.stats}
* Sets the default <code>HostnameVerifier</code> inherited by a
* new instance of this class.
* <P>
* If this method is not called, the default
* <code>HostnameVerifier</code> assumes the connection should not
* be permitted.
*
* @param v the default host name verifier
* @throws IllegalArgumentException if the <code>HostnameVerifier</code>
* parameter is null.
* @throws SecurityException if a security manager exists and its
* <code>checkPermission</code> method does not allow
* <code>SSLPermission("setHostnameVerifier")</code>
* @see #getDefaultHostnameVerifier()
*/
public static void setDefaultHostnameVerifier(HostnameVerifier v) {
if (v == null) {
throw new IllegalArgumentException(
"no default HostnameVerifier specified");
}
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new SSLPermission("setHostnameVerifier"));
}
defaultHostnameVerifier = v;
}
/** {@collect.stats}
* Gets the default <code>HostnameVerifier</code> that is inherited
* by new instances of this class.
*
* @return the default host name verifier
* @see #setDefaultHostnameVerifier(HostnameVerifier)
*/
public static HostnameVerifier getDefaultHostnameVerifier() {
return defaultHostnameVerifier;
}
/** {@collect.stats}
* Sets the <code>HostnameVerifier</code> for this instance.
* <P>
* New instances of this class inherit the default static hostname
* verifier set by {@link #setDefaultHostnameVerifier(HostnameVerifier)
* setDefaultHostnameVerifier}. Calls to this method replace
* this object's <code>HostnameVerifier</code>.
*
* @param v the host name verifier
* @throws IllegalArgumentException if the <code>HostnameVerifier</code>
* parameter is null.
* @see #getHostnameVerifier()
* @see #setDefaultHostnameVerifier(HostnameVerifier)
*/
public void setHostnameVerifier(HostnameVerifier v) {
if (v == null) {
throw new IllegalArgumentException(
"no HostnameVerifier specified");
}
hostnameVerifier = v;
}
/** {@collect.stats}
* Gets the <code>HostnameVerifier</code> in place on this instance.
*
* @return the host name verifier
* @see #setHostnameVerifier(HostnameVerifier)
* @see #setDefaultHostnameVerifier(HostnameVerifier)
*/
public HostnameVerifier getHostnameVerifier() {
return hostnameVerifier;
}
private static SSLSocketFactory defaultSSLSocketFactory = null;
/** {@collect.stats}
* The <code>SSLSocketFactory</code> inherited when an instance
* of this class is created.
*/
private SSLSocketFactory sslSocketFactory = getDefaultSSLSocketFactory();
/** {@collect.stats}
* Sets the default <code>SSLSocketFactory</code> inherited by new
* instances of this class.
* <P>
* The socket factories are used when creating sockets for secure
* https URL connections.
*
* @param sf the default SSL socket factory
* @throws IllegalArgumentException if the SSLSocketFactory
* parameter is null.
* @throws SecurityException if a security manager exists and its
* <code>checkSetFactory</code> method does not allow
* a socket factory to be specified.
* @see #getDefaultSSLSocketFactory()
*/
public static void setDefaultSSLSocketFactory(SSLSocketFactory sf) {
if (sf == null) {
throw new IllegalArgumentException(
"no default SSLSocketFactory specified");
}
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkSetFactory();
}
defaultSSLSocketFactory = sf;
}
/** {@collect.stats}
* Gets the default static <code>SSLSocketFactory</code> that is
* inherited by new instances of this class.
* <P>
* The socket factories are used when creating sockets for secure
* https URL connections.
*
* @return the default <code>SSLSocketFactory</code>
* @see #setDefaultSSLSocketFactory(SSLSocketFactory)
*/
public static SSLSocketFactory getDefaultSSLSocketFactory() {
if (defaultSSLSocketFactory == null) {
defaultSSLSocketFactory =
(SSLSocketFactory)SSLSocketFactory.getDefault();
}
return defaultSSLSocketFactory;
}
/** {@collect.stats}
* Sets the <code>SSLSocketFactory</code> to be used when this instance
* creates sockets for secure https URL connections.
* <P>
* New instances of this class inherit the default static
* <code>SSLSocketFactory</code> set by
* {@link #setDefaultSSLSocketFactory(SSLSocketFactory)
* setDefaultSSLSocketFactory}. Calls to this method replace
* this object's <code>SSLSocketFactory</code>.
*
* @param sf the SSL socket factory
* @throws IllegalArgumentException if the <code>SSLSocketFactory</code>
* parameter is null.
* @see #getSSLSocketFactory()
*/
public void setSSLSocketFactory(SSLSocketFactory sf) {
if (sf == null) {
throw new IllegalArgumentException(
"no SSLSocketFactory specified");
}
sslSocketFactory = sf;
}
/** {@collect.stats}
* Gets the SSL socket factory to be used when creating sockets
* for secure https URL connections.
*
* @return the <code>SSLSocketFactory</code>
* @see #setSSLSocketFactory(SSLSocketFactory)
*/
public SSLSocketFactory getSSLSocketFactory() {
return sslSocketFactory;
}
}
|
Java
|
/*
* Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.net.ssl;
import java.security.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.security.Permissions;
import java.lang.SecurityManager;
/** {@collect.stats}
* This class is for various network permissions.
* An SSLPermission contains a name (also referred to as a "target name") but
* no actions list; you either have the named permission
* or you don't.
* <P>
* The target name is the name of the network permission (see below). The naming
* convention follows the hierarchical property naming convention.
* Also, an asterisk
* may appear at the end of the name, following a ".", or by itself, to
* signify a wildcard match. For example: "foo.*" or "*" is valid,
* "*foo" or "a*b" is not valid.
* <P>
* The following table lists all the possible SSLPermission target names,
* and for each provides a description of what the permission allows
* and a discussion of the risks of granting code the permission.
* <P>
*
* <table border=1 cellpadding=5
* summary="permission name, what it allows, and associated risks">
* <tr>
* <th>Permission Target Name</th>
* <th>What the Permission Allows</th>
* <th>Risks of Allowing this Permission</th>
* </tr>
*
* <tr>
* <td>setHostnameVerifier</td>
* <td>The ability to set a callback which can decide whether to
* allow a mismatch between the host being connected to by
* an HttpsURLConnection and the common name field in
* server certificate.
* </td>
* <td>Malicious
* code can set a verifier that monitors host names visited by
* HttpsURLConnection requests or that allows server certificates
* with invalid common names.
* </td>
* </tr>
*
* <tr>
* <td>getSSLSessionContext</td>
* <td>The ability to get the SSLSessionContext of an SSLSession.
* </td>
* <td>Malicious code may monitor sessions which have been established
* with SSL peers or might invalidate sessions to slow down performance.
* </td>
* </tr>
*
* <tr>
* <td>setDefaultSSLContext</td>
* <td>The ability to set the default SSL context
* </td>
* <td>Malicious code can set a context that monitors the opening of
* connections or the plaintext data that is transmitted.
* </td>
* </tr>
*
* </table>
*
* @see java.security.BasicPermission
* @see java.security.Permission
* @see java.security.Permissions
* @see java.security.PermissionCollection
* @see java.lang.SecurityManager
*
* @since 1.4
* @author Marianne Mueller
* @author Roland Schemers
*/
public final class SSLPermission extends BasicPermission {
private static final long serialVersionUID = -3456898025505876775L;
/** {@collect.stats}
* Creates a new SSLPermission with the specified name.
* The name is the symbolic name of the SSLPermission, such as
* "setDefaultAuthenticator", etc. An asterisk
* may appear at the end of the name, following a ".", or by itself, to
* signify a wildcard match.
*
* @param name the name of the SSLPermission.
*
* @throws NullPointerException if <code>name</code> is null.
* @throws IllegalArgumentException if <code>name</code> is empty.
*/
public SSLPermission(String name)
{
super(name);
}
/** {@collect.stats}
* Creates a new SSLPermission object with the specified name.
* The name is the symbolic name of the SSLPermission, and the
* actions String is currently unused and should be null.
*
* @param name the name of the SSLPermission.
* @param actions ignored.
*
* @throws NullPointerException if <code>name</code> is null.
* @throws IllegalArgumentException if <code>name</code> is empty.
*/
public SSLPermission(String name, String actions)
{
super(name, actions);
}
}
|
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.net.ssl;
import java.security.*;
/** {@collect.stats}
* This class defines the <i>Service Provider Interface</i> (<b>SPI</b>)
* for the <code>KeyManagerFactory</code> class.
*
* <p> All the abstract methods in this class must be implemented by each
* cryptographic service provider who wishes to supply the implementation
* of a particular key manager factory.
*
* @since 1.4
* @see KeyManagerFactory
* @see KeyManager
*/
public abstract class KeyManagerFactorySpi {
/** {@collect.stats}
* Initializes this factory with a source of key material.
*
* @param ks the key store or null
* @param password the password for recovering keys
* @throws KeyStoreException if this operation fails
* @throws NoSuchAlgorithmException if the specified algorithm is not
* available from the specified provider.
* @throws UnrecoverableKeyException if the key cannot be recovered
* @see KeyManagerFactory#init(KeyStore, char[])
*/
protected abstract void engineInit(KeyStore ks, char[] password) throws
KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException;
/** {@collect.stats}
* Initializes this factory with a source of key material.
* <P>
* In some cases, initialization parameters other than a keystore
* and password may be needed by a provider. Users of that
* particular provider are expected to pass an implementation of
* the appropriate <CODE>ManagerFactoryParameters</CODE> as
* defined by the provider. The provider can then call the
* specified methods in the ManagerFactoryParameters
* implementation to obtain the needed information.
*
* @param spec an implementation of a provider-specific parameter
* specification
* @throws InvalidAlgorithmParameterException if there is problem
* with the parameters
* @see KeyManagerFactory#init(ManagerFactoryParameters spec)
*/
protected abstract void engineInit(ManagerFactoryParameters spec)
throws InvalidAlgorithmParameterException;
/** {@collect.stats}
* Returns one key manager for each type of key material.
*
* @return the key managers
* @throws IllegalStateException
* if the KeyManagerFactorySpi is not initialized
*/
protected abstract KeyManager[] engineGetKeyManagers();
}
|
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.net.ssl;
import java.io.*;
import java.net.*;
/** {@collect.stats}
* This class extends <code>ServerSocket</code>s and
* provides secure server sockets using protocols such as the Secure
* Sockets Layer (SSL) or Transport Layer Security (TLS) protocols.
* <P>
* Instances of this class are generally created using a
* <code>SSLServerSocketFactory</code>. The primary function
* of <code>SSLServerSocket</code>s
* is to create <code>SSLSocket</code>s by <code>accept</code>ing
* connections.
* <P>
* <code>SSLServerSocket</code>s contain several pieces of state data
* which are inherited by the <code>SSLSocket</code> at
* socket creation. These include the enabled cipher
* suites and protocols, whether client
* authentication is necessary, and whether created sockets should
* begin handshaking in client or server mode. The state
* inherited by the created <code>SSLSocket</code> can be
* overriden by calling the appropriate methods.
*
* @see java.net.ServerSocket
* @see SSLSocket
*
* @since 1.4
* @author David Brownell
*/
public abstract class SSLServerSocket extends ServerSocket
{
/** {@collect.stats}
* Used only by subclasses.
* <P>
* Create an unbound TCP server socket using the default authentication
* context.
*
* @throws IOException if an I/O error occurs when creating the socket
*/
protected SSLServerSocket()
throws IOException
{ super(); }
/** {@collect.stats}
* Used only by subclasses.
* <P>
* Create a TCP server socket on a port, using the default
* authentication context. The connection backlog defaults to
* fifty connections queued up before the system starts to
* reject new connection requests.
*
* @param port the port on which to listen
* @throws IOException if an I/O error occurs when creating the socket
*/
protected SSLServerSocket(int port)
throws IOException
{ super(port); }
/** {@collect.stats}
* Used only by subclasses.
* <P>
* Create a TCP server socket on a port, using the default
* authentication context and a specified backlog of connections.
*
* @param port the port on which to listen
* @param backlog how many connections may be pending before
* the system should start rejecting new requests
* @throws IOException if an I/O error occurs when creating the socket
*/
protected SSLServerSocket(int port, int backlog)
throws IOException
{ super(port, backlog); }
/** {@collect.stats}
* Used only by subclasses.
* <P>
* Create a TCP server socket on a port, using the default
* authentication context and a specified backlog of connections
* as well as a particular specified network interface. This
* constructor is used on multihomed hosts, such as those used
* for firewalls or as routers, to control through which interface
* a network service is provided.
*
* @param port the port on which to listen
* @param backlog how many connections may be pending before
* the system should start rejecting new requests
* @param address the address of the network interface through
* which connections will be accepted
* @throws IOException if an I/O error occurs when creating the socket
*/
protected SSLServerSocket(int port, int backlog, InetAddress address)
throws IOException
{ super(port, backlog, address); }
/** {@collect.stats}
* Returns the list of cipher suites which are currently enabled
* for use by newly accepted connections.
* <P>
* If this list has not been explicitly modified, a system-provided
* default guarantees a minimum quality of service in all enabled
* cipher suites.
* <P>
* There are several reasons why an enabled cipher suite might
* not actually be used. For example: the server socket might
* not have appropriate private keys available to it or the cipher
* suite might be anonymous, precluding the use of client authentication,
* while the server socket has been told to require that sort of
* authentication.
*
* @return an array of cipher suites enabled
* @see #getSupportedCipherSuites()
* @see #setEnabledCipherSuites(String [])
*/
public abstract String [] getEnabledCipherSuites();
/** {@collect.stats}
* Sets the cipher suites enabled for use by accepted connections.
* <P>
* The cipher suites must have been listed by getSupportedCipherSuites()
* as being supported. Following a successful call to this method,
* only suites listed in the <code>suites</code> parameter are enabled
* for use.
* <P>
* Suites that require authentication information which is not available
* in this ServerSocket's authentication context will not be used
* in any case, even if they are enabled.
* <P>
* <code>SSLSocket</code>s returned from <code>accept()</code>
* inherit this setting.
*
* @param suites Names of all the cipher suites to enable
* @exception IllegalArgumentException when one or more of ciphers
* named by the parameter is not supported, or when
* the parameter is null.
* @see #getSupportedCipherSuites()
* @see #getEnabledCipherSuites()
*/
public abstract void setEnabledCipherSuites(String suites []);
/** {@collect.stats}
* Returns the names of the cipher suites which could be enabled for use
* on an SSL connection.
* <P>
* Normally, only a subset of these will actually
* be enabled by default, since this list may include cipher suites which
* do not meet quality of service requirements for those defaults. Such
* cipher suites are useful in specialized applications.
*
* @return an array of cipher suite names
* @see #getEnabledCipherSuites()
* @see #setEnabledCipherSuites(String [])
*/
public abstract String [] getSupportedCipherSuites();
/** {@collect.stats}
* Returns the names of the protocols which could be enabled for use.
*
* @return an array of protocol names supported
* @see #getEnabledProtocols()
* @see #setEnabledProtocols(String [])
*/
public abstract String [] getSupportedProtocols();
/** {@collect.stats}
* Returns the names of the protocols which are currently
* enabled for use by the newly accepted connections.
*
* @return an array of protocol names
* @see #getSupportedProtocols()
* @see #setEnabledProtocols(String [])
*/
public abstract String [] getEnabledProtocols();
/** {@collect.stats}
* Controls which particular protocols are enabled for use by
* accepted connections.
* <P>
* The protocols must have been listed by
* getSupportedProtocols() as being supported.
* Following a successful call to this method, only protocols listed
* in the <code>protocols</code> parameter are enabled for use.
* <P>
* <code>SSLSocket</code>s returned from <code>accept()</code>
* inherit this setting.
*
* @param protocols Names of all the protocols to enable.
* @exception IllegalArgumentException when one or more of
* the protocols named by the parameter is not supported or
* when the protocols parameter is null.
* @see #getEnabledProtocols()
* @see #getSupportedProtocols()
*/
public abstract void setEnabledProtocols(String protocols[]);
/** {@collect.stats}
* Controls whether <code>accept</code>ed server-mode
* <code>SSLSockets</code> will be initially configured to
* <i>require</i> client authentication.
* <P>
* A socket's client authentication setting is one of the following:
* <ul>
* <li> client authentication required
* <li> client authentication requested
* <li> no client authentication desired
* </ul>
* <P>
* Unlike {@link #setWantClientAuth(boolean)}, if the accepted
* socket's option is set and the client chooses not to provide
* authentication information about itself, <i>the negotiations
* will stop and the connection will be dropped</i>.
* <P>
* Calling this method overrides any previous setting made by
* this method or {@link #setWantClientAuth(boolean)}.
* <P>
* The initial inherited setting may be overridden by calling
* {@link SSLSocket#setNeedClientAuth(boolean)} or
* {@link SSLSocket#setWantClientAuth(boolean)}.
*
* @param need set to true if client authentication is required,
* or false if no client authentication is desired.
* @see #getNeedClientAuth()
* @see #setWantClientAuth(boolean)
* @see #getWantClientAuth()
* @see #setUseClientMode(boolean)
*/
public abstract void setNeedClientAuth(boolean need);
/** {@collect.stats}
* Returns true if client authentication will be <i>required</i> on
* newly <code>accept</code>ed server-mode <code>SSLSocket</code>s.
* <P>
* The initial inherited setting may be overridden by calling
* {@link SSLSocket#setNeedClientAuth(boolean)} or
* {@link SSLSocket#setWantClientAuth(boolean)}.
*
* @return true if client authentication is required,
* or false if no client authentication is desired.
* @see #setNeedClientAuth(boolean)
* @see #setWantClientAuth(boolean)
* @see #getWantClientAuth()
* @see #setUseClientMode(boolean)
*/
public abstract boolean getNeedClientAuth();
/** {@collect.stats}
* Controls whether <code>accept</code>ed server-mode
* <code>SSLSockets</code> will be initially configured to
* <i>request</i> client authentication.
* <P>
* A socket's client authentication setting is one of the following:
* <ul>
* <li> client authentication required
* <li> client authentication requested
* <li> no client authentication desired
* </ul>
* <P>
* Unlike {@link #setNeedClientAuth(boolean)}, if the accepted
* socket's option is set and the client chooses not to provide
* authentication information about itself, <i>the negotiations
* will continue</i>.
* <P>
* Calling this method overrides any previous setting made by
* this method or {@link #setNeedClientAuth(boolean)}.
* <P>
* The initial inherited setting may be overridden by calling
* {@link SSLSocket#setNeedClientAuth(boolean)} or
* {@link SSLSocket#setWantClientAuth(boolean)}.
*
* @param want set to true if client authentication is requested,
* or false if no client authentication is desired.
* @see #getWantClientAuth()
* @see #setNeedClientAuth(boolean)
* @see #getNeedClientAuth()
* @see #setUseClientMode(boolean)
*/
public abstract void setWantClientAuth(boolean want);
/** {@collect.stats}
* Returns true if client authentication will be <i>requested</i> on
* newly accepted server-mode connections.
* <P>
* The initial inherited setting may be overridden by calling
* {@link SSLSocket#setNeedClientAuth(boolean)} or
* {@link SSLSocket#setWantClientAuth(boolean)}.
*
* @return true if client authentication is requested,
* or false if no client authentication is desired.
* @see #setWantClientAuth(boolean)
* @see #setNeedClientAuth(boolean)
* @see #getNeedClientAuth()
* @see #setUseClientMode(boolean)
*/
public abstract boolean getWantClientAuth();
/** {@collect.stats}
* Controls whether accepted connections are in the (default) SSL
* server mode, or the SSL client mode.
* <P>
* Servers normally authenticate themselves, and clients are not
* required to do so.
* <P>
* In rare cases, TCP servers
* need to act in the SSL client mode on newly accepted
* connections. For example, FTP clients acquire server sockets
* and listen there for reverse connections from the server. An
* FTP client would use an SSLServerSocket in "client" mode to
* accept the reverse connection while the FTP server uses an
* SSLSocket with "client" mode disabled to initiate the
* connection. During the resulting handshake, existing SSL
* sessions may be reused.
* <P>
* <code>SSLSocket</code>s returned from <code>accept()</code>
* inherit this setting.
*
* @param mode true if newly accepted connections should use SSL
* client mode.
* @see #getUseClientMode()
*/
public abstract void setUseClientMode(boolean mode);
/** {@collect.stats}
* Returns true if accepted connections will be in SSL client mode.
*
* @see #setUseClientMode(boolean)
* @return true if the connection should use SSL client mode.
*/
public abstract boolean getUseClientMode();
/** {@collect.stats}
* Controls whether new SSL sessions may be established by the
* sockets which are created from this server socket.
* <P>
* <code>SSLSocket</code>s returned from <code>accept()</code>
* inherit this setting.
*
* @param flag true indicates that sessions may be created; this
* is the default. false indicates that an existing session
* must be resumed.
* @see #getEnableSessionCreation()
*/
public abstract void setEnableSessionCreation(boolean flag);
/** {@collect.stats}
* Returns true if new SSL sessions may be established by the
* sockets which are created from this server socket.
*
* @return true indicates that sessions may be created; this
* is the default. false indicates that an existing
* session must be resumed.
* @see #setEnableSessionCreation(boolean)
*/
public abstract boolean getEnableSessionCreation();
}
|
Java
|
/*
* Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.net.ssl;
/** {@collect.stats}
* Reports a bad SSL key. Normally, this indicates misconfiguration
* of the server or client SSL certificate and private key.
*
* @since 1.4
* @author David Brownell
*/
public
class SSLKeyException extends SSLException
{
private static final long serialVersionUID = -8071664081941937874L;
/** {@collect.stats}
* Constructs an exception reporting a key management error
* found by an SSL subsystem.
*
* @param reason describes the problem.
*/
public SSLKeyException(String reason)
{
super(reason);
}
}
|
Java
|
/*
* Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.net.ssl;
/** {@collect.stats}
* Indicates that the client and server could not negotiate the
* desired level of security. The connection is no longer usable.
*
* @since 1.4
* @author David Brownell
*/
public
class SSLHandshakeException extends SSLException
{
private static final long serialVersionUID = -5045881315018326890L;
/** {@collect.stats}
* Constructs an exception reporting an error found by
* an SSL subsystem during handshaking.
*
* @param reason describes the problem.
*/
public SSLHandshakeException(String reason)
{
super(reason);
}
}
|
Java
|
/*
* Copyright (c) 1997, 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.net.ssl;
import java.util.EventListener;
/** {@collect.stats}
* This interface is implemented by objects which want to know when
* they are being bound or unbound from a SSLSession. When either event
* occurs via {@link SSLSession#putValue(String, Object)}
* or {@link SSLSession#removeValue(String)}, the event is communicated
* through a SSLSessionBindingEvent identifying the session.
*
* @see SSLSession
* @see SSLSessionBindingEvent
*
* @since 1.4
* @author Nathan Abramson
* @author David Brownell
*/
public
interface SSLSessionBindingListener
extends EventListener
{
/** {@collect.stats}
* This is called to notify the listener that it is being bound into
* an SSLSession.
*
* @param event the event identifying the SSLSession into
* which the listener is being bound.
*/
public void valueBound(SSLSessionBindingEvent event);
/** {@collect.stats}
* This is called to notify the listener that it is being unbound
* from a SSLSession.
*
* @param event the event identifying the SSLSession from
* which the listener is being unbound.
*/
public void valueUnbound(SSLSessionBindingEvent event);
}
|
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.net.ssl;
import java.net.InetAddress;
import java.security.Principal;
/** {@collect.stats}
* In SSL, sessions are used to describe an ongoing relationship between
* two entities. Each SSL connection involves one session at a time, but
* that session may be used on many connections between those entities,
* simultaneously or sequentially. The session used on a connection may
* also be replaced by a different session. Sessions are created, or
* rejoined, as part of the SSL handshaking protocol. Sessions may be
* invalidated due to policies affecting security or resource usage,
* or by an application explicitly calling <code>invalidate</code>.
* Session management policies are typically used to tune performance.
*
* <P> In addition to the standard session attributes, SSL sessions expose
* these read-only attributes: <UL>
*
* <LI> <em>Peer Identity.</em> Sessions are between a particular
* client and a particular server. The identity of the peer may
* have been established as part of session setup. Peers are
* generally identified by X.509 certificate chains.
*
* <LI> <em>Cipher Suite Name.</em> Cipher suites describe the
* kind of cryptographic protection that's used by connections
* in a particular session.
*
* <LI> <em>Peer Host.</em> All connections in a session are
* between the same two hosts. The address of the host on the other
* side of the connection is available.
*
* </UL>
*
* <P> Sessions may be explicitly invalidated. Invalidation may also
* be done implicitly, when faced with certain kinds of errors.
*
* @since 1.4
* @author David Brownell
*/
public interface SSLSession {
/** {@collect.stats}
* Returns the identifier assigned to this Session.
*
* @return the Session identifier
*/
public byte[] getId();
/** {@collect.stats}
* Returns the context in which this session is bound.
* <P>
* This context may be unavailable in some environments,
* in which case this method returns null.
* <P>
* If the context is available and there is a
* security manager installed, the caller may require
* permission to access it or a security exception may be thrown.
* In a Java environment, the security manager's
* <code>checkPermission</code> method is called with a
* <code>SSLPermission("getSSLSessionContext")</code> permission.
*
* @throws SecurityException if the calling thread does not have
* permission to get SSL session context.
* @return the session context used for this session, or null
* if the context is unavailable.
*/
public SSLSessionContext getSessionContext();
/** {@collect.stats}
* Returns the time at which this Session representation was created,
* in milliseconds since midnight, January 1, 1970 UTC.
*
* @return the time this Session was created
*/
public long getCreationTime();
/** {@collect.stats}
* Returns the last time this Session representation was accessed by the
* session level infrastructure, in milliseconds since
* midnight, January 1, 1970 UTC.
* <P>
* Access indicates a new connection being established using session data.
* Application level operations, such as getting or setting a value
* associated with the session, are not reflected in this access time.
*
* <P> This information is particularly useful in session management
* policies. For example, a session manager thread could leave all
* sessions in a given context which haven't been used in a long time;
* or, the sessions might be sorted according to age to optimize some task.
*
* @return the last time this Session was accessed
*/
public long getLastAccessedTime();
/** {@collect.stats}
* Invalidates the session.
* <P>
* Future connections will not be able to
* resume or join this session. However, any existing connection
* using this session can continue to use the session until the
* connection is closed.
*
* @see #isValid()
*/
public void invalidate();
/** {@collect.stats}
* Returns whether this session is valid and available for resuming or
* joining.
*
* @return true if this session may be rejoined.
* @see #invalidate()
*
* @since 1.5
*/
public boolean isValid();
/** {@collect.stats}
*
* Binds the specified <code>value</code> object into the
* session's application layer data
* with the given <code>name</code>.
* <P>
* Any existing binding using the same <code>name</code> is
* replaced. If the new (or existing) <code>value</code> implements the
* <code>SSLSessionBindingListener</code> interface, the object
* represented by <code>value</code> is notified appropriately.
* <p>
* For security reasons, the same named values may not be
* visible across different access control contexts.
*
* @param name the name to which the data object will be bound.
* This may not be null.
* @param value the data object to be bound. This may not be null.
* @throws IllegalArgumentException if either argument is null.
*/
public void putValue(String name, Object value);
/** {@collect.stats}
* Returns the object bound to the given name in the session's
* application layer data. Returns null if there is no such binding.
* <p>
* For security reasons, the same named values may not be
* visible across different access control contexts.
*
* @param name the name of the binding to find.
* @return the value bound to that name, or null if the binding does
* not exist.
* @throws IllegalArgumentException if the argument is null.
*/
public Object getValue(String name);
/** {@collect.stats}
* Removes the object bound to the given name in the session's
* application layer data. Does nothing if there is no object
* bound to the given name. If the bound existing object
* implements the <code>SessionBindingListener</code> interface,
* it is notified appropriately.
* <p>
* For security reasons, the same named values may not be
* visible across different access control contexts.
*
* @param name the name of the object to remove visible
* across different access control contexts
* @throws IllegalArgumentException if the argument is null.
*/
public void removeValue(String name);
/** {@collect.stats}
* Returns an array of the names of all the application layer
* data objects bound into the Session.
* <p>
* For security reasons, the same named values may not be
* visible across different access control contexts.
*
* @return a non-null (possibly empty) array of names of the objects
* bound to this Session.
*/
public String [] getValueNames();
/** {@collect.stats}
* Returns the identity of the peer which was established as part
* of defining the session.
* <P>
* Note: This method can be used only when using certificate-based
* cipher suites; using it with non-certificate-based cipher suites,
* such as Kerberos, will throw an SSLPeerUnverifiedException.
*
* @return an ordered array of peer certificates,
* with the peer's own certificate first followed by any
* certificate authorities.
* @exception SSLPeerUnverifiedException if the peer's identity has not
* been verified
* @see #getPeerPrincipal()
*/
public java.security.cert.Certificate [] getPeerCertificates()
throws SSLPeerUnverifiedException;
/** {@collect.stats}
* Returns the certificate(s) that were sent to the peer during
* handshaking.
* <P>
* Note: This method is useful only when using certificate-based
* cipher suites.
* <P>
* When multiple certificates are available for use in a
* handshake, the implementation chooses what it considers the
* "best" certificate chain available, and transmits that to
* the other side. This method allows the caller to know
* which certificate chain was actually used.
*
* @return an ordered array of certificates,
* with the local certificate first followed by any
* certificate authorities. If no certificates were sent,
* then null is returned.
*
* @see #getLocalPrincipal()
*/
public java.security.cert.Certificate [] getLocalCertificates();
/** {@collect.stats}
* Returns the identity of the peer which was identified as part
* of defining the session.
* <P>
* Note: This method can be used only when using certificate-based
* cipher suites; using it with non-certificate-based cipher suites,
* such as Kerberos, will throw an SSLPeerUnverifiedException.
*
* <p><em>Note: this method exists for compatibility with previous
* releases. New applications should use
* {@link #getPeerCertificates} instead.</em></p>
*
* @return an ordered array of peer X.509 certificates,
* with the peer's own certificate first followed by any
* certificate authorities. (The certificates are in
* the original JSSE certificate
* {@link javax.security.cert.X509Certificate} format.)
* @exception SSLPeerUnverifiedException if the peer's identity
* has not been verified
* @see #getPeerPrincipal()
*/
public javax.security.cert.X509Certificate [] getPeerCertificateChain()
throws SSLPeerUnverifiedException;
/** {@collect.stats}
* Returns the identity of the peer which was established as part of
* defining the session.
*
* @return the peer's principal. Returns an X500Principal of the
* end-entity certiticate for X509-based cipher suites, and
* KerberosPrincipal for Kerberos cipher suites.
*
* @throws SSLPeerUnverifiedException if the peer's identity has not
* been verified
*
* @see #getPeerCertificates()
* @see #getLocalPrincipal()
*
* @since 1.5
*/
public Principal getPeerPrincipal()
throws SSLPeerUnverifiedException;
/** {@collect.stats}
* Returns the principal that was sent to the peer during handshaking.
*
* @return the principal sent to the peer. Returns an X500Principal
* of the end-entity certificate for X509-based cipher suites, and
* KerberosPrincipal for Kerberos cipher suites. If no principal was
* sent, then null is returned.
*
* @see #getLocalCertificates()
* @see #getPeerPrincipal()
*
* @since 1.5
*/
public Principal getLocalPrincipal();
/** {@collect.stats}
* Returns the name of the SSL cipher suite which is used for all
* connections in the session.
*
* <P> This defines the level of protection
* provided to the data sent on the connection, including the kind
* of encryption used and most aspects of how authentication is done.
*
* @return the name of the session's cipher suite
*/
public String getCipherSuite();
/** {@collect.stats}
* Returns the standard name of the protocol used for all
* connections in the session.
*
* <P> This defines the protocol used in the connection.
*
* @return the standard name of the protocol used for all
* connections in the session.
*/
public String getProtocol();
/** {@collect.stats}
* Returns the host name of the peer in this session.
* <P>
* For the server, this is the client's host; and for
* the client, it is the server's host. The name may not be
* a fully qualified host name or even a host name at all as
* it may represent a string encoding of the peer's network address.
* If such a name is desired, it might
* be resolved through a name service based on the value returned
* by this method.
* <P>
* This value is not authenticated and should not be relied upon.
* It is mainly used as a hint for <code>SSLSession</code> caching
* strategies.
*
* @return the host name of the peer host, or null if no information
* is available.
*/
public String getPeerHost();
/** {@collect.stats}
* Returns the port number of the peer in this session.
* <P>
* For the server, this is the client's port number; and for
* the client, it is the server's port number.
* <P>
* This value is not authenticated and should not be relied upon.
* It is mainly used as a hint for <code>SSLSession</code> caching
* strategies.
*
* @return the port number of the peer host, or -1 if no information
* is available.
*
* @since 1.5
*/
public int getPeerPort();
/** {@collect.stats}
* Gets the current size of the largest SSL/TLS packet that is expected
* when using this session.
* <P>
* A <code>SSLEngine</code> using this session may generate SSL/TLS
* packets of any size up to and including the value returned by this
* method. All <code>SSLEngine</code> network buffers should be sized
* at least this large to avoid insufficient space problems when
* performing <code>wrap</code> and <code>unwrap</code> calls.
*
* @return the current maximum expected network packet size
*
* @see SSLEngine#wrap(ByteBuffer, ByteBuffer)
* @see SSLEngine#unwrap(ByteBuffer, ByteBuffer)
*
* @since 1.5
*/
public int getPacketBufferSize();
/** {@collect.stats}
* Gets the current size of the largest application data that is
* expected when using this session.
* <P>
* <code>SSLEngine</code> application data buffers must be large
* enough to hold the application data from any inbound network
* application data packet received. Typically, outbound
* application data buffers can be of any size.
*
* @return the current maximum expected application packet size
*
* @see SSLEngine#wrap(ByteBuffer, ByteBuffer)
* @see SSLEngine#unwrap(ByteBuffer, ByteBuffer)
*
* @since 1.5
*/
public int getApplicationBufferSize();
}
|
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.net.ssl;
import java.security.*;
/** {@collect.stats}
* This class defines the <i>Service Provider Interface</i> (<b>SPI</b>)
* for the <code>TrustManagerFactory</code> class.
*
* <p> All the abstract methods in this class must be implemented by each
* cryptographic service provider who wishes to supply the implementation
* of a particular trust manager factory.
*
* @since 1.4
* @see TrustManagerFactory
* @see TrustManager
*/
public abstract class TrustManagerFactorySpi {
/** {@collect.stats}
* Initializes this factory with a source of certificate
* authorities and related trust material.
*
* @param ks the key store or null
* @throws KeyStoreException if this operation fails
* @see TrustManagerFactory#init(KeyStore)
*/
protected abstract void engineInit(KeyStore ks) throws KeyStoreException;
/** {@collect.stats}
* Initializes this factory with a source of provider-specific
* key material.
* <P>
* In some cases, initialization parameters other than a keystore
* may be needed by a provider. Users of that
* particular provider are expected to pass an implementation of
* the appropriate <CODE>ManagerFactoryParameters</CODE> as
* defined by the provider. The provider can then call the
* specified methods in the <CODE>ManagerFactoryParameters</CODE>
* implementation to obtain the needed information.
*
* @param spec an implementation of a provider-specific parameter
* specification
* @throws InvalidAlgorithmParameterException if there is problem
* with the parameters
* @see TrustManagerFactory#init(ManagerFactoryParameters spec)
*/
protected abstract void engineInit(ManagerFactoryParameters spec)
throws InvalidAlgorithmParameterException;
/** {@collect.stats}
* Returns one trust manager for each type of trust material.
*
* @return the trust managers
*/
protected abstract TrustManager[] engineGetTrustManagers();
}
|
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.net.ssl;
/** {@collect.stats}
* Encapsulates parameters for an SSL/TLS connection. The parameters
* are the list of ciphersuites to be accepted in an SSL/TLS handshake,
* the list of protocols to be allowed, and whether SSL/TLS servers should
* request or require client authentication.
*
* <p>SSLParameters can be created via the constructors in this class.
* Objects can also be obtained using the <code>getSSLParameters()</code>
* methods in
* {@link SSLSocket#getSSLParameters SSLSocket} and
* {@link SSLEngine#getSSLParameters SSLEngine} or the
* {@link SSLContext#getDefaultSSLParameters getDefaultSSLParameters()} and
* {@link SSLContext#getSupportedSSLParameters getSupportedSSLParameters()}
* methods in <code>SSLContext</code>.
*
* <P>SSLParameters can be applied to a connection via the methods
* {@link SSLSocket#setSSLParameters SSLSocket.setSSLParameters()} and
* {@link SSLEngine#setSSLParameters SSLEngine.getSSLParameters()}.
*
* @see SSLSocket
* @see SSLEngine
* @see SSLContext
*
* @since 1.6
*/
public class SSLParameters {
private String[] cipherSuites;
private String[] protocols;
private boolean wantClientAuth;
private boolean needClientAuth;
/** {@collect.stats}
* Constructs SSLParameters.
*
* <p>The cipherSuites and protocols values are set to <code>null</code>,
* wantClientAuth and needClientAuth are set to <code>false</code>.
*/
public SSLParameters() {
// empty
}
/** {@collect.stats}
* Constructs SSLParameters from the specified array of ciphersuites.
* Calling this constructor is equivalent to calling the no-args
* constructor followed by
* <code>setCipherSuites(cipherSuites);</code>.
*
* @param cipherSuites the array of ciphersuites (or null)
*/
public SSLParameters(String[] cipherSuites) {
setCipherSuites(cipherSuites);
}
/** {@collect.stats}
* Constructs SSLParameters from the specified array of ciphersuites
* and protocols.
* Calling this constructor is equivalent to calling the no-args
* constructor followed by
* <code>setCipherSuites(cipherSuites); setProtocols(protocols);</code>.
*
* @param cipherSuites the array of ciphersuites (or null)
* @param protocols the array of protocols (or null)
*/
public SSLParameters(String[] cipherSuites, String[] protocols) {
setCipherSuites(cipherSuites);
setProtocols(protocols);
}
private static String[] clone(String[] s) {
return (s == null) ? null : s.clone();
}
/** {@collect.stats}
* Returns a copy of the array of ciphersuites or null if none
* have been set.
*
* @return a copy of the array of ciphersuites or null if none
* have been set.
*/
public String[] getCipherSuites() {
return clone(cipherSuites);
}
/** {@collect.stats}
* Sets the array of ciphersuites.
*
* @param cipherSuites the array of ciphersuites (or null)
*/
public void setCipherSuites(String[] cipherSuites) {
this.cipherSuites = clone(cipherSuites);
}
/** {@collect.stats}
* Returns a copy of the array of protocols or null if none
* have been set.
*
* @return a copy of the array of protocols or null if none
* have been set.
*/
public String[] getProtocols() {
return clone(protocols);
}
/** {@collect.stats}
* Sets the array of protocols.
*
* @param protocols the array of protocols (or null)
*/
public void setProtocols(String[] protocols) {
this.protocols = clone(protocols);
}
/** {@collect.stats}
* Returns whether client authentication should be requested.
*
* @return whether client authentication should be requested.
*/
public boolean getWantClientAuth() {
return wantClientAuth;
}
/** {@collect.stats}
* Sets whether client authentication should be requested. Calling
* this method clears the <code>needClientAuth</code> flag.
*
* @param wantClientAuth whether client authentication should be requested
*/
public void setWantClientAuth(boolean wantClientAuth) {
this.wantClientAuth = wantClientAuth;
this.needClientAuth = false;
}
/** {@collect.stats}
* Returns whether client authentication should be required.
*
* @return whether client authentication should be required.
*/
public boolean getNeedClientAuth() {
return needClientAuth;
}
/** {@collect.stats}
* Sets whether client authentication should be required. Calling
* this method clears the <code>wantClientAuth</code> flag.
*
* @param needClientAuth whether client authentication should be required
*/
public void setNeedClientAuth(boolean needClientAuth) {
this.wantClientAuth = false;
this.needClientAuth = needClientAuth;
}
}
|
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.net.ssl;
/** {@collect.stats}
* An encapsulation of the result state produced by
* <code>SSLEngine</code> I/O calls.
*
* <p> A <code>SSLEngine</code> provides a means for establishing
* secure communication sessions between two peers. <code>SSLEngine</code>
* operations typically consume bytes from an input buffer and produce
* bytes in an output buffer. This class provides operational result
* values describing the state of the <code>SSLEngine</code>, including
* indications of what operations are needed to finish an
* ongoing handshake. Lastly, it reports the number of bytes consumed
* and produced as a result of this operation.
*
* @see SSLEngine
* @see SSLEngine#wrap(ByteBuffer, ByteBuffer)
* @see SSLEngine#unwrap(ByteBuffer, ByteBuffer)
*
* @author Brad R. Wetmore
* @since 1.5
*/
public class SSLEngineResult {
/** {@collect.stats}
* An <code>SSLEngineResult</code> enum describing the overall result
* of the <code>SSLEngine</code> operation.
*
* The <code>Status</code> value does not reflect the
* state of a <code>SSLEngine</code> handshake currently
* in progress. The <code>SSLEngineResult's HandshakeStatus</code>
* should be consulted for that information.
*
* @author Brad R. Wetmore
* @since 1.5
*/
public static enum Status {
/** {@collect.stats}
* The <code>SSLEngine</code> was not able to unwrap the
* incoming data because there were not enough source bytes
* available to make a complete packet.
*
* <P>
* Repeat the call once more bytes are available.
*/
BUFFER_UNDERFLOW,
/** {@collect.stats}
* The <code>SSLEngine</code> was not able to process the
* operation because there are not enough bytes available in the
* destination buffer to hold the result.
* <P>
* Repeat the call once more bytes are available.
*
* @see SSLSession#getPacketBufferSize()
* @see SSLSession#getApplicationBufferSize()
*/
BUFFER_OVERFLOW,
/** {@collect.stats}
* The <code>SSLEngine</code> completed the operation, and
* is available to process similar calls.
*/
OK,
/** {@collect.stats}
* The operation just closed this side of the
* <code>SSLEngine</code>, or the operation
* could not be completed because it was already closed.
*/
CLOSED;
}
/** {@collect.stats}
* An <code>SSLEngineResult</code> enum describing the current
* handshaking state of this <code>SSLEngine</code>.
*
* @author Brad R. Wetmore
* @since 1.5
*/
public static enum HandshakeStatus {
/** {@collect.stats}
* The <code>SSLEngine</code> is not currently handshaking.
*/
NOT_HANDSHAKING,
/** {@collect.stats}
* The <code>SSLEngine</code> has just finished handshaking.
* <P>
* This value is only generated by a call to
* <code>SSLEngine.wrap()/unwrap()</code> when that call
* finishes a handshake. It is never generated by
* <code>SSLEngine.getHandshakeStatus()</code>.
*
* @see SSLEngine#wrap(ByteBuffer, ByteBuffer)
* @see SSLEngine#unwrap(ByteBuffer, ByteBuffer)
* @see SSLEngine#getHandshakeStatus()
*/
FINISHED,
/** {@collect.stats}
* The <code>SSLEngine</code> needs the results of one (or more)
* delegated tasks before handshaking can continue.
*
* @see SSLEngine#getDelegatedTask()
*/
NEED_TASK,
/** {@collect.stats}
* The <code>SSLEngine</code> must send data to the remote side
* before handshaking can continue, so <code>SSLEngine.wrap()</code>
* should be called.
*
* @see SSLEngine#wrap(ByteBuffer, ByteBuffer)
*/
NEED_WRAP,
/** {@collect.stats}
* The <code>SSLEngine</code> needs to receive data from the
* remote side before handshaking can continue.
*/
NEED_UNWRAP;
}
private final Status status;
private final HandshakeStatus handshakeStatus;
private final int bytesConsumed;
private final int bytesProduced;
/** {@collect.stats}
* Initializes a new instance of this class.
*
* @param status
* the return value of the operation.
*
* @param handshakeStatus
* the current handshaking status.
*
* @param bytesConsumed
* the number of bytes consumed from the source ByteBuffer
*
* @param bytesProduced
* the number of bytes placed into the destination ByteBuffer
*
* @throws IllegalArgumentException
* if the <code>status</code> or <code>handshakeStatus</code>
* arguments are null, or if <<code>bytesConsumed</code> or
* <code>bytesProduced</code> is negative.
*/
public SSLEngineResult(Status status, HandshakeStatus handshakeStatus,
int bytesConsumed, int bytesProduced) {
if ((status == null) || (handshakeStatus == null) ||
(bytesConsumed < 0) || (bytesProduced < 0)) {
throw new IllegalArgumentException("Invalid Parameter(s)");
}
this.status = status;
this.handshakeStatus = handshakeStatus;
this.bytesConsumed = bytesConsumed;
this.bytesProduced = bytesProduced;
}
/** {@collect.stats}
* Gets the return value of this <code>SSLEngine</code> operation.
*
* @return the return value
*/
final public Status getStatus() {
return status;
}
/** {@collect.stats}
* Gets the handshake status of this <code>SSLEngine</code>
* operation.
*
* @return the handshake status
*/
final public HandshakeStatus getHandshakeStatus() {
return handshakeStatus;
}
/** {@collect.stats}
* Returns the number of bytes consumed from the input buffer.
*
* @return the number of bytes consumed.
*/
final public int bytesConsumed() {
return bytesConsumed;
}
/** {@collect.stats}
* Returns the number of bytes written to the output buffer.
*
* @return the number of bytes produced
*/
final public int bytesProduced() {
return bytesProduced;
}
/** {@collect.stats}
* Returns a String representation of this object.
*/
public String toString() {
return ("Status = " + status +
" HandshakeStatus = " + handshakeStatus +
"\nbytesConsumed = " + bytesConsumed +
" bytesProduced = " + bytesProduced);
}
}
|
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.net.ssl;
import java.util.Enumeration;
/** {@collect.stats}
* A <code>SSLSessionContext</code> represents a set of
* <code>SSLSession</code>s associated with a single entity. For example,
* it could be associated with a server or client who participates in many
* sessions concurrently.
* <p>
* Not all environments will contain session contexts.
* <p>
* There are <code>SSLSessionContext</code> parameters that affect how
* sessions are stored:
* <UL>
* <LI>Sessions can be set to expire after a specified
* time limit.
* <LI>The number of sessions that can be stored in context
* can be limited.
* </UL>
* A session can be retrieved based on its session id, and all session id's
* in a <code>SSLSessionContext</code> can be listed.
*
* @see SSLSession
*
* @since 1.4
* @author Nathan Abramson
* @author David Brownell
*/
public interface SSLSessionContext {
/** {@collect.stats}
* Returns the <code>SSLSession</code> bound to the specified session id.
*
* @param sessionId the Session identifier
* @return the <code>SSLSession</code> or null if
* the specified session id does not refer to a valid SSLSession.
*
* @throws NullPointerException if <code>sessionId</code> is null.
*/
public SSLSession getSession(byte[] sessionId);
/** {@collect.stats}
* Returns an Enumeration of all session id's grouped under this
* <code>SSLSessionContext</code>.
*
* @return an enumeration of all the Session id's
*/
public Enumeration<byte[]> getIds();
/** {@collect.stats}
* Sets the timeout limit for <code>SSLSession</code> objects grouped
* under this <code>SSLSessionContext</code>.
* <p>
* If the timeout limit is set to 't' seconds, a session exceeds the
* timeout limit 't' seconds after its creation time.
* When the timeout limit is exceeded for a session, the
* <code>SSLSession</code> object is invalidated and future connections
* cannot resume or rejoin the session.
* A check for sessions exceeding the timeout is made immediately whenever
* the timeout limit is changed for this <code>SSLSessionContext</code>.
*
* @param seconds the new session timeout limit in seconds; zero means
* there is no limit.
*
* @exception IllegalArgumentException if the timeout specified is < 0.
* @see #getSessionTimeout
*/
public void setSessionTimeout(int seconds)
throws IllegalArgumentException;
/** {@collect.stats}
* Returns the timeout limit of <code>SSLSession</code> objects grouped
* under this <code>SSLSessionContext</code>.
* <p>
* If the timeout limit is set to 't' seconds, a session exceeds the
* timeout limit 't' seconds after its creation time.
* When the timeout limit is exceeded for a session, the
* <code>SSLSession</code> object is invalidated and future connections
* cannot resume or rejoin the session.
* A check for sessions exceeding the timeout limit is made immediately
* whenever the timeout limit is changed for this
* <code>SSLSessionContext</code>.
*
* @return the session timeout limit in seconds; zero means there is no
* limit.
* @see #setSessionTimeout
*/
public int getSessionTimeout();
/** {@collect.stats}
* Sets the size of the cache used for storing
* <code>SSLSession</code> objects grouped under this
* <code>SSLSessionContext</code>.
*
* @param size the new session cache size limit; zero means there is no
* limit.
* @exception IllegalArgumentException if the specified size is < 0.
* @see #getSessionCacheSize
*/
public void setSessionCacheSize(int size)
throws IllegalArgumentException;
/** {@collect.stats}
* Returns the size of the cache used for storing
* <code>SSLSession</code> objects grouped under this
* <code>SSLSessionContext</code>.
*
* @return size of the session cache; zero means there is no size limit.
* @see #setSessionCacheSize
*/
public int getSessionCacheSize();
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.net.ssl;
import java.security.Security;
import java.security.*;
import sun.security.jca.GetInstance;
/** {@collect.stats}
* This class acts as a factory for key managers based on a
* source of key material. Each key manager manages a specific
* type of key material for use by secure sockets. The key
* material is based on a KeyStore and/or provider specific sources.
*
* @since 1.4
* @see KeyManager
*/
public class KeyManagerFactory {
// The provider
private Provider provider;
// The provider implementation (delegate)
private KeyManagerFactorySpi factorySpi;
// The name of the key management algorithm.
private String algorithm;
/** {@collect.stats}
* Obtains the default KeyManagerFactory algorithm name.
*
* <p>The default algorithm can be changed at runtime by setting
* the value of the "ssl.KeyManagerFactory.algorithm" security
* property (set in the Java security properties file or by calling
* {@link java.security.Security#setProperty(java.lang.String,
* java.lang.String)})
* to the desired algorithm name.
*
* @see java.security.Security#setProperty(java.lang.String,
* java.lang.String)
* @return the default algorithm name as specified in the
* Java security properties, or an implementation-specific
* default if no such property exists.
*/
public final static String getDefaultAlgorithm() {
String type;
type = AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return Security.getProperty(
"ssl.KeyManagerFactory.algorithm");
}
});
if (type == null) {
type = "SunX509";
}
return type;
}
/** {@collect.stats}
* Creates a KeyManagerFactory object.
*
* @param factorySpi the delegate
* @param provider the provider
* @param algorithm the algorithm
*/
protected KeyManagerFactory(KeyManagerFactorySpi factorySpi,
Provider provider, String algorithm) {
this.factorySpi = factorySpi;
this.provider = provider;
this.algorithm = algorithm;
}
/** {@collect.stats}
* Returns the algorithm name of this <code>KeyManagerFactory</code> object.
*
* <p>This is the same name that was specified in one of the
* <code>getInstance</code> calls that created this
* <code>KeyManagerFactory</code> object.
*
* @return the algorithm name of this <code>KeyManagerFactory</code> object.
*/
public final String getAlgorithm() {
return this.algorithm;
}
/** {@collect.stats}
* Returns a <code>KeyManagerFactory</code> object that acts as a
* factory for key managers.
*
* <p> This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new KeyManagerFactory object encapsulating the
* KeyManagerFactorySpi implementation from the first
* Provider that supports the specified algorithm is returned.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the standard name of the requested algorithm.
* See the <a href=
* "{@docRoot}/../technotes/guides/security/jsse/JSSERefGuide.html">
* Java Secure Socket Extension Reference Guide </a>
* for information about standard algorithm names.
*
* @return the new <code>KeyManagerFactory</code> object.
*
* @exception NoSuchAlgorithmException if no Provider supports a
* KeyManagerFactorySpi implementation for the
* specified algorithm.
*
* @see java.security.Provider
*/
public static final KeyManagerFactory getInstance(String algorithm)
throws NoSuchAlgorithmException {
GetInstance.Instance instance = GetInstance.getInstance
("KeyManagerFactory", KeyManagerFactorySpi.class,
algorithm);
return new KeyManagerFactory((KeyManagerFactorySpi)instance.impl,
instance.provider, algorithm);
}
/** {@collect.stats}
* Returns a <code>KeyManagerFactory</code> object that acts as a
* factory for key managers.
*
* <p> A new KeyManagerFactory object encapsulating the
* KeyManagerFactorySpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
* @param algorithm the standard name of the requested algorithm.
* See the <a href=
* "{@docRoot}/../technotes/guides/security/jsse/JSSERefGuide.html">
* Java Secure Socket Extension Reference Guide </a>
* for information about standard algorithm names.
*
* @param provider the name of the provider.
*
* @return the new <code>KeyManagerFactory</code> object.
*
* @throws NoSuchAlgorithmException if a KeyManagerFactorySpi
* implementation for the specified algorithm is not
* available from the specified provider.
*
* @throws NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @throws IllegalArgumentException if the provider name is null or empty.
*
* @see java.security.Provider
*/
public static final KeyManagerFactory getInstance(String algorithm,
String provider) throws NoSuchAlgorithmException,
NoSuchProviderException {
GetInstance.Instance instance = GetInstance.getInstance
("KeyManagerFactory", KeyManagerFactorySpi.class,
algorithm, provider);
return new KeyManagerFactory((KeyManagerFactorySpi)instance.impl,
instance.provider, algorithm);
}
/** {@collect.stats}
* Returns a <code>KeyManagerFactory</code> object that acts as a
* factory for key managers.
*
* <p> A new KeyManagerFactory object encapsulating the
* KeyManagerFactorySpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param algorithm the standard name of the requested algorithm.
* See the <a href=
* "{@docRoot}/../technotes/guides/security/jsse/JSSERefGuide.html">
* Java Secure Socket Extension Reference Guide </a>
* for information about standard algorithm names.
*
* @param provider an instance of the provider.
*
* @return the new <code>KeyManagerFactory</code> object.
*
* @throws NoSuchAlgorithmException if a KeyManagerFactorySpi
* implementation for the specified algorithm is not available
* from the specified Provider object.
*
* @throws IllegalArgumentException if provider is null.
*
* @see java.security.Provider
*/
public static final KeyManagerFactory getInstance(String algorithm,
Provider provider) throws NoSuchAlgorithmException {
GetInstance.Instance instance = GetInstance.getInstance
("KeyManagerFactory", KeyManagerFactorySpi.class,
algorithm, provider);
return new KeyManagerFactory((KeyManagerFactorySpi)instance.impl,
instance.provider, algorithm);
}
/** {@collect.stats}
* Returns the provider of this <code>KeyManagerFactory</code> object.
*
* @return the provider of this <code>KeyManagerFactory</code> object
*/
public final Provider getProvider() {
return this.provider;
}
/** {@collect.stats}
* Initializes this factory with a source of key material.
* <P>
* The provider typically uses a KeyStore for obtaining
* key material for use during secure socket negotiations.
* The KeyStore is generally password-protected.
* <P>
* For more flexible initialization, please see
* {@link #init(ManagerFactoryParameters)}.
* <P>
*
* @param ks the key store or null
* @param password the password for recovering keys in the KeyStore
* @throws KeyStoreException if this operation fails
* @throws NoSuchAlgorithmException if the specified algorithm is not
* available from the specified provider.
* @throws UnrecoverableKeyException if the key cannot be recovered
* (e.g. the given password is wrong).
*/
public final void init(KeyStore ks, char[] password) throws
KeyStoreException, NoSuchAlgorithmException,
UnrecoverableKeyException {
factorySpi.engineInit(ks, password);
}
/** {@collect.stats}
* Initializes this factory with a source of provider-specific
* key material.
* <P>
* In some cases, initialization parameters other than a keystore
* and password may be needed by a provider. Users of that
* particular provider are expected to pass an implementation of
* the appropriate <CODE>ManagerFactoryParameters</CODE> as
* defined by the provider. The provider can then call the
* specified methods in the <CODE>ManagerFactoryParameters</CODE>
* implementation to obtain the needed information.
*
* @param spec an implementation of a provider-specific parameter
* specification
* @throws InvalidAlgorithmParameterException if an error is encountered
*/
public final void init(ManagerFactoryParameters spec) throws
InvalidAlgorithmParameterException {
factorySpi.engineInit(spec);
}
/** {@collect.stats}
* Returns one key manager for each type of key material.
*
* @return the key managers
* @throws IllegalStateException if the KeyManagerFactory is not initialized
*/
public final KeyManager[] getKeyManagers() {
return factorySpi.engineGetKeyManagers();
}
}
|
Java
|
/*
* Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.net.ssl;
import java.io.IOException;
/** {@collect.stats}
* Indicates some kind of error detected by an SSL subsystem.
* This class is the general class of exceptions produced
* by failed SSL-related operations.
*
* @since 1.4
* @author David Brownell
*/
public
class SSLException extends IOException
{
private static final long serialVersionUID = 4511006460650708967L;
/** {@collect.stats}
* Constructs an exception reporting an error found by
* an SSL subsystem.
*
* @param reason describes the problem.
*/
public SSLException(String reason)
{
super(reason);
}
/** {@collect.stats}
* Creates a <code>SSLException</code> with the specified
* detail message and cause.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.5
*/
public SSLException(String message, Throwable cause) {
super(message);
initCause(cause);
}
/** {@collect.stats}
* Creates a <code>SSLException</code> with the specified cause
* and a detail message of <tt>(cause==null ? null : cause.toString())</tt>
* (which typically contains the class and detail message of
* <tt>cause</tt>).
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.5
*/
public SSLException(Throwable cause) {
super(cause == null ? null : cause.toString());
initCause(cause);
}
}
|
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.net.ssl;
/** {@collect.stats}
* This is the base interface for JSSE trust managers.
* <P>
* <code>TrustManager</code>s are responsible for managing the trust material
* that is used when making trust decisions, and for deciding whether
* credentials presented by a peer should be accepted.
* <P>
* <code>TrustManager</code>s are created by either
* using a <code>TrustManagerFactory</code>,
* or by implementing one of the <code>TrustManager</code> subclasses.
*
* @see TrustManagerFactory
* @since 1.4
*/
public interface TrustManager {
}
|
Java
|
/*
* Copyright (c) 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.net.ssl;
/** {@collect.stats}
* This class is the base interface for hostname verification.
* <P>
* During handshaking, if the URL's hostname and
* the server's identification hostname mismatch, the
* verification mechanism can call back to implementers of this
* interface to determine if this connection should be allowed.
* <P>
* The policies can be certificate-based
* or may depend on other authentication schemes.
* <P>
* These callbacks are used when the default rules for URL hostname
* verification fail.
*
* @author Brad R. Wetmore
* @since 1.4
*/
public interface HostnameVerifier {
/** {@collect.stats}
* Verify that the host name is an acceptable match with
* the server's authentication scheme.
*
* @param hostname the host name
* @param session SSLSession used on the connection to host
* @return true if the host name is acceptable
*/
public boolean verify(String hostname, SSLSession session);
}
|
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.net.ssl;
import java.net.*;
import javax.net.SocketFactory;
import java.io.IOException;
import java.security.*;
import sun.security.action.GetPropertyAction;
/** {@collect.stats}
* <code>SSLSocketFactory</code>s create <code>SSLSocket</code>s.
*
* @since 1.4
* @see SSLSocket
* @author David Brownell
*/
public abstract class SSLSocketFactory extends SocketFactory
{
private static SSLSocketFactory theFactory;
private static boolean propertyChecked;
static final boolean DEBUG;
static {
String s = java.security.AccessController.doPrivileged(
new GetPropertyAction("javax.net.debug", "")).toLowerCase();
DEBUG = s.contains("all") || s.contains("ssl");
}
private static void log(String msg) {
if (DEBUG) {
System.out.println(msg);
}
}
/** {@collect.stats}
* Constructor is used only by subclasses.
*/
public SSLSocketFactory() {
}
/** {@collect.stats}
* Returns the default SSL socket factory.
*
* <p>The first time this method is called, the security property
* "ssl.SocketFactory.provider" is examined. If it is non-null, a class by
* that name is loaded and instantiated. If that is successful and the
* object is an instance of SSLSocketFactory, it is made the default SSL
* socket factory.
*
* <p>Otherwise, this method returns
* <code>SSLContext.getDefault().getSocketFactory()</code>. If that
* call fails, an inoperative factory is returned.
*
* @return the default <code>SocketFactory</code>
* @see SSLContext#getDefault
*/
public static synchronized SocketFactory getDefault() {
if (theFactory != null) {
return theFactory;
}
if (propertyChecked == false) {
propertyChecked = true;
String clsName = getSecurityProperty("ssl.SocketFactory.provider");
if (clsName != null) {
log("setting up default SSLSocketFactory");
try {
Class cls = null;
try {
cls = Class.forName(clsName);
} catch (ClassNotFoundException e) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
if (cl != null) {
cls = cl.loadClass(clsName);
}
}
log("class " + clsName + " is loaded");
SSLSocketFactory fac = (SSLSocketFactory)cls.newInstance();
log("instantiated an instance of class " + clsName);
theFactory = fac;
return fac;
} catch (Exception e) {
log("SSLSocketFactory instantiation failed: " + e.toString());
theFactory = new DefaultSSLSocketFactory(e);
return theFactory;
}
}
}
try {
return SSLContext.getDefault().getSocketFactory();
} catch (NoSuchAlgorithmException e) {
return new DefaultSSLSocketFactory(e);
}
}
static String getSecurityProperty(final String name) {
return AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
String s = java.security.Security.getProperty(name);
if (s != null) {
s = s.trim();
if (s.length() == 0) {
s = null;
}
}
return s;
}
});
}
/** {@collect.stats}
* Returns the list of cipher suites which are enabled by default.
* Unless a different list is enabled, handshaking on an SSL connection
* will use one of these cipher suites. The minimum quality of service
* for these defaults requires confidentiality protection and server
* authentication (that is, no anonymous cipher suites).
*
* @see #getSupportedCipherSuites()
* @return array of the cipher suites enabled by default
*/
public abstract String [] getDefaultCipherSuites();
/** {@collect.stats}
* Returns the names of the cipher suites which could be enabled for use
* on an SSL connection. Normally, only a subset of these will actually
* be enabled by default, since this list may include cipher suites which
* do not meet quality of service requirements for those defaults. Such
* cipher suites are useful in specialized applications.
*
* @see #getDefaultCipherSuites()
* @return an array of cipher suite names
*/
public abstract String [] getSupportedCipherSuites();
/** {@collect.stats}
* Returns a socket layered over an existing socket connected to the named
* host, at the given port. This constructor can be used when tunneling SSL
* through a proxy or when negotiating the use of SSL over an existing
* socket. The host and port refer to the logical peer destination.
* This socket is configured using the socket options established for
* this factory.
*
* @param s the existing socket
* @param host the server host
* @param port the server port
* @param autoClose close the underlying socket when this socket is closed
* @return a socket connected to the specified host and port
* @throws IOException if an I/O error occurs when creating the socket
* @throws UnknownHostException if the host is not known
*/
public abstract Socket createSocket(Socket s, String host,
int port, boolean autoClose)
throws IOException;
}
// file private
class DefaultSSLSocketFactory extends SSLSocketFactory
{
private Exception reason;
DefaultSSLSocketFactory(Exception reason) {
this.reason = reason;
}
private Socket throwException() throws SocketException {
throw (SocketException)
new SocketException(reason.toString()).initCause(reason);
}
public Socket createSocket()
throws IOException
{
return throwException();
}
public Socket createSocket(String host, int port)
throws IOException
{
return throwException();
}
public Socket createSocket(Socket s, String host,
int port, boolean autoClose)
throws IOException
{
return throwException();
}
public Socket createSocket(InetAddress address, int port)
throws IOException
{
return throwException();
}
public Socket createSocket(String host, int port,
InetAddress clientAddress, int clientPort)
throws IOException
{
return throwException();
}
public Socket createSocket(InetAddress address, int port,
InetAddress clientAddress, int clientPort)
throws IOException
{
return throwException();
}
public String [] getDefaultCipherSuites() {
return new String[0];
}
public String [] getSupportedCipherSuites() {
return new String[0];
}
}
|
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.net.ssl;
import java.security.cert.*;
/** {@collect.stats}
* Instance of this interface manage which X509 certificates
* may be used to authenticate the remote side of a secure
* socket. Decisions may be based on trusted certificate
* authorities, certificate revocation lists, online
* status checking or other means.
*
* @since 1.4
*/
public interface X509TrustManager extends TrustManager {
/** {@collect.stats}
* Given the partial or complete certificate chain provided by the
* peer, build a certificate path to a trusted root and return if
* it can be validated and is trusted for client SSL
* authentication based on the authentication type.
* <p>
* The authentication type is determined by the actual certificate
* used. For instance, if RSAPublicKey is used, the authType
* should be "RSA". Checking is case-sensitive.
*
* @param chain the peer certificate chain
* @param authType the authentication type based on the client certificate
* @throws IllegalArgumentException if null or zero-length chain
* is passed in for the chain parameter or if null or zero-length
* string is passed in for the authType parameter
* @throws CertificateException if the certificate chain is not trusted
* by this TrustManager.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException;
/** {@collect.stats}
* Given the partial or complete certificate chain provided by the
* peer, build a certificate path to a trusted root and return if
* it can be validated and is trusted for server SSL
* authentication based on the authentication type.
* <p>
* The authentication type is the key exchange algorithm portion
* of the cipher suites represented as a String, such as "RSA",
* "DHE_DSS". Note: for some exportable cipher suites, the key
* exchange algorithm is determined at run time during the
* handshake. For instance, for TLS_RSA_EXPORT_WITH_RC4_40_MD5,
* the authType should be RSA_EXPORT when an ephemeral RSA key is
* used for the key exchange, and RSA when the key from the server
* certificate is used. Checking is case-sensitive.
*
* @param chain the peer certificate chain
* @param authType the key exchange algorithm used
* @throws IllegalArgumentException if null or zero-length chain
* is passed in for the chain parameter or if null or zero-length
* string is passed in for the authType parameter
* @throws CertificateException if the certificate chain is not trusted
* by this TrustManager.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException;
/** {@collect.stats}
* Return an array of certificate authority certificates
* which are trusted for authenticating peers.
*
* @return a non-null (possibly empty) array of acceptable
* CA issuer certificates.
*/
public X509Certificate[] getAcceptedIssuers();
}
|
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.net.ssl;
import java.util.EventObject;
/** {@collect.stats}
* This event is propagated to a SSLSessionBindingListener.
* When a listener object is bound or unbound to an SSLSession by
* {@link SSLSession#putValue(String, Object)}
* or {@link SSLSession#removeValue(String)}, objects which
* implement the SSLSessionBindingListener will be receive an
* event of this type. The event's <code>name</code> field is the
* key in which the listener is being bound or unbound.
*
* @see SSLSession
* @see SSLSessionBindingListener
*
* @since 1.4
* @author Nathan Abramson
* @author David Brownell
*/
public
class SSLSessionBindingEvent
extends EventObject
{
private static final long serialVersionUID = 3989172637106345L;
/** {@collect.stats}
* @serial The name to which the object is being bound or unbound
*/
private String name;
/** {@collect.stats}
* Constructs a new SSLSessionBindingEvent.
*
* @param session the SSLSession acting as the source of the event
* @param name the name to which the object is being bound or unbound
* @exception IllegalArgumentException if <code>session</code> is null.
*/
public SSLSessionBindingEvent(SSLSession session, String name)
{
super(session);
this.name = name;
}
/** {@collect.stats}
* Returns the name to which the object is being bound, or the name
* from which the object is being unbound.
*
* @return the name to which the object is being bound or unbound
*/
public String getName()
{
return name;
}
/** {@collect.stats}
* Returns the SSLSession into which the listener is being bound or
* from which the listener is being unbound.
*
* @return the <code>SSLSession</code>
*/
public SSLSession getSession()
{
return (SSLSession) getSource();
}
}
|
Java
|
/*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.net.ssl;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
/** {@collect.stats}
* A class which enables secure communications using protocols such as
* the Secure Sockets Layer (SSL) or
* <A HREF="http://www.ietf.org/rfc/rfc2246.txt"> IETF RFC 2246 "Transport
* Layer Security" (TLS) </A> protocols, but is transport independent.
* <P>
* The secure communications modes include: <UL>
*
* <LI> <em>Integrity Protection</em>. SSL/TLS protects against
* modification of messages by an active wiretapper.
*
* <LI> <em>Authentication</em>. In most modes, SSL/TLS provides
* peer authentication. Servers are usually authenticated, and
* clients may be authenticated as requested by servers.
*
* <LI> <em>Confidentiality (Privacy Protection)</em>. In most
* modes, SSL/TLS encrypts data being sent between client and
* server. This protects the confidentiality of data, so that
* passive wiretappers won't see sensitive data such as financial
* information or personal information of many kinds.
*
* </UL>
*
* These kinds of protection are specified by a "cipher suite", which
* is a combination of cryptographic algorithms used by a given SSL
* connection. During the negotiation process, the two endpoints must
* agree on a cipher suite that is available in both environments. If
* there is no such suite in common, no SSL connection can be
* established, and no data can be exchanged.
* <P>
* The cipher suite used is established by a negotiation process called
* "handshaking". The goal of this process is to create or rejoin a
* "session", which may protect many connections over time. After
* handshaking has completed, you can access session attributes by
* using the {@link #getSession()} method.
* <P>
* The <code>SSLSocket</code> class provides much of the same security
* functionality, but all of the inbound and outbound data is
* automatically transported using the underlying {@link
* java.net.Socket Socket}, which by design uses a blocking model.
* While this is appropriate for many applications, this model does not
* provide the scalability required by large servers.
* <P>
* The primary distinction of an <code>SSLEngine</code> is that it
* operates on inbound and outbound byte streams, independent of the
* transport mechanism. It is the responsibility of the
* <code>SSLEngine</code> user to arrange for reliable I/O transport to
* the peer. By separating the SSL/TLS abstraction from the I/O
* transport mechanism, the <code>SSLEngine</code> can be used for a
* wide variety of I/O types, such as {@link
* java.nio.channels.spi.AbstractSelectableChannel#configureBlocking(boolean)
* non-blocking I/O (polling)}, {@link java.nio.channels.Selector
* selectable non-blocking I/O}, {@link java.net.Socket Socket} and the
* traditional Input/OutputStreams, local {@link java.nio.ByteBuffer
* ByteBuffers} or byte arrays, <A
* HREF="http://www.jcp.org/en/jsr/detail?id=203"> future asynchronous
* I/O models </A>, and so on.
* <P>
* At a high level, the <code>SSLEngine</code> appears thus:
*
* <pre>
* app data
*
* | ^
* | | |
* v | |
* +----+-----|-----+----+
* | | |
* | SSL|Engine |
* wrap() | | | unwrap()
* | OUTBOUND | INBOUND |
* | | |
* +----+-----|-----+----+
* | | ^
* | | |
* v |
*
* net data
* </pre>
* Application data (also known as plaintext or cleartext) is data which
* is produced or consumed by an application. Its counterpart is
* network data, which consists of either handshaking and/or ciphertext
* (encrypted) data, and destined to be transported via an I/O
* mechanism. Inbound data is data which has been received from the
* peer, and outbound data is destined for the peer.
* <P>
* (In the context of an <code>SSLEngine</code>, the term "handshake
* data" is taken to mean any data exchanged to establish and control a
* secure connection. Handshake data includes the SSL/TLS messages
* "alert", "change_cipher_spec," and "handshake.")
* <P>
* There are five distinct phases to an <code>SSLEngine</code>.
*
* <OL>
* <li> Creation - The <code>SSLEngine</code> has been created and
* initialized, but has not yet been used. During this phase, an
* application may set any <code>SSLEngine</code>-specific settings
* (enabled cipher suites, whether the <code>SSLEngine</code> should
* handshake in client or server mode, and so on). Once
* handshaking has begun, though, any new settings (except
* client/server mode, see below) will be used for
* the next handshake.
*
* <li> Initial Handshake - The initial handshake is a procedure by
* which the two peers exchange communication parameters until an
* SSLSession is established. Application data can not be sent during
* this phase.
*
* <li> Application Data - Once the communication parameters have
* been established and the handshake is complete, application data
* may flow through the <code>SSLEngine</code>. Outbound
* application messages are encrypted and integrity protected,
* and inbound messages reverse the process.
*
* <li> Rehandshaking - Either side may request a renegotiation of
* the session at any time during the Application Data phase. New
* handshaking data can be intermixed among the application data.
* Before starting the rehandshake phase, the application may
* reset the SSL/TLS communication parameters such as the list of
* enabled ciphersuites and whether to use client authentication,
* but can not change between client/server modes. As before, once
* handshaking has begun, any new <code>SSLEngine</code>
* configuration settings will not be used until the next
* handshake.
*
* <li> Closure - When the connection is no longer needed, the
* application should close the <code>SSLEngine</code> and should
* send/receive any remaining messages to the peer before
* closing the underlying transport mechanism. Once an engine is
* closed, it is not reusable: a new <code>SSLEngine</code> must
* be created.
* </OL>
* An <code>SSLEngine</code> is created by calling {@link
* SSLContext#createSSLEngine()} from an initialized
* <code>SSLContext</code>. Any configuration
* parameters should be set before making the first call to
* <code>wrap()</code>, <code>unwrap()</code>, or
* <code>beginHandshake()</code>. These methods all trigger the
* initial handshake.
* <P>
* Data moves through the engine by calling {@link #wrap(ByteBuffer,
* ByteBuffer) wrap()} or {@link #unwrap(ByteBuffer, ByteBuffer)
* unwrap()} on outbound or inbound data, respectively. Depending on
* the state of the <code>SSLEngine</code>, a <code>wrap()</code> call
* may consume application data from the source buffer and may produce
* network data in the destination buffer. The outbound data
* may contain application and/or handshake data. A call to
* <code>unwrap()</code> will examine the source buffer and may
* advance the handshake if the data is handshaking information, or
* may place application data in the destination buffer if the data
* is application. The state of the underlying SSL/TLS algorithm
* will determine when data is consumed and produced.
* <P>
* Calls to <code>wrap()</code> and <code>unwrap()</code> return an
* <code>SSLEngineResult</code> which indicates the status of the
* operation, and (optionally) how to interact with the engine to make
* progress.
* <P>
* The <code>SSLEngine</code> produces/consumes complete SSL/TLS
* packets only, and does not store application data internally between
* calls to <code>wrap()/unwrap()</code>. Thus input and output
* <code>ByteBuffer</code>s must be sized appropriately to hold the
* maximum record that can be produced. Calls to {@link
* SSLSession#getPacketBufferSize()} and {@link
* SSLSession#getApplicationBufferSize()} should be used to determine
* the appropriate buffer sizes. The size of the outbound application
* data buffer generally does not matter. If buffer conditions do not
* allow for the proper consumption/production of data, the application
* must determine (via {@link SSLEngineResult}) and correct the
* problem, and then try the call again.
* <P>
* For example, <code>unwrap()</code> will return a {@link
* SSLEngineResult.Status#BUFFER_OVERFLOW} result if the engine
* determines that there is not enough destination buffer space available.
* Applications should call {@link SSLSession#getApplicationBufferSize()}
* and compare that value with the space available in the destination buffer,
* enlarging the buffer if necessary. Similarly, if <code>unwrap()</code>
* were to return a {@link SSLEngineResult.Status#BUFFER_UNDERFLOW}, the
* application should call {@link SSLSession#getPacketBufferSize()} to ensure
* that the source buffer has enough room to hold a record (enlarging if
* necessary), and then obtain more inbound data.
*
* <pre>
* SSLEngineResult r = engine.unwrap(src, dst);
* switch (r.getStatus()) {
* BUFFER_OVERFLOW:
* // Could attempt to drain the dst buffer of any already obtained
* // data, but we'll just increase it to the size needed.
* int appSize = engine.getSession().getApplicationBufferSize();
* ByteBuffer b = ByteBuffer.allocate(appSize + dst.position());
* dst.flip();
* b.put(dst);
* dst = b;
* // retry the operation.
* break;
* BUFFER_UNDERFLOW:
* int netSize = engine.getSession().getPacketBufferSize();
* // Resize buffer if needed.
* if (netSize > dst.capacity()) {
* ByteBuffer b = ByteBuffer.allocate(netSize);
* src.flip();
* b.put(src);
* src = b;
* }
* // Obtain more inbound network data for src,
* // then retry the operation.
* break;
* // other cases: CLOSED, OK.
* }
* </pre>
*
* <P>
* Unlike <code>SSLSocket</code>, all methods of SSLEngine are
* non-blocking. <code>SSLEngine</code> implementations may
* require the results of tasks that may take an extended period of
* time to complete, or may even block. For example, a TrustManager
* may need to connect to a remote certificate validation service,
* or a KeyManager might need to prompt a user to determine which
* certificate to use as part of client authentication. Additionally,
* creating cryptographic signatures and verifying them can be slow,
* seemingly blocking.
* <P>
* For any operation which may potentially block, the
* <code>SSLEngine</code> will create a {@link java.lang.Runnable}
* delegated task. When <code>SSLEngineResult</code> indicates that a
* delegated task result is needed, the application must call {@link
* #getDelegatedTask()} to obtain an outstanding delegated task and
* call its {@link java.lang.Runnable#run() run()} method (possibly using
* a different thread depending on the compute strategy). The
* application should continue obtaining delegated tasks until no more
* exist, and try the original operation again.
* <P>
* At the end of a communication session, applications should properly
* close the SSL/TLS link. The SSL/TLS protocols have closure handshake
* messages, and these messages should be communicated to the peer
* before releasing the <code>SSLEngine</code> and closing the
* underlying transport mechanism. A close can be initiated by one of:
* an SSLException, an inbound closure handshake message, or one of the
* close methods. In all cases, closure handshake messages are
* generated by the engine, and <code>wrap()</code> should be repeatedly
* called until the resulting <code>SSLEngineResult</code>'s status
* returns "CLOSED", or {@link #isOutboundDone()} returns true. All
* data obtained from the <code>wrap()</code> method should be sent to the
* peer.
* <P>
* {@link #closeOutbound()} is used to signal the engine that the
* application will not be sending any more data.
* <P>
* A peer will signal its intent to close by sending its own closure
* handshake message. After this message has been received and
* processed by the local <code>SSLEngine</code>'s <code>unwrap()</code>
* call, the application can detect the close by calling
* <code>unwrap()</code> and looking for a <code>SSLEngineResult</code>
* with status "CLOSED", or if {@link #isInboundDone()} returns true.
* If for some reason the peer closes the communication link without
* sending the proper SSL/TLS closure message, the application can
* detect the end-of-stream and can signal the engine via {@link
* #closeInbound()} that there will no more inbound messages to
* process. Some applications might choose to require orderly shutdown
* messages from a peer, in which case they can check that the closure
* was generated by a handshake message and not by an end-of-stream
* condition.
* <P>
* There are two groups of cipher suites which you will need to know
* about when managing cipher suites:
*
* <UL>
* <LI> <em>Supported</em> cipher suites: all the suites which are
* supported by the SSL implementation. This list is reported
* using {@link #getSupportedCipherSuites()}.
*
* <LI> <em>Enabled</em> cipher suites, which may be fewer than
* the full set of supported suites. This group is set using the
* {@link #setEnabledCipherSuites(String [])} method, and
* queried using the {@link #getEnabledCipherSuites()} method.
* Initially, a default set of cipher suites will be enabled on a
* new engine that represents the minimum suggested
* configuration.
* </UL>
*
* Implementation defaults require that only cipher suites which
* authenticate servers and provide confidentiality be enabled by
* default. Only if both sides explicitly agree to unauthenticated
* and/or non-private (unencrypted) communications will such a
* cipher suite be selected.
* <P>
* Each SSL/TLS connection must have one client and one server, thus
* each endpoint must decide which role to assume. This choice determines
* who begins the handshaking process as well as which type of messages
* should be sent by each party. The method {@link
* #setUseClientMode(boolean)} configures the mode. Once the initial
* handshaking has started, an <code>SSLEngine</code> can not switch
* between client and server modes, even when performing renegotiations.
* <P>
* Applications might choose to process delegated tasks in different
* threads. When an <code>SSLEngine</code>
* is created, the current {@link java.security.AccessControlContext}
* is saved. All future delegated tasks will be processed using this
* context: that is, all access control decisions will be made using the
* context captured at engine creation.
* <P>
* <HR>
*
* <B>Concurrency Notes</B>:
* There are two concurrency issues to be aware of:
*
* <OL>
* <li>The <code>wrap()</code> and <code>unwrap()</code> methods
* may execute concurrently of each other.
*
* <li> The SSL/TLS protocols employ ordered packets.
* Applications must take care to ensure that generated packets
* are delivered in sequence. If packets arrive
* out-of-order, unexpected or fatal results may occur.
* <P>
* For example:
* <P>
* <pre>
* synchronized (outboundLock) {
* sslEngine.wrap(src, dst);
* outboundQueue.put(dst);
* }
* </pre>
*
* As a corollary, two threads must not attempt to call the same method
* (either <code>wrap()</code> or <code>unwrap()</code>) concurrently,
* because there is no way to guarantee the eventual packet ordering.
* </OL>
*
* @see SSLContext
* @see SSLSocket
* @see SSLServerSocket
* @see SSLSession
* @see java.net.Socket
*
* @since 1.5
* @author Brad R. Wetmore
*/
public abstract class SSLEngine {
private String peerHost = null;
private int peerPort = -1;
/** {@collect.stats}
* Constructor for an <code>SSLEngine</code> providing no hints
* for an internal session reuse strategy.
*
* @see SSLContext#createSSLEngine()
* @see SSLSessionContext
*/
protected SSLEngine() {
}
/** {@collect.stats}
* Constructor for an <code>SSLEngine</code>.
* <P>
* <code>SSLEngine</code> implementations may use the
* <code>peerHost</code> and <code>peerPort</code> parameters as hints
* for their internal session reuse strategy.
* <P>
* Some cipher suites (such as Kerberos) require remote hostname
* information. Implementations of this class should use this
* constructor to use Kerberos.
* <P>
* The parameters are not authenticated by the
* <code>SSLEngine</code>.
*
* @param peerHost the name of the peer host
* @param peerPort the port number of the peer
* @see SSLContext#createSSLEngine(String, int)
* @see SSLSessionContext
*/
protected SSLEngine(String peerHost, int peerPort) {
this.peerHost = peerHost;
this.peerPort = peerPort;
}
/** {@collect.stats}
* Returns the host name of the peer.
* <P>
* Note that the value is not authenticated, and should not be
* relied upon.
*
* @return the host name of the peer, or null if nothing is
* available.
*/
public String getPeerHost() {
return peerHost;
}
/** {@collect.stats}
* Returns the port number of the peer.
* <P>
* Note that the value is not authenticated, and should not be
* relied upon.
*
* @return the port number of the peer, or -1 if nothing is
* available.
*/
public int getPeerPort() {
return peerPort;
}
/** {@collect.stats}
* Attempts to encode a buffer of plaintext application data into
* SSL/TLS network data.
* <P>
* An invocation of this method behaves in exactly the same manner
* as the invocation:
* <blockquote><pre>
* {@link #wrap(ByteBuffer [], int, int, ByteBuffer)
* engine.wrap(new ByteBuffer [] { src }, 0, 1, dst);}
* </pre</blockquote>
*
* @param src
* a <code>ByteBuffer</code> containing outbound application data
* @param dst
* a <code>ByteBuffer</code> to hold outbound network data
* @return an <code>SSLEngineResult</code> describing the result
* of this operation.
* @throws SSLException
* A problem was encountered while processing the
* data that caused the <code>SSLEngine</code> to abort.
* See the class description for more information on
* engine closure.
* @throws ReadOnlyBufferException
* if the <code>dst</code> buffer is read-only.
* @throws IllegalArgumentException
* if either <code>src</code> or <code>dst</code>
* is null.
* @throws IllegalStateException if the client/server mode
* has not yet been set.
* @see #wrap(ByteBuffer [], int, int, ByteBuffer)
*/
public SSLEngineResult wrap(ByteBuffer src,
ByteBuffer dst) throws SSLException {
return wrap(new ByteBuffer [] { src }, 0, 1, dst);
}
/** {@collect.stats}
* Attempts to encode plaintext bytes from a sequence of data
* buffers into SSL/TLS network data.
* <P>
* An invocation of this method behaves in exactly the same manner
* as the invocation:
* <blockquote><pre>
* {@link #wrap(ByteBuffer [], int, int, ByteBuffer)
* engine.wrap(srcs, 0, srcs.length, dst);}
* </pre</blockquote>
*
* @param srcs
* an array of <code>ByteBuffers</code> containing the
* outbound application data
* @param dst
* a <code>ByteBuffer</code> to hold outbound network data
* @return an <code>SSLEngineResult</code> describing the result
* of this operation.
* @throws SSLException
* A problem was encountered while processing the
* data that caused the <code>SSLEngine</code> to abort.
* See the class description for more information on
* engine closure.
* @throws ReadOnlyBufferException
* if the <code>dst</code> buffer is read-only.
* @throws IllegalArgumentException
* if either <code>srcs</code> or <code>dst</code>
* is null, or if any element in <code>srcs</code> is null.
* @throws IllegalStateException if the client/server mode
* has not yet been set.
* @see #wrap(ByteBuffer [], int, int, ByteBuffer)
*/
public SSLEngineResult wrap(ByteBuffer [] srcs,
ByteBuffer dst) throws SSLException {
if (srcs == null) {
throw new IllegalArgumentException("src == null");
}
return wrap(srcs, 0, srcs.length, dst);
}
/** {@collect.stats}
* Attempts to encode plaintext bytes from a subsequence of data
* buffers into SSL/TLS network data. This <i>"gathering"</i>
* operation encodes, in a single invocation, a sequence of bytes
* from one or more of a given sequence of buffers. Gathering
* wraps are often useful when implementing network protocols or
* file formats that, for example, group data into segments
* consisting of one or more fixed-length headers followed by a
* variable-length body. See
* {@link java.nio.channels.GatheringByteChannel} for more
* information on gathering, and {@link
* java.nio.channels.GatheringByteChannel#write(ByteBuffer[],
* int, int)} for more information on the subsequence
* behavior.
* <P>
* Depending on the state of the SSLEngine, this method may produce
* network data without consuming any application data (for example,
* it may generate handshake data.)
* <P>
* The application is responsible for reliably transporting the
* network data to the peer, and for ensuring that data created by
* multiple calls to wrap() is transported in the same order in which
* it was generated. The application must properly synchronize
* multiple calls to this method.
* <P>
* If this <code>SSLEngine</code> has not yet started its initial
* handshake, this method will automatically start the handshake.
* <P>
* This method will attempt to produce one SSL/TLS packet, and will
* consume as much source data as possible, but will never consume
* more than the sum of the bytes remaining in each buffer. Each
* <code>ByteBuffer</code>'s position is updated to reflect the
* amount of data consumed or produced. The limits remain the
* same.
* <P>
* The underlying memory used by the <code>srcs</code> and
* <code>dst ByteBuffer</code>s must not be the same.
* <P>
* See the class description for more information on engine closure.
*
* @param srcs
* an array of <code>ByteBuffers</code> containing the
* outbound application data
* @param offset
* The offset within the buffer array of the first buffer from
* which bytes are to be retrieved; it must be non-negative
* and no larger than <code>srcs.length</code>
* @param length
* The maximum number of buffers to be accessed; it must be
* non-negative and no larger than
* <code>srcs.length</code> - <code>offset</code>
* @param dst
* a <code>ByteBuffer</code> to hold outbound network data
* @return an <code>SSLEngineResult</code> describing the result
* of this operation.
* @throws SSLException
* A problem was encountered while processing the
* data that caused the <code>SSLEngine</code> to abort.
* See the class description for more information on
* engine closure.
* @throws IndexOutOfBoundsException
* if the preconditions on the <code>offset</code> and
* <code>length</code> parameters do not hold.
* @throws ReadOnlyBufferException
* if the <code>dst</code> buffer is read-only.
* @throws IllegalArgumentException
* if either <code>srcs</code> or <code>dst</code>
* is null, or if any element in the <code>srcs</code>
* subsequence specified is null.
* @throws IllegalStateException if the client/server mode
* has not yet been set.
* @see java.nio.channels.GatheringByteChannel
* @see java.nio.channels.GatheringByteChannel#write(
* ByteBuffer[], int, int)
*/
public abstract SSLEngineResult wrap(ByteBuffer [] srcs, int offset,
int length, ByteBuffer dst) throws SSLException;
/** {@collect.stats}
* Attempts to decode SSL/TLS network data into a plaintext
* application data buffer.
* <P>
* An invocation of this method behaves in exactly the same manner
* as the invocation:
* <blockquote><pre>
* {@link #unwrap(ByteBuffer, ByteBuffer [], int, int)
* engine.unwrap(src, new ByteBuffer [] { dst }, 0, 1);}
* </pre</blockquote>
*
* @param src
* a <code>ByteBuffer</code> containing inbound network data.
* @param dst
* a <code>ByteBuffer</code> to hold inbound application data.
* @return an <code>SSLEngineResult</code> describing the result
* of this operation.
* @throws SSLException
* A problem was encountered while processing the
* data that caused the <code>SSLEngine</code> to abort.
* See the class description for more information on
* engine closure.
* @throws ReadOnlyBufferException
* if the <code>dst</code> buffer is read-only.
* @throws IllegalArgumentException
* if either <code>src</code> or <code>dst</code>
* is null.
* @throws IllegalStateException if the client/server mode
* has not yet been set.
* @see #unwrap(ByteBuffer, ByteBuffer [], int, int)
*/
public SSLEngineResult unwrap(ByteBuffer src,
ByteBuffer dst) throws SSLException {
return unwrap(src, new ByteBuffer [] { dst }, 0, 1);
}
/** {@collect.stats}
* Attempts to decode SSL/TLS network data into a sequence of plaintext
* application data buffers.
* <P>
* An invocation of this method behaves in exactly the same manner
* as the invocation:
* <blockquote><pre>
* {@link #unwrap(ByteBuffer, ByteBuffer [], int, int)
* engine.unwrap(src, dsts, 0, dsts.length);}
* </pre</blockquote>
*
* @param src
* a <code>ByteBuffer</code> containing inbound network data.
* @param dsts
* an array of <code>ByteBuffer</code>s to hold inbound
* application data.
* @return an <code>SSLEngineResult</code> describing the result
* of this operation.
* @throws SSLException
* A problem was encountered while processing the
* data that caused the <code>SSLEngine</code> to abort.
* See the class description for more information on
* engine closure.
* @throws ReadOnlyBufferException
* if any of the <code>dst</code> buffers are read-only.
* @throws IllegalArgumentException
* if either <code>src</code> or <code>dsts</code>
* is null, or if any element in <code>dsts</code> is null.
* @throws IllegalStateException if the client/server mode
* has not yet been set.
* @see #unwrap(ByteBuffer, ByteBuffer [], int, int)
*/
public SSLEngineResult unwrap(ByteBuffer src,
ByteBuffer [] dsts) throws SSLException {
if (dsts == null) {
throw new IllegalArgumentException("dsts == null");
}
return unwrap(src, dsts, 0, dsts.length);
}
/** {@collect.stats}
* Attempts to decode SSL/TLS network data into a subsequence of
* plaintext application data buffers. This <i>"scattering"</i>
* operation decodes, in a single invocation, a sequence of bytes
* into one or more of a given sequence of buffers. Scattering
* unwraps are often useful when implementing network protocols or
* file formats that, for example, group data into segments
* consisting of one or more fixed-length headers followed by a
* variable-length body. See
* {@link java.nio.channels.ScatteringByteChannel} for more
* information on scattering, and {@link
* java.nio.channels.ScatteringByteChannel#read(ByteBuffer[],
* int, int)} for more information on the subsequence
* behavior.
* <P>
* Depending on the state of the SSLEngine, this method may consume
* network data without producing any application data (for example,
* it may consume handshake data.)
* <P>
* The application is responsible for reliably obtaining the network
* data from the peer, and for invoking unwrap() on the data in the
* order it was received. The application must properly synchronize
* multiple calls to this method.
* <P>
* If this <code>SSLEngine</code> has not yet started its initial
* handshake, this method will automatically start the handshake.
* <P>
* This method will attempt to consume one complete SSL/TLS network
* packet, but will never consume more than the sum of the bytes
* remaining in the buffers. Each <code>ByteBuffer</code>'s
* position is updated to reflect the amount of data consumed or
* produced. The limits remain the same.
* <P>
* The underlying memory used by the <code>src</code> and
* <code>dsts ByteBuffer</code>s must not be the same.
* <P>
* The inbound network buffer may be modified as a result of this
* call: therefore if the network data packet is required for some
* secondary purpose, the data should be duplicated before calling this
* method. Note: the network data will not be useful to a second
* SSLEngine, as each SSLEngine contains unique random state which
* influences the SSL/TLS messages.
* <P>
* See the class description for more information on engine closure.
*
* @param src
* a <code>ByteBuffer</code> containing inbound network data.
* @param dsts
* an array of <code>ByteBuffer</code>s to hold inbound
* application data.
* @param offset
* The offset within the buffer array of the first buffer from
* which bytes are to be transferred; it must be non-negative
* and no larger than <code>dsts.length</code>.
* @param length
* The maximum number of buffers to be accessed; it must be
* non-negative and no larger than
* <code>dsts.length</code> - <code>offset</code>.
* @return an <code>SSLEngineResult</code> describing the result
* of this operation.
* @throws SSLException
* A problem was encountered while processing the
* data that caused the <code>SSLEngine</code> to abort.
* See the class description for more information on
* engine closure.
* @throws IndexOutOfBoundsException
* If the preconditions on the <code>offset</code> and
* <code>length</code> parameters do not hold.
* @throws ReadOnlyBufferException
* if any of the <code>dst</code> buffers are read-only.
* @throws IllegalArgumentException
* if either <code>src</code> or <code>dsts</code>
* is null, or if any element in the <code>dsts</code>
* subsequence specified is null.
* @throws IllegalStateException if the client/server mode
* has not yet been set.
* @see java.nio.channels.ScatteringByteChannel
* @see java.nio.channels.ScatteringByteChannel#read(
* ByteBuffer[], int, int)
*/
public abstract SSLEngineResult unwrap(ByteBuffer src,
ByteBuffer [] dsts, int offset, int length) throws SSLException;
/** {@collect.stats}
* Returns a delegated <code>Runnable</code> task for
* this <code>SSLEngine</code>.
* <P>
* <code>SSLEngine</code> operations may require the results of
* operations that block, or may take an extended period of time to
* complete. This method is used to obtain an outstanding {@link
* java.lang.Runnable} operation (task). Each task must be assigned
* a thread (possibly the current) to perform the {@link
* java.lang.Runnable#run() run} operation. Once the
* <code>run</code> method returns, the <code>Runnable</code> object
* is no longer needed and may be discarded.
* <P>
* Delegated tasks run in the <code>AccessControlContext</code>
* in place when this object was created.
* <P>
* A call to this method will return each outstanding task
* exactly once.
* <P>
* Multiple delegated tasks can be run in parallel.
*
* @return a delegated <code>Runnable</code> task, or null
* if none are available.
*/
public abstract Runnable getDelegatedTask();
/** {@collect.stats}
* Signals that no more inbound network data will be sent
* to this <code>SSLEngine</code>.
* <P>
* If the application initiated the closing process by calling
* {@link #closeOutbound()}, under some circumstances it is not
* required that the initiator wait for the peer's corresponding
* close message. (See section 7.2.1 of the TLS specification (<A
* HREF="http://www.ietf.org/rfc/rfc2246.txt">RFC 2246</A>) for more
* information on waiting for closure alerts.) In such cases, this
* method need not be called.
* <P>
* But if the application did not initiate the closure process, or
* if the circumstances above do not apply, this method should be
* called whenever the end of the SSL/TLS data stream is reached.
* This ensures closure of the inbound side, and checks that the
* peer followed the SSL/TLS close procedure properly, thus
* detecting possible truncation attacks.
* <P>
* This method is idempotent: if the inbound side has already
* been closed, this method does not do anything.
* <P>
* {@link #wrap(ByteBuffer, ByteBuffer) wrap()} should be
* called to flush any remaining handshake data.
*
* @throws SSLException
* if this engine has not received the proper SSL/TLS close
* notification message from the peer.
*
* @see #isInboundDone()
* @see #isOutboundDone()
*/
public abstract void closeInbound() throws SSLException;
/** {@collect.stats}
* Returns whether {@link #unwrap(ByteBuffer, ByteBuffer)} will
* accept any more inbound data messages.
*
* @return true if the <code>SSLEngine</code> will not
* consume anymore network data (and by implication,
* will not produce any more application data.)
* @see #closeInbound()
*/
public abstract boolean isInboundDone();
/** {@collect.stats}
* Signals that no more outbound application data will be sent
* on this <code>SSLEngine</code>.
* <P>
* This method is idempotent: if the outbound side has already
* been closed, this method does not do anything.
* <P>
* {@link #wrap(ByteBuffer, ByteBuffer)} should be
* called to flush any remaining handshake data.
*
* @see #isOutboundDone()
*/
public abstract void closeOutbound();
/** {@collect.stats}
* Returns whether {@link #wrap(ByteBuffer, ByteBuffer)} will
* produce any more outbound data messages.
* <P>
* Note that during the closure phase, a <code>SSLEngine</code> may
* generate handshake closure data that must be sent to the peer.
* <code>wrap()</code> must be called to generate this data. When
* this method returns true, no more outbound data will be created.
*
* @return true if the <code>SSLEngine</code> will not produce
* any more network data
*
* @see #closeOutbound()
* @see #closeInbound()
*/
public abstract boolean isOutboundDone();
/** {@collect.stats}
* Returns the names of the cipher suites which could be enabled for use
* on this engine. Normally, only a subset of these will actually
* be enabled by default, since this list may include cipher suites which
* do not meet quality of service requirements for those defaults. Such
* cipher suites might be useful in specialized applications.
*
* @return an array of cipher suite names
* @see #getEnabledCipherSuites()
* @see #setEnabledCipherSuites(String [])
*/
public abstract String [] getSupportedCipherSuites();
/** {@collect.stats}
* Returns the names of the SSL cipher suites which are currently
* enabled for use on this engine. When an SSLEngine is first
* created, all enabled cipher suites support a minimum quality of
* service. Thus, in some environments this value might be empty.
* <P>
* Even if a suite has been enabled, it might never be used. (For
* example, the peer does not support it, the requisite
* certificates/private keys for the suite are not available, or an
* anonymous suite is enabled but authentication is required.)
*
* @return an array of cipher suite names
* @see #getSupportedCipherSuites()
* @see #setEnabledCipherSuites(String [])
*/
public abstract String [] getEnabledCipherSuites();
/** {@collect.stats}
* Sets the cipher suites enabled for use on this engine.
* <P>
* Each cipher suite in the <code>suites</code> parameter must have
* been listed by getSupportedCipherSuites(), or the method will
* fail. Following a successful call to this method, only suites
* listed in the <code>suites</code> parameter are enabled for use.
* <P>
* See {@link #getEnabledCipherSuites()} for more information
* on why a specific cipher suite may never be used on a engine.
*
* @param suites Names of all the cipher suites to enable
* @throws IllegalArgumentException when one or more of the ciphers
* named by the parameter is not supported, or when the
* parameter is null.
* @see #getSupportedCipherSuites()
* @see #getEnabledCipherSuites()
*/
public abstract void setEnabledCipherSuites(String suites []);
/** {@collect.stats}
* Returns the names of the protocols which could be enabled for use
* with this <code>SSLEngine</code>.
*
* @return an array of protocols supported
*/
public abstract String [] getSupportedProtocols();
/** {@collect.stats}
* Returns the names of the protocol versions which are currently
* enabled for use with this <code>SSLEngine</code>.
*
* @return an array of protocols
* @see #setEnabledProtocols(String [])
*/
public abstract String [] getEnabledProtocols();
/** {@collect.stats}
* Set the protocol versions enabled for use on this engine.
* <P>
* The protocols must have been listed by getSupportedProtocols()
* as being supported. Following a successful call to this method,
* only protocols listed in the <code>protocols</code> parameter
* are enabled for use.
*
* @param protocols Names of all the protocols to enable.
* @throws IllegalArgumentException when one or more of
* the protocols named by the parameter is not supported or
* when the protocols parameter is null.
* @see #getEnabledProtocols()
*/
public abstract void setEnabledProtocols(String protocols[]);
/** {@collect.stats}
* Returns the <code>SSLSession</code> in use in this
* <code>SSLEngine</code>.
* <P>
* These can be long lived, and frequently correspond to an entire
* login session for some user. The session specifies a particular
* cipher suite which is being actively used by all connections in
* that session, as well as the identities of the session's client
* and server.
* <P>
* Unlike {@link SSLSocket#getSession()}
* this method does not block until handshaking is complete.
* <P>
* Until the initial handshake has completed, this method returns
* a session object which reports an invalid cipher suite of
* "SSL_NULL_WITH_NULL_NULL".
*
* @return the <code>SSLSession</code> for this <code>SSLEngine</code>
* @see SSLSession
*/
public abstract SSLSession getSession();
/** {@collect.stats}
* Initiates handshaking (initial or renegotiation) on this SSLEngine.
* <P>
* This method is not needed for the initial handshake, as the
* <code>wrap()</code> and <code>unwrap()</code> methods will
* implicitly call this method if handshaking has not already begun.
* <P>
* Note that the peer may also request a session renegotiation with
* this <code>SSLEngine</code> by sending the appropriate
* session renegotiate handshake message.
* <P>
* Unlike the {@link SSLSocket#startHandshake()
* SSLSocket#startHandshake()} method, this method does not block
* until handshaking is completed.
* <P>
* To force a complete SSL/TLS session renegotiation, the current
* session should be invalidated prior to calling this method.
* <P>
* Some protocols may not support multiple handshakes on an existing
* engine and may throw an <code>SSLException</code>.
*
* @throws SSLException
* if a problem was encountered while signaling the
* <code>SSLEngine</code> to begin a new handshake.
* See the class description for more information on
* engine closure.
* @throws IllegalStateException if the client/server mode
* has not yet been set.
* @see SSLSession#invalidate()
*/
public abstract void beginHandshake() throws SSLException;
/** {@collect.stats}
* Returns the current handshake status for this <code>SSLEngine</code>.
*
* @return the current <code>SSLEngineResult.HandshakeStatus</code>.
*/
public abstract SSLEngineResult.HandshakeStatus getHandshakeStatus();
/** {@collect.stats}
* Configures the engine to use client (or server) mode when
* handshaking.
* <P>
* This method must be called before any handshaking occurs.
* Once handshaking has begun, the mode can not be reset for the
* life of this engine.
* <P>
* Servers normally authenticate themselves, and clients
* are not required to do so.
*
* @param mode true if the engine should start its handshaking
* in "client" mode
* @throws IllegalArgumentException if a mode change is attempted
* after the initial handshake has begun.
* @see #getUseClientMode()
*/
public abstract void setUseClientMode(boolean mode);
/** {@collect.stats}
* Returns true if the engine is set to use client mode when
* handshaking.
*
* @return true if the engine should do handshaking
* in "client" mode
* @see #setUseClientMode(boolean)
*/
public abstract boolean getUseClientMode();
/** {@collect.stats}
* Configures the engine to <i>require</i> client authentication. This
* option is only useful for engines in the server mode.
* <P>
* An engine's client authentication setting is one of the following:
* <ul>
* <li> client authentication required
* <li> client authentication requested
* <li> no client authentication desired
* </ul>
* <P>
* Unlike {@link #setWantClientAuth(boolean)}, if this option is set and
* the client chooses not to provide authentication information
* about itself, <i>the negotiations will stop and the engine will
* begin its closure procedure</i>.
* <P>
* Calling this method overrides any previous setting made by
* this method or {@link #setWantClientAuth(boolean)}.
*
* @param need set to true if client authentication is required,
* or false if no client authentication is desired.
* @see #getNeedClientAuth()
* @see #setWantClientAuth(boolean)
* @see #getWantClientAuth()
* @see #setUseClientMode(boolean)
*/
public abstract void setNeedClientAuth(boolean need);
/** {@collect.stats}
* Returns true if the engine will <i>require</i> client authentication.
* This option is only useful to engines in the server mode.
*
* @return true if client authentication is required,
* or false if no client authentication is desired.
* @see #setNeedClientAuth(boolean)
* @see #setWantClientAuth(boolean)
* @see #getWantClientAuth()
* @see #setUseClientMode(boolean)
*/
public abstract boolean getNeedClientAuth();
/** {@collect.stats}
* Configures the engine to <i>request</i> client authentication.
* This option is only useful for engines in the server mode.
* <P>
* An engine's client authentication setting is one of the following:
* <ul>
* <li> client authentication required
* <li> client authentication requested
* <li> no client authentication desired
* </ul>
* <P>
* Unlike {@link #setNeedClientAuth(boolean)}, if this option is set and
* the client chooses not to provide authentication information
* about itself, <i>the negotiations will continue</i>.
* <P>
* Calling this method overrides any previous setting made by
* this method or {@link #setNeedClientAuth(boolean)}.
*
* @param want set to true if client authentication is requested,
* or false if no client authentication is desired.
* @see #getWantClientAuth()
* @see #setNeedClientAuth(boolean)
* @see #getNeedClientAuth()
* @see #setUseClientMode(boolean)
*/
public abstract void setWantClientAuth(boolean want);
/** {@collect.stats}
* Returns true if the engine will <i>request</i> client authentication.
* This option is only useful for engines in the server mode.
*
* @return true if client authentication is requested,
* or false if no client authentication is desired.
* @see #setNeedClientAuth(boolean)
* @see #getNeedClientAuth()
* @see #setWantClientAuth(boolean)
* @see #setUseClientMode(boolean)
*/
public abstract boolean getWantClientAuth();
/** {@collect.stats}
* Controls whether new SSL sessions may be established by this engine.
* If session creations are not allowed, and there are no
* existing sessions to resume, there will be no successful
* handshaking.
*
* @param flag true indicates that sessions may be created; this
* is the default. false indicates that an existing session
* must be resumed
* @see #getEnableSessionCreation()
*/
public abstract void setEnableSessionCreation(boolean flag);
/** {@collect.stats}
* Returns true if new SSL sessions may be established by this engine.
*
* @return true indicates that sessions may be created; this
* is the default. false indicates that an existing session
* must be resumed
* @see #setEnableSessionCreation(boolean)
*/
public abstract boolean getEnableSessionCreation();
/** {@collect.stats}
* Returns the SSLParameters in effect for this SSLEngine.
* The ciphersuites and protocols of the returned SSLParameters
* are always non-null.
*
* @return the SSLParameters in effect for this SSLEngine.
* @since 1.6
*/
public SSLParameters getSSLParameters() {
SSLParameters params = new SSLParameters();
params.setCipherSuites(getEnabledCipherSuites());
params.setProtocols(getEnabledProtocols());
if (getNeedClientAuth()) {
params.setNeedClientAuth(true);
} else if (getWantClientAuth()) {
params.setWantClientAuth(true);
}
return params;
}
/** {@collect.stats}
* Applies SSLParameters to this engine.
*
* <p>This means:
* <ul>
* <li>if <code>params.getCipherSuites()</code> is non-null,
* <code>setEnabledCipherSuites()</code> is called with that value
* <li>if <code>params.getProtocols()</code> is non-null,
* <code>setEnabledProtocols()</code> is called with that value
* <li>if <code>params.getNeedClientAuth()</code> or
* <code>params.getWantClientAuth()</code> return <code>true</code>,
* <code>setNeedClientAuth(true)</code> and
* <code>setWantClientAuth(true)</code> are called, respectively;
* otherwise <code>setWantClientAuth(false)</code> is called.
* </ul>
*
* @param params the parameters
* @throws IllegalArgumentException if the setEnabledCipherSuites() or
* the setEnabledProtocols() call fails
* @since 1.6
*/
public void setSSLParameters(SSLParameters params) {
String[] s;
s = params.getCipherSuites();
if (s != null) {
setEnabledCipherSuites(s);
}
s = params.getProtocols();
if (s != null) {
setEnabledProtocols(s);
}
if (params.getNeedClientAuth()) {
setNeedClientAuth(true);
} else if (params.getWantClientAuth()) {
setWantClientAuth(true);
} else {
setWantClientAuth(false);
}
}
}
|
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.net.ssl;
/** {@collect.stats}
* This is the base interface for JSSE key managers.
* <P>
* <code>KeyManager</code>s are responsible for managing the
* key material which is used to authenticate the local SSLSocket
* to its peer. If no key material is available, the socket will
* be unable to present authentication credentials.
* <P>
* <code>KeyManager</code>s are created by either
* using a <code>KeyManagerFactory</code>,
* or by implementing one of the <code>KeyManager</code> subclasses.
*
* @since 1.4
* @see KeyManagerFactory
*/
public interface KeyManager {
}
|
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.net.ssl;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.SocketException;
import javax.net.ServerSocketFactory;
import java.security.*;
/** {@collect.stats}
* <code>SSLServerSocketFactory</code>s create
* <code>SSLServerSocket</code>s.
*
* @since 1.4
* @see SSLSocket
* @see SSLServerSocket
* @author David Brownell
*/
public abstract class SSLServerSocketFactory extends ServerSocketFactory
{
private static SSLServerSocketFactory theFactory;
private static boolean propertyChecked;
private static void log(String msg) {
if (SSLSocketFactory.DEBUG) {
System.out.println(msg);
}
}
/** {@collect.stats}
* Constructor is used only by subclasses.
*/
protected SSLServerSocketFactory() { /* NOTHING */ }
/** {@collect.stats}
* Returns the default SSL server socket factory.
*
* <p>The first time this method is called, the security property
* "ssl.ServerSocketFactory.provider" is examined. If it is non-null, a
* class by that name is loaded and instantiated. If that is successful and
* the object is an instance of SSLServerSocketFactory, it is made the
* default SSL server socket factory.
*
* <p>Otherwise, this method returns
* <code>SSLContext.getDefault().getServerSocketFactory()</code>. If that
* call fails, an inoperative factory is returned.
*
* @return the default <code>ServerSocketFactory</code>
* @see SSLContext#getDefault
*/
public static synchronized ServerSocketFactory getDefault() {
if (theFactory != null) {
return theFactory;
}
if (propertyChecked == false) {
propertyChecked = true;
String clsName = SSLSocketFactory.getSecurityProperty
("ssl.ServerSocketFactory.provider");
if (clsName != null) {
log("setting up default SSLServerSocketFactory");
try {
Class cls = null;
try {
cls = Class.forName(clsName);
} catch (ClassNotFoundException e) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
if (cl != null) {
cls = cl.loadClass(clsName);
}
}
log("class " + clsName + " is loaded");
SSLServerSocketFactory fac = (SSLServerSocketFactory)cls.newInstance();
log("instantiated an instance of class " + clsName);
theFactory = fac;
return fac;
} catch (Exception e) {
log("SSLServerSocketFactory instantiation failed: " + e);
theFactory = new DefaultSSLServerSocketFactory(e);
return theFactory;
}
}
}
try {
return SSLContext.getDefault().getServerSocketFactory();
} catch (NoSuchAlgorithmException e) {
return new DefaultSSLServerSocketFactory(e);
}
}
/** {@collect.stats}
* Returns the list of cipher suites which are enabled by default.
* Unless a different list is enabled, handshaking on an SSL connection
* will use one of these cipher suites. The minimum quality of service
* for these defaults requires confidentiality protection and server
* authentication (that is, no anonymous cipher suites).
*
* @see #getSupportedCipherSuites()
* @return array of the cipher suites enabled by default
*/
public abstract String [] getDefaultCipherSuites();
/** {@collect.stats}
* Returns the names of the cipher suites which could be enabled for use
* on an SSL connection created by this factory.
* Normally, only a subset of these will actually
* be enabled by default, since this list may include cipher suites which
* do not meet quality of service requirements for those defaults. Such
* cipher suites are useful in specialized applications.
*
* @return an array of cipher suite names
* @see #getDefaultCipherSuites()
*/
public abstract String [] getSupportedCipherSuites();
}
//
// The default factory does NOTHING.
//
class DefaultSSLServerSocketFactory extends SSLServerSocketFactory {
private final Exception reason;
DefaultSSLServerSocketFactory(Exception reason) {
this.reason = reason;
}
private ServerSocket throwException() throws SocketException {
throw (SocketException)
new SocketException(reason.toString()).initCause(reason);
}
public ServerSocket createServerSocket() throws IOException {
return throwException();
}
public ServerSocket createServerSocket(int port)
throws IOException
{
return throwException();
}
public ServerSocket createServerSocket(int port, int backlog)
throws IOException
{
return throwException();
}
public ServerSocket
createServerSocket(int port, int backlog, InetAddress ifAddress)
throws IOException
{
return throwException();
}
public String [] getDefaultCipherSuites() {
return new String[0];
}
public String [] getSupportedCipherSuites() {
return new String[0];
}
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
/** {@collect.stats}
* {@description.open}
* Constants written into the Object Serialization Stream.
* {@description.close}
*
* @author unascribed
* @since JDK 1.1
*/
public interface ObjectStreamConstants {
/** {@collect.stats}
* {@description.open}
* Magic number that is written to the stream header.
* {@description.close}
*/
final static short STREAM_MAGIC = (short)0xaced;
/** {@collect.stats}
* {@description.open}
* Version number that is written to the stream header.
* {@description.close}
*/
final static short STREAM_VERSION = 5;
/* Each item in the stream is preceded by a tag
*/
/** {@collect.stats}
* {@description.open}
* First tag value.
* {@description.close}
*/
final static byte TC_BASE = 0x70;
/** {@collect.stats}
* {@description.open}
* Null object reference.
* {@description.close}
*/
final static byte TC_NULL = (byte)0x70;
/** {@collect.stats}
* {@description.open}
* Reference to an object already written into the stream.
* {@description.close}
*/
final static byte TC_REFERENCE = (byte)0x71;
/** {@collect.stats}
* {@description.open}
* new Class Descriptor.
* {@description.close}
*/
final static byte TC_CLASSDESC = (byte)0x72;
/** {@collect.stats}
* {@description.open}
* new Object.
* {@description.close}
*/
final static byte TC_OBJECT = (byte)0x73;
/** {@collect.stats}
* {@description.open}
* new String.
* {@description.close}
*/
final static byte TC_STRING = (byte)0x74;
/** {@collect.stats}
* {@description.open}
* new Array.
* {@description.close}
*/
final static byte TC_ARRAY = (byte)0x75;
/** {@collect.stats}
* {@description.open}
* Reference to Class.
* {@description.close}
*/
final static byte TC_CLASS = (byte)0x76;
/** {@collect.stats}
* {@description.open}
* Block of optional data. Byte following tag indicates number
* of bytes in this block data.
* {@description.close}
*/
final static byte TC_BLOCKDATA = (byte)0x77;
/** {@collect.stats}
* {@description.open}
* End of optional block data blocks for an object.
* {@description.close}
*/
final static byte TC_ENDBLOCKDATA = (byte)0x78;
/** {@collect.stats}
* {@description.open}
* Reset stream context. All handles written into stream are reset.
* {@description.close}
*/
final static byte TC_RESET = (byte)0x79;
/** {@collect.stats}
* {@description.open}
* long Block data. The long following the tag indicates the
* number of bytes in this block data.
* {@description.close}
*/
final static byte TC_BLOCKDATALONG= (byte)0x7A;
/** {@collect.stats}
* {@description.open}
* Exception during write.
* {@description.close}
*/
final static byte TC_EXCEPTION = (byte)0x7B;
/** {@collect.stats}
* {@description.open}
* Long string.
* {@description.close}
*/
final static byte TC_LONGSTRING = (byte)0x7C;
/** {@collect.stats}
* {@description.open}
* new Proxy Class Descriptor.
* {@description.close}
*/
final static byte TC_PROXYCLASSDESC = (byte)0x7D;
/** {@collect.stats}
* {@description.open}
* new Enum constant.
* {@description.close}
* @since 1.5
*/
final static byte TC_ENUM = (byte)0x7E;
/** {@collect.stats}
* {@description.open}
* Last tag value.
* {@description.close}
*/
final static byte TC_MAX = (byte)0x7E;
/** {@collect.stats}
* {@description.open}
* First wire handle to be assigned.
* {@description.close}
*/
final static int baseWireHandle = 0x7e0000;
/** {@collect.stats}****************************************************/
/* Bit masks for ObjectStreamClass flag.*/
/** {@collect.stats}
* {@description.open}
* Bit mask for ObjectStreamClass flag. Indicates a Serializable class
* defines its own writeObject method.
* {@description.close}
*/
final static byte SC_WRITE_METHOD = 0x01;
/** {@collect.stats}
* {@description.open}
* Bit mask for ObjectStreamClass flag. Indicates Externalizable data
* written in Block Data mode.
* Added for PROTOCOL_VERSION_2.
* {@description.close}
*
* @see #PROTOCOL_VERSION_2
* @since 1.2
*/
final static byte SC_BLOCK_DATA = 0x08;
/** {@collect.stats}
* {@description.open}
* Bit mask for ObjectStreamClass flag. Indicates class is Serializable.
* {@description.close}
*/
final static byte SC_SERIALIZABLE = 0x02;
/** {@collect.stats}
* {@description.open}
* Bit mask for ObjectStreamClass flag. Indicates class is Externalizable.
* {@description.close}
*/
final static byte SC_EXTERNALIZABLE = 0x04;
/** {@collect.stats}
* {@description.open}
* Bit mask for ObjectStreamClass flag. Indicates class is an enum type.
* {@description.close}
* @since 1.5
*/
final static byte SC_ENUM = 0x10;
/* *******************************************************************/
/* Security permissions */
/** {@collect.stats}
* {@description.open}
* Enable substitution of one object for another during
* serialization/deserialization.
* {@description.close}
*
* @see java.io.ObjectOutputStream#enableReplaceObject(boolean)
* @see java.io.ObjectInputStream#enableResolveObject(boolean)
* @since 1.2
*/
final static SerializablePermission SUBSTITUTION_PERMISSION =
new SerializablePermission("enableSubstitution");
/** {@collect.stats}
* {@description.open}
* Enable overriding of readObject and writeObject.
* {@description.close}
*
* @see java.io.ObjectOutputStream#writeObjectOverride(Object)
* @see java.io.ObjectInputStream#readObjectOverride()
* @since 1.2
*/
final static SerializablePermission SUBCLASS_IMPLEMENTATION_PERMISSION =
new SerializablePermission("enableSubclassImplementation");
/** {@collect.stats}
* {@description.open}
* A Stream Protocol Version. <p>
*
* All externalizable data is written in JDK 1.1 external data
* format after calling this method. This version is needed to write
* streams containing Externalizable data that can be read by
* pre-JDK 1.1.6 JVMs.
* {@description.close}
*
* @see java.io.ObjectOutputStream#useProtocolVersion(int)
* @since 1.2
*/
public final static int PROTOCOL_VERSION_1 = 1;
/** {@collect.stats}
* {@description.open}
* A Stream Protocol Version. <p>
*
* This protocol is written by JVM 1.2.
*
* Externalizable data is written in block data mode and is
* terminated with TC_ENDBLOCKDATA. Externalizable classdescriptor
* flags has SC_BLOCK_DATA enabled. JVM 1.1.6 and greater can
* read this format change.
*
* Enables writing a nonSerializable class descriptor into the
* stream. The serialVersionUID of a nonSerializable class is
* set to 0L.
* {@description.close}
*
* @see java.io.ObjectOutputStream#useProtocolVersion(int)
* @see #SC_BLOCK_DATA
* @since 1.2
*/
public final static int PROTOCOL_VERSION_2 = 2;
}
|
Java
|
/*
* Copyright (c) 1994, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
import java.nio.channels.FileChannel;
import sun.nio.ch.FileChannelImpl;
/** {@collect.stats}
* {@description.open}
* Instances of this class support both reading and writing to a
* random access file. A random access file behaves like a large
* array of bytes stored in the file system. There is a kind of cursor,
* or index into the implied array, called the <em>file pointer</em>;
* input operations read bytes starting at the file pointer and advance
* the file pointer past the bytes read. If the random access file is
* created in read/write mode, then output operations are also available;
* output operations write bytes starting at the file pointer and advance
* the file pointer past the bytes written. Output operations that write
* past the current end of the implied array cause the array to be
* extended. The file pointer can be read by the
* <code>getFilePointer</code> method and set by the <code>seek</code>
* method.
* <p>
* It is generally true of all the reading routines in this class that
* if end-of-file is reached before the desired number of bytes has been
* read, an <code>EOFException</code> (which is a kind of
* <code>IOException</code>) is thrown. If any byte cannot be read for
* any reason other than end-of-file, an <code>IOException</code> other
* than <code>EOFException</code> is thrown. In particular, an
* <code>IOException</code> may be thrown if the stream has been closed.
* {@description.close}
*
* @author unascribed
* @since JDK1.0
*/
public class RandomAccessFile implements DataOutput, DataInput, Closeable {
private FileDescriptor fd;
private FileChannel channel = null;
private boolean rw;
private Object closeLock = new Object();
private volatile boolean closed = false;
private static final int O_RDONLY = 1;
private static final int O_RDWR = 2;
private static final int O_SYNC = 4;
private static final int O_DSYNC = 8;
/** {@collect.stats}
* {@description.open}
* Creates a random access file stream to read from, and optionally
* to write to, a file with the specified name. A new
* {@link FileDescriptor} object is created to represent the
* connection to the file.
*
* <p> The <tt>mode</tt> argument specifies the access mode with which the
* file is to be opened. The permitted values and their meanings are as
* specified for the <a
* href="#mode"><tt>RandomAccessFile(File,String)</tt></a> constructor.
*
* <p>
* If there is a security manager, its <code>checkRead</code> method
* is called with the <code>name</code> argument
* as its argument to see if read access to the file is allowed.
* If the mode allows writing, the security manager's
* <code>checkWrite</code> method
* is also called with the <code>name</code> argument
* as its argument to see if write access to the file is allowed.
* {@description.close}
*
* @param name the system-dependent filename
* @param mode the access <a href="#mode">mode</a>
* @exception IllegalArgumentException if the mode argument is not equal
* to one of <tt>"r"</tt>, <tt>"rw"</tt>, <tt>"rws"</tt>, or
* <tt>"rwd"</tt>
* @exception FileNotFoundException
* if the mode is <tt>"r"</tt> but the given string does not
* denote an existing regular file, or if the mode begins with
* <tt>"rw"</tt> but the given string does not denote an
* existing, writable regular file and a new regular file of
* that name cannot be created, or if some other error occurs
* while opening or creating the file
* @exception SecurityException if a security manager exists and its
* <code>checkRead</code> method denies read access to the file
* or the mode is "rw" and the security manager's
* <code>checkWrite</code> method denies write access to the file
* @see java.lang.SecurityException
* @see java.lang.SecurityManager#checkRead(java.lang.String)
* @see java.lang.SecurityManager#checkWrite(java.lang.String)
* @revised 1.4
* @spec JSR-51
*/
public RandomAccessFile(String name, String mode)
throws FileNotFoundException
{
this(name != null ? new File(name) : null, mode);
}
/** {@collect.stats}
* {@description.open}
* Creates a random access file stream to read from, and optionally to
* write to, the file specified by the {@link File} argument. A new {@link
* FileDescriptor} object is created to represent this file connection.
*
* <a name="mode"><p> The <tt>mode</tt> argument specifies the access mode
* in which the file is to be opened. The permitted values and their
* meanings are:
*
* <blockquote><table summary="Access mode permitted values and meanings">
* <tr><th><p align="left">Value</p></th><th><p align="left">Meaning</p></th></tr>
* <tr><td valign="top"><tt>"r"</tt></td>
* <td> Open for reading only. Invoking any of the <tt>write</tt>
* methods of the resulting object will cause an {@link
* java.io.IOException} to be thrown. </td></tr>
* <tr><td valign="top"><tt>"rw"</tt></td>
* <td> Open for reading and writing. If the file does not already
* exist then an attempt will be made to create it. </td></tr>
* <tr><td valign="top"><tt>"rws"</tt></td>
* <td> Open for reading and writing, as with <tt>"rw"</tt>, and also
* require that every update to the file's content or metadata be
* written synchronously to the underlying storage device. </td></tr>
* <tr><td valign="top"><tt>"rwd" </tt></td>
* <td> Open for reading and writing, as with <tt>"rw"</tt>, and also
* require that every update to the file's content be written
* synchronously to the underlying storage device. </td></tr>
* </table></blockquote>
*
* The <tt>"rws"</tt> and <tt>"rwd"</tt> modes work much like the {@link
* java.nio.channels.FileChannel#force(boolean) force(boolean)} method of
* the {@link java.nio.channels.FileChannel} class, passing arguments of
* <tt>true</tt> and <tt>false</tt>, respectively, except that they always
* apply to every I/O operation and are therefore often more efficient. If
* the file resides on a local storage device then when an invocation of a
* method of this class returns it is guaranteed that all changes made to
* the file by that invocation will have been written to that device. This
* is useful for ensuring that critical information is not lost in the
* event of a system crash. If the file does not reside on a local device
* then no such guarantee is made.
*
* <p> The <tt>"rwd"</tt> mode can be used to reduce the number of I/O
* operations performed. Using <tt>"rwd"</tt> only requires updates to the
* file's content to be written to storage; using <tt>"rws"</tt> requires
* updates to both the file's content and its metadata to be written, which
* generally requires at least one more low-level I/O operation.
*
* <p> If there is a security manager, its <code>checkRead</code> method is
* called with the pathname of the <code>file</code> argument as its
* argument to see if read access to the file is allowed. If the mode
* allows writing, the security manager's <code>checkWrite</code> method is
* also called with the path argument to see if write access to the file is
* allowed.
* {@description.close}
*
* @param file the file object
* @param mode the access mode, as described
* <a href="#mode">above</a>
* @exception IllegalArgumentException if the mode argument is not equal
* to one of <tt>"r"</tt>, <tt>"rw"</tt>, <tt>"rws"</tt>, or
* <tt>"rwd"</tt>
* @exception FileNotFoundException
* if the mode is <tt>"r"</tt> but the given file object does
* not denote an existing regular file, or if the mode begins
* with <tt>"rw"</tt> but the given file object does not denote
* an existing, writable regular file and a new regular file of
* that name cannot be created, or if some other error occurs
* while opening or creating the file
* @exception SecurityException if a security manager exists and its
* <code>checkRead</code> method denies read access to the file
* or the mode is "rw" and the security manager's
* <code>checkWrite</code> method denies write access to the file
* @see java.lang.SecurityManager#checkRead(java.lang.String)
* @see java.lang.SecurityManager#checkWrite(java.lang.String)
* @see java.nio.channels.FileChannel#force(boolean)
* @revised 1.4
* @spec JSR-51
*/
public RandomAccessFile(File file, String mode)
throws FileNotFoundException
{
String name = (file != null ? file.getPath() : null);
int imode = -1;
if (mode.equals("r"))
imode = O_RDONLY;
else if (mode.startsWith("rw")) {
imode = O_RDWR;
rw = true;
if (mode.length() > 2) {
if (mode.equals("rws"))
imode |= O_SYNC;
else if (mode.equals("rwd"))
imode |= O_DSYNC;
else
imode = -1;
}
}
if (imode < 0)
throw new IllegalArgumentException("Illegal mode \"" + mode
+ "\" must be one of "
+ "\"r\", \"rw\", \"rws\","
+ " or \"rwd\"");
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(name);
if (rw) {
security.checkWrite(name);
}
}
if (name == null) {
throw new NullPointerException();
}
fd = new FileDescriptor();
fd.incrementAndGetUseCount();
open(name, imode);
}
/** {@collect.stats}
* {@description.open}
* Returns the opaque file descriptor object associated with this
* stream. </p>
* {@description.close}
*
* @return the file descriptor object associated with this stream.
* @exception IOException if an I/O error occurs.
* @see java.io.FileDescriptor
*/
public final FileDescriptor getFD() throws IOException {
if (fd != null) return fd;
throw new IOException();
}
/** {@collect.stats}
* {@description.open}
* Returns the unique {@link java.nio.channels.FileChannel FileChannel}
* object associated with this file.
*
* <p> The {@link java.nio.channels.FileChannel#position()
* </code>position<code>} of the returned channel will always be equal to
* this object's file-pointer offset as returned by the {@link
* #getFilePointer getFilePointer} method. Changing this object's
* file-pointer offset, whether explicitly or by reading or writing bytes,
* will change the position of the channel, and vice versa. Changing the
* file's length via this object will change the length seen via the file
* channel, and vice versa.
* {@description.close}
*
* @return the file channel associated with this file
*
* @since 1.4
* @spec JSR-51
*/
public final FileChannel getChannel() {
synchronized (this) {
if (channel == null) {
channel = FileChannelImpl.open(fd, true, rw, this);
/*
* FileDescriptor could be shared by FileInputStream or
* FileOutputStream.
* Ensure that FD is GC'ed only when all the streams/channels
* are done using it.
* Increment fd's use count. Invoking the channel's close()
* method will result in decrementing the use count set for
* the channel.
*/
fd.incrementAndGetUseCount();
}
return channel;
}
}
/** {@collect.stats}
* {@description.open}
* Opens a file and returns the file descriptor. The file is
* opened in read-write mode if the O_RDWR bit in <code>mode</code>
* is true, else the file is opened as read-only.
* If the <code>name</code> refers to a directory, an IOException
* is thrown.
* {@description.close}
*
* @param name the name of the file
* @param mode the mode flags, a combination of the O_ constants
* defined above
*/
private native void open(String name, int mode)
throws FileNotFoundException;
// 'Read' primitives
/** {@collect.stats}
* {@description.open}
* Reads a byte of data from this file. The byte is returned as an
* integer in the range 0 to 255 (<code>0x00-0x0ff</code>).
* {@description.close}
* {@description.open blocking}
* This
* method blocks if no input is yet available.
* {@description.close}
* {@description.open}
* <p>
* Although <code>RandomAccessFile</code> is not a subclass of
* <code>InputStream</code>, this method behaves in exactly the same
* way as the {@link InputStream#read()} method of
* <code>InputStream</code>.
* {@description.close}
*
* @return the next byte of data, or <code>-1</code> if the end of the
* file has been reached.
* @exception IOException if an I/O error occurs. Not thrown if
* end-of-file has been reached.
*/
public native int read() throws IOException;
/** {@collect.stats}
* {@description.open}
* Reads a sub array as a sequence of bytes.
* {@description.close}
* @param b the buffer into which the data is read.
* @param off the start offset of the data.
* @param len the number of bytes to read.
* @exception IOException If an I/O error has occurred.
*/
private native int readBytes(byte b[], int off, int len) throws IOException;
/** {@collect.stats}
* {@description.open}
* Reads up to <code>len</code> bytes of data from this file into an
* array of bytes.
* {@description.close}
* {@description.open blocking}
* This method blocks until at least one byte of input
* is available.
* {@description.close}
* {@description.open}
* <p>
* Although <code>RandomAccessFile</code> is not a subclass of
* <code>InputStream</code>, this method behaves in exactly the
* same way as the {@link InputStream#read(byte[], int, int)} method of
* <code>InputStream</code>.
* {@description.close}
*
* @param b the buffer into which the data is read.
* @param off the start offset in array <code>b</code>
* at which the data is written.
* @param len the maximum number of bytes read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the file has been reached.
* @exception IOException If the first byte cannot be read for any reason
* other than end of file, or if the random access file has been closed, or if
* some other I/O error occurs.
* @exception NullPointerException If <code>b</code> is <code>null</code>.
* @exception IndexOutOfBoundsException If <code>off</code> is negative,
* <code>len</code> is negative, or <code>len</code> is greater than
* <code>b.length - off</code>
*/
public int read(byte b[], int off, int len) throws IOException {
return readBytes(b, off, len);
}
/** {@collect.stats}
* {@description.open}
* Reads up to <code>b.length</code> bytes of data from this file
* into an array of bytes.
* {@description.close}
* {@description.open blocking}
* This method blocks until at least one byte
* of input is available.
* {@description.close}
* {@description.open}
* <p>
* Although <code>RandomAccessFile</code> is not a subclass of
* <code>InputStream</code>, this method behaves in exactly the
* same way as the {@link InputStream#read(byte[])} method of
* <code>InputStream</code>.
* {@description.close}
*
* @param b the buffer into which the data is read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* this file has been reached.
* @exception IOException If the first byte cannot be read for any reason
* other than end of file, or if the random access file has been closed, or if
* some other I/O error occurs.
* @exception NullPointerException If <code>b</code> is <code>null</code>.
*/
public int read(byte b[]) throws IOException {
return readBytes(b, 0, b.length);
}
/** {@collect.stats}
* {@description.open}
* Reads <code>b.length</code> bytes from this file into the byte
* array, starting at the current file pointer. This method reads
* repeatedly from the file until the requested number of bytes are
* read.
* {@description.close}
* {@description.open blocking}
* This method blocks until the requested number of bytes are
* read, the end of the stream is detected, or an exception is thrown.
* {@description.close}
*
* @param b the buffer into which the data is read.
* @exception EOFException if this file reaches the end before reading
* all the bytes.
* @exception IOException if an I/O error occurs.
*/
public final void readFully(byte b[]) throws IOException {
readFully(b, 0, b.length);
}
/** {@collect.stats}
* {@description.open}
* Reads exactly <code>len</code> bytes from this file into the byte
* array, starting at the current file pointer. This method reads
* repeatedly from the file until the requested number of bytes are
* read.
* {@description.close}
* {@description.open blocking}
* This method blocks until the requested number of bytes are
* read, the end of the stream is detected, or an exception is thrown.
* {@description.close}
*
* @param b the buffer into which the data is read.
* @param off the start offset of the data.
* @param len the number of bytes to read.
* @exception EOFException if this file reaches the end before reading
* all the bytes.
* @exception IOException if an I/O error occurs.
*/
public final void readFully(byte b[], int off, int len) throws IOException {
int n = 0;
do {
int count = this.read(b, off + n, len - n);
if (count < 0)
throw new EOFException();
n += count;
} while (n < len);
}
/** {@collect.stats}
* {@description.open}
* Attempts to skip over <code>n</code> bytes of input discarding the
* skipped bytes.
* <p>
*
* This method may skip over some smaller number of bytes, possibly zero.
* This may result from any of a number of conditions; reaching end of
* file before <code>n</code> bytes have been skipped is only one
* possibility. This method never throws an <code>EOFException</code>.
* The actual number of bytes skipped is returned. If <code>n</code>
* is negative, no bytes are skipped.
* {@description.close}
*
* @param n the number of bytes to be skipped.
* @return the actual number of bytes skipped.
* @exception IOException if an I/O error occurs.
*/
public int skipBytes(int n) throws IOException {
long pos;
long len;
long newpos;
if (n <= 0) {
return 0;
}
pos = getFilePointer();
len = length();
newpos = pos + n;
if (newpos > len) {
newpos = len;
}
seek(newpos);
/* return the actual number of bytes skipped */
return (int) (newpos - pos);
}
// 'Write' primitives
/** {@collect.stats}
* {@description.open}
* Writes the specified byte to this file. The write starts at
* the current file pointer.
* {@description.close}
*
* @param b the <code>byte</code> to be written.
* @exception IOException if an I/O error occurs.
*/
public native void write(int b) throws IOException;
/** {@collect.stats}
* {@description.open}
* Writes a sub array as a sequence of bytes.
* {@description.close}
* @param b the data to be written
* @param off the start offset in the data
* @param len the number of bytes that are written
* @exception IOException If an I/O error has occurred.
*/
private native void writeBytes(byte b[], int off, int len) throws IOException;
/** {@collect.stats}
* {@description.open}
* Writes <code>b.length</code> bytes from the specified byte array
* to this file, starting at the current file pointer.
* {@description.close}
*
* @param b the data.
* @exception IOException if an I/O error occurs.
*/
public void write(byte b[]) throws IOException {
writeBytes(b, 0, b.length);
}
/** {@collect.stats}
* {@description.open}
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this file.
* {@description.close}
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
*/
public void write(byte b[], int off, int len) throws IOException {
writeBytes(b, off, len);
}
// 'Random access' stuff
/** {@collect.stats}
* {@description.open}
* Returns the current offset in this file.
* {@description.close}
*
* @return the offset from the beginning of the file, in bytes,
* at which the next read or write occurs.
* @exception IOException if an I/O error occurs.
*/
public native long getFilePointer() throws IOException;
/** {@collect.stats}
* {@description.open}
* Sets the file-pointer offset, measured from the beginning of this
* file, at which the next read or write occurs. The offset may be
* set beyond the end of the file. Setting the offset beyond the end
* of the file does not change the file length. The file length will
* change only by writing after the offset has been set beyond the end
* of the file.
* {@description.close}
*
* @param pos the offset position, measured in bytes from the
* beginning of the file, at which to set the file
* pointer.
* @exception IOException if <code>pos</code> is less than
* <code>0</code> or if an I/O error occurs.
*/
public native void seek(long pos) throws IOException;
/** {@collect.stats}
* {@description.open}
* Returns the length of this file.
* {@description.close}
*
* @return the length of this file, measured in bytes.
* @exception IOException if an I/O error occurs.
*/
public native long length() throws IOException;
/** {@collect.stats}
* {@description.open}
* Sets the length of this file.
*
* <p> If the present length of the file as returned by the
* <code>length</code> method is greater than the <code>newLength</code>
* argument then the file will be truncated. In this case, if the file
* offset as returned by the <code>getFilePointer</code> method is greater
* than <code>newLength</code> then after this method returns the offset
* will be equal to <code>newLength</code>.
*
* <p> If the present length of the file as returned by the
* <code>length</code> method is smaller than the <code>newLength</code>
* argument then the file will be extended. In this case, the contents of
* the extended portion of the file are not defined.
* {@description.close}
*
* @param newLength The desired length of the file
* @exception IOException If an I/O error occurs
* @since 1.2
*/
public native void setLength(long newLength) throws IOException;
/** {@collect.stats}
* {@description.open}
* Closes this random access file stream and releases any system
* resources associated with the stream.
* {@description.close}
* {@property.open runtime formal:java.io.RandomAccessFile_ManipulateAfterClose}
* A closed random access
* file cannot perform input or output operations and cannot be
* reopened.
* {@property.close}
*
* {@description.open}
* <p> If this file has an associated channel then the channel is closed
* as well.
* {@description.close}
*
* @exception IOException if an I/O error occurs.
*
* @revised 1.4
* @spec JSR-51
*/
public void close() throws IOException {
synchronized (closeLock) {
if (closed) {
return;
}
closed = true;
}
if (channel != null) {
/*
* Decrement FD use count associated with the channel. The FD use
* count is incremented whenever a new channel is obtained from
* this stream.
*/
fd.decrementAndGetUseCount();
channel.close();
}
/*
* Decrement FD use count associated with this stream.
* The count got incremented by FileDescriptor during its construction.
*/
fd.decrementAndGetUseCount();
close0();
}
//
// Some "reading/writing Java data types" methods stolen from
// DataInputStream and DataOutputStream.
//
/** {@collect.stats}
* {@description.open}
* Reads a <code>boolean</code> from this file. This method reads a
* single byte from the file, starting at the current file pointer.
* A value of <code>0</code> represents
* <code>false</code>. Any other value represents <code>true</code>.
* {@description.close}
* {@description.open blocking}
* This method blocks until the byte is read, the end of the stream
* is detected, or an exception is thrown.
* {@description.close}
*
* @return the <code>boolean</code> value read.
* @exception EOFException if this file has reached the end.
* @exception IOException if an I/O error occurs.
*/
public final boolean readBoolean() throws IOException {
int ch = this.read();
if (ch < 0)
throw new EOFException();
return (ch != 0);
}
/** {@collect.stats}
* {@description.open}
* Reads a signed eight-bit value from this file. This method reads a
* byte from the file, starting from the current file pointer.
* If the byte read is <code>b</code>, where
* <code>0 <= b <= 255</code>,
* then the result is:
* <blockquote><pre>
* (byte)(b)
* </pre></blockquote>
* <p>
* {@description.close}
* {@description.open blocking}
* This method blocks until the byte is read, the end of the stream
* is detected, or an exception is thrown.
* {@description.close}
*
* @return the next byte of this file as a signed eight-bit
* <code>byte</code>.
* @exception EOFException if this file has reached the end.
* @exception IOException if an I/O error occurs.
*/
public final byte readByte() throws IOException {
int ch = this.read();
if (ch < 0)
throw new EOFException();
return (byte)(ch);
}
/** {@collect.stats}
* {@description.open}
* Reads an unsigned eight-bit number from this file. This method reads
* a byte from this file, starting at the current file pointer,
* and returns that byte.
* <p>
* {@description.close}
* {@description.open blocking}
* This method blocks until the byte is read, the end of the stream
* is detected, or an exception is thrown.
* {@description.close}
*
* @return the next byte of this file, interpreted as an unsigned
* eight-bit number.
* @exception EOFException if this file has reached the end.
* @exception IOException if an I/O error occurs.
*/
public final int readUnsignedByte() throws IOException {
int ch = this.read();
if (ch < 0)
throw new EOFException();
return ch;
}
/** {@collect.stats}
* {@description.open}
* Reads a signed 16-bit number from this file. The method reads two
* bytes from this file, starting at the current file pointer.
* If the two bytes read, in order, are
* <code>b1</code> and <code>b2</code>, where each of the two values is
* between <code>0</code> and <code>255</code>, inclusive, then the
* result is equal to:
* <blockquote><pre>
* (short)((b1 << 8) | b2)
* </pre></blockquote>
* <p>
* {@description.close}
* {@description.open blocking}
* This method blocks until the two bytes are read, the end of the
* stream is detected, or an exception is thrown.
* {@description.close}
*
* @return the next two bytes of this file, interpreted as a signed
* 16-bit number.
* @exception EOFException if this file reaches the end before reading
* two bytes.
* @exception IOException if an I/O error occurs.
*/
public final short readShort() throws IOException {
int ch1 = this.read();
int ch2 = this.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (short)((ch1 << 8) + (ch2 << 0));
}
/** {@collect.stats}
* {@description.open}
* Reads an unsigned 16-bit number from this file. This method reads
* two bytes from the file, starting at the current file pointer.
* If the bytes read, in order, are
* <code>b1</code> and <code>b2</code>, where
* <code>0 <= b1, b2 <= 255</code>,
* then the result is equal to:
* <blockquote><pre>
* (b1 << 8) | b2
* </pre></blockquote>
* <p>
* {@description.close}
* {@description.open blocking}
* This method blocks until the two bytes are read, the end of the
* stream is detected, or an exception is thrown.
* {@description.close}
*
* @return the next two bytes of this file, interpreted as an unsigned
* 16-bit integer.
* @exception EOFException if this file reaches the end before reading
* two bytes.
* @exception IOException if an I/O error occurs.
*/
public final int readUnsignedShort() throws IOException {
int ch1 = this.read();
int ch2 = this.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (ch1 << 8) + (ch2 << 0);
}
/** {@collect.stats}
* {@description.open}
* Reads a character from this file. This method reads two
* bytes from the file, starting at the current file pointer.
* If the bytes read, in order, are
* <code>b1</code> and <code>b2</code>, where
* <code>0 <= b1, b2 <= 255</code>,
* then the result is equal to:
* <blockquote><pre>
* (char)((b1 << 8) | b2)
* </pre></blockquote>
* <p>
* {@description.close}
* {@description.open blocking}
* This method blocks until the two bytes are read, the end of the
* stream is detected, or an exception is thrown.
* {@description.close}
*
* @return the next two bytes of this file, interpreted as a
* <code>char</code>.
* @exception EOFException if this file reaches the end before reading
* two bytes.
* @exception IOException if an I/O error occurs.
*/
public final char readChar() throws IOException {
int ch1 = this.read();
int ch2 = this.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (char)((ch1 << 8) + (ch2 << 0));
}
/** {@collect.stats}
* {@description.open}
* Reads a signed 32-bit integer from this file. This method reads 4
* bytes from the file, starting at the current file pointer.
* If the bytes read, in order, are <code>b1</code>,
* <code>b2</code>, <code>b3</code>, and <code>b4</code>, where
* <code>0 <= b1, b2, b3, b4 <= 255</code>,
* then the result is equal to:
* <blockquote><pre>
* (b1 << 24) | (b2 << 16) + (b3 << 8) + b4
* </pre></blockquote>
* <p>
* {@description.close}
* {@description.open blocking}
* This method blocks until the four bytes are read, the end of the
* stream is detected, or an exception is thrown.
* {@description.close}
*
* @return the next four bytes of this file, interpreted as an
* <code>int</code>.
* @exception EOFException if this file reaches the end before reading
* four bytes.
* @exception IOException if an I/O error occurs.
*/
public final int readInt() throws IOException {
int ch1 = this.read();
int ch2 = this.read();
int ch3 = this.read();
int ch4 = this.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
}
/** {@collect.stats}
* {@description.open}
* Reads a signed 64-bit integer from this file. This method reads eight
* bytes from the file, starting at the current file pointer.
* If the bytes read, in order, are
* <code>b1</code>, <code>b2</code>, <code>b3</code>,
* <code>b4</code>, <code>b5</code>, <code>b6</code>,
* <code>b7</code>, and <code>b8,</code> where:
* <blockquote><pre>
* 0 <= b1, b2, b3, b4, b5, b6, b7, b8 <=255,
* </pre></blockquote>
* <p>
* then the result is equal to:
* <p><blockquote><pre>
* ((long)b1 << 56) + ((long)b2 << 48)
* + ((long)b3 << 40) + ((long)b4 << 32)
* + ((long)b5 << 24) + ((long)b6 << 16)
* + ((long)b7 << 8) + b8
* </pre></blockquote>
* <p>
* {@description.close}
* {@description.open blocking}
* This method blocks until the eight bytes are read, the end of the
* stream is detected, or an exception is thrown.
* {@description.close}
*
* @return the next eight bytes of this file, interpreted as a
* <code>long</code>.
* @exception EOFException if this file reaches the end before reading
* eight bytes.
* @exception IOException if an I/O error occurs.
*/
public final long readLong() throws IOException {
return ((long)(readInt()) << 32) + (readInt() & 0xFFFFFFFFL);
}
/** {@collect.stats}
* {@description.open}
* Reads a <code>float</code> from this file. This method reads an
* <code>int</code> value, starting at the current file pointer,
* as if by the <code>readInt</code> method
* and then converts that <code>int</code> to a <code>float</code>
* using the <code>intBitsToFloat</code> method in class
* <code>Float</code>.
* <p>
* {@description.close}
* {@description.open blocking}
* This method blocks until the four bytes are read, the end of the
* stream is detected, or an exception is thrown.
* {@description.close}
*
* @return the next four bytes of this file, interpreted as a
* <code>float</code>.
* @exception EOFException if this file reaches the end before reading
* four bytes.
* @exception IOException if an I/O error occurs.
* @see java.io.RandomAccessFile#readInt()
* @see java.lang.Float#intBitsToFloat(int)
*/
public final float readFloat() throws IOException {
return Float.intBitsToFloat(readInt());
}
/** {@collect.stats}
* {@description.open}
* Reads a <code>double</code> from this file. This method reads a
* <code>long</code> value, starting at the current file pointer,
* as if by the <code>readLong</code> method
* and then converts that <code>long</code> to a <code>double</code>
* using the <code>longBitsToDouble</code> method in
* class <code>Double</code>.
* <p>
* {@description.close}
* {@description.open blocking}
* This method blocks until the eight bytes are read, the end of the
* stream is detected, or an exception is thrown.
* {@description.close}
*
* @return the next eight bytes of this file, interpreted as a
* <code>double</code>.
* @exception EOFException if this file reaches the end before reading
* eight bytes.
* @exception IOException if an I/O error occurs.
* @see java.io.RandomAccessFile#readLong()
* @see java.lang.Double#longBitsToDouble(long)
*/
public final double readDouble() throws IOException {
return Double.longBitsToDouble(readLong());
}
/** {@collect.stats}
* {@description.open}
* Reads the next line of text from this file. This method successively
* reads bytes from the file, starting at the current file pointer,
* until it reaches a line terminator or the end
* of the file. Each byte is converted into a character by taking the
* byte's value for the lower eight bits of the character and setting the
* high eight bits of the character to zero. This method does not,
* therefore, support the full Unicode character set.
*
* <p> A line of text is terminated by a carriage-return character
* (<code>'\r'</code>), a newline character (<code>'\n'</code>), a
* carriage-return character immediately followed by a newline character,
* or the end of the file. Line-terminating characters are discarded and
* are not included as part of the string returned.
* {@description.close}
*
* {@description.open blocking}
* <p> This method blocks until a newline character is read, a carriage
* return and the byte following it are read (to see if it is a newline),
* the end of the file is reached, or an exception is thrown.
* {@description.close}
*
* @return the next line of text from this file, or null if end
* of file is encountered before even one byte is read.
* @exception IOException if an I/O error occurs.
*/
public final String readLine() throws IOException {
StringBuffer input = new StringBuffer();
int c = -1;
boolean eol = false;
while (!eol) {
switch (c = read()) {
case -1:
case '\n':
eol = true;
break;
case '\r':
eol = true;
long cur = getFilePointer();
if ((read()) != '\n') {
seek(cur);
}
break;
default:
input.append((char)c);
break;
}
}
if ((c == -1) && (input.length() == 0)) {
return null;
}
return input.toString();
}
/** {@collect.stats}
* {@description.open}
* Reads in a string from this file. The string has been encoded
* using a
* <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
* format.
* <p>
* The first two bytes are read, starting from the current file
* pointer, as if by
* <code>readUnsignedShort</code>. This value gives the number of
* following bytes that are in the encoded string, not
* the length of the resulting string. The following bytes are then
* interpreted as bytes encoding characters in the modified UTF-8 format
* and are converted into characters.
* {@description.close}
* {@description.open blocking}
* <p>
* This method blocks until all the bytes are read, the end of the
* stream is detected, or an exception is thrown.
* {@description.close}
*
* @return a Unicode string.
* @exception EOFException if this file reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
* @exception UTFDataFormatException if the bytes do not represent
* valid modified UTF-8 encoding of a Unicode string.
* @see java.io.RandomAccessFile#readUnsignedShort()
*/
public final String readUTF() throws IOException {
return DataInputStream.readUTF(this);
}
/** {@collect.stats}
* {@description.open}
* Writes a <code>boolean</code> to the file as a one-byte value. The
* value <code>true</code> is written out as the value
* <code>(byte)1</code>; the value <code>false</code> is written out
* as the value <code>(byte)0</code>. The write starts at
* the current position of the file pointer.
* {@description.close}
*
* @param v a <code>boolean</code> value to be written.
* @exception IOException if an I/O error occurs.
*/
public final void writeBoolean(boolean v) throws IOException {
write(v ? 1 : 0);
//written++;
}
/** {@collect.stats}
* {@description.open}
* Writes a <code>byte</code> to the file as a one-byte value. The
* write starts at the current position of the file pointer.
* {@description.close}
*
* @param v a <code>byte</code> value to be written.
* @exception IOException if an I/O error occurs.
*/
public final void writeByte(int v) throws IOException {
write(v);
//written++;
}
/** {@collect.stats}
* {@description.open}
* Writes a <code>short</code> to the file as two bytes, high byte first.
* The write starts at the current position of the file pointer.
* {@description.close}
*
* @param v a <code>short</code> to be written.
* @exception IOException if an I/O error occurs.
*/
public final void writeShort(int v) throws IOException {
write((v >>> 8) & 0xFF);
write((v >>> 0) & 0xFF);
//written += 2;
}
/** {@collect.stats}
* {@description.open}
* Writes a <code>char</code> to the file as a two-byte value, high
* byte first. The write starts at the current position of the
* file pointer.
* {@description.close}
*
* @param v a <code>char</code> value to be written.
* @exception IOException if an I/O error occurs.
*/
public final void writeChar(int v) throws IOException {
write((v >>> 8) & 0xFF);
write((v >>> 0) & 0xFF);
//written += 2;
}
/** {@collect.stats}
* {@description.open}
* Writes an <code>int</code> to the file as four bytes, high byte first.
* The write starts at the current position of the file pointer.
* {@description.close}
*
* @param v an <code>int</code> to be written.
* @exception IOException if an I/O error occurs.
*/
public final void writeInt(int v) throws IOException {
write((v >>> 24) & 0xFF);
write((v >>> 16) & 0xFF);
write((v >>> 8) & 0xFF);
write((v >>> 0) & 0xFF);
//written += 4;
}
/** {@collect.stats}
* {@description.open}
* Writes a <code>long</code> to the file as eight bytes, high byte first.
* The write starts at the current position of the file pointer.
* {@description.close}
*
* @param v a <code>long</code> to be written.
* @exception IOException if an I/O error occurs.
*/
public final void writeLong(long v) throws IOException {
write((int)(v >>> 56) & 0xFF);
write((int)(v >>> 48) & 0xFF);
write((int)(v >>> 40) & 0xFF);
write((int)(v >>> 32) & 0xFF);
write((int)(v >>> 24) & 0xFF);
write((int)(v >>> 16) & 0xFF);
write((int)(v >>> 8) & 0xFF);
write((int)(v >>> 0) & 0xFF);
//written += 8;
}
/** {@collect.stats}
* {@description.open}
* Converts the float argument to an <code>int</code> using the
* <code>floatToIntBits</code> method in class <code>Float</code>,
* and then writes that <code>int</code> value to the file as a
* four-byte quantity, high byte first. The write starts at the
* current position of the file pointer.
* {@description.close}
*
* @param v a <code>float</code> value to be written.
* @exception IOException if an I/O error occurs.
* @see java.lang.Float#floatToIntBits(float)
*/
public final void writeFloat(float v) throws IOException {
writeInt(Float.floatToIntBits(v));
}
/** {@collect.stats}
* {@description.open}
* Converts the double argument to a <code>long</code> using the
* <code>doubleToLongBits</code> method in class <code>Double</code>,
* and then writes that <code>long</code> value to the file as an
* eight-byte quantity, high byte first. The write starts at the current
* position of the file pointer.
* {@description.close}
*
* @param v a <code>double</code> value to be written.
* @exception IOException if an I/O error occurs.
* @see java.lang.Double#doubleToLongBits(double)
*/
public final void writeDouble(double v) throws IOException {
writeLong(Double.doubleToLongBits(v));
}
/** {@collect.stats}
* {@description.open}
* Writes the string to the file as a sequence of bytes. Each
* character in the string is written out, in sequence, by discarding
* its high eight bits. The write starts at the current position of
* the file pointer.
* {@description.close}
*
* @param s a string of bytes to be written.
* @exception IOException if an I/O error occurs.
*/
public final void writeBytes(String s) throws IOException {
int len = s.length();
byte[] b = new byte[len];
s.getBytes(0, len, b, 0);
writeBytes(b, 0, len);
}
/** {@collect.stats}
* {@description.open}
* Writes a string to the file as a sequence of characters. Each
* character is written to the data output stream as if by the
* <code>writeChar</code> method. The write starts at the current
* position of the file pointer.
* {@description.close}
*
* @param s a <code>String</code> value to be written.
* @exception IOException if an I/O error occurs.
* @see java.io.RandomAccessFile#writeChar(int)
*/
public final void writeChars(String s) throws IOException {
int clen = s.length();
int blen = 2*clen;
byte[] b = new byte[blen];
char[] c = new char[clen];
s.getChars(0, clen, c, 0);
for (int i = 0, j = 0; i < clen; i++) {
b[j++] = (byte)(c[i] >>> 8);
b[j++] = (byte)(c[i] >>> 0);
}
writeBytes(b, 0, blen);
}
/** {@collect.stats}
* {@description.open}
* Writes a string to the file using
* <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
* encoding in a machine-independent manner.
* <p>
* First, two bytes are written to the file, starting at the
* current file pointer, as if by the
* <code>writeShort</code> method giving the number of bytes to
* follow. This value is the number of bytes actually written out,
* not the length of the string. Following the length, each character
* of the string is output, in sequence, using the modified UTF-8 encoding
* for each character.
* {@description.close}
*
* @param str a string to be written.
* @exception IOException if an I/O error occurs.
*/
public final void writeUTF(String str) throws IOException {
DataOutputStream.writeUTF(str, this);
}
private static native void initIDs();
private native void close0() throws IOException;
static {
initIDs();
}
}
|
Java
|
/*
* Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
/** {@collect.stats}
* {@description.open}
* This class implements a character buffer that can be used as a
* character-input stream.
* {@description.close}
*
* @author Herb Jellinek
* @since JDK1.1
*/
public class CharArrayReader extends Reader {
/** {@collect.stats}
* {@description.open}
* The character buffer.
* {@description.close}
*/
protected char buf[];
/** {@collect.stats}
* {@description.open}
* The current buffer position.
* {@description.close}
*/
protected int pos;
/** {@collect.stats}
* {@description.open}
* The position of mark in buffer.
* {@description.close}
*/
protected int markedPos = 0;
/** {@collect.stats}
* {@description.open}
* The index of the end of this buffer. There is not valid
* data at or beyond this index.
* {@description.close}
*/
protected int count;
/** {@collect.stats}
* {@description.open}
* Creates a CharArrayReader from the specified array of chars.
* {@description.close}
* @param buf Input buffer (not copied)
*/
public CharArrayReader(char buf[]) {
this.buf = buf;
this.pos = 0;
this.count = buf.length;
}
/** {@collect.stats}
* {@description.open}
* Creates a CharArrayReader from the specified array of chars.
*
* <p> The resulting reader will start reading at the given
* <tt>offset</tt>. The total number of <tt>char</tt> values that can be
* read from this reader will be either <tt>length</tt> or
* <tt>buf.length-offset</tt>, whichever is smaller.
* {@description.close}
*
* @throws IllegalArgumentException
* If <tt>offset</tt> is negative or greater than
* <tt>buf.length</tt>, or if <tt>length</tt> is negative, or if
* the sum of these two values is negative.
*
* @param buf Input buffer (not copied)
* @param offset Offset of the first char to read
* @param length Number of chars to read
*/
public CharArrayReader(char buf[], int offset, int length) {
if ((offset < 0) || (offset > buf.length) || (length < 0) ||
((offset + length) < 0)) {
throw new IllegalArgumentException();
}
this.buf = buf;
this.pos = offset;
this.count = Math.min(offset + length, buf.length);
this.markedPos = offset;
}
/** {@collect.stats}
* {@description.open}
* Checks to make sure that the stream has not been closed
* {@description.close}
*/
private void ensureOpen() throws IOException {
if (buf == null)
throw new IOException("Stream closed");
}
/** {@collect.stats}
* {@description.open}
* Reads a single character.
* {@description.close}
*
* @exception IOException If an I/O error occurs
*/
public int read() throws IOException {
synchronized (lock) {
ensureOpen();
if (pos >= count)
return -1;
else
return buf[pos++];
}
}
/** {@collect.stats}
* {@description.open}
* Reads characters into a portion of an array.
* {@description.close}
* @param b Destination buffer
* @param off Offset at which to start storing characters
* @param len Maximum number of characters to read
* @return The actual number of characters read, or -1 if
* the end of the stream has been reached
*
* @exception IOException If an I/O error occurs
*/
public int read(char b[], int off, int len) throws IOException {
synchronized (lock) {
ensureOpen();
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
if (pos >= count) {
return -1;
}
if (pos + len > count) {
len = count - pos;
}
if (len <= 0) {
return 0;
}
System.arraycopy(buf, pos, b, off, len);
pos += len;
return len;
}
}
/** {@collect.stats}
* {@description.open}
* Skips characters. Returns the number of characters that were skipped.
*
* <p>The <code>n</code> parameter may be negative, even though the
* <code>skip</code> method of the {@link Reader} superclass throws
* an exception in this case. If <code>n</code> is negative, then
* this method does nothing and returns <code>0</code>.
* {@description.close}
*
* @param n The number of characters to skip
* @return The number of characters actually skipped
* @exception IOException If the stream is closed, or an I/O error occurs
*/
public long skip(long n) throws IOException {
synchronized (lock) {
ensureOpen();
if (pos + n > count) {
n = count - pos;
}
if (n < 0) {
return 0;
}
pos += n;
return n;
}
}
/** {@collect.stats}
* {@description.open}
* Tells whether this stream is ready to be read. Character-array readers
* are always ready to be read.
* {@description.close}
*
* @exception IOException If an I/O error occurs
*/
public boolean ready() throws IOException {
synchronized (lock) {
ensureOpen();
return (count - pos) > 0;
}
}
/** {@collect.stats}
* {@property.open runtime formal:java.io.Reader_MarkReset}
* Tells whether this stream supports the mark() operation, which it does.
* {@property.close}
*/
public boolean markSupported() {
return true;
}
/** {@collect.stats}
* {@description.open}
* Marks the present position in the stream. Subsequent calls to reset()
* will reposition the stream to this point.
* {@description.close}
*
* @param readAheadLimit Limit on the number of characters that may be
* read while still preserving the mark. Because
* the stream's input comes from a character array,
* there is no actual limit; hence this argument is
* ignored.
*
* @exception IOException If an I/O error occurs
*/
public void mark(int readAheadLimit) throws IOException {
synchronized (lock) {
ensureOpen();
markedPos = pos;
}
}
/** {@collect.stats}
* {@property.open runtime formal:java.io.Reader_UnmarkedReset}
* Resets the stream to the most recent mark, or to the beginning if it has
* never been marked.
* {@property.close}
*
* @exception IOException If an I/O error occurs
*/
public void reset() throws IOException {
synchronized (lock) {
ensureOpen();
pos = markedPos;
}
}
/** {@collect.stats}
* {@description.open}
* Closes the stream and releases any system resources associated with
* it.
* {@description.close}
* {@property.open runtime formal:java.io.Reader_ManipulateAfterClose}
* Once the stream has been closed, further read(), ready(),
* mark(), reset(), or skip() invocations will throw an IOException.
* {@property.close}
* {@property.open runtime formal:java.io.Closeable_MultipleClose}
* Closing a previously closed stream has no effect.
* {@property.close}
*/
public void close() {
buf = null;
}
}
|
Java
|
/*
* Copyright (c) 1996, 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 java.io;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.security.AccessController;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import sun.misc.Unsafe;
import sun.reflect.ReflectionFactory;
/** {@collect.stats}
* {@description.open}
* Serialization's descriptor for classes. It contains the name and
* serialVersionUID of the class. The ObjectStreamClass for a specific class
* loaded in this Java VM can be found/created using the lookup method.
*
* <p>The algorithm to compute the SerialVersionUID is described in
* <a href="../../../platform/serialization/spec/class.html#4100">Object
* Serialization Specification, Section 4.6, Stream Unique Identifiers</a>.
* {@description.close}
*
* @author Mike Warres
* @author Roger Riggs
* @see ObjectStreamField
* @see <a href="../../../platform/serialization/spec/class.html">Object Serialization Specification, Section 4, Class Descriptors</a>
* @since JDK1.1
*/
public class ObjectStreamClass implements Serializable {
/** {@collect.stats}
* {@description.open}
* serialPersistentFields value indicating no serializable fields
* {@description.close}
*/
public static final ObjectStreamField[] NO_FIELDS =
new ObjectStreamField[0];
private static final long serialVersionUID = -6120832682080437368L;
private static final ObjectStreamField[] serialPersistentFields =
NO_FIELDS;
/** {@collect.stats}
* {@description.open}
* reflection factory for obtaining serialization constructors
* {@description.close}
*/
private static final ReflectionFactory reflFactory = (ReflectionFactory)
AccessController.doPrivileged(
new ReflectionFactory.GetReflectionFactoryAction());
private static class Caches {
/** {@collect.stats}
* {@description.open}
* cache mapping local classes -> descriptors
* {@description.close}
*/
static final ConcurrentMap<WeakClassKey,Reference<?>> localDescs =
new ConcurrentHashMap<WeakClassKey,Reference<?>>();
/** {@collect.stats}
* {@description.open}
* cache mapping field group/local desc pairs -> field reflectors
* {@description.close}
*/
static final ConcurrentMap<FieldReflectorKey,Reference<?>> reflectors =
new ConcurrentHashMap<FieldReflectorKey,Reference<?>>();
/** {@collect.stats}
* {@description.open}
* queue for WeakReferences to local classes
* {@description.close}
*/
private static final ReferenceQueue<Class<?>> localDescsQueue =
new ReferenceQueue<Class<?>>();
/** {@collect.stats}
* {@description.open}
* queue for WeakReferences to field reflectors keys
* {@description.close}
*/
private static final ReferenceQueue<Class<?>> reflectorsQueue =
new ReferenceQueue<Class<?>>();
}
/** {@collect.stats}
* {@description.open}
* class associated with this descriptor (if any)
* {@description.close}
*/
private Class cl;
/** {@collect.stats}
* {@description.open}
* name of class represented by this descriptor
* {@description.close}
*/
private String name;
/** {@collect.stats}
* {@description.open}
* serialVersionUID of represented class (null if not computed yet)
* {@description.close}
*/
private volatile Long suid;
/** {@collect.stats}
* {@description.open}
* true if represents dynamic proxy class
* {@description.close}
*/
private boolean isProxy;
/** {@collect.stats}
* {@description.open}
* true if represents enum type
* {@description.close}
*/
private boolean isEnum;
/** {@collect.stats}
* {@description.open}
* true if represented class implements Serializable
* {@description.close}
*/
private boolean serializable;
/** {@collect.stats}
* {@description.open}
* true if represented class implements Externalizable
* {@description.close}
*/
private boolean externalizable;
/** {@collect.stats}
* {@description.open}
* true if desc has data written by class-defined writeObject method
* {@description.close}
*/
private boolean hasWriteObjectData;
/** {@collect.stats}
* {@description.open}
* true if desc has externalizable data written in block data format; this
* must be true by default to accommodate ObjectInputStream subclasses which
* override readClassDescriptor() to return class descriptors obtained from
* ObjectStreamClass.lookup() (see 4461737)
* {@description.close}
*/
private boolean hasBlockExternalData = true;
/** {@collect.stats}
* {@description.open}
* exception (if any) thrown while attempting to resolve class
* {@description.close}
*/
private ClassNotFoundException resolveEx;
/** {@collect.stats}
* {@description.open}
* exception (if any) to throw if non-enum deserialization attempted
* {@description.close}
*/
private InvalidClassException deserializeEx;
/** {@collect.stats}
* {@description.open}
* exception (if any) to throw if non-enum serialization attempted
* {@description.close}
*/
private InvalidClassException serializeEx;
/** {@collect.stats}
* {@description.open}
* exception (if any) to throw if default serialization attempted
* {@description.close}
*/
private InvalidClassException defaultSerializeEx;
/** {@collect.stats}
* {@description.open}
* serializable fields
* {@description.close}
*/
private ObjectStreamField[] fields;
/** {@collect.stats}
* {@description.open}
* aggregate marshalled size of primitive fields
* {@description.close}
*/
private int primDataSize;
/** {@collect.stats}
* {@description.open}
* number of non-primitive fields
* {@description.close}
*/
private int numObjFields;
/** {@collect.stats}
* {@description.open}
* reflector for setting/getting serializable field values
* {@description.close}
*/
private FieldReflector fieldRefl;
/** {@collect.stats}
* {@description.open}
* data layout of serialized objects described by this class desc
* {@description.close}
*/
private volatile ClassDataSlot[] dataLayout;
/** {@collect.stats}
* {@description.open}
* serialization-appropriate constructor, or null if none
* {@description.close}
*/
private Constructor cons;
/** {@collect.stats}
* {@description.open}
* class-defined writeObject method, or null if none
* {@description.close}
*/
private Method writeObjectMethod;
/** {@collect.stats}
* {@description.open}
* class-defined readObject method, or null if none
* {@description.close}
*/
private Method readObjectMethod;
/** {@collect.stats}
* {@description.open}
* class-defined readObjectNoData method, or null if none
* {@description.close}
*/
private Method readObjectNoDataMethod;
/** {@collect.stats}
* {@description.open}
* class-defined writeReplace method, or null if none
* {@description.close}
*/
private Method writeReplaceMethod;
/** {@collect.stats}
* {@description.open}
* class-defined readResolve method, or null if none
* {@description.close}
*/
private Method readResolveMethod;
/** {@collect.stats}
* {@description.open}
* local class descriptor for represented class (may point to self)
* {@description.close}
*/
private ObjectStreamClass localDesc;
/** {@collect.stats}
* {@description.open}
* superclass descriptor appearing in stream
* {@description.close}
*/
private ObjectStreamClass superDesc;
/** {@collect.stats}
* {@description.open}
* Initializes native code.
* {@description.close}
*/
private static native void initNative();
static {
initNative();
}
/** {@collect.stats}
* {@description.open}
* Find the descriptor for a class that can be serialized. Creates an
* ObjectStreamClass instance if one does not exist yet for class. Null is
* returned if the specified class does not implement java.io.Serializable
* or java.io.Externalizable.
* {@description.close}
*
* @param cl class for which to get the descriptor
* @return the class descriptor for the specified class
*/
public static ObjectStreamClass lookup(Class<?> cl) {
return lookup(cl, false);
}
/** {@collect.stats}
* {@description.open}
* Returns the descriptor for any class, regardless of whether it
* implements {@link Serializable}.
* {@description.close}
*
* @param cl class for which to get the descriptor
* @return the class descriptor for the specified class
* @since 1.6
*/
public static ObjectStreamClass lookupAny(Class<?> cl) {
return lookup(cl, true);
}
/** {@collect.stats}
* {@description.open}
* Returns the name of the class described by this descriptor.
* This method returns the name of the class in the format that
* is used by the {@link Class#getName} method.
* {@description.close}
*
* @return a string representing the name of the class
*/
public String getName() {
return name;
}
/** {@collect.stats}
* {@description.open}
* Return the serialVersionUID for this class. The serialVersionUID
* defines a set of classes all with the same name that have evolved from a
* common root class and agree to be serialized and deserialized using a
* common format. NonSerializable classes have a serialVersionUID of 0L.
* {@description.close}
*
* @return the SUID of the class described by this descriptor
*/
public long getSerialVersionUID() {
// REMIND: synchronize instead of relying on volatile?
if (suid == null) {
suid = (Long) AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
return Long.valueOf(computeDefaultSUID(cl));
}
}
);
}
return suid.longValue();
}
/** {@collect.stats}
* {@description.open}
* Return the class in the local VM that this version is mapped to. Null
* is returned if there is no corresponding local class.
* {@description.close}
*
* @return the <code>Class</code> instance that this descriptor represents
*/
public Class<?> forClass() {
return cl;
}
/** {@collect.stats}
* {@description.open}
* Return an array of the fields of this serializable class.
* {@description.close}
*
* @return an array containing an element for each persistent field of
* this class. Returns an array of length zero if there are no
* fields.
* @since 1.2
*/
public ObjectStreamField[] getFields() {
return getFields(true);
}
/** {@collect.stats}
* {@description.open}
* Get the field of this class by name.
* {@description.close}
*
* @param name the name of the data field to look for
* @return The ObjectStreamField object of the named field or null if
* there is no such named field.
*/
public ObjectStreamField getField(String name) {
return getField(name, null);
}
/** {@collect.stats}
* {@description.open}
* Return a string describing this ObjectStreamClass.
* {@description.close}
*/
public String toString() {
return name + ": static final long serialVersionUID = " +
getSerialVersionUID() + "L;";
}
/** {@collect.stats}
* {@description.open}
* Looks up and returns class descriptor for given class, or null if class
* is non-serializable and "all" is set to false.
* {@description.close}
*
* @param cl class to look up
* @param all if true, return descriptors for all classes; if false, only
* return descriptors for serializable classes
*/
static ObjectStreamClass lookup(Class cl, boolean all) {
if (!(all || Serializable.class.isAssignableFrom(cl))) {
return null;
}
processQueue(Caches.localDescsQueue, Caches.localDescs);
WeakClassKey key = new WeakClassKey(cl, Caches.localDescsQueue);
Reference<?> ref = Caches.localDescs.get(key);
Object entry = null;
if (ref != null) {
entry = ref.get();
}
EntryFuture future = null;
if (entry == null) {
EntryFuture newEntry = new EntryFuture();
Reference<?> newRef = new SoftReference<EntryFuture>(newEntry);
do {
if (ref != null) {
Caches.localDescs.remove(key, ref);
}
ref = Caches.localDescs.putIfAbsent(key, newRef);
if (ref != null) {
entry = ref.get();
}
} while (ref != null && entry == null);
if (entry == null) {
future = newEntry;
}
}
if (entry instanceof ObjectStreamClass) { // check common case first
return (ObjectStreamClass) entry;
}
if (entry instanceof EntryFuture) {
future = (EntryFuture) entry;
if (future.getOwner() == Thread.currentThread()) {
/*
* Handle nested call situation described by 4803747: waiting
* for future value to be set by a lookup() call further up the
* stack will result in deadlock, so calculate and set the
* future value here instead.
*/
entry = null;
} else {
entry = future.get();
}
}
if (entry == null) {
try {
entry = new ObjectStreamClass(cl);
} catch (Throwable th) {
entry = th;
}
if (future.set(entry)) {
Caches.localDescs.put(key, new SoftReference<Object>(entry));
} else {
// nested lookup call already set future
entry = future.get();
}
}
if (entry instanceof ObjectStreamClass) {
return (ObjectStreamClass) entry;
} else if (entry instanceof RuntimeException) {
throw (RuntimeException) entry;
} else if (entry instanceof Error) {
throw (Error) entry;
} else {
throw new InternalError("unexpected entry: " + entry);
}
}
/** {@collect.stats}
* {@description.open}
* Placeholder used in class descriptor and field reflector lookup tables
* for an entry in the process of being initialized. (Internal) callers
* which receive an EntryFuture belonging to another thread as the result
* of a lookup should call the get() method of the EntryFuture; this will
* return the actual entry once it is ready for use and has been set(). To
* conserve objects, EntryFutures synchronize on themselves.
* {@description.close}
*/
private static class EntryFuture {
private static final Object unset = new Object();
private final Thread owner = Thread.currentThread();
private Object entry = unset;
/** {@collect.stats}
* {@description.open}
* Attempts to set the value contained by this EntryFuture. If the
* EntryFuture's value has not been set already, then the value is
* saved, any callers blocked in the get() method are notified, and
* true is returned. If the value has already been set, then no saving
* or notification occurs, and false is returned.
* {@description.close}
*/
synchronized boolean set(Object entry) {
if (this.entry != unset) {
return false;
}
this.entry = entry;
notifyAll();
return true;
}
/** {@collect.stats}
* {@description.open}
* Returns the value contained by this EntryFuture, blocking if
* necessary until a value is set.
* {@description.close}
*/
synchronized Object get() {
boolean interrupted = false;
while (entry == unset) {
try {
wait();
} catch (InterruptedException ex) {
interrupted = true;
}
}
if (interrupted) {
AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
Thread.currentThread().interrupt();
return null;
}
}
);
}
return entry;
}
/** {@collect.stats}
* {@description.open}
* Returns the thread that created this EntryFuture.
* {@description.close}
*/
Thread getOwner() {
return owner;
}
}
/** {@collect.stats}
* {@description.open}
* Creates local class descriptor representing given class.
* {@description.close}
*/
private ObjectStreamClass(final Class cl) {
this.cl = cl;
name = cl.getName();
isProxy = Proxy.isProxyClass(cl);
isEnum = Enum.class.isAssignableFrom(cl);
serializable = Serializable.class.isAssignableFrom(cl);
externalizable = Externalizable.class.isAssignableFrom(cl);
Class superCl = cl.getSuperclass();
superDesc = (superCl != null) ? lookup(superCl, false) : null;
localDesc = this;
if (serializable) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
if (isEnum) {
suid = Long.valueOf(0);
fields = NO_FIELDS;
return null;
}
if (cl.isArray()) {
fields = NO_FIELDS;
return null;
}
suid = getDeclaredSUID(cl);
try {
fields = getSerialFields(cl);
computeFieldOffsets();
} catch (InvalidClassException e) {
serializeEx = deserializeEx = e;
fields = NO_FIELDS;
}
if (externalizable) {
cons = getExternalizableConstructor(cl);
} else {
cons = getSerializableConstructor(cl);
writeObjectMethod = getPrivateMethod(cl, "writeObject",
new Class[] { ObjectOutputStream.class },
Void.TYPE);
readObjectMethod = getPrivateMethod(cl, "readObject",
new Class[] { ObjectInputStream.class },
Void.TYPE);
readObjectNoDataMethod = getPrivateMethod(
cl, "readObjectNoData", null, Void.TYPE);
hasWriteObjectData = (writeObjectMethod != null);
}
writeReplaceMethod = getInheritableMethod(
cl, "writeReplace", null, Object.class);
readResolveMethod = getInheritableMethod(
cl, "readResolve", null, Object.class);
return null;
}
});
} else {
suid = Long.valueOf(0);
fields = NO_FIELDS;
}
try {
fieldRefl = getReflector(fields, this);
} catch (InvalidClassException ex) {
// field mismatches impossible when matching local fields vs. self
throw new InternalError();
}
if (deserializeEx == null) {
if (isEnum) {
deserializeEx = new InvalidClassException(name, "enum type");
} else if (cons == null) {
deserializeEx = new InvalidClassException(
name, "no valid constructor");
}
}
for (int i = 0; i < fields.length; i++) {
if (fields[i].getField() == null) {
defaultSerializeEx = new InvalidClassException(
name, "unmatched serializable field(s) declared");
}
}
}
/** {@collect.stats}
* {@property.open runtime formal:java.io.ObjectStreamClass_Initialize}
* Creates blank class descriptor which should be initialized via a
* subsequent call to initProxy(), initNonProxy() or readNonProxy().
* {@property.close}
*/
ObjectStreamClass() {
}
/** {@collect.stats}
* {@description.open}
* Initializes class descriptor representing a proxy class.
* {@description.close}
*/
void initProxy(Class cl,
ClassNotFoundException resolveEx,
ObjectStreamClass superDesc)
throws InvalidClassException
{
this.cl = cl;
this.resolveEx = resolveEx;
this.superDesc = superDesc;
isProxy = true;
serializable = true;
suid = Long.valueOf(0);
fields = NO_FIELDS;
if (cl != null) {
localDesc = lookup(cl, true);
if (!localDesc.isProxy) {
throw new InvalidClassException(
"cannot bind proxy descriptor to a non-proxy class");
}
name = localDesc.name;
externalizable = localDesc.externalizable;
cons = localDesc.cons;
writeReplaceMethod = localDesc.writeReplaceMethod;
readResolveMethod = localDesc.readResolveMethod;
deserializeEx = localDesc.deserializeEx;
}
fieldRefl = getReflector(fields, localDesc);
}
/** {@collect.stats}
* {@description.open}
* Initializes class descriptor representing a non-proxy class.
* {@description.close}
*/
void initNonProxy(ObjectStreamClass model,
Class cl,
ClassNotFoundException resolveEx,
ObjectStreamClass superDesc)
throws InvalidClassException
{
this.cl = cl;
this.resolveEx = resolveEx;
this.superDesc = superDesc;
name = model.name;
suid = Long.valueOf(model.getSerialVersionUID());
isProxy = false;
isEnum = model.isEnum;
serializable = model.serializable;
externalizable = model.externalizable;
hasBlockExternalData = model.hasBlockExternalData;
hasWriteObjectData = model.hasWriteObjectData;
fields = model.fields;
primDataSize = model.primDataSize;
numObjFields = model.numObjFields;
if (cl != null) {
localDesc = lookup(cl, true);
if (localDesc.isProxy) {
throw new InvalidClassException(
"cannot bind non-proxy descriptor to a proxy class");
}
if (isEnum != localDesc.isEnum) {
throw new InvalidClassException(isEnum ?
"cannot bind enum descriptor to a non-enum class" :
"cannot bind non-enum descriptor to an enum class");
}
if (serializable == localDesc.serializable &&
!cl.isArray() &&
suid.longValue() != localDesc.getSerialVersionUID())
{
throw new InvalidClassException(localDesc.name,
"local class incompatible: " +
"stream classdesc serialVersionUID = " + suid +
", local class serialVersionUID = " +
localDesc.getSerialVersionUID());
}
if (!classNamesEqual(name, localDesc.name)) {
throw new InvalidClassException(localDesc.name,
"local class name incompatible with stream class " +
"name \"" + name + "\"");
}
if (!isEnum) {
if ((serializable == localDesc.serializable) &&
(externalizable != localDesc.externalizable))
{
throw new InvalidClassException(localDesc.name,
"Serializable incompatible with Externalizable");
}
if ((serializable != localDesc.serializable) ||
(externalizable != localDesc.externalizable) ||
!(serializable || externalizable))
{
deserializeEx = new InvalidClassException(localDesc.name,
"class invalid for deserialization");
}
}
cons = localDesc.cons;
writeObjectMethod = localDesc.writeObjectMethod;
readObjectMethod = localDesc.readObjectMethod;
readObjectNoDataMethod = localDesc.readObjectNoDataMethod;
writeReplaceMethod = localDesc.writeReplaceMethod;
readResolveMethod = localDesc.readResolveMethod;
if (deserializeEx == null) {
deserializeEx = localDesc.deserializeEx;
}
}
fieldRefl = getReflector(fields, localDesc);
// reassign to matched fields so as to reflect local unshared settings
fields = fieldRefl.getFields();
}
/** {@collect.stats}
* {@description.open}
* Reads non-proxy class descriptor information from given input stream.
* The resulting class descriptor is not fully functional; it can only be
* used as input to the ObjectInputStream.resolveClass() and
* ObjectStreamClass.initNonProxy() methods.
* {@description.close}
*/
void readNonProxy(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
name = in.readUTF();
suid = Long.valueOf(in.readLong());
isProxy = false;
byte flags = in.readByte();
hasWriteObjectData =
((flags & ObjectStreamConstants.SC_WRITE_METHOD) != 0);
hasBlockExternalData =
((flags & ObjectStreamConstants.SC_BLOCK_DATA) != 0);
externalizable =
((flags & ObjectStreamConstants.SC_EXTERNALIZABLE) != 0);
boolean sflag =
((flags & ObjectStreamConstants.SC_SERIALIZABLE) != 0);
if (externalizable && sflag) {
throw new InvalidClassException(
name, "serializable and externalizable flags conflict");
}
serializable = externalizable || sflag;
isEnum = ((flags & ObjectStreamConstants.SC_ENUM) != 0);
if (isEnum && suid.longValue() != 0L) {
throw new InvalidClassException(name,
"enum descriptor has non-zero serialVersionUID: " + suid);
}
int numFields = in.readShort();
if (isEnum && numFields != 0) {
throw new InvalidClassException(name,
"enum descriptor has non-zero field count: " + numFields);
}
fields = (numFields > 0) ?
new ObjectStreamField[numFields] : NO_FIELDS;
for (int i = 0; i < numFields; i++) {
char tcode = (char) in.readByte();
String fname = in.readUTF();
String signature = ((tcode == 'L') || (tcode == '[')) ?
in.readTypeString() : new String(new char[] { tcode });
try {
fields[i] = new ObjectStreamField(fname, signature, false);
} catch (RuntimeException e) {
throw (IOException) new InvalidClassException(name,
"invalid descriptor for field " + fname).initCause(e);
}
}
computeFieldOffsets();
}
/** {@collect.stats}
* {@description.open}
* Writes non-proxy class descriptor information to given output stream.
* {@description.close}
*/
void writeNonProxy(ObjectOutputStream out) throws IOException {
out.writeUTF(name);
out.writeLong(getSerialVersionUID());
byte flags = 0;
if (externalizable) {
flags |= ObjectStreamConstants.SC_EXTERNALIZABLE;
int protocol = out.getProtocolVersion();
if (protocol != ObjectStreamConstants.PROTOCOL_VERSION_1) {
flags |= ObjectStreamConstants.SC_BLOCK_DATA;
}
} else if (serializable) {
flags |= ObjectStreamConstants.SC_SERIALIZABLE;
}
if (hasWriteObjectData) {
flags |= ObjectStreamConstants.SC_WRITE_METHOD;
}
if (isEnum) {
flags |= ObjectStreamConstants.SC_ENUM;
}
out.writeByte(flags);
out.writeShort(fields.length);
for (int i = 0; i < fields.length; i++) {
ObjectStreamField f = fields[i];
out.writeByte(f.getTypeCode());
out.writeUTF(f.getName());
if (!f.isPrimitive()) {
out.writeTypeString(f.getTypeString());
}
}
}
/** {@collect.stats}
* {@description.open}
* Returns ClassNotFoundException (if any) thrown while attempting to
* resolve local class corresponding to this class descriptor.
* {@description.close}
*/
ClassNotFoundException getResolveException() {
return resolveEx;
}
/** {@collect.stats}
* {@description.open}
* Throws an InvalidClassException if object instances referencing this
* class descriptor should not be allowed to deserialize. This method does
* not apply to deserialization of enum constants.
* {@description.close}
*/
void checkDeserialize() throws InvalidClassException {
if (deserializeEx != null) {
InvalidClassException ice =
new InvalidClassException(deserializeEx.classname,
deserializeEx.getMessage());
ice.initCause(deserializeEx);
throw ice;
}
}
/** {@collect.stats}
* {@description.open}
* Throws an InvalidClassException if objects whose class is represented by
* this descriptor should not be allowed to serialize. This method does
* not apply to serialization of enum constants.
* {@description.close}
*/
void checkSerialize() throws InvalidClassException {
if (serializeEx != null) {
InvalidClassException ice =
new InvalidClassException(serializeEx.classname,
serializeEx.getMessage());
ice.initCause(serializeEx);
throw ice;
}
}
/** {@collect.stats}
* {@description.open}
* Throws an InvalidClassException if objects whose class is represented by
* this descriptor should not be permitted to use default serialization
* (e.g., if the class declares serializable fields that do not correspond
* to actual fields, and hence must use the GetField API). This method
* does not apply to deserialization of enum constants.
* {@description.close}
*/
void checkDefaultSerialize() throws InvalidClassException {
if (defaultSerializeEx != null) {
InvalidClassException ice =
new InvalidClassException(defaultSerializeEx.classname,
defaultSerializeEx.getMessage());
ice.initCause(defaultSerializeEx);
throw ice;
}
}
/** {@collect.stats}
* {@description.open}
* Returns superclass descriptor. Note that on the receiving side, the
* superclass descriptor may be bound to a class that is not a superclass
* of the subclass descriptor's bound class.
* {@description.close}
*/
ObjectStreamClass getSuperDesc() {
return superDesc;
}
/** {@collect.stats}
* {@description.open}
* Returns the "local" class descriptor for the class associated with this
* class descriptor (i.e., the result of
* ObjectStreamClass.lookup(this.forClass())) or null if there is no class
* associated with this descriptor.
* {@description.close}
*/
ObjectStreamClass getLocalDesc() {
return localDesc;
}
/** {@collect.stats}
* {@description.open}
* Returns arrays of ObjectStreamFields representing the serializable
* fields of the represented class. If copy is true, a clone of this class
* descriptor's field array is returned, otherwise the array itself is
* returned.
* {@description.close}
*/
ObjectStreamField[] getFields(boolean copy) {
return copy ? fields.clone() : fields;
}
/** {@collect.stats}
* {@description.open}
* Looks up a serializable field of the represented class by name and type.
* A specified type of null matches all types, Object.class matches all
* non-primitive types, and any other non-null type matches assignable
* types only. Returns matching field, or null if no match found.
* {@description.close}
*/
ObjectStreamField getField(String name, Class type) {
for (int i = 0; i < fields.length; i++) {
ObjectStreamField f = fields[i];
if (f.getName().equals(name)) {
if (type == null ||
(type == Object.class && !f.isPrimitive()))
{
return f;
}
Class ftype = f.getType();
if (ftype != null && type.isAssignableFrom(ftype)) {
return f;
}
}
}
return null;
}
/** {@collect.stats}
* {@description.open}
* Returns true if class descriptor represents a dynamic proxy class, false
* otherwise.
* {@description.close}
*/
boolean isProxy() {
return isProxy;
}
/** {@collect.stats}
* {@description.open}
* Returns true if class descriptor represents an enum type, false
* otherwise.
* {@description.close}
*/
boolean isEnum() {
return isEnum;
}
/** {@collect.stats}
* {@description.open}
* Returns true if represented class implements Externalizable, false
* otherwise.
* {@description.close}
*/
boolean isExternalizable() {
return externalizable;
}
/** {@collect.stats}
* {@description.open}
* Returns true if represented class implements Serializable, false
* otherwise.
* {@description.close}
*/
boolean isSerializable() {
return serializable;
}
/** {@collect.stats}
* {@description.open}
* Returns true if class descriptor represents externalizable class that
* has written its data in 1.2 (block data) format, false otherwise.
* {@description.close}
*/
boolean hasBlockExternalData() {
return hasBlockExternalData;
}
/** {@collect.stats}
* {@description.open}
* Returns true if class descriptor represents serializable (but not
* externalizable) class which has written its data via a custom
* writeObject() method, false otherwise.
* {@description.close}
*/
boolean hasWriteObjectData() {
return hasWriteObjectData;
}
/** {@collect.stats}
* {@description.open}
* Returns true if represented class is serializable/externalizable and can
* be instantiated by the serialization runtime--i.e., if it is
* externalizable and defines a public no-arg constructor, or if it is
* non-externalizable and its first non-serializable superclass defines an
* accessible no-arg constructor. Otherwise, returns false.
* {@description.close}
*/
boolean isInstantiable() {
return (cons != null);
}
/** {@collect.stats}
* {@description.open}
* Returns true if represented class is serializable (but not
* externalizable) and defines a conformant writeObject method. Otherwise,
* returns false.
* {@description.close}
*/
boolean hasWriteObjectMethod() {
return (writeObjectMethod != null);
}
/** {@collect.stats}
* {@description.open}
* Returns true if represented class is serializable (but not
* externalizable) and defines a conformant readObject method. Otherwise,
* returns false.
* {@description.close}
*/
boolean hasReadObjectMethod() {
return (readObjectMethod != null);
}
/** {@collect.stats}
* {@description.open}
* Returns true if represented class is serializable (but not
* externalizable) and defines a conformant readObjectNoData method.
* Otherwise, returns false.
* {@description.close}
*/
boolean hasReadObjectNoDataMethod() {
return (readObjectNoDataMethod != null);
}
/** {@collect.stats}
* {@description.open}
* Returns true if represented class is serializable or externalizable and
* defines a conformant writeReplace method. Otherwise, returns false.
* {@description.close}
*/
boolean hasWriteReplaceMethod() {
return (writeReplaceMethod != null);
}
/** {@collect.stats}
* {@description.open}
* Returns true if represented class is serializable or externalizable and
* defines a conformant readResolve method. Otherwise, returns false.
* {@description.close}
*/
boolean hasReadResolveMethod() {
return (readResolveMethod != null);
}
/** {@collect.stats}
* {@description.open}
* Creates a new instance of the represented class. If the class is
* externalizable, invokes its public no-arg constructor; otherwise, if the
* class is serializable, invokes the no-arg constructor of the first
* non-serializable superclass. Throws UnsupportedOperationException if
* this class descriptor is not associated with a class, if the associated
* class is non-serializable or if the appropriate no-arg constructor is
* inaccessible/unavailable.
* {@description.close}
*/
Object newInstance()
throws InstantiationException, InvocationTargetException,
UnsupportedOperationException
{
if (cons != null) {
try {
return cons.newInstance();
} catch (IllegalAccessException ex) {
// should not occur, as access checks have been suppressed
throw new InternalError();
}
} else {
throw new UnsupportedOperationException();
}
}
/** {@collect.stats}
* {@description.open}
* Invokes the writeObject method of the represented serializable class.
* Throws UnsupportedOperationException if this class descriptor is not
* associated with a class, or if the class is externalizable,
* non-serializable or does not define writeObject.
* {@description.close}
*/
void invokeWriteObject(Object obj, ObjectOutputStream out)
throws IOException, UnsupportedOperationException
{
if (writeObjectMethod != null) {
try {
writeObjectMethod.invoke(obj, new Object[]{ out });
} catch (InvocationTargetException ex) {
Throwable th = ex.getTargetException();
if (th instanceof IOException) {
throw (IOException) th;
} else {
throwMiscException(th);
}
} catch (IllegalAccessException ex) {
// should not occur, as access checks have been suppressed
throw new InternalError();
}
} else {
throw new UnsupportedOperationException();
}
}
/** {@collect.stats}
* {@description.open}
* Invokes the readObject method of the represented serializable class.
* Throws UnsupportedOperationException if this class descriptor is not
* associated with a class, or if the class is externalizable,
* non-serializable or does not define readObject.
* {@description.close}
*/
void invokeReadObject(Object obj, ObjectInputStream in)
throws ClassNotFoundException, IOException,
UnsupportedOperationException
{
if (readObjectMethod != null) {
try {
readObjectMethod.invoke(obj, new Object[]{ in });
} catch (InvocationTargetException ex) {
Throwable th = ex.getTargetException();
if (th instanceof ClassNotFoundException) {
throw (ClassNotFoundException) th;
} else if (th instanceof IOException) {
throw (IOException) th;
} else {
throwMiscException(th);
}
} catch (IllegalAccessException ex) {
// should not occur, as access checks have been suppressed
throw new InternalError();
}
} else {
throw new UnsupportedOperationException();
}
}
/** {@collect.stats}
* {@description.open}
* Invokes the readObjectNoData method of the represented serializable
* class. Throws UnsupportedOperationException if this class descriptor is
* not associated with a class, or if the class is externalizable,
* non-serializable or does not define readObjectNoData.
* {@description.close}
*/
void invokeReadObjectNoData(Object obj)
throws IOException, UnsupportedOperationException
{
if (readObjectNoDataMethod != null) {
try {
readObjectNoDataMethod.invoke(obj, (Object[]) null);
} catch (InvocationTargetException ex) {
Throwable th = ex.getTargetException();
if (th instanceof ObjectStreamException) {
throw (ObjectStreamException) th;
} else {
throwMiscException(th);
}
} catch (IllegalAccessException ex) {
// should not occur, as access checks have been suppressed
throw new InternalError();
}
} else {
throw new UnsupportedOperationException();
}
}
/** {@collect.stats}
* {@description.open}
* Invokes the writeReplace method of the represented serializable class and
* returns the result. Throws UnsupportedOperationException if this class
* descriptor is not associated with a class, or if the class is
* non-serializable or does not define writeReplace.
* {@description.close}
*/
Object invokeWriteReplace(Object obj)
throws IOException, UnsupportedOperationException
{
if (writeReplaceMethod != null) {
try {
return writeReplaceMethod.invoke(obj, (Object[]) null);
} catch (InvocationTargetException ex) {
Throwable th = ex.getTargetException();
if (th instanceof ObjectStreamException) {
throw (ObjectStreamException) th;
} else {
throwMiscException(th);
throw new InternalError(); // never reached
}
} catch (IllegalAccessException ex) {
// should not occur, as access checks have been suppressed
throw new InternalError();
}
} else {
throw new UnsupportedOperationException();
}
}
/** {@collect.stats}
* {@description.open}
* Invokes the readResolve method of the represented serializable class and
* returns the result. Throws UnsupportedOperationException if this class
* descriptor is not associated with a class, or if the class is
* non-serializable or does not define readResolve.
* {@description.close}
*/
Object invokeReadResolve(Object obj)
throws IOException, UnsupportedOperationException
{
if (readResolveMethod != null) {
try {
return readResolveMethod.invoke(obj, (Object[]) null);
} catch (InvocationTargetException ex) {
Throwable th = ex.getTargetException();
if (th instanceof ObjectStreamException) {
throw (ObjectStreamException) th;
} else {
throwMiscException(th);
throw new InternalError(); // never reached
}
} catch (IllegalAccessException ex) {
// should not occur, as access checks have been suppressed
throw new InternalError();
}
} else {
throw new UnsupportedOperationException();
}
}
/** {@collect.stats}
* {@description.open}
* Class representing the portion of an object's serialized form allotted
* to data described by a given class descriptor. If "hasData" is false,
* the object's serialized form does not contain data associated with the
* class descriptor.
* {@description.close}
*/
static class ClassDataSlot {
/** {@collect.stats} class descriptor "occupying" this slot */
final ObjectStreamClass desc;
/** {@collect.stats} true if serialized form includes data for this slot's descriptor */
final boolean hasData;
ClassDataSlot(ObjectStreamClass desc, boolean hasData) {
this.desc = desc;
this.hasData = hasData;
}
}
/** {@collect.stats}
* {@description.open}
* Returns array of ClassDataSlot instances representing the data layout
* (including superclass data) for serialized objects described by this
* class descriptor. ClassDataSlots are ordered by inheritance with those
* containing "higher" superclasses appearing first. The final
* ClassDataSlot contains a reference to this descriptor.
* {@description.close}
*/
ClassDataSlot[] getClassDataLayout() throws InvalidClassException {
// REMIND: synchronize instead of relying on volatile?
if (dataLayout == null) {
dataLayout = getClassDataLayout0();
}
return dataLayout;
}
private ClassDataSlot[] getClassDataLayout0()
throws InvalidClassException
{
ArrayList slots = new ArrayList();
Class start = cl, end = cl;
// locate closest non-serializable superclass
while (end != null && Serializable.class.isAssignableFrom(end)) {
end = end.getSuperclass();
}
for (ObjectStreamClass d = this; d != null; d = d.superDesc) {
// search up inheritance hierarchy for class with matching name
String searchName = (d.cl != null) ? d.cl.getName() : d.name;
Class match = null;
for (Class c = start; c != end; c = c.getSuperclass()) {
if (searchName.equals(c.getName())) {
match = c;
break;
}
}
// add "no data" slot for each unmatched class below match
if (match != null) {
for (Class c = start; c != match; c = c.getSuperclass()) {
slots.add(new ClassDataSlot(
ObjectStreamClass.lookup(c, true), false));
}
start = match.getSuperclass();
}
// record descriptor/class pairing
slots.add(new ClassDataSlot(d.getVariantFor(match), true));
}
// add "no data" slot for any leftover unmatched classes
for (Class c = start; c != end; c = c.getSuperclass()) {
slots.add(new ClassDataSlot(
ObjectStreamClass.lookup(c, true), false));
}
// order slots from superclass -> subclass
Collections.reverse(slots);
return (ClassDataSlot[])
slots.toArray(new ClassDataSlot[slots.size()]);
}
/** {@collect.stats}
* {@description.open}
* Returns aggregate size (in bytes) of marshalled primitive field values
* for represented class.
* {@description.close}
*/
int getPrimDataSize() {
return primDataSize;
}
/** {@collect.stats}
* {@description.open}
* Returns number of non-primitive serializable fields of represented
* class.
* {@description.close}
*/
int getNumObjFields() {
return numObjFields;
}
/** {@collect.stats}
* {@description.open}
* Fetches the serializable primitive field values of object obj and
* marshals them into byte array buf starting at offset 0. It is the
* responsibility of the caller to ensure that obj is of the proper type if
* non-null.
* {@description.close}
*/
void getPrimFieldValues(Object obj, byte[] buf) {
fieldRefl.getPrimFieldValues(obj, buf);
}
/** {@collect.stats}
* {@description.open}
* Sets the serializable primitive fields of object obj using values
* unmarshalled from byte array buf starting at offset 0. It is the
* responsibility of the caller to ensure that obj is of the proper type if
* non-null.
* {@description.close}
*/
void setPrimFieldValues(Object obj, byte[] buf) {
fieldRefl.setPrimFieldValues(obj, buf);
}
/** {@collect.stats}
* {@description.open}
* Fetches the serializable object field values of object obj and stores
* them in array vals starting at offset 0. It is the responsibility of
* the caller to ensure that obj is of the proper type if non-null.
* {@description.close}
*/
void getObjFieldValues(Object obj, Object[] vals) {
fieldRefl.getObjFieldValues(obj, vals);
}
/** {@collect.stats}
* {@description.open}
* Sets the serializable object fields of object obj using values from
* array vals starting at offset 0. It is the responsibility of the caller
* to ensure that obj is of the proper type if non-null.
* {@description.close}
*/
void setObjFieldValues(Object obj, Object[] vals) {
fieldRefl.setObjFieldValues(obj, vals);
}
/** {@collect.stats}
* {@description.open}
* Calculates and sets serializable field offsets, as well as primitive
* data size and object field count totals. Throws InvalidClassException
* if fields are illegally ordered.
* {@description.close}
*/
private void computeFieldOffsets() throws InvalidClassException {
primDataSize = 0;
numObjFields = 0;
int firstObjIndex = -1;
for (int i = 0; i < fields.length; i++) {
ObjectStreamField f = fields[i];
switch (f.getTypeCode()) {
case 'Z':
case 'B':
f.setOffset(primDataSize++);
break;
case 'C':
case 'S':
f.setOffset(primDataSize);
primDataSize += 2;
break;
case 'I':
case 'F':
f.setOffset(primDataSize);
primDataSize += 4;
break;
case 'J':
case 'D':
f.setOffset(primDataSize);
primDataSize += 8;
break;
case '[':
case 'L':
f.setOffset(numObjFields++);
if (firstObjIndex == -1) {
firstObjIndex = i;
}
break;
default:
throw new InternalError();
}
}
if (firstObjIndex != -1 &&
firstObjIndex + numObjFields != fields.length)
{
throw new InvalidClassException(name, "illegal field order");
}
}
/** {@collect.stats}
* {@description.open}
* If given class is the same as the class associated with this class
* descriptor, returns reference to this class descriptor. Otherwise,
* returns variant of this class descriptor bound to given class.
* {@description.close}
*/
private ObjectStreamClass getVariantFor(Class cl)
throws InvalidClassException
{
if (this.cl == cl) {
return this;
}
ObjectStreamClass desc = new ObjectStreamClass();
if (isProxy) {
desc.initProxy(cl, null, superDesc);
} else {
desc.initNonProxy(this, cl, null, superDesc);
}
return desc;
}
/** {@collect.stats}
* {@description.open}
* Returns public no-arg constructor of given class, or null if none found.
* Access checks are disabled on the returned constructor (if any), since
* the defining class may still be non-public.
* {@description.close}
*/
private static Constructor getExternalizableConstructor(Class cl) {
try {
Constructor cons = cl.getDeclaredConstructor((Class[]) null);
cons.setAccessible(true);
return ((cons.getModifiers() & Modifier.PUBLIC) != 0) ?
cons : null;
} catch (NoSuchMethodException ex) {
return null;
}
}
/** {@collect.stats}
* {@description.open}
* Returns subclass-accessible no-arg constructor of first non-serializable
* superclass, or null if none found. Access checks are disabled on the
* returned constructor (if any).
* {@description.close}
*/
private static Constructor getSerializableConstructor(Class cl) {
Class initCl = cl;
while (Serializable.class.isAssignableFrom(initCl)) {
if ((initCl = initCl.getSuperclass()) == null) {
return null;
}
}
try {
Constructor cons = initCl.getDeclaredConstructor((Class[]) null);
int mods = cons.getModifiers();
if ((mods & Modifier.PRIVATE) != 0 ||
((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
!packageEquals(cl, initCl)))
{
return null;
}
cons = reflFactory.newConstructorForSerialization(cl, cons);
cons.setAccessible(true);
return cons;
} catch (NoSuchMethodException ex) {
return null;
}
}
/** {@collect.stats}
* {@description.open}
* Returns non-static, non-abstract method with given signature provided it
* is defined by or accessible (via inheritance) by the given class, or
* null if no match found. Access checks are disabled on the returned
* method (if any).
* {@description.close}
*/
private static Method getInheritableMethod(Class cl, String name,
Class[] argTypes,
Class returnType)
{
Method meth = null;
Class defCl = cl;
while (defCl != null) {
try {
meth = defCl.getDeclaredMethod(name, argTypes);
break;
} catch (NoSuchMethodException ex) {
defCl = defCl.getSuperclass();
}
}
if ((meth == null) || (meth.getReturnType() != returnType)) {
return null;
}
meth.setAccessible(true);
int mods = meth.getModifiers();
if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) {
return null;
} else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) {
return meth;
} else if ((mods & Modifier.PRIVATE) != 0) {
return (cl == defCl) ? meth : null;
} else {
return packageEquals(cl, defCl) ? meth : null;
}
}
/** {@collect.stats}
* {@description.open}
* Returns non-static private method with given signature defined by given
* class, or null if none found. Access checks are disabled on the
* returned method (if any).
* {@description.close}
*/
private static Method getPrivateMethod(Class cl, String name,
Class[] argTypes,
Class returnType)
{
try {
Method meth = cl.getDeclaredMethod(name, argTypes);
meth.setAccessible(true);
int mods = meth.getModifiers();
return ((meth.getReturnType() == returnType) &&
((mods & Modifier.STATIC) == 0) &&
((mods & Modifier.PRIVATE) != 0)) ? meth : null;
} catch (NoSuchMethodException ex) {
return null;
}
}
/** {@collect.stats}
* {@description.open}
* Returns true if classes are defined in the same runtime package, false
* otherwise.
* {@description.close}
*/
private static boolean packageEquals(Class cl1, Class cl2) {
return (cl1.getClassLoader() == cl2.getClassLoader() &&
getPackageName(cl1).equals(getPackageName(cl2)));
}
/** {@collect.stats}
* {@description.open}
* Returns package name of given class.
* {@description.close}
*/
private static String getPackageName(Class cl) {
String s = cl.getName();
int i = s.lastIndexOf('[');
if (i >= 0) {
s = s.substring(i + 2);
}
i = s.lastIndexOf('.');
return (i >= 0) ? s.substring(0, i) : "";
}
/** {@collect.stats}
* {@description.open}
* Compares class names for equality, ignoring package names. Returns true
* if class names equal, false otherwise.
* {@description.close}
*/
private static boolean classNamesEqual(String name1, String name2) {
name1 = name1.substring(name1.lastIndexOf('.') + 1);
name2 = name2.substring(name2.lastIndexOf('.') + 1);
return name1.equals(name2);
}
/** {@collect.stats}
* {@description.open}
* Returns JVM type signature for given class.
* {@description.close}
*/
static String getClassSignature(Class cl) {
StringBuilder sbuf = new StringBuilder();
while (cl.isArray()) {
sbuf.append('[');
cl = cl.getComponentType();
}
if (cl.isPrimitive()) {
if (cl == Integer.TYPE) {
sbuf.append('I');
} else if (cl == Byte.TYPE) {
sbuf.append('B');
} else if (cl == Long.TYPE) {
sbuf.append('J');
} else if (cl == Float.TYPE) {
sbuf.append('F');
} else if (cl == Double.TYPE) {
sbuf.append('D');
} else if (cl == Short.TYPE) {
sbuf.append('S');
} else if (cl == Character.TYPE) {
sbuf.append('C');
} else if (cl == Boolean.TYPE) {
sbuf.append('Z');
} else if (cl == Void.TYPE) {
sbuf.append('V');
} else {
throw new InternalError();
}
} else {
sbuf.append('L' + cl.getName().replace('.', '/') + ';');
}
return sbuf.toString();
}
/** {@collect.stats}
* {@description.open}
* Returns JVM type signature for given list of parameters and return type.
* {@description.close}
*/
private static String getMethodSignature(Class[] paramTypes,
Class retType)
{
StringBuilder sbuf = new StringBuilder();
sbuf.append('(');
for (int i = 0; i < paramTypes.length; i++) {
sbuf.append(getClassSignature(paramTypes[i]));
}
sbuf.append(')');
sbuf.append(getClassSignature(retType));
return sbuf.toString();
}
/** {@collect.stats}
* {@description.open}
* Convenience method for throwing an exception that is either a
* RuntimeException, Error, or of some unexpected type (in which case it is
* wrapped inside an IOException).
* {@description.close}
*/
private static void throwMiscException(Throwable th) throws IOException {
if (th instanceof RuntimeException) {
throw (RuntimeException) th;
} else if (th instanceof Error) {
throw (Error) th;
} else {
IOException ex = new IOException("unexpected exception type");
ex.initCause(th);
throw ex;
}
}
/** {@collect.stats}
* {@description.open}
* Returns ObjectStreamField array describing the serializable fields of
* the given class. Serializable fields backed by an actual field of the
* class are represented by ObjectStreamFields with corresponding non-null
* Field objects. Throws InvalidClassException if the (explicitly
* declared) serializable fields are invalid.
* {@description.close}
*/
private static ObjectStreamField[] getSerialFields(Class cl)
throws InvalidClassException
{
ObjectStreamField[] fields;
if (Serializable.class.isAssignableFrom(cl) &&
!Externalizable.class.isAssignableFrom(cl) &&
!Proxy.isProxyClass(cl) &&
!cl.isInterface())
{
if ((fields = getDeclaredSerialFields(cl)) == null) {
fields = getDefaultSerialFields(cl);
}
Arrays.sort(fields);
} else {
fields = NO_FIELDS;
}
return fields;
}
/** {@collect.stats}
* {@description.open}
* Returns serializable fields of given class as defined explicitly by a
* "serialPersistentFields" field, or null if no appropriate
* "serialPersistentFields" field is defined. Serializable fields backed
* by an actual field of the class are represented by ObjectStreamFields
* with corresponding non-null Field objects. For compatibility with past
* releases, a "serialPersistentFields" field with a null value is
* considered equivalent to not declaring "serialPersistentFields". Throws
* InvalidClassException if the declared serializable fields are
* invalid--e.g., if multiple fields share the same name.
* {@description.close}
*/
private static ObjectStreamField[] getDeclaredSerialFields(Class cl)
throws InvalidClassException
{
ObjectStreamField[] serialPersistentFields = null;
try {
Field f = cl.getDeclaredField("serialPersistentFields");
int mask = Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL;
if ((f.getModifiers() & mask) == mask) {
f.setAccessible(true);
serialPersistentFields = (ObjectStreamField[]) f.get(null);
}
} catch (Exception ex) {
}
if (serialPersistentFields == null) {
return null;
} else if (serialPersistentFields.length == 0) {
return NO_FIELDS;
}
ObjectStreamField[] boundFields =
new ObjectStreamField[serialPersistentFields.length];
Set fieldNames = new HashSet(serialPersistentFields.length);
for (int i = 0; i < serialPersistentFields.length; i++) {
ObjectStreamField spf = serialPersistentFields[i];
String fname = spf.getName();
if (fieldNames.contains(fname)) {
throw new InvalidClassException(
"multiple serializable fields named " + fname);
}
fieldNames.add(fname);
try {
Field f = cl.getDeclaredField(fname);
if ((f.getType() == spf.getType()) &&
((f.getModifiers() & Modifier.STATIC) == 0))
{
boundFields[i] =
new ObjectStreamField(f, spf.isUnshared(), true);
}
} catch (NoSuchFieldException ex) {
}
if (boundFields[i] == null) {
boundFields[i] = new ObjectStreamField(
fname, spf.getType(), spf.isUnshared());
}
}
return boundFields;
}
/** {@collect.stats}
* {@description.open}
* Returns array of ObjectStreamFields corresponding to all non-static
* non-transient fields declared by given class. Each ObjectStreamField
* contains a Field object for the field it represents. If no default
* serializable fields exist, NO_FIELDS is returned.
* {@description.close}
*/
private static ObjectStreamField[] getDefaultSerialFields(Class cl) {
Field[] clFields = cl.getDeclaredFields();
ArrayList list = new ArrayList();
int mask = Modifier.STATIC | Modifier.TRANSIENT;
for (int i = 0; i < clFields.length; i++) {
if ((clFields[i].getModifiers() & mask) == 0) {
list.add(new ObjectStreamField(clFields[i], false, true));
}
}
int size = list.size();
return (size == 0) ? NO_FIELDS :
(ObjectStreamField[]) list.toArray(new ObjectStreamField[size]);
}
/** {@collect.stats}
* {@description.open}
* Returns explicit serial version UID value declared by given class, or
* null if none.
* {@description.close}
*/
private static Long getDeclaredSUID(Class cl) {
try {
Field f = cl.getDeclaredField("serialVersionUID");
int mask = Modifier.STATIC | Modifier.FINAL;
if ((f.getModifiers() & mask) == mask) {
f.setAccessible(true);
return Long.valueOf(f.getLong(null));
}
} catch (Exception ex) {
}
return null;
}
/** {@collect.stats}
* {@description.open}
* Computes the default serial version UID value for the given class.
* {@description.close}
*/
private static long computeDefaultSUID(Class cl) {
if (!Serializable.class.isAssignableFrom(cl) || Proxy.isProxyClass(cl))
{
return 0L;
}
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
dout.writeUTF(cl.getName());
int classMods = cl.getModifiers() &
(Modifier.PUBLIC | Modifier.FINAL |
Modifier.INTERFACE | Modifier.ABSTRACT);
/*
* compensate for javac bug in which ABSTRACT bit was set for an
* interface only if the interface declared methods
*/
Method[] methods = cl.getDeclaredMethods();
if ((classMods & Modifier.INTERFACE) != 0) {
classMods = (methods.length > 0) ?
(classMods | Modifier.ABSTRACT) :
(classMods & ~Modifier.ABSTRACT);
}
dout.writeInt(classMods);
if (!cl.isArray()) {
/*
* compensate for change in 1.2FCS in which
* Class.getInterfaces() was modified to return Cloneable and
* Serializable for array classes.
*/
Class[] interfaces = cl.getInterfaces();
String[] ifaceNames = new String[interfaces.length];
for (int i = 0; i < interfaces.length; i++) {
ifaceNames[i] = interfaces[i].getName();
}
Arrays.sort(ifaceNames);
for (int i = 0; i < ifaceNames.length; i++) {
dout.writeUTF(ifaceNames[i]);
}
}
Field[] fields = cl.getDeclaredFields();
MemberSignature[] fieldSigs = new MemberSignature[fields.length];
for (int i = 0; i < fields.length; i++) {
fieldSigs[i] = new MemberSignature(fields[i]);
}
Arrays.sort(fieldSigs, new Comparator() {
public int compare(Object o1, Object o2) {
String name1 = ((MemberSignature) o1).name;
String name2 = ((MemberSignature) o2).name;
return name1.compareTo(name2);
}
});
for (int i = 0; i < fieldSigs.length; i++) {
MemberSignature sig = fieldSigs[i];
int mods = sig.member.getModifiers() &
(Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED |
Modifier.STATIC | Modifier.FINAL | Modifier.VOLATILE |
Modifier.TRANSIENT);
if (((mods & Modifier.PRIVATE) == 0) ||
((mods & (Modifier.STATIC | Modifier.TRANSIENT)) == 0))
{
dout.writeUTF(sig.name);
dout.writeInt(mods);
dout.writeUTF(sig.signature);
}
}
if (hasStaticInitializer(cl)) {
dout.writeUTF("<clinit>");
dout.writeInt(Modifier.STATIC);
dout.writeUTF("()V");
}
Constructor[] cons = cl.getDeclaredConstructors();
MemberSignature[] consSigs = new MemberSignature[cons.length];
for (int i = 0; i < cons.length; i++) {
consSigs[i] = new MemberSignature(cons[i]);
}
Arrays.sort(consSigs, new Comparator() {
public int compare(Object o1, Object o2) {
String sig1 = ((MemberSignature) o1).signature;
String sig2 = ((MemberSignature) o2).signature;
return sig1.compareTo(sig2);
}
});
for (int i = 0; i < consSigs.length; i++) {
MemberSignature sig = consSigs[i];
int mods = sig.member.getModifiers() &
(Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED |
Modifier.STATIC | Modifier.FINAL |
Modifier.SYNCHRONIZED | Modifier.NATIVE |
Modifier.ABSTRACT | Modifier.STRICT);
if ((mods & Modifier.PRIVATE) == 0) {
dout.writeUTF("<init>");
dout.writeInt(mods);
dout.writeUTF(sig.signature.replace('/', '.'));
}
}
MemberSignature[] methSigs = new MemberSignature[methods.length];
for (int i = 0; i < methods.length; i++) {
methSigs[i] = new MemberSignature(methods[i]);
}
Arrays.sort(methSigs, new Comparator() {
public int compare(Object o1, Object o2) {
MemberSignature ms1 = (MemberSignature) o1;
MemberSignature ms2 = (MemberSignature) o2;
int comp = ms1.name.compareTo(ms2.name);
if (comp == 0) {
comp = ms1.signature.compareTo(ms2.signature);
}
return comp;
}
});
for (int i = 0; i < methSigs.length; i++) {
MemberSignature sig = methSigs[i];
int mods = sig.member.getModifiers() &
(Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED |
Modifier.STATIC | Modifier.FINAL |
Modifier.SYNCHRONIZED | Modifier.NATIVE |
Modifier.ABSTRACT | Modifier.STRICT);
if ((mods & Modifier.PRIVATE) == 0) {
dout.writeUTF(sig.name);
dout.writeInt(mods);
dout.writeUTF(sig.signature.replace('/', '.'));
}
}
dout.flush();
MessageDigest md = MessageDigest.getInstance("SHA");
byte[] hashBytes = md.digest(bout.toByteArray());
long hash = 0;
for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
hash = (hash << 8) | (hashBytes[i] & 0xFF);
}
return hash;
} catch (IOException ex) {
throw new InternalError();
} catch (NoSuchAlgorithmException ex) {
throw new SecurityException(ex.getMessage());
}
}
/** {@collect.stats}
* {@description.open}
* Returns true if the given class defines a static initializer method,
* false otherwise.
* {@description.close}
*/
private native static boolean hasStaticInitializer(Class cl);
/** {@collect.stats}
* {@description.open}
* Class for computing and caching field/constructor/method signatures
* during serialVersionUID calculation.
* {@description.close}
*/
private static class MemberSignature {
public final Member member;
public final String name;
public final String signature;
public MemberSignature(Field field) {
member = field;
name = field.getName();
signature = getClassSignature(field.getType());
}
public MemberSignature(Constructor cons) {
member = cons;
name = cons.getName();
signature = getMethodSignature(
cons.getParameterTypes(), Void.TYPE);
}
public MemberSignature(Method meth) {
member = meth;
name = meth.getName();
signature = getMethodSignature(
meth.getParameterTypes(), meth.getReturnType());
}
}
/** {@collect.stats}
* {@description.open}
* Class for setting and retrieving serializable field values in batch.
* {@description.close}
*/
// REMIND: dynamically generate these?
private static class FieldReflector {
/** {@collect.stats}
* {@description.open}
* handle for performing unsafe operations
* {@description.close}
*/
private static final Unsafe unsafe = Unsafe.getUnsafe();
/** {@collect.stats}
* {@description.open}
* fields to operate on
* {@description.close}
*/
private final ObjectStreamField[] fields;
/** {@collect.stats}
* {@description.open}
* number of primitive fields
* {@description.close}
*/
private final int numPrimFields;
/** {@collect.stats}
* {@description.open}
* unsafe field keys for reading fields - may contain dupes
* {@description.close}
*/
private final long[] readKeys;
/** {@collect.stats}
* {@description.open}
* unsafe fields keys for writing fields - no dupes
* {@description.close}
/
private final long[] writeKeys;
/** {@collect.stats}
* {@description.open}
* field data offsets
* {@description.close}
*/
private final int[] offsets;
/** {@collect.stats}
* {@description.open}
* field type codes
* {@description.close}
*/
private final char[] typeCodes;
/** {@collect.stats}
* {@description.open}
* field types
* {@description.close}
*/
private final Class[] types;
/** {@collect.stats}
* {@description.open}
* Constructs FieldReflector capable of setting/getting values from the
* subset of fields whose ObjectStreamFields contain non-null
* reflective Field objects. ObjectStreamFields with null Fields are
* treated as filler, for which get operations return default values
* and set operations discard given values.
* {@description.close}
*/
FieldReflector(ObjectStreamField[] fields) {
this.fields = fields;
int nfields = fields.length;
readKeys = new long[nfields];
writeKeys = new long[nfields];
offsets = new int[nfields];
typeCodes = new char[nfields];
ArrayList typeList = new ArrayList();
Set<Long> usedKeys = new HashSet<Long>();
for (int i = 0; i < nfields; i++) {
ObjectStreamField f = fields[i];
Field rf = f.getField();
long key = (rf != null) ?
unsafe.objectFieldOffset(rf) : Unsafe.INVALID_FIELD_OFFSET;
readKeys[i] = key;
writeKeys[i] = usedKeys.add(key) ?
key : Unsafe.INVALID_FIELD_OFFSET;
offsets[i] = f.getOffset();
typeCodes[i] = f.getTypeCode();
if (!f.isPrimitive()) {
typeList.add((rf != null) ? rf.getType() : null);
}
}
types = (Class[]) typeList.toArray(new Class[typeList.size()]);
numPrimFields = nfields - types.length;
}
/** {@collect.stats}
* {@description.open}
* Returns list of ObjectStreamFields representing fields operated on
* by this reflector. The shared/unshared values and Field objects
* contained by ObjectStreamFields in the list reflect their bindings
* to locally defined serializable fields.
* {@description.close}
*/
ObjectStreamField[] getFields() {
return fields;
}
/** {@collect.stats}
* {@description.open}
* Fetches the serializable primitive field values of object obj and
* marshals them into byte array buf starting at offset 0. The caller
* is responsible for ensuring that obj is of the proper type.
* {@description.close}
*/
void getPrimFieldValues(Object obj, byte[] buf) {
if (obj == null) {
throw new NullPointerException();
}
/* assuming checkDefaultSerialize() has been called on the class
* descriptor this FieldReflector was obtained from, no field keys
* in array should be equal to Unsafe.INVALID_FIELD_OFFSET.
*/
for (int i = 0; i < numPrimFields; i++) {
long key = readKeys[i];
int off = offsets[i];
switch (typeCodes[i]) {
case 'Z':
Bits.putBoolean(buf, off, unsafe.getBoolean(obj, key));
break;
case 'B':
buf[off] = unsafe.getByte(obj, key);
break;
case 'C':
Bits.putChar(buf, off, unsafe.getChar(obj, key));
break;
case 'S':
Bits.putShort(buf, off, unsafe.getShort(obj, key));
break;
case 'I':
Bits.putInt(buf, off, unsafe.getInt(obj, key));
break;
case 'F':
Bits.putFloat(buf, off, unsafe.getFloat(obj, key));
break;
case 'J':
Bits.putLong(buf, off, unsafe.getLong(obj, key));
break;
case 'D':
Bits.putDouble(buf, off, unsafe.getDouble(obj, key));
break;
default:
throw new InternalError();
}
}
}
/** {@collect.stats}
* {@description.open}
* Sets the serializable primitive fields of object obj using values
* unmarshalled from byte array buf starting at offset 0. The caller
* is responsible for ensuring that obj is of the proper type.
* {@description.close}
*/
void setPrimFieldValues(Object obj, byte[] buf) {
if (obj == null) {
throw new NullPointerException();
}
for (int i = 0; i < numPrimFields; i++) {
long key = writeKeys[i];
if (key == Unsafe.INVALID_FIELD_OFFSET) {
continue; // discard value
}
int off = offsets[i];
switch (typeCodes[i]) {
case 'Z':
unsafe.putBoolean(obj, key, Bits.getBoolean(buf, off));
break;
case 'B':
unsafe.putByte(obj, key, buf[off]);
break;
case 'C':
unsafe.putChar(obj, key, Bits.getChar(buf, off));
break;
case 'S':
unsafe.putShort(obj, key, Bits.getShort(buf, off));
break;
case 'I':
unsafe.putInt(obj, key, Bits.getInt(buf, off));
break;
case 'F':
unsafe.putFloat(obj, key, Bits.getFloat(buf, off));
break;
case 'J':
unsafe.putLong(obj, key, Bits.getLong(buf, off));
break;
case 'D':
unsafe.putDouble(obj, key, Bits.getDouble(buf, off));
break;
default:
throw new InternalError();
}
}
}
/** {@collect.stats}
* {@description.open}
* Fetches the serializable object field values of object obj and
* stores them in array vals starting at offset 0. The caller is
* responsible for ensuring that obj is of the proper type.
* {@description.close}
*/
void getObjFieldValues(Object obj, Object[] vals) {
if (obj == null) {
throw new NullPointerException();
}
/* assuming checkDefaultSerialize() has been called on the class
* descriptor this FieldReflector was obtained from, no field keys
* in array should be equal to Unsafe.INVALID_FIELD_OFFSET.
*/
for (int i = numPrimFields; i < fields.length; i++) {
switch (typeCodes[i]) {
case 'L':
case '[':
vals[offsets[i]] = unsafe.getObject(obj, readKeys[i]);
break;
default:
throw new InternalError();
}
}
}
/** {@collect.stats}
* {@description.open}
* Sets the serializable object fields of object obj using values from
* array vals starting at offset 0. The caller is responsible for
* ensuring that obj is of the proper type; however, attempts to set a
* field with a value of the wrong type will trigger an appropriate
* ClassCastException.
* {@description.close}
*/
void setObjFieldValues(Object obj, Object[] vals) {
if (obj == null) {
throw new NullPointerException();
}
for (int i = numPrimFields; i < fields.length; i++) {
long key = writeKeys[i];
if (key == Unsafe.INVALID_FIELD_OFFSET) {
continue; // discard value
}
switch (typeCodes[i]) {
case 'L':
case '[':
Object val = vals[offsets[i]];
if (val != null &&
!types[i - numPrimFields].isInstance(val))
{
Field f = fields[i].getField();
throw new ClassCastException(
"cannot assign instance of " +
val.getClass().getName() + " to field " +
f.getDeclaringClass().getName() + "." +
f.getName() + " of type " +
f.getType().getName() + " in instance of " +
obj.getClass().getName());
}
unsafe.putObject(obj, key, val);
break;
default:
throw new InternalError();
}
}
}
}
/** {@collect.stats}
* {@description.open}
* Matches given set of serializable fields with serializable fields
* described by the given local class descriptor, and returns a
* FieldReflector instance capable of setting/getting values from the
* subset of fields that match (non-matching fields are treated as filler,
* for which get operations return default values and set operations
* discard given values). Throws InvalidClassException if unresolvable
* type conflicts exist between the two sets of fields.
* {@description.close}
*/
private static FieldReflector getReflector(ObjectStreamField[] fields,
ObjectStreamClass localDesc)
throws InvalidClassException
{
// class irrelevant if no fields
Class cl = (localDesc != null && fields.length > 0) ?
localDesc.cl : null;
processQueue(Caches.reflectorsQueue, Caches.reflectors);
FieldReflectorKey key = new FieldReflectorKey(cl, fields,
Caches.reflectorsQueue);
Reference<?> ref = Caches.reflectors.get(key);
Object entry = null;
if (ref != null) {
entry = ref.get();
}
EntryFuture future = null;
if (entry == null) {
EntryFuture newEntry = new EntryFuture();
Reference<?> newRef = new SoftReference<EntryFuture>(newEntry);
do {
if (ref != null) {
Caches.reflectors.remove(key, ref);
}
ref = Caches.reflectors.putIfAbsent(key, newRef);
if (ref != null) {
entry = ref.get();
}
} while (ref != null && entry == null);
if (entry == null) {
future = newEntry;
}
}
if (entry instanceof FieldReflector) { // check common case first
return (FieldReflector) entry;
} else if (entry instanceof EntryFuture) {
entry = ((EntryFuture) entry).get();
} else if (entry == null) {
try {
entry = new FieldReflector(matchFields(fields, localDesc));
} catch (Throwable th) {
entry = th;
}
future.set(entry);
Caches.reflectors.put(key, new SoftReference<Object>(entry));
}
if (entry instanceof FieldReflector) {
return (FieldReflector) entry;
} else if (entry instanceof InvalidClassException) {
throw (InvalidClassException) entry;
} else if (entry instanceof RuntimeException) {
throw (RuntimeException) entry;
} else if (entry instanceof Error) {
throw (Error) entry;
} else {
throw new InternalError("unexpected entry: " + entry);
}
}
/** {@collect.stats}
* {@description.open}
* FieldReflector cache lookup key. Keys are considered equal if they
* refer to the same class and equivalent field formats.
* {@description.close}
*/
private static class FieldReflectorKey extends WeakReference<Class<?>> {
private final String sigs;
private final int hash;
private final boolean nullClass;
FieldReflectorKey(Class cl, ObjectStreamField[] fields,
ReferenceQueue<Class<?>> queue)
{
super(cl, queue);
nullClass = (cl == null);
StringBuilder sbuf = new StringBuilder();
for (int i = 0; i < fields.length; i++) {
ObjectStreamField f = fields[i];
sbuf.append(f.getName()).append(f.getSignature());
}
sigs = sbuf.toString();
hash = System.identityHashCode(cl) + sigs.hashCode();
}
public int hashCode() {
return hash;
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof FieldReflectorKey) {
FieldReflectorKey other = (FieldReflectorKey) obj;
Class<?> referent;
return (nullClass ? other.nullClass
: ((referent = get()) != null) &&
(referent == other.get())) &&
sigs.equals(other.sigs);
} else {
return false;
}
}
}
/** {@collect.stats}
* {@description.open}
* Matches given set of serializable fields with serializable fields
* obtained from the given local class descriptor (which contain bindings
* to reflective Field objects). Returns list of ObjectStreamFields in
* which each ObjectStreamField whose signature matches that of a local
* field contains a Field object for that field; unmatched
* ObjectStreamFields contain null Field objects. Shared/unshared settings
* of the returned ObjectStreamFields also reflect those of matched local
* ObjectStreamFields. Throws InvalidClassException if unresolvable type
* conflicts exist between the two sets of fields.
* {@description.close}
*/
private static ObjectStreamField[] matchFields(ObjectStreamField[] fields,
ObjectStreamClass localDesc)
throws InvalidClassException
{
ObjectStreamField[] localFields = (localDesc != null) ?
localDesc.fields : NO_FIELDS;
/*
* Even if fields == localFields, we cannot simply return localFields
* here. In previous implementations of serialization,
* ObjectStreamField.getType() returned Object.class if the
* ObjectStreamField represented a non-primitive field and belonged to
* a non-local class descriptor. To preserve this (questionable)
* behavior, the ObjectStreamField instances returned by matchFields
* cannot report non-primitive types other than Object.class; hence
* localFields cannot be returned directly.
*/
ObjectStreamField[] matches = new ObjectStreamField[fields.length];
for (int i = 0; i < fields.length; i++) {
ObjectStreamField f = fields[i], m = null;
for (int j = 0; j < localFields.length; j++) {
ObjectStreamField lf = localFields[j];
if (f.getName().equals(lf.getName())) {
if ((f.isPrimitive() || lf.isPrimitive()) &&
f.getTypeCode() != lf.getTypeCode())
{
throw new InvalidClassException(localDesc.name,
"incompatible types for field " + f.getName());
}
if (lf.getField() != null) {
m = new ObjectStreamField(
lf.getField(), lf.isUnshared(), false);
} else {
m = new ObjectStreamField(
lf.getName(), lf.getSignature(), lf.isUnshared());
}
}
}
if (m == null) {
m = new ObjectStreamField(
f.getName(), f.getSignature(), false);
}
m.setOffset(f.getOffset());
matches[i] = m;
}
return matches;
}
/** {@collect.stats}
* {@description.open}
* Removes from the specified map any keys that have been enqueued
* on the specified reference queue.
* {@description.close}
*/
static void processQueue(ReferenceQueue<Class<?>> queue,
ConcurrentMap<? extends
WeakReference<Class<?>>, ?> map)
{
Reference<? extends Class<?>> ref;
while((ref = queue.poll()) != null) {
map.remove(ref);
}
}
/** {@collect.stats}
* {@description.open}
* Weak key for Class objects.
* {@description.close}
*
**/
static class WeakClassKey extends WeakReference<Class<?>> {
/** {@collect.stats}
* {@description.open}
* saved value of the referent's identity hash code, to maintain
* a consistent hash code after the referent has been cleared
* {@description.close}
*/
private final int hash;
/** {@collect.stats}
* {@description.open}
* Create a new WeakClassKey to the given object, registered
* with a queue.
* {@description.close}
*/
WeakClassKey(Class<?> cl, ReferenceQueue<Class<?>> refQueue) {
super(cl, refQueue);
hash = System.identityHashCode(cl);
}
/** {@collect.stats}
* {@description.open}
* Returns the identity hash code of the original referent.
* {@description.close}
*/
public int hashCode() {
return hash;
}
/** {@collect.stats}
* {@description.open}
* Returns true if the given object is this identical
* WeakClassKey instance, or, if this object's referent has not
* been cleared, if the given object is another WeakClassKey
* instance with the identical non-null referent as this one.
* {@description.close}
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof WeakClassKey) {
Object referent = get();
return (referent != null) &&
(referent == ((WeakClassKey) obj).get());
} else {
return false;
}
}
}
}
|
Java
|
/*
* Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Vector;
/** {@collect.stats}
* {@description.open}
* A <code>SequenceInputStream</code> represents
* the logical concatenation of other input
* streams. It starts out with an ordered
* collection of input streams and reads from
* the first one until end of file is reached,
* whereupon it reads from the second one,
* and so on, until end of file is reached
* on the last of the contained input streams.
* {@description.close}
*
* @author Author van Hoff
* @since JDK1.0
*/
public
class SequenceInputStream extends InputStream {
Enumeration e;
InputStream in;
/** {@collect.stats}
* {@description.open}
* Initializes a newly created <code>SequenceInputStream</code>
* by remembering the argument, which must
* be an <code>Enumeration</code> that produces
* objects whose run-time type is <code>InputStream</code>.
* The input streams that are produced by
* the enumeration will be read, in order,
* to provide the bytes to be read from this
* <code>SequenceInputStream</code>. After
* each input stream from the enumeration
* is exhausted, it is closed by calling its
* <code>close</code> method.
* {@description.close}
*
* @param e an enumeration of input streams.
* @see java.util.Enumeration
*/
public SequenceInputStream(Enumeration<? extends InputStream> e) {
this.e = e;
try {
nextStream();
} catch (IOException ex) {
// This should never happen
throw new Error("panic");
}
}
/** {@collect.stats}
* {@description.open}
* Initializes a newly
* created <code>SequenceInputStream</code>
* by remembering the two arguments, which
* will be read in order, first <code>s1</code>
* and then <code>s2</code>, to provide the
* bytes to be read from this <code>SequenceInputStream</code>.
* {@description.close}
*
* @param s1 the first input stream to read.
* @param s2 the second input stream to read.
*/
public SequenceInputStream(InputStream s1, InputStream s2) {
Vector v = new Vector(2);
v.addElement(s1);
v.addElement(s2);
e = v.elements();
try {
nextStream();
} catch (IOException ex) {
// This should never happen
throw new Error("panic");
}
}
/** {@collect.stats}
* {@description.open}
* Continues reading in the next stream if an EOF is reached.
* {@description.close}
*/
final void nextStream() throws IOException {
if (in != null) {
in.close();
}
if (e.hasMoreElements()) {
in = (InputStream) e.nextElement();
if (in == null)
throw new NullPointerException();
}
else in = null;
}
/** {@collect.stats}
* {@description.open}
* Returns an estimate of the number of bytes that can be read (or
* skipped over) from the current underlying input stream without
* blocking by the next invocation of a method for the current
* underlying input stream. The next invocation might be
* the same thread or another thread. A single read or skip of this
* many bytes will not block, but may read or skip fewer bytes.
* <p>
* This method simply calls {@code available} of the current underlying
* input stream and returns the result.
* {@description.close}
*
* @return an estimate of the number of bytes that can be read (or
* skipped over) from the current underlying input stream
* without blocking or {@code 0} if this input stream
* has been closed by invoking its {@link #close()} method
* @exception IOException if an I/O error occurs.
*
* @since JDK1.1
*/
public int available() throws IOException {
if(in == null) {
return 0; // no way to signal EOF from available()
}
return in.available();
}
/** {@collect.stats}
* {@description.open}
* Reads the next byte of data from this input stream. The byte is
* returned as an <code>int</code> in the range <code>0</code> to
* <code>255</code>. If no byte is available because the end of the
* stream has been reached, the value <code>-1</code> is returned.
* {@description.close}
* {@description.open blocking}
* This method blocks until input data is available, the end of the
* stream is detected, or an exception is thrown.
* {@description.close}
* {@description.open}
* <p>
* This method
* tries to read one character from the current substream. If it
* reaches the end of the stream, it calls the <code>close</code>
* method of the current substream and begins reading from the next
* substream.
* {@description.close}
*
* @return the next byte of data, or <code>-1</code> if the end of the
* stream is reached.
* @exception IOException if an I/O error occurs.
*/
public int read() throws IOException {
if (in == null) {
return -1;
}
int c = in.read();
if (c == -1) {
nextStream();
return read();
}
return c;
}
/** {@collect.stats}
* {@description.open}
* Reads up to <code>len</code> bytes of data from this input stream
* into an array of bytes.
* {@description.close}
* {@description.open blocking}
* If <code>len</code> is not zero, the method
* blocks until at least 1 byte of input is available; otherwise, no
* bytes are read and <code>0</code> is returned.
* {@description.close}
* {@description.open}
* <p>
* The <code>read</code> method of <code>SequenceInputStream</code>
* tries to read the data from the current substream. If it fails to
* read any characters because the substream has reached the end of
* the stream, it calls the <code>close</code> method of the current
* substream and begins reading from the next substream.
* {@description.close}
*
* @param b the buffer into which the data is read.
* @param off the start offset in array <code>b</code>
* at which the data is written.
* @param len the maximum number of bytes read.
* @return int the number of bytes read.
* @exception NullPointerException If <code>b</code> is <code>null</code>.
* @exception IndexOutOfBoundsException If <code>off</code> is negative,
* <code>len</code> is negative, or <code>len</code> is greater than
* <code>b.length - off</code>
* @exception IOException if an I/O error occurs.
*/
public int read(byte b[], int off, int len) throws IOException {
if (in == null) {
return -1;
} else if (b == null) {
throw new NullPointerException();
} else if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
int n = in.read(b, off, len);
if (n <= 0) {
nextStream();
return read(b, off, len);
}
return n;
}
/** {@collect.stats}
* {@description.open}
* Closes this input stream and releases any system resources
* associated with the stream.
* {@description.close}
* {@property.open runtime formal:java.io.InputStream_ManipulateAfterClose}
* A closed <code>SequenceInputStream</code>
* cannot perform input operations and cannot
* be reopened.
* <p>
* {@property.close}
* {@description.open}
* If this stream was created
* from an enumeration, all remaining elements
* are requested from the enumeration and closed
* before the <code>close</code> method returns.
* {@description.close}
*
* @exception IOException if an I/O error occurs.
*/
public void close() throws IOException {
do {
nextStream();
} while (in != null);
}
}
|
Java
|
/*
* Copyright (c) 1998, 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
/** {@collect.stats}
* {@description.open}
* A filter for abstract pathnames.
*
* <p> Instances of this interface may be passed to the <code>{@link
* File#listFiles(java.io.FileFilter) listFiles(FileFilter)}</code> method
* of the <code>{@link java.io.File}</code> class.
* {@description.close}
*
* @since 1.2
*/
public interface FileFilter {
/** {@collect.stats}
* {@description.open}
* Tests whether or not the specified abstract pathname should be
* included in a pathname list.
* {@description.close}
*
* @param pathname The abstract pathname to be tested
* @return <code>true</code> if and only if <code>pathname</code>
* should be included
*/
boolean accept(File pathname);
}
|
Java
|
/*
* Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
/** {@collect.stats}
* {@description.open}
* Exception indicating the failure of an object read operation due to
* unread primitive data, or the end of data belonging to a serialized
* object in the stream. This exception may be thrown in two cases:
*
* <ul>
* <li>An attempt was made to read an object when the next element in the
* stream is primitive data. In this case, the OptionalDataException's
* length field is set to the number of bytes of primitive data
* immediately readable from the stream, and the eof field is set to
* false.
*
* <li>An attempt was made to read past the end of data consumable by a
* class-defined readObject or readExternal method. In this case, the
* OptionalDataException's eof field is set to true, and the length field
* is set to 0.
* </ul>
* {@description.close}
*
* @author unascribed
* @since JDK1.1
*/
public class OptionalDataException extends ObjectStreamException {
private static final long serialVersionUID = -8011121865681257820L;
/*
* Create an <code>OptionalDataException</code> with a length.
*/
OptionalDataException(int len) {
eof = false;
length = len;
}
/*
* Create an <code>OptionalDataException</code> signifying no
* more primitive data is available.
*/
OptionalDataException(boolean end) {
length = 0;
eof = end;
}
/** {@collect.stats}
* {@description.open}
* The number of bytes of primitive data available to be read
* in the current buffer.
* {@description.close}
*
* @serial
*/
public int length;
/** {@collect.stats}
* {@description.open}
* True if there is no more data in the buffered part of the stream.
* {@description.close}
*
* @serial
*/
public boolean eof;
}
|
Java
|
/*
* Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
import java.util.Arrays;
/** {@collect.stats}
* {@description.open}
* This class implements a character buffer that can be used as an Writer.
* The buffer automatically grows when data is written to the stream. The data
* can be retrieved using toCharArray() and toString().
* {@description.close}
* {@property.open runtime formal:java.io.Closeable_MeaninglessClose}
* <P>
* Note: Invoking close() on this class has no effect, and methods
* of this class can be called after the stream has closed
* without generating an IOException.
* {@property.close}
*
* @author Herb Jellinek
* @since JDK1.1
*/
public
class CharArrayWriter extends Writer {
/** {@collect.stats}
* {@description.open}
* The buffer where data is stored.
* {@description.close}
*/
protected char buf[];
/** {@collect.stats}
* {@description.open}
* The number of chars in the buffer.
* {@description.close}
*/
protected int count;
/** {@collect.stats}
* {@description.open}
* Creates a new CharArrayWriter.
* {@description.close}
*/
public CharArrayWriter() {
this(32);
}
/** {@collect.stats}
* {@description.open}
* Creates a new CharArrayWriter with the specified initial size.
* {@description.close}
*
* @param initialSize an int specifying the initial buffer size.
* @exception IllegalArgumentException if initialSize is negative
*/
public CharArrayWriter(int initialSize) {
if (initialSize < 0) {
throw new IllegalArgumentException("Negative initial size: "
+ initialSize);
}
buf = new char[initialSize];
}
/** {@collect.stats}
* {@description.open}
* Writes a character to the buffer.
* {@description.close}
*/
public void write(int c) {
synchronized (lock) {
int newcount = count + 1;
if (newcount > buf.length) {
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
}
buf[count] = (char)c;
count = newcount;
}
}
/** {@collect.stats}
* {@description.open}
* Writes characters to the buffer.
* {@description.close}
* @param c the data to be written
* @param off the start offset in the data
* @param len the number of chars that are written
*/
public void write(char c[], int off, int len) {
if ((off < 0) || (off > c.length) || (len < 0) ||
((off + len) > c.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
synchronized (lock) {
int newcount = count + len;
if (newcount > buf.length) {
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
}
System.arraycopy(c, off, buf, count, len);
count = newcount;
}
}
/** {@collect.stats}
* {@description.open}
* Write a portion of a string to the buffer.
* {@description.close}
* @param str String to be written from
* @param off Offset from which to start reading characters
* @param len Number of characters to be written
*/
public void write(String str, int off, int len) {
synchronized (lock) {
int newcount = count + len;
if (newcount > buf.length) {
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
}
str.getChars(off, off + len, buf, count);
count = newcount;
}
}
/** {@collect.stats}
* {@description.open}
* Writes the contents of the buffer to another character stream.
* {@description.close}
*
* @param out the output stream to write to
* @throws IOException If an I/O error occurs.
*/
public void writeTo(Writer out) throws IOException {
synchronized (lock) {
out.write(buf, 0, count);
}
}
/** {@collect.stats}
* {@description.open}
* Appends the specified character sequence to this writer.
*
* <p> An invocation of this method of the form <tt>out.append(csq)</tt>
* behaves in exactly the same way as the invocation
*
* <pre>
* out.write(csq.toString()) </pre>
*
* <p> Depending on the specification of <tt>toString</tt> for the
* character sequence <tt>csq</tt>, the entire sequence may not be
* appended. For instance, invoking the <tt>toString</tt> method of a
* character buffer will return a subsequence whose content depends upon
* the buffer's position and limit.
* {@description.close}
*
* @param csq
* The character sequence to append. If <tt>csq</tt> is
* <tt>null</tt>, then the four characters <tt>"null"</tt> are
* appended to this writer.
*
* @return This writer
*
* @since 1.5
*/
public CharArrayWriter append(CharSequence csq) {
String s = (csq == null ? "null" : csq.toString());
write(s, 0, s.length());
return this;
}
/** {@collect.stats}
* {@description.open}
* Appends a subsequence of the specified character sequence to this writer.
*
* <p> An invocation of this method of the form <tt>out.append(csq, start,
* end)</tt> when <tt>csq</tt> is not <tt>null</tt>, behaves in
* exactly the same way as the invocation
*
* <pre>
* out.write(csq.subSequence(start, end).toString()) </pre>
* {@description.close}
*
* @param csq
* The character sequence from which a subsequence will be
* appended. If <tt>csq</tt> is <tt>null</tt>, then characters
* will be appended as if <tt>csq</tt> contained the four
* characters <tt>"null"</tt>.
*
* @param start
* The index of the first character in the subsequence
*
* @param end
* The index of the character following the last character in the
* subsequence
*
* @return This writer
*
* @throws IndexOutOfBoundsException
* If <tt>start</tt> or <tt>end</tt> are negative, <tt>start</tt>
* is greater than <tt>end</tt>, or <tt>end</tt> is greater than
* <tt>csq.length()</tt>
*
* @since 1.5
*/
public CharArrayWriter append(CharSequence csq, int start, int end) {
String s = (csq == null ? "null" : csq).subSequence(start, end).toString();
write(s, 0, s.length());
return this;
}
/** {@collect.stats}
* {@description.open}
* Appends the specified character to this writer.
*
* <p> An invocation of this method of the form <tt>out.append(c)</tt>
* behaves in exactly the same way as the invocation
*
* <pre>
* out.write(c) </pre>
* {@description.close}
*
* @param c
* The 16-bit character to append
*
* @return This writer
*
* @since 1.5
*/
public CharArrayWriter append(char c) {
write(c);
return this;
}
/** {@collect.stats}
* {@description.open}
* Resets the buffer so that you can use it again without
* throwing away the already allocated buffer.
* {@description.close}
*/
public void reset() {
count = 0;
}
/** {@collect.stats}
* {@description.open}
* Returns a copy of the input data.
* {@description.close}
*
* @return an array of chars copied from the input data.
*/
public char toCharArray()[] {
synchronized (lock) {
return Arrays.copyOf(buf, count);
}
}
/** {@collect.stats}
* {@description.open}
* Returns the current size of the buffer.
* {@description.close}
*
* @return an int representing the current size of the buffer.
*/
public int size() {
return count;
}
/** {@collect.stats}
* {@description.open}
* Converts input data to a string.
* {@description.close}
* @return the string.
*/
public String toString() {
synchronized (lock) {
return new String(buf, 0, count);
}
}
/** {@collect.stats}
* {@description.open}
* Flush the stream.
* {@description.close}
*/
public void flush() { }
/** {@collect.stats}
* {@description.open}
* Close the stream.
* {@description.close}
* {@property.open runtime formal:java.io.Closeable_MeaninglessClose}
* This method does not release the buffer, since its
* contents might still be required. Note: Invoking this method in this class
* will have no effect.
* {@property.close}
*/
public void close() { }
}
|
Java
|
/*
* Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
/** {@collect.stats}
* {@description.open}
* Abstract class for writing filtered character streams.
* The abstract class <code>FilterWriter</code> itself
* provides default methods that pass all requests to the
* contained stream. Subclasses of <code>FilterWriter</code>
* should override some of these methods and may also
* provide additional methods and fields.
* {@description.close}
*
* @author Mark Reinhold
* @since JDK1.1
*/
public abstract class FilterWriter extends Writer {
/** {@collect.stats}
* {@description.open}
* The underlying character-output stream.
* {@description.close}
*/
protected Writer out;
/** {@collect.stats}
* {@description.open}
* Create a new filtered writer.
* {@description.close}
*
* @param out a Writer object to provide the underlying stream.
* @throws NullPointerException if <code>out</code> is <code>null</code>
*/
protected FilterWriter(Writer out) {
super(out);
this.out = out;
}
/** {@collect.stats}
* {@description.open}
* Writes a single character.
* {@description.close}
*
* @exception IOException If an I/O error occurs
*/
public void write(int c) throws IOException {
out.write(c);
}
/** {@collect.stats}
* {@description.open}
* Writes a portion of an array of characters.
* {@description.close}
*
* @param cbuf Buffer of characters to be written
* @param off Offset from which to start reading characters
* @param len Number of characters to be written
*
* @exception IOException If an I/O error occurs
*/
public void write(char cbuf[], int off, int len) throws IOException {
out.write(cbuf, off, len);
}
/** {@collect.stats}
* {@description.open}
* Writes a portion of a string.
* {@description.close}
*
* @param str String to be written
* @param off Offset from which to start reading characters
* @param len Number of characters to be written
*
* @exception IOException If an I/O error occurs
*/
public void write(String str, int off, int len) throws IOException {
out.write(str, off, len);
}
/** {@collect.stats}
* {@description.open}
* Flushes the stream.
* {@description.close}
*
* @exception IOException If an I/O error occurs
*/
public void flush() throws IOException {
out.flush();
}
public void close() throws IOException {
out.close();
}
}
|
Java
|
/*
* Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
/** {@collect.stats}
* {@description.open}
* Package-private abstract class for the local filesystem abstraction.
* {@description.close}
*/
abstract class FileSystem {
/** {@collect.stats}
* {@description.open}
* Return the FileSystem object representing this platform's local
* filesystem.
* {@description.close}
*/
public static native FileSystem getFileSystem();
/* -- Normalization and construction -- */
/** {@collect.stats}
* {@description.open}
* Return the local filesystem's name-separator character.
* {@description.close}
*/
public abstract char getSeparator();
/** {@collect.stats}
* {@description.open}
* Return the local filesystem's path-separator character.
* {@description.close}
*/
public abstract char getPathSeparator();
/** {@collect.stats}
* {@description.open}
* Convert the given pathname string to normal form. If the string is
* already in normal form then it is simply returned.
* {@description.close}
*/
public abstract String normalize(String path);
/** {@collect.stats}
* {@description.open}
* Compute the length of this pathname string's prefix. The pathname
* string must be in normal form.
* {@description.close}
*/
public abstract int prefixLength(String path);
/** {@collect.stats}
* {@description.open}
* Resolve the child pathname string against the parent.
* Both strings must be in normal form, and the result
* will be in normal form.
* {@description.close}
*/
public abstract String resolve(String parent, String child);
/** {@collect.stats}
* {@description.open}
* Return the parent pathname string to be used when the parent-directory
* argument in one of the two-argument File constructors is the empty
* pathname.
* {@description.close}
*/
public abstract String getDefaultParent();
/** {@collect.stats}
* {@description.open}
* Post-process the given URI path string if necessary. This is used on
* win32, e.g., to transform "/c:/foo" into "c:/foo". The path string
* still has slash separators; code in the File class will translate them
* after this method returns.
* {@description.close}
*/
public abstract String fromURIPath(String path);
/* -- Path operations -- */
/** {@collect.stats}
* {@description.open}
* Tell whether or not the given abstract pathname is absolute.
* {@description.close}
*/
public abstract boolean isAbsolute(File f);
/** {@collect.stats}
* {@description.open}
* Resolve the given abstract pathname into absolute form. Invoked by the
* getAbsolutePath and getCanonicalPath methods in the File class.
* {@description.close}
*/
public abstract String resolve(File f);
public abstract String canonicalize(String path) throws IOException;
/* -- Attribute accessors -- */
/* Constants for simple boolean attributes */
public static final int BA_EXISTS = 0x01;
public static final int BA_REGULAR = 0x02;
public static final int BA_DIRECTORY = 0x04;
public static final int BA_HIDDEN = 0x08;
/** {@collect.stats}
* {@description.open}
* Return the simple boolean attributes for the file or directory denoted
* by the given abstract pathname, or zero if it does not exist or some
* other I/O error occurs.
* {@description.close}
*/
public abstract int getBooleanAttributes(File f);
public static final int ACCESS_READ = 0x04;
public static final int ACCESS_WRITE = 0x02;
public static final int ACCESS_EXECUTE = 0x01;
/** {@collect.stats}
* {@description.open}
* Check whether the file or directory denoted by the given abstract
* pathname may be accessed by this process. The second argument specifies
* which access, ACCESS_READ, ACCESS_WRITE or ACCESS_EXECUTE, to check.
* Return false if access is denied or an I/O error occurs
* {@description.close}
*/
public abstract boolean checkAccess(File f, int access);
/** {@collect.stats}
* {@description.open}
* Set on or off the access permission (to owner only or to all) to the file
* or directory denoted by the given abstract pathname, based on the parameters
* enable, access and oweronly.
* {@description.close}
*/
public abstract boolean setPermission(File f, int access, boolean enable, boolean owneronly);
/** {@collect.stats}
* {@description.open}
* Return the time at which the file or directory denoted by the given
* abstract pathname was last modified, or zero if it does not exist or
* some other I/O error occurs.
* {@description.close}
*/
public abstract long getLastModifiedTime(File f);
/** {@collect.stats}
* {@description.open}
* Return the length in bytes of the file denoted by the given abstract
* pathname, or zero if it does not exist, is a directory, or some other
* I/O error occurs.
* {@description.close}
*/
public abstract long getLength(File f);
/* -- File operations -- */
/** {@collect.stats}
* {@description.open}
* Create a new empty file with the given pathname. Return
* <code>true</code> if the file was created and <code>false</code> if a
* file or directory with the given pathname already exists. Throw an
* IOException if an I/O error occurs.
* {@description.close}
*/
public abstract boolean createFileExclusively(String pathname)
throws IOException;
/** {@collect.stats}
* {@description.open}
* Delete the file or directory denoted by the given abstract pathname,
* returning <code>true</code> if and only if the operation succeeds.
* {@description.close}
*/
public abstract boolean delete(File f);
/** {@collect.stats}
* {@description.open}
* List the elements of the directory denoted by the given abstract
* pathname. Return an array of strings naming the elements of the
* directory if successful; otherwise, return <code>null</code>.
* {@description.close}
*/
public abstract String[] list(File f);
/** {@collect.stats}
* {@description.open}
* Create a new directory denoted by the given abstract pathname,
* returning <code>true</code> if and only if the operation succeeds.
* {@description.close}
*/
public abstract boolean createDirectory(File f);
/** {@collect.stats}
* {@description.open}
* Rename the file or directory denoted by the first abstract pathname to
* the second abstract pathname, returning <code>true</code> if and only if
* the operation succeeds.
* {@description.close}
*/
public abstract boolean rename(File f1, File f2);
/** {@collect.stats}
* {@description.open}
* Set the last-modified time of the file or directory denoted by the
* given abstract pathname, returning <code>true</code> if and only if the
* operation succeeds.
* {@description.close}
*/
public abstract boolean setLastModifiedTime(File f, long time);
/** {@collect.stats}
* {@description.open}
* Mark the file or directory denoted by the given abstract pathname as
* read-only, returning <code>true</code> if and only if the operation
* succeeds.
* {@description.close}
*/
public abstract boolean setReadOnly(File f);
/* -- Filesystem interface -- */
/** {@collect.stats}
* {@description.open}
* List the available filesystem roots.
* {@description.close}
*/
public abstract File[] listRoots();
/* -- Disk usage -- */
public static final int SPACE_TOTAL = 0;
public static final int SPACE_FREE = 1;
public static final int SPACE_USABLE = 2;
public abstract long getSpace(File f, int t);
/* -- Basic infrastructure -- */
/** {@collect.stats}
* {@description.open}
* Compare two abstract pathnames lexicographically.
* {@description.close}
*/
public abstract int compare(File f1, File f2);
/** {@collect.stats}
* {@description.open}
* Compute the hash code of an abstract pathname.
* {@description.close}
*/
public abstract int hashCode(File f);
// Flags for enabling/disabling performance optimizations for file
// name canonicalization
static boolean useCanonCaches = true;
static boolean useCanonPrefixCache = true;
private static boolean getBooleanProperty(String prop, boolean defaultVal) {
String val = System.getProperty(prop);
if (val == null) return defaultVal;
if (val.equalsIgnoreCase("true")) {
return true;
} else {
return false;
}
}
static {
useCanonCaches = getBooleanProperty("sun.io.useCanonCaches",
useCanonCaches);
useCanonPrefixCache = getBooleanProperty("sun.io.useCanonPrefixCache",
useCanonPrefixCache);
}
}
|
Java
|
/*
* Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
/** {@collect.stats}
* {@description.open}
* Signals that one of the ObjectStreamExceptions was thrown during a
* write operation. Thrown during a read operation when one of the
* ObjectStreamExceptions was thrown during a write operation. The
* exception that terminated the write can be found in the detail
* field. The stream is reset to it's initial state and all references
* to objects already deserialized are discarded.
*
* <p>As of release 1.4, this exception has been retrofitted to conform to
* the general purpose exception-chaining mechanism. The "exception causing
* the abort" that is provided at construction time and
* accessed via the public {@link #detail} field is now known as the
* <i>cause</i>, and may be accessed via the {@link Throwable#getCause()}
* method, as well as the aforementioned "legacy field."
* {@description.close}
*
* @author unascribed
* @since JDK1.1
*/
public class WriteAbortedException extends ObjectStreamException {
private static final long serialVersionUID = -3326426625597282442L;
/** {@collect.stats}
* {@description.open}
* Exception that was caught while writing the ObjectStream.
*
* <p>This field predates the general-purpose exception chaining facility.
* The {@link Throwable#getCause()} method is now the preferred means of
* obtaining this information.
* {@description.close}
*
* @serial
*/
public Exception detail;
/** {@collect.stats}
* {@description.open}
* Constructs a WriteAbortedException with a string describing
* the exception and the exception causing the abort.
* {@description.close}
* @param s String describing the exception.
* @param ex Exception causing the abort.
*/
public WriteAbortedException(String s, Exception ex) {
super(s);
initCause(null); // Disallow subsequent initCause
detail = ex;
}
/** {@collect.stats}
* {@description.open}
* Produce the message and include the message from the nested
* exception, if there is one.
* {@description.close}
*/
public String getMessage() {
if (detail == null)
return super.getMessage();
else
return super.getMessage() + "; " + detail.toString();
}
/** {@collect.stats}
* {@description.open}
* Returns the exception that terminated the operation (the <i>cause</i>).
* {@description.close}
*
* @return the exception that terminated the operation (the <i>cause</i>),
* which may be null.
* @since 1.4
*/
public Throwable getCause() {
return detail;
}
}
|
Java
|
/*
* Copyright (c) 1996, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
/** {@collect.stats}
* {@description.open}
* Convenience class for writing character files. The constructors of this
* class assume that the default character encoding and the default byte-buffer
* size are acceptable. To specify these values yourself, construct an
* OutputStreamWriter on a FileOutputStream.
* {@description.close}
*
* {@property.open}
* <p>Whether or not a file is available or may be created depends upon the
* underlying platform. Some platforms, in particular, allow a file to be
* opened for writing by only one <tt>FileWriter</tt> (or other file-writing
* object) at a time. In such situations the constructors in this class
* will fail if the file involved is already open.
* {@property.close}
*
* {@description.open}
* <p><code>FileWriter</code> is meant for writing streams of characters.
* For writing streams of raw bytes, consider using a
* <code>FileOutputStream</code>.
* {@description.close}
*
* @see OutputStreamWriter
* @see FileOutputStream
*
* @author Mark Reinhold
* @since JDK1.1
*/
public class FileWriter extends OutputStreamWriter {
/** {@collect.stats}
* {@description.open}
* Constructs a FileWriter object given a file name.
* {@description.close}
*
* @param fileName String The system-dependent filename.
* @throws IOException if the named file exists but is a directory rather
* than a regular file, does not exist but cannot be
* created, or cannot be opened for any other reason
*/
public FileWriter(String fileName) throws IOException {
super(new FileOutputStream(fileName));
}
/** {@collect.stats}
* {@description.open}
* Constructs a FileWriter object given a file name with a boolean
* indicating whether or not to append the data written.
* {@description.close}
*
* @param fileName String The system-dependent filename.
* @param append boolean if <code>true</code>, then data will be written
* to the end of the file rather than the beginning.
* @throws IOException if the named file exists but is a directory rather
* than a regular file, does not exist but cannot be
* created, or cannot be opened for any other reason
*/
public FileWriter(String fileName, boolean append) throws IOException {
super(new FileOutputStream(fileName, append));
}
/** {@collect.stats}
* {@description.open}
* Constructs a FileWriter object given a File object.
* {@description.close}
*
* @param file a File object to write to.
* @throws IOException if the file exists but is a directory rather than
* a regular file, does not exist but cannot be created,
* or cannot be opened for any other reason
*/
public FileWriter(File file) throws IOException {
super(new FileOutputStream(file));
}
/** {@collect.stats}
* {@description.open}
* Constructs a FileWriter object given a File object. If the second
* argument is <code>true</code>, then bytes will be written to the end
* of the file rather than the beginning.
* {@description.close}
*
* @param file a File object to write to
* @param append if <code>true</code>, then bytes will be written
* to the end of the file rather than the beginning
* @throws IOException if the file exists but is a directory rather than
* a regular file, does not exist but cannot be created,
* or cannot be opened for any other reason
* @since 1.4
*/
public FileWriter(File file, boolean append) throws IOException {
super(new FileOutputStream(file, append));
}
/** {@collect.stats}
* {@description.open}
* Constructs a FileWriter object associated with a file descriptor.
* {@description.close}
*
* @param fd FileDescriptor object to write to.
*/
public FileWriter(FileDescriptor fd) {
super(new FileOutputStream(fd));
}
}
|
Java
|
/*
* Copyright (c) 1996, 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
/** {@collect.stats}
* {@description.open}
* Callback interface to allow validation of objects within a graph.
* Allows an object to be called when a complete graph of objects has
* been deserialized.
* {@description.close}
*
* @author unascribed
* @see ObjectInputStream
* @see ObjectInputStream#registerValidation(java.io.ObjectInputValidation, int)
* @since JDK1.1
*/
public interface ObjectInputValidation {
/** {@collect.stats}
* {@description.open}
* Validates the object.
* {@description.close}
*
* @exception InvalidObjectException If the object cannot validate itself.
*/
public void validateObject() throws InvalidObjectException;
}
|
Java
|
/*
* Copyright (c) 1994, 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
/** {@collect.stats}
* {@description.open}
* This class is the superclass of all classes that filter output
* streams. These streams sit on top of an already existing output
* stream (the <i>underlying</i> output stream) which it uses as its
* basic sink of data, but possibly transforming the data along the
* way or providing additional functionality.
* <p>
* The class <code>FilterOutputStream</code> itself simply overrides
* all methods of <code>OutputStream</code> with versions that pass
* all requests to the underlying output stream. Subclasses of
* <code>FilterOutputStream</code> may further override some of these
* methods as well as provide additional methods and fields.
* {@description.close}
*
* @author Jonathan Payne
* @since JDK1.0
*/
public
class FilterOutputStream extends OutputStream {
/** {@collect.stats}
* {@description.open}
* The underlying output stream to be filtered.
* {@description.close}
*/
protected OutputStream out;
/** {@collect.stats}
* {@description.open}
* Creates an output stream filter built on top of the specified
* underlying output stream.
* {@description.close}
*
* @param out the underlying output stream to be assigned to
* the field <tt>this.out</tt> for later use, or
* <code>null</code> if this instance is to be
* created without an underlying stream.
*/
public FilterOutputStream(OutputStream out) {
this.out = out;
}
/** {@collect.stats}
* {@description.open}
* Writes the specified <code>byte</code> to this output stream.
* <p>
* The <code>write</code> method of <code>FilterOutputStream</code>
* calls the <code>write</code> method of its underlying output stream,
* that is, it performs <tt>out.write(b)</tt>.
* <p>
* Implements the abstract <tt>write</tt> method of <tt>OutputStream</tt>.
* {@description.close}
*
* @param b the <code>byte</code>.
* @exception IOException if an I/O error occurs.
*/
public void write(int b) throws IOException {
out.write(b);
}
/** {@collect.stats}
* {@description.open}
* Writes <code>b.length</code> bytes to this output stream.
* <p>
* The <code>write</code> method of <code>FilterOutputStream</code>
* calls its <code>write</code> method of three arguments with the
* arguments <code>b</code>, <code>0</code>, and
* <code>b.length</code>.
* <p>
* Note that this method does not call the one-argument
* <code>write</code> method of its underlying stream with the single
* argument <code>b</code>.
* {@description.close}
*
* @param b the data to be written.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#write(byte[], int, int)
*/
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
/** {@collect.stats}
* {@description.open}
* Writes <code>len</code> bytes from the specified
* <code>byte</code> array starting at offset <code>off</code> to
* this output stream.
* <p>
* The <code>write</code> method of <code>FilterOutputStream</code>
* calls the <code>write</code> method of one argument on each
* <code>byte</code> to output.
* <p>
* Note that this method does not call the <code>write</code> method
* of its underlying input stream with the same arguments. Subclasses
* of <code>FilterOutputStream</code> should provide a more efficient
* implementation of this method.
* {@description.close}
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#write(int)
*/
public void write(byte b[], int off, int len) throws IOException {
if ((off | len | (b.length - (len + off)) | (off + len)) < 0)
throw new IndexOutOfBoundsException();
for (int i = 0 ; i < len ; i++) {
write(b[off + i]);
}
}
/** {@collect.stats}
* {@description.open}
* Flushes this output stream and forces any buffered output bytes
* to be written out to the stream.
* <p>
* The <code>flush</code> method of <code>FilterOutputStream</code>
* calls the <code>flush</code> method of its underlying output stream.
* {@description.close}
*
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
public void flush() throws IOException {
out.flush();
}
/** {@collect.stats}
* {@description.open}
* Closes this output stream and releases any system resources
* associated with the stream.
* <p>
* The <code>close</code> method of <code>FilterOutputStream</code>
* calls its <code>flush</code> method, and then calls the
* <code>close</code> method of its underlying output stream.
* {@description.close}
*
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#flush()
* @see java.io.FilterOutputStream#out
*/
public void close() throws IOException {
try {
flush();
} catch (IOException ignored) {
}
out.close();
}
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
import java.util.Formatter;
import java.util.Locale;
/** {@collect.stats}
* {@description.open}
* A <code>PrintStream</code> adds functionality to another output stream,
* namely the ability to print representations of various data values
* conveniently. Two other features are provided as well. Unlike other output
* streams, a <code>PrintStream</code> never throws an
* <code>IOException</code>; instead, exceptional situations merely set an
* internal flag that can be tested via the <code>checkError</code> method.
* Optionally, a <code>PrintStream</code> can be created so as to flush
* automatically; this means that the <code>flush</code> method is
* automatically invoked after a byte array is written, one of the
* <code>println</code> methods is invoked, or a newline character or byte
* (<code>'\n'</code>) is written.
*
* <p> All characters printed by a <code>PrintStream</code> are converted into
* bytes using the platform's default character encoding. The <code>{@link
* PrintWriter}</code> class should be used in situations that require writing
* characters rather than bytes.
* {@description.close}
*
* @author Frank Yellin
* @author Mark Reinhold
* @since JDK1.0
*/
public class PrintStream extends FilterOutputStream
implements Appendable, Closeable
{
private boolean autoFlush = false;
private boolean trouble = false;
private Formatter formatter;
/** {@collect.stats}
* {@description.open}
* Track both the text- and character-output streams, so that their buffers
* can be flushed without flushing the entire stream.
* {@description.close}
*/
private BufferedWriter textOut;
private OutputStreamWriter charOut;
/** {@collect.stats}
* {@description.open}
* Creates a new print stream. This stream will not flush automatically.
* {@description.close}
*
* @param out The output stream to which values and objects will be
* printed
*
* @see java.io.PrintWriter#PrintWriter(java.io.OutputStream)
*/
public PrintStream(OutputStream out) {
this(out, false);
}
/* Initialization is factored into a private constructor (note the swapped
* parameters so that this one isn't confused with the public one) and a
* separate init method so that the following two public constructors can
* share code. We use a separate init method so that the constructor that
* takes an encoding will throw an NPE for a null stream before it throws
* an UnsupportedEncodingException for an unsupported encoding.
*/
private PrintStream(boolean autoFlush, OutputStream out)
{
super(out);
if (out == null)
throw new NullPointerException("Null output stream");
this.autoFlush = autoFlush;
}
private void init(OutputStreamWriter osw) {
this.charOut = osw;
this.textOut = new BufferedWriter(osw);
}
/** {@collect.stats}
* {@description.open}
* Creates a new print stream.
* {@description.close}
*
* @param out The output stream to which values and objects will be
* printed
* @param autoFlush A boolean; if true, the output buffer will be flushed
* whenever a byte array is written, one of the
* <code>println</code> methods is invoked, or a newline
* character or byte (<code>'\n'</code>) is written
*
* @see java.io.PrintWriter#PrintWriter(java.io.OutputStream, boolean)
*/
public PrintStream(OutputStream out, boolean autoFlush) {
this(autoFlush, out);
init(new OutputStreamWriter(this));
}
/** {@collect.stats}
* {@description.open}
* Creates a new print stream.
* {@description.close}
*
* @param out The output stream to which values and objects will be
* printed
* @param autoFlush A boolean; if true, the output buffer will be flushed
* whenever a byte array is written, one of the
* <code>println</code> methods is invoked, or a newline
* character or byte (<code>'\n'</code>) is written
* @param encoding The name of a supported
* <a href="../lang/package-summary.html#charenc">
* character encoding</a>
*
* @throws UnsupportedEncodingException
* If the named encoding is not supported
*
* @since 1.4
*/
public PrintStream(OutputStream out, boolean autoFlush, String encoding)
throws UnsupportedEncodingException
{
this(autoFlush, out);
init(new OutputStreamWriter(this, encoding));
}
/** {@collect.stats}
* {@description.open}
* Creates a new print stream, without automatic line flushing, with the
* specified file name. This convenience constructor creates
* the necessary intermediate {@link java.io.OutputStreamWriter
* OutputStreamWriter}, which will encode characters using the
* {@linkplain java.nio.charset.Charset#defaultCharset() default charset}
* for this instance of the Java virtual machine.
* {@description.close}
*
* @param fileName
* The name of the file to use as the destination of this print
* stream. If the file exists, then it will be truncated to
* zero size; otherwise, a new file will be created. The output
* will be written to the file and is buffered.
*
* @throws FileNotFoundException
* If the given file object does not denote an existing, writable
* regular file and a new regular file of that name cannot be
* created, or if some other error occurs while opening or
* creating the file
*
* @throws SecurityException
* If a security manager is present and {@link
* SecurityManager#checkWrite checkWrite(fileName)} denies write
* access to the file
*
* @since 1.5
*/
public PrintStream(String fileName) throws FileNotFoundException {
this(false, new FileOutputStream(fileName));
init(new OutputStreamWriter(this));
}
/** {@collect.stats}
* {@description.open}
* Creates a new print stream, without automatic line flushing, with the
* specified file name and charset. This convenience constructor creates
* the necessary intermediate {@link java.io.OutputStreamWriter
* OutputStreamWriter}, which will encode characters using the provided
* charset.
* {@description.close}
*
* @param fileName
* The name of the file to use as the destination of this print
* stream. If the file exists, then it will be truncated to
* zero size; otherwise, a new file will be created. The output
* will be written to the file and is buffered.
*
* @param csn
* The name of a supported {@linkplain java.nio.charset.Charset
* charset}
*
* @throws FileNotFoundException
* If the given file object does not denote an existing, writable
* regular file and a new regular file of that name cannot be
* created, or if some other error occurs while opening or
* creating the file
*
* @throws SecurityException
* If a security manager is present and {@link
* SecurityManager#checkWrite checkWrite(fileName)} denies write
* access to the file
*
* @throws UnsupportedEncodingException
* If the named charset is not supported
*
* @since 1.5
*/
public PrintStream(String fileName, String csn)
throws FileNotFoundException, UnsupportedEncodingException
{
this(false, new FileOutputStream(fileName));
init(new OutputStreamWriter(this, csn));
}
/** {@collect.stats}
* {@description.open}
* Creates a new print stream, without automatic line flushing, with the
* specified file. This convenience constructor creates the necessary
* intermediate {@link java.io.OutputStreamWriter OutputStreamWriter},
* which will encode characters using the {@linkplain
* java.nio.charset.Charset#defaultCharset() default charset} for this
* instance of the Java virtual machine.
* {@description.close}
*
* @param file
* The file to use as the destination of this print stream. If the
* file exists, then it will be truncated to zero size; otherwise,
* a new file will be created. The output will be written to the
* file and is buffered.
*
* @throws FileNotFoundException
* If the given file object does not denote an existing, writable
* regular file and a new regular file of that name cannot be
* created, or if some other error occurs while opening or
* creating the file
*
* @throws SecurityException
* If a security manager is present and {@link
* SecurityManager#checkWrite checkWrite(file.getPath())}
* denies write access to the file
*
* @since 1.5
*/
public PrintStream(File file) throws FileNotFoundException {
this(false, new FileOutputStream(file));
init(new OutputStreamWriter(this));
}
/** {@collect.stats}
* {@description.open}
* Creates a new print stream, without automatic line flushing, with the
* specified file and charset. This convenience constructor creates
* the necessary intermediate {@link java.io.OutputStreamWriter
* OutputStreamWriter}, which will encode characters using the provided
* charset.
* {@description.close}
*
* @param file
* The file to use as the destination of this print stream. If the
* file exists, then it will be truncated to zero size; otherwise,
* a new file will be created. The output will be written to the
* file and is buffered.
*
* @param csn
* The name of a supported {@linkplain java.nio.charset.Charset
* charset}
*
* @throws FileNotFoundException
* If the given file object does not denote an existing, writable
* regular file and a new regular file of that name cannot be
* created, or if some other error occurs while opening or
* creating the file
*
* @throws SecurityException
* If a security manager is presentand {@link
* SecurityManager#checkWrite checkWrite(file.getPath())}
* denies write access to the file
*
* @throws UnsupportedEncodingException
* If the named charset is not supported
*
* @since 1.5
*/
public PrintStream(File file, String csn)
throws FileNotFoundException, UnsupportedEncodingException
{
this(false, new FileOutputStream(file));
init(new OutputStreamWriter(this, csn));
}
/** {@collect.stats}
* {@description.open}
* Check to make sure that the stream has not been closed
* {@description.close}
*/
private void ensureOpen() throws IOException {
if (out == null)
throw new IOException("Stream closed");
}
/** {@collect.stats}
* {@description.open}
* Flushes the stream. This is done by writing any buffered output bytes to
* the underlying output stream and then flushing that stream.
* {@description.close}
*
* @see java.io.OutputStream#flush()
*/
public void flush() {
synchronized (this) {
try {
ensureOpen();
out.flush();
}
catch (IOException x) {
trouble = true;
}
}
}
private boolean closing = false; /* To avoid recursive closing */
/** {@collect.stats}
* {@description.open}
* Closes the stream. This is done by flushing the stream and then closing
* the underlying output stream.
* {@description.close}
*
* @see java.io.OutputStream#close()
*/
public void close() {
synchronized (this) {
if (! closing) {
closing = true;
try {
textOut.close();
out.close();
}
catch (IOException x) {
trouble = true;
}
textOut = null;
charOut = null;
out = null;
}
}
}
/** {@collect.stats}
* {@description.open}
* Flushes the stream and checks its error state. The internal error state
* is set to <code>true</code> when the underlying output stream throws an
* <code>IOException</code> other than <code>InterruptedIOException</code>,
* and when the <code>setError</code> method is invoked. If an operation
* on the underlying output stream throws an
* <code>InterruptedIOException</code>, then the <code>PrintStream</code>
* converts the exception back into an interrupt by doing:
* <pre>
* Thread.currentThread().interrupt();
* </pre>
* or the equivalent.
* {@description.close}
*
* @return <code>true</code> if and only if this stream has encountered an
* <code>IOException</code> other than
* <code>InterruptedIOException</code>, or the
* <code>setError</code> method has been invoked
*/
public boolean checkError() {
if (out != null)
flush();
if (out instanceof java.io.PrintStream) {
PrintStream ps = (PrintStream) out;
return ps.checkError();
}
return trouble;
}
/** {@collect.stats}
* {@description.open}
* Sets the error state of the stream to <code>true</code>.
*
* <p> This method will cause subsequent invocations of {@link
* #checkError()} to return <tt>true</tt> until {@link
* #clearError()} is invoked.
* {@description.close}
*
* @since JDK1.1
*/
protected void setError() {
trouble = true;
}
/** {@collect.stats}
* {@description.open}
* Clears the internal error state of this stream.
*
* <p> This method will cause subsequent invocations of {@link
* #checkError()} to return <tt>false</tt> until another write
* operation fails and invokes {@link #setError()}.
* {@description.close}
*
* @since 1.6
*/
protected void clearError() {
trouble = false;
}
/*
* Exception-catching, synchronized output operations,
* which also implement the write() methods of OutputStream
*/
/** {@collect.stats}
* {@description.open}
* Writes the specified byte to this stream. If the byte is a newline and
* automatic flushing is enabled then the <code>flush</code> method will be
* invoked.
*
* <p> Note that the byte is written as given; to write a character that
* will be translated according to the platform's default character
* encoding, use the <code>print(char)</code> or <code>println(char)</code>
* methods.
* {@description.close}
*
* @param b The byte to be written
* @see #print(char)
* @see #println(char)
*/
public void write(int b) {
try {
synchronized (this) {
ensureOpen();
out.write(b);
if ((b == '\n') && autoFlush)
out.flush();
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}
/** {@collect.stats}
* {@description.open}
* Writes <code>len</code> bytes from the specified byte array starting at
* offset <code>off</code> to this stream. If automatic flushing is
* enabled then the <code>flush</code> method will be invoked.
*
* <p> Note that the bytes will be written as given; to write characters
* that will be translated according to the platform's default character
* encoding, use the <code>print(char)</code> or <code>println(char)</code>
* methods.
* {@description.close}
*
* @param buf A byte array
* @param off Offset from which to start taking bytes
* @param len Number of bytes to write
*/
public void write(byte buf[], int off, int len) {
try {
synchronized (this) {
ensureOpen();
out.write(buf, off, len);
if (autoFlush)
out.flush();
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}
/*
* The following private methods on the text- and character-output streams
* always flush the stream buffers, so that writes to the underlying byte
* stream occur as promptly as with the original PrintStream.
*/
private void write(char buf[]) {
try {
synchronized (this) {
ensureOpen();
textOut.write(buf);
textOut.flushBuffer();
charOut.flushBuffer();
if (autoFlush) {
for (int i = 0; i < buf.length; i++)
if (buf[i] == '\n')
out.flush();
}
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}
private void write(String s) {
try {
synchronized (this) {
ensureOpen();
textOut.write(s);
textOut.flushBuffer();
charOut.flushBuffer();
if (autoFlush && (s.indexOf('\n') >= 0))
out.flush();
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}
private void newLine() {
try {
synchronized (this) {
ensureOpen();
textOut.newLine();
textOut.flushBuffer();
charOut.flushBuffer();
if (autoFlush)
out.flush();
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}
/* Methods that do not terminate lines */
/** {@collect.stats}
* {@description.open}
* Prints a boolean value. The string produced by <code>{@link
* java.lang.String#valueOf(boolean)}</code> is translated into bytes
* according to the platform's default character encoding, and these bytes
* are written in exactly the manner of the
* <code>{@link #write(int)}</code> method.
* {@description.close}
*
* @param b The <code>boolean</code> to be printed
*/
public void print(boolean b) {
write(b ? "true" : "false");
}
/** {@collect.stats}
* {@description.open}
* Prints a character. The character is translated into one or more bytes
* according to the platform's default character encoding, and these bytes
* are written in exactly the manner of the
* <code>{@link #write(int)}</code> method.
* {@description.close}
*
* @param c The <code>char</code> to be printed
*/
public void print(char c) {
write(String.valueOf(c));
}
/** {@collect.stats}
* {@description.open}
* Prints an integer. The string produced by <code>{@link
* java.lang.String#valueOf(int)}</code> is translated into bytes
* according to the platform's default character encoding, and these bytes
* are written in exactly the manner of the
* <code>{@link #write(int)}</code> method.
* {@description.close}
*
* @param i The <code>int</code> to be printed
* @see java.lang.Integer#toString(int)
*/
public void print(int i) {
write(String.valueOf(i));
}
/** {@collect.stats}
* {@description.open}
* Prints a long integer. The string produced by <code>{@link
* java.lang.String#valueOf(long)}</code> is translated into bytes
* according to the platform's default character encoding, and these bytes
* are written in exactly the manner of the
* <code>{@link #write(int)}</code> method.
* {@description.close}
*
* @param l The <code>long</code> to be printed
* @see java.lang.Long#toString(long)
*/
public void print(long l) {
write(String.valueOf(l));
}
/** {@collect.stats}
* {@description.open}
* Prints a floating-point number. The string produced by <code>{@link
* java.lang.String#valueOf(float)}</code> is translated into bytes
* according to the platform's default character encoding, and these bytes
* are written in exactly the manner of the
* <code>{@link #write(int)}</code> method.
* {@description.close}
*
* @param f The <code>float</code> to be printed
* @see java.lang.Float#toString(float)
*/
public void print(float f) {
write(String.valueOf(f));
}
/** {@collect.stats}
* {@description.open}
* Prints a double-precision floating-point number. The string produced by
* <code>{@link java.lang.String#valueOf(double)}</code> is translated into
* bytes according to the platform's default character encoding, and these
* bytes are written in exactly the manner of the <code>{@link
* #write(int)}</code> method.
* {@description.close}
*
* @param d The <code>double</code> to be printed
* @see java.lang.Double#toString(double)
*/
public void print(double d) {
write(String.valueOf(d));
}
/** {@collect.stats}
* {@description.open}
* Prints an array of characters. The characters are converted into bytes
* according to the platform's default character encoding, and these bytes
* are written in exactly the manner of the
* <code>{@link #write(int)}</code> method.
* {@description.close}
*
* @param s The array of chars to be printed
*
* @throws NullPointerException If <code>s</code> is <code>null</code>
*/
public void print(char s[]) {
write(s);
}
/** {@collect.stats}
* {@description.open}
* Prints a string. If the argument is <code>null</code> then the string
* <code>"null"</code> is printed. Otherwise, the string's characters are
* converted into bytes according to the platform's default character
* encoding, and these bytes are written in exactly the manner of the
* <code>{@link #write(int)}</code> method.
* {@description.close}
*
* @param s The <code>String</code> to be printed
*/
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
/** {@collect.stats}
* {@description.open}
* Prints an object. The string produced by the <code>{@link
* java.lang.String#valueOf(Object)}</code> method is translated into bytes
* according to the platform's default character encoding, and these bytes
* are written in exactly the manner of the
* <code>{@link #write(int)}</code> method.
* {@description.close}
*
* @param obj The <code>Object</code> to be printed
* @see java.lang.Object#toString()
*/
public void print(Object obj) {
write(String.valueOf(obj));
}
/* Methods that do terminate lines */
/** {@collect.stats}
* {@description.open}
* Terminates the current line by writing the line separator string. The
* line separator string is defined by the system property
* <code>line.separator</code>, and is not necessarily a single newline
* character (<code>'\n'</code>).
* {@description.close}
*/
public void println() {
newLine();
}
/** {@collect.stats}
* {@description.open}
* Prints a boolean and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(boolean)}</code> and then
* <code>{@link #println()}</code>.
* {@description.close}
*
* @param x The <code>boolean</code> to be printed
*/
public void println(boolean x) {
synchronized (this) {
print(x);
newLine();
}
}
/** {@collect.stats}
* {@description.open}
* Prints a character and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(char)}</code> and then
* <code>{@link #println()}</code>.
* {@description.close}
*
* @param x The <code>char</code> to be printed.
*/
public void println(char x) {
synchronized (this) {
print(x);
newLine();
}
}
/** {@collect.stats}
* {@description.open}
* Prints an integer and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(int)}</code> and then
* <code>{@link #println()}</code>.
* {@description.close}
*
* @param x The <code>int</code> to be printed.
*/
public void println(int x) {
synchronized (this) {
print(x);
newLine();
}
}
/** {@collect.stats}
* {@description.open}
* Prints a long and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(long)}</code> and then
* <code>{@link #println()}</code>.
* {@description.close}
*
* @param x a The <code>long</code> to be printed.
*/
public void println(long x) {
synchronized (this) {
print(x);
newLine();
}
}
/** {@collect.stats}
* {@description.open}
* Prints a float and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(float)}</code> and then
* <code>{@link #println()}</code>.
* {@description.close}
*
* @param x The <code>float</code> to be printed.
*/
public void println(float x) {
synchronized (this) {
print(x);
newLine();
}
}
/** {@collect.stats}
* {@description.open}
* Prints a double and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(double)}</code> and then
* <code>{@link #println()}</code>.
* {@description.close}
*
* @param x The <code>double</code> to be printed.
*/
public void println(double x) {
synchronized (this) {
print(x);
newLine();
}
}
/** {@collect.stats}
* {@description.open}
* Prints an array of characters and then terminate the line. This method
* behaves as though it invokes <code>{@link #print(char[])}</code> and
* then <code>{@link #println()}</code>.
* {@description.close}
*
* @param x an array of chars to print.
*/
public void println(char x[]) {
synchronized (this) {
print(x);
newLine();
}
}
/** {@collect.stats}
* {@description.open}
* Prints a String and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
* {@description.close}
*
* @param x The <code>String</code> to be printed.
*/
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
/** {@collect.stats}
* {@description.open}
* Prints an Object and then terminate the line. This method calls
* at first String.valueOf(x) to get the printed object's string value,
* then behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
* {@description.close}
*
* @param x The <code>Object</code> to be printed.
*/
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
/** {@collect.stats}
* {@description.open}
* A convenience method to write a formatted string to this output stream
* using the specified format string and arguments.
*
* <p> An invocation of this method of the form <tt>out.printf(format,
* args)</tt> behaves in exactly the same way as the invocation
*
* <pre>
* out.format(format, args) </pre>
* {@description.close}
*
* @param format
* A format string as described in <a
* href="../util/Formatter.html#syntax">Format string syntax</a>
*
* @param args
* Arguments referenced by the format specifiers in the format
* string. If there are more arguments than format specifiers, the
* extra arguments are ignored. The number of arguments is
* variable and may be zero. The maximum number of arguments is
* limited by the maximum dimension of a Java array as defined by
* the <a href="http://java.sun.com/docs/books/vmspec/">Java
* Virtual Machine Specification</a>. The behaviour on a
* <tt>null</tt> argument depends on the <a
* href="../util/Formatter.html#syntax">conversion</a>.
*
* @throws IllegalFormatException
* If a format string contains an illegal syntax, a format
* specifier that is incompatible with the given arguments,
* insufficient arguments given the format string, or other
* illegal conditions. For specification of all possible
* formatting errors, see the <a
* href="../util/Formatter.html#detail">Details</a> section of the
* formatter class specification.
*
* @throws NullPointerException
* If the <tt>format</tt> is <tt>null</tt>
*
* @return This output stream
*
* @since 1.5
*/
public PrintStream printf(String format, Object ... args) {
return format(format, args);
}
/** {@collect.stats}
* {@description.open}
* A convenience method to write a formatted string to this output stream
* using the specified format string and arguments.
*
* <p> An invocation of this method of the form <tt>out.printf(l, format,
* args)</tt> behaves in exactly the same way as the invocation
*
* <pre>
* out.format(l, format, args) </pre>
* {@description.close}
*
* @param l
* The {@linkplain java.util.Locale locale} to apply during
* formatting. If <tt>l</tt> is <tt>null</tt> then no localization
* is applied.
*
* @param format
* A format string as described in <a
* href="../util/Formatter.html#syntax">Format string syntax</a>
*
* @param args
* Arguments referenced by the format specifiers in the format
* string. If there are more arguments than format specifiers, the
* extra arguments are ignored. The number of arguments is
* variable and may be zero. The maximum number of arguments is
* limited by the maximum dimension of a Java array as defined by
* the <a href="http://java.sun.com/docs/books/vmspec/">Java
* Virtual Machine Specification</a>. The behaviour on a
* <tt>null</tt> argument depends on the <a
* href="../util/Formatter.html#syntax">conversion</a>.
*
* @throws IllegalFormatException
* If a format string contains an illegal syntax, a format
* specifier that is incompatible with the given arguments,
* insufficient arguments given the format string, or other
* illegal conditions. For specification of all possible
* formatting errors, see the <a
* href="../util/Formatter.html#detail">Details</a> section of the
* formatter class specification.
*
* @throws NullPointerException
* If the <tt>format</tt> is <tt>null</tt>
*
* @return This output stream
*
* @since 1.5
*/
public PrintStream printf(Locale l, String format, Object ... args) {
return format(l, format, args);
}
/** {@collect.stats}
* {@description.open}
* Writes a formatted string to this output stream using the specified
* format string and arguments.
*
* <p> The locale always used is the one returned by {@link
* java.util.Locale#getDefault() Locale.getDefault()}, regardless of any
* previous invocations of other formatting methods on this object.
* {@description.close}
*
* @param format
* A format string as described in <a
* href="../util/Formatter.html#syntax">Format string syntax</a>
*
* @param args
* Arguments referenced by the format specifiers in the format
* string. If there are more arguments than format specifiers, the
* extra arguments are ignored. The number of arguments is
* variable and may be zero. The maximum number of arguments is
* limited by the maximum dimension of a Java array as defined by
* the <a href="http://java.sun.com/docs/books/vmspec/">Java
* Virtual Machine Specification</a>. The behaviour on a
* <tt>null</tt> argument depends on the <a
* href="../util/Formatter.html#syntax">conversion</a>.
*
* @throws IllegalFormatException
* If a format string contains an illegal syntax, a format
* specifier that is incompatible with the given arguments,
* insufficient arguments given the format string, or other
* illegal conditions. For specification of all possible
* formatting errors, see the <a
* href="../util/Formatter.html#detail">Details</a> section of the
* formatter class specification.
*
* @throws NullPointerException
* If the <tt>format</tt> is <tt>null</tt>
*
* @return This output stream
*
* @since 1.5
*/
public PrintStream format(String format, Object ... args) {
try {
synchronized (this) {
ensureOpen();
if ((formatter == null)
|| (formatter.locale() != Locale.getDefault()))
formatter = new Formatter((Appendable) this);
formatter.format(Locale.getDefault(), format, args);
}
} catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
} catch (IOException x) {
trouble = true;
}
return this;
}
/** {@collect.stats}
* {@description.open}
* Writes a formatted string to this output stream using the specified
* format string and arguments.
* {@description.close}
*
* @param l
* The {@linkplain java.util.Locale locale} to apply during
* formatting. If <tt>l</tt> is <tt>null</tt> then no localization
* is applied.
*
* @param format
* A format string as described in <a
* href="../util/Formatter.html#syntax">Format string syntax</a>
*
* @param args
* Arguments referenced by the format specifiers in the format
* string. If there are more arguments than format specifiers, the
* extra arguments are ignored. The number of arguments is
* variable and may be zero. The maximum number of arguments is
* limited by the maximum dimension of a Java array as defined by
* the <a href="http://java.sun.com/docs/books/vmspec/">Java
* Virtual Machine Specification</a>. The behaviour on a
* <tt>null</tt> argument depends on the <a
* href="../util/Formatter.html#syntax">conversion</a>.
*
* @throws IllegalFormatException
* If a format string contains an illegal syntax, a format
* specifier that is incompatible with the given arguments,
* insufficient arguments given the format string, or other
* illegal conditions. For specification of all possible
* formatting errors, see the <a
* href="../util/Formatter.html#detail">Details</a> section of the
* formatter class specification.
*
* @throws NullPointerException
* If the <tt>format</tt> is <tt>null</tt>
*
* @return This output stream
*
* @since 1.5
*/
public PrintStream format(Locale l, String format, Object ... args) {
try {
synchronized (this) {
ensureOpen();
if ((formatter == null)
|| (formatter.locale() != l))
formatter = new Formatter(this, l);
formatter.format(l, format, args);
}
} catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
} catch (IOException x) {
trouble = true;
}
return this;
}
/** {@collect.stats}
* {@description.open}
* Appends the specified character sequence to this output stream.
*
* <p> An invocation of this method of the form <tt>out.append(csq)</tt>
* behaves in exactly the same way as the invocation
*
* <pre>
* out.print(csq.toString()) </pre>
*
* <p> Depending on the specification of <tt>toString</tt> for the
* character sequence <tt>csq</tt>, the entire sequence may not be
* appended. For instance, invoking then <tt>toString</tt> method of a
* character buffer will return a subsequence whose content depends upon
* the buffer's position and limit.
* {@description.close}
*
* @param csq
* The character sequence to append. If <tt>csq</tt> is
* <tt>null</tt>, then the four characters <tt>"null"</tt> are
* appended to this output stream.
*
* @return This output stream
*
* @since 1.5
*/
public PrintStream append(CharSequence csq) {
if (csq == null)
print("null");
else
print(csq.toString());
return this;
}
/** {@collect.stats}
* {@description.open}
* Appends a subsequence of the specified character sequence to this output
* stream.
*
* <p> An invocation of this method of the form <tt>out.append(csq, start,
* end)</tt> when <tt>csq</tt> is not <tt>null</tt>, behaves in
* exactly the same way as the invocation
*
* <pre>
* out.print(csq.subSequence(start, end).toString()) </pre>
* {@description.close}
*
* @param csq
* The character sequence from which a subsequence will be
* appended. If <tt>csq</tt> is <tt>null</tt>, then characters
* will be appended as if <tt>csq</tt> contained the four
* characters <tt>"null"</tt>.
*
* @param start
* The index of the first character in the subsequence
*
* @param end
* The index of the character following the last character in the
* subsequence
*
* @return This output stream
*
* @throws IndexOutOfBoundsException
* If <tt>start</tt> or <tt>end</tt> are negative, <tt>start</tt>
* is greater than <tt>end</tt>, or <tt>end</tt> is greater than
* <tt>csq.length()</tt>
*
* @since 1.5
*/
public PrintStream append(CharSequence csq, int start, int end) {
CharSequence cs = (csq == null ? "null" : csq);
write(cs.subSequence(start, end).toString());
return this;
}
/** {@collect.stats}
* {@description.open}
* Appends the specified character to this output stream.
*
* <p> An invocation of this method of the form <tt>out.append(c)</tt>
* behaves in exactly the same way as the invocation
*
* <pre>
* out.print(c) </pre>
* {@description.close}
*
* @param c
* The 16-bit character to append
*
* @return This output stream
*
* @since 1.5
*/
public PrintStream append(char c) {
print(c);
return this;
}
}
|
Java
|
/*
* Copyright (c) 1994, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
import java.nio.channels.FileChannel;
import sun.nio.ch.FileChannelImpl;
/** {@collect.stats}
* {@description.open}
* A <code>FileInputStream</code> obtains input bytes
* from a file in a file system. What files
* are available depends on the host environment.
*
* <p><code>FileInputStream</code> is meant for reading streams of raw bytes
* such as image data. For reading streams of characters, consider using
* <code>FileReader</code>.
* {@description.close}
*
* @author Arthur van Hoff
* @see java.io.File
* @see java.io.FileDescriptor
* @see java.io.FileOutputStream
* @since JDK1.0
*/
public
class FileInputStream extends InputStream
{
/* File Descriptor - handle to the open file */
private FileDescriptor fd;
private FileChannel channel = null;
private Object closeLock = new Object();
private volatile boolean closed = false;
private static ThreadLocal<Boolean> runningFinalize =
new ThreadLocal<Boolean>();
private static boolean isRunningFinalize() {
Boolean val;
if ((val = runningFinalize.get()) != null)
return val.booleanValue();
return false;
}
/** {@collect.stats}
* {@description.open}
* Creates a <code>FileInputStream</code> by
* opening a connection to an actual file,
* the file named by the path name <code>name</code>
* in the file system. A new <code>FileDescriptor</code>
* object is created to represent this file
* connection.
* <p>
* First, if there is a security
* manager, its <code>checkRead</code> method
* is called with the <code>name</code> argument
* as its argument.
* <p>
* If the named file does not exist, is a directory rather than a regular
* file, or for some other reason cannot be opened for reading then a
* <code>FileNotFoundException</code> is thrown.
* {@description.close}
*
* @param name the system-dependent file name.
* @exception FileNotFoundException if the file does not exist,
* is a directory rather than a regular file,
* or for some other reason cannot be opened for
* reading.
* @exception SecurityException if a security manager exists and its
* <code>checkRead</code> method denies read access
* to the file.
* @see java.lang.SecurityManager#checkRead(java.lang.String)
*/
public FileInputStream(String name) throws FileNotFoundException {
this(name != null ? new File(name) : null);
}
/** {@collect.stats}
* {@description.open}
* Creates a <code>FileInputStream</code> by
* opening a connection to an actual file,
* the file named by the <code>File</code>
* object <code>file</code> in the file system.
* A new <code>FileDescriptor</code> object
* is created to represent this file connection.
* <p>
* First, if there is a security manager,
* its <code>checkRead</code> method is called
* with the path represented by the <code>file</code>
* argument as its argument.
* <p>
* If the named file does not exist, is a directory rather than a regular
* file, or for some other reason cannot be opened for reading then a
* <code>FileNotFoundException</code> is thrown.
* {@description.close}
*
* @param file the file to be opened for reading.
* @exception FileNotFoundException if the file does not exist,
* is a directory rather than a regular file,
* or for some other reason cannot be opened for
* reading.
* @exception SecurityException if a security manager exists and its
* <code>checkRead</code> method denies read access to the file.
* @see java.io.File#getPath()
* @see java.lang.SecurityManager#checkRead(java.lang.String)
*/
public FileInputStream(File file) throws FileNotFoundException {
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(name);
}
if (name == null) {
throw new NullPointerException();
}
fd = new FileDescriptor();
fd.incrementAndGetUseCount();
open(name);
}
/** {@collect.stats}
* {@description.open}
* Creates a <code>FileInputStream</code> by using the file descriptor
* <code>fdObj</code>, which represents an existing connection to an
* actual file in the file system.
* <p>
* If there is a security manager, its <code>checkRead</code> method is
* called with the file descriptor <code>fdObj</code> as its argument to
* see if it's ok to read the file descriptor. If read access is denied
* to the file descriptor a <code>SecurityException</code> is thrown.
* <p>
* If <code>fdObj</code> is null then a <code>NullPointerException</code>
* is thrown.
* {@description.close}
*
* @param fdObj the file descriptor to be opened for reading.
* @throws SecurityException if a security manager exists and its
* <code>checkRead</code> method denies read access to the
* file descriptor.
* @see SecurityManager#checkRead(java.io.FileDescriptor)
*/
public FileInputStream(FileDescriptor fdObj) {
SecurityManager security = System.getSecurityManager();
if (fdObj == null) {
throw new NullPointerException();
}
if (security != null) {
security.checkRead(fdObj);
}
fd = fdObj;
/*
* FileDescriptor is being shared by streams.
* Ensure that it's GC'ed only when all the streams/channels are done
* using it.
*/
fd.incrementAndGetUseCount();
}
/** {@collect.stats}
* {@description.open}
* Opens the specified file for reading.
* {@description.close}
* @param name the name of the file
*/
private native void open(String name) throws FileNotFoundException;
/** {@collect.stats}
* {@description.open}
* Reads a byte of data from this input stream.
* {@description.close}
* {@description.open blocking}
* This method blocks
* if no input is yet available.
* {@description.close}
*
* @return the next byte of data, or <code>-1</code> if the end of the
* file is reached.
* @exception IOException if an I/O error occurs.
*/
public native int read() throws IOException;
/** {@collect.stats}
* {@description.open}
* Reads a subarray as a sequence of bytes.
* {@description.close}
* @param b the data to be written
* @param off the start offset in the data
* @param len the number of bytes that are written
* @exception IOException If an I/O error has occurred.
*/
private native int readBytes(byte b[], int off, int len) throws IOException;
/** {@collect.stats}
* {@description.open}
* Reads up to <code>b.length</code> bytes of data from this input
* stream into an array of bytes.
* {@description.close}
* {@description.open blocking}
* This method blocks until some input
* is available.
* {@description.close}
*
* @param b the buffer into which the data is read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the file has been reached.
* @exception IOException if an I/O error occurs.
*/
public int read(byte b[]) throws IOException {
return readBytes(b, 0, b.length);
}
/** {@collect.stats}
* {@description.open}
* Reads up to <code>len</code> bytes of data from this input stream
* into an array of bytes.
* {@description.close}
* {@description.open blocking}
* If <code>len</code> is not zero, the method
* blocks until some input is available; otherwise, no
* bytes are read and <code>0</code> is returned.
* {@description.close}
*
* @param b the buffer into which the data is read.
* @param off the start offset in the destination array <code>b</code>
* @param len the maximum number of bytes read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the file has been reached.
* @exception NullPointerException If <code>b</code> is <code>null</code>.
* @exception IndexOutOfBoundsException If <code>off</code> is negative,
* <code>len</code> is negative, or <code>len</code> is greater than
* <code>b.length - off</code>
* @exception IOException if an I/O error occurs.
*/
public int read(byte b[], int off, int len) throws IOException {
return readBytes(b, off, len);
}
/** {@collect.stats}
* {@description.open}
* Skips over and discards <code>n</code> bytes of data from the
* input stream.
*
* <p>The <code>skip</code> method may, for a variety of
* reasons, end up skipping over some smaller number of bytes,
* possibly <code>0</code>. If <code>n</code> is negative, an
* <code>IOException</code> is thrown, even though the <code>skip</code>
* method of the {@link InputStream} superclass does nothing in this case.
* The actual number of bytes skipped is returned.
*
* <p>This method may skip more bytes than are remaining in the backing
* file. This produces no exception and the number of bytes skipped
* may include some number of bytes that were beyond the EOF of the
* backing file. Attempting to read from the stream after skipping past
* the end will result in -1 indicating the end of the file.
* {@description.close}
*
* @param n the number of bytes to be skipped.
* @return the actual number of bytes skipped.
* @exception IOException if n is negative, if the stream does not
* support seek, or if an I/O error occurs.
*/
public native long skip(long n) throws IOException;
/** {@collect.stats}
* {@description.open blocking}
* Returns an estimate of the number of remaining bytes that can be read (or
* skipped over) from this input stream without blocking by the next
* invocation of a method for this input stream.
* {@description.close}
* {@description.open}
* The next invocation might be
* the same thread or another thread. A single read or skip of this
* many bytes will not block, but may read or skip fewer bytes.
*
* <p> In some cases, a non-blocking read (or skip) may appear to be
* blocked when it is merely slow, for example when reading large
* files over slow networks.
* {@description.close}
*
* @return an estimate of the number of remaining bytes that can be read
* (or skipped over) from this input stream without blocking.
* @exception IOException if this file input stream has been closed by calling
* {@code close} or an I/O error occurs.
*/
public native int available() throws IOException;
/** {@collect.stats}
* {@description.open}
* Closes this file input stream and releases any system resources
* associated with the stream.
*
* <p> If this stream has an associated channel then the channel is closed
* as well.
* {@description.close}
*
* @exception IOException if an I/O error occurs.
*
* @revised 1.4
* @spec JSR-51
*/
public void close() throws IOException {
synchronized (closeLock) {
if (closed) {
return;
}
closed = true;
}
if (channel != null) {
/*
* Decrement the FD use count associated with the channel
* The use count is incremented whenever a new channel
* is obtained from this stream.
*/
fd.decrementAndGetUseCount();
channel.close();
}
/*
* Decrement the FD use count associated with this stream
*/
int useCount = fd.decrementAndGetUseCount();
/*
* If FileDescriptor is still in use by another stream, the finalizer
* will not close it.
*/
if ((useCount <= 0) || !isRunningFinalize()) {
close0();
}
}
/** {@collect.stats}
* {@description.open}
* Returns the <code>FileDescriptor</code>
* object that represents the connection to
* the actual file in the file system being
* used by this <code>FileInputStream</code>.
* {@description.close}
*
* @return the file descriptor object associated with this stream.
* @exception IOException if an I/O error occurs.
* @see java.io.FileDescriptor
*/
public final FileDescriptor getFD() throws IOException {
if (fd != null) return fd;
throw new IOException();
}
/** {@collect.stats}
* {@description.open}
* Returns the unique {@link java.nio.channels.FileChannel FileChannel}
* object associated with this file input stream.
*
* <p> The initial {@link java.nio.channels.FileChannel#position()
* </code>position<code>} of the returned channel will be equal to the
* number of bytes read from the file so far. Reading bytes from this
* stream will increment the channel's position. Changing the channel's
* position, either explicitly or by reading, will change this stream's
* file position.
* {@description.close}
*
* @return the file channel associated with this file input stream
*
* @since 1.4
* @spec JSR-51
*/
public FileChannel getChannel() {
synchronized (this) {
if (channel == null) {
channel = FileChannelImpl.open(fd, true, false, this);
/*
* Increment fd's use count. Invoking the channel's close()
* method will result in decrementing the use count set for
* the channel.
*/
fd.incrementAndGetUseCount();
}
return channel;
}
}
private static native void initIDs();
private native void close0() throws IOException;
static {
initIDs();
}
/** {@collect.stats}
* {@description.open}
* Ensures that the <code>close</code> method of this file input stream is
* called when there are no more references to it.
* {@description.close}
*
* @exception IOException if an I/O error occurs.
* @see java.io.FileInputStream#close()
*/
protected void finalize() throws IOException {
if ((fd != null) && (fd != fd.in)) {
/*
* Finalizer should not release the FileDescriptor if another
* stream is still using it. If the user directly invokes
* close() then the FileDescriptor is also released.
*/
runningFinalize.set(Boolean.TRUE);
try {
close();
} finally {
runningFinalize.set(Boolean.FALSE);
}
}
}
}
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.