migrated to Java 5
This commit is contained in:
Scott Battaglia 2010-10-25 03:59:14 +00:00
parent 1911c7242c
commit aa4afd9c5f
61 changed files with 341 additions and 358 deletions

View File

@ -48,6 +48,6 @@ public interface AttributePrincipal extends Principal, Serializable {
* The Map of key/value pairs associated with this principal.
* @return the map of key/value pairs associated with this principal.
*/
Map getAttributes();
Map<String,Object> getAttributes();
}

View File

@ -42,7 +42,7 @@ public class AttributePrincipalImpl extends SimplePrincipal implements Attribute
private static final long serialVersionUID = -1443182634624927187L;
/** Map of key/value pairs about this principal. */
private final Map attributes;
private final Map<String,Object> attributes;
/** The CAS 2 ticket used to retrieve a proxy ticket. */
private final String proxyGrantingTicket;
@ -56,7 +56,7 @@ public class AttributePrincipalImpl extends SimplePrincipal implements Attribute
* @param name the unique identifier for the principal.
*/
public AttributePrincipalImpl(final String name) {
this(name, Collections.EMPTY_MAP);
this(name, Collections.<String, Object>emptyMap());
}
/**
@ -65,7 +65,7 @@ public class AttributePrincipalImpl extends SimplePrincipal implements Attribute
* @param name the unique identifier for the principal.
* @param attributes the key/value pairs for this principal.
*/
public AttributePrincipalImpl(final String name, final Map attributes) {
public AttributePrincipalImpl(final String name, final Map<String,Object> attributes) {
this(name, attributes, null, null);
}
@ -77,7 +77,7 @@ public class AttributePrincipalImpl extends SimplePrincipal implements Attribute
* @param proxyRetriever the ProxyRetriever implementation to call back to the CAS server.
*/
public AttributePrincipalImpl(final String name, final String proxyGrantingTicket, final ProxyRetriever proxyRetriever) {
this(name, Collections.EMPTY_MAP, proxyGrantingTicket, proxyRetriever);
this(name, Collections.<String, Object>emptyMap(), proxyGrantingTicket, proxyRetriever);
}
/**
@ -88,7 +88,7 @@ public class AttributePrincipalImpl extends SimplePrincipal implements Attribute
* @param proxyGrantingTicket the ticket associated with this principal.
* @param proxyRetriever the ProxyRetriever implementation to call back to the CAS server.
*/
public AttributePrincipalImpl(final String name, final Map attributes, final String proxyGrantingTicket, final ProxyRetriever proxyRetriever) {
public AttributePrincipalImpl(final String name, final Map<String,Object> attributes, final String proxyGrantingTicket, final ProxyRetriever proxyRetriever) {
super(name);
this.attributes = attributes;
this.proxyGrantingTicket = proxyGrantingTicket;
@ -97,7 +97,7 @@ public class AttributePrincipalImpl extends SimplePrincipal implements Attribute
CommonUtils.assertNotNull(this.attributes, "attributes cannot be null.");
}
public Map getAttributes() {
public Map<String,Object> getAttributes() {
return this.attributes;
}

View File

@ -38,7 +38,7 @@ public final class SimpleGroup extends SimplePrincipal implements Group {
private static final long serialVersionUID = 1541943977571896383L;
private final Set members = new HashSet();
private final Set<Principal> members = new HashSet<Principal>();
/**
* Creates a new group with the given name.
@ -56,7 +56,7 @@ public final class SimpleGroup extends SimplePrincipal implements Group {
return this.members.contains(member);
}
public Enumeration members() {
public Enumeration<? extends Principal> members() {
return new EnumerationAdapter(this.members.iterator());
}
@ -71,16 +71,16 @@ public final class SimpleGroup extends SimplePrincipal implements Group {
/**
* Adapts a {@link java.util.Iterator} onto an {@link java.util.Enumeration}.
*/
private static class EnumerationAdapter implements Enumeration {
private static class EnumerationAdapter implements Enumeration<Principal> {
/** Iterator backing enumeration operations */
private Iterator iterator;
private Iterator<? extends Principal> iterator;
/**
* Creates a new instance backed by the given iterator.
* @param i Iterator backing enumeration operations.
*/
public EnumerationAdapter(final Iterator i) {
public EnumerationAdapter(final Iterator<? extends Principal> i) {
this.iterator = i;
}
@ -88,7 +88,7 @@ public final class SimpleGroup extends SimplePrincipal implements Group {
return this.iterator.hasNext();
}
public Object nextElement() {
public Principal nextElement() {
return this.iterator.next();
}
}

View File

@ -24,6 +24,7 @@ import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.security.Principal;
import java.security.acl.Group;
import java.util.*;
import java.util.concurrent.Executor;
@ -130,11 +131,11 @@ public class CasLoginModule implements LoginModule {
/**
* Stores mapping of ticket to assertion to support JAAS providers that
* attempt to periodically reauthenticate to renew principal. Since
* attempt to periodically re-authenticate to renew principal. Since
* CAS tickets are one-time-use, a cached assertion must be provided on
* reauthentication.
* re-authentication.
*/
protected static final Map ASSERTION_CACHE = new HashMap();
protected static final Map<TicketCredential,Assertion> ASSERTION_CACHE = new HashMap<TicketCredential,Assertion>();
/** Executor responsible for assertion cache cleanup */
protected static Executor cacheCleanerExecutor = Executors.newSingleThreadExecutor();
@ -161,13 +162,13 @@ public class CasLoginModule implements LoginModule {
protected TicketCredential ticket;
/** Login module shared state */
protected Map sharedState;
protected Map<String,Object> sharedState;
/** Roles to be added to all authenticated principals by default */
protected String[] defaultRoles;
/** Names of attributes in the CAS assertion that should be used for role data */
protected Set roleAttributeNames = new HashSet();
protected Set<String> roleAttributeNames = new HashSet<String>();
/** Name of JAAS Group containing caller principal */
protected String principalGroupName = DEFAULT_PRINCIPAL_GROUP_NAME;
@ -179,8 +180,7 @@ public class CasLoginModule implements LoginModule {
protected boolean cacheAssertions;
/** Assertion cache timeout in minutes */
protected int cacheTimeout;
protected int cacheTimeout = DEFAULT_CACHE_TIMEOUT;
/**
* Initializes the CAS login module.
@ -203,16 +203,17 @@ public class CasLoginModule implements LoginModule {
* <li>cacheTimeout (optional) - assertion cache timeout in minutes.</li>
* </ul>
*/
public void initialize(final Subject subject, final CallbackHandler handler, final Map state, final Map options) {
public void initialize(final Subject subject, final CallbackHandler handler, final Map<String,?> state, final Map<String, ?> options) {
this.assertion = null;
this.callbackHandler = handler;
this.subject = subject;
this.sharedState = state;
this.sharedState = new HashMap(state);
String ticketValidatorClass = null;
final Iterator iter = options.keySet().iterator();
while (iter.hasNext()) {
final Object key = iter.next();
for (final String key : options.keySet()) {
log.trace("Processing option " + key);
if ("service".equals(key)) {
this.service = (String) options.get(key);
@ -245,6 +246,7 @@ public class CasLoginModule implements LoginModule {
log.debug("Set cacheTimeout=" + this.cacheTimeout);
}
}
if (this.cacheAssertions) {
cacheCleanerExecutor.execute(new CacheCleaner());
}
@ -275,7 +277,7 @@ public class CasLoginModule implements LoginModule {
synchronized(ASSERTION_CACHE) {
if (ASSERTION_CACHE.get(ticket) != null) {
log.debug("Assertion found in cache.");
this.assertion = (Assertion) ASSERTION_CACHE.get(ticket);
this.assertion = ASSERTION_CACHE.get(ticket);
}
}
}
@ -290,7 +292,7 @@ public class CasLoginModule implements LoginModule {
if (log.isDebugEnabled()) {
log.debug("Attempting ticket validation with service=" + service + " and ticket=" + ticket);
}
this.assertion = this.ticketValidator.validate(this.ticket.getTicket(), service);
this.assertion = this.ticketValidator.validate(this.ticket.getName(), service);
} catch (final Exception e) {
log.info("Login failed due to CAS ticket validation failure: " + e);
@ -334,20 +336,19 @@ public class CasLoginModule implements LoginModule {
// Add group principal containing role data
final Group roleGroup = new SimpleGroup(this.roleGroupName);
for (int i = 0; i < defaultRoles.length; i++) {
roleGroup.addMember(new SimplePrincipal(defaultRoles[i]));
for (final String defaultRole : defaultRoles) {
roleGroup.addMember(new SimplePrincipal(defaultRole));
}
final Map attributes = this.assertion.getPrincipal().getAttributes();
final Iterator nameIterator = attributes.keySet().iterator();
while (nameIterator.hasNext()) {
final Object key = nameIterator.next();
final Map<String,Object> attributes = this.assertion.getPrincipal().getAttributes();
for (final String key : attributes.keySet()) {
if (this.roleAttributeNames.contains(key)) {
// Attribute value is Object if singular or Collection if plural
final Object value = attributes.get(key);
if (value instanceof Collection) {
final Iterator valueIterator = ((Collection) value).iterator();
while (valueIterator.hasNext()) {
roleGroup.addMember(new SimplePrincipal(valueIterator.next().toString()));
for (final Object o : (Collection) value) {
roleGroup.addMember(new SimplePrincipal(o.toString()));
}
} else {
roleGroup.addMember(new SimplePrincipal(value.toString()));
@ -357,7 +358,7 @@ public class CasLoginModule implements LoginModule {
this.subject.getPrincipals().add(roleGroup);
// Place principal name in shared state for downstream JAAS modules (module chaining use case)
this.sharedState.put(LOGIN_NAME, casPrincipal.getName());
this.sharedState.put(LOGIN_NAME, new Object()); // casPrincipal.getName());
if (log.isDebugEnabled()) {
if (log.isDebugEnabled()) {
@ -403,7 +404,7 @@ public class CasLoginModule implements LoginModule {
* @param propertyMap Map of property name/value pairs to set on validator instance.
* @return Ticket validator with properties set.
*/
private TicketValidator createTicketValidator(final String className, final Map propertyMap) {
private TicketValidator createTicketValidator(final String className, final Map<String,?> propertyMap) {
CommonUtils.assertTrue(propertyMap.containsKey("casServerUrlPrefix"), "Required property casServerUrlPrefix not found.");
final Class validatorClass = ReflectUtils.loadClass(className);
@ -411,9 +412,8 @@ public class CasLoginModule implements LoginModule {
try {
final BeanInfo info = Introspector.getBeanInfo(validatorClass);
final Iterator iter = propertyMap.keySet().iterator();
while (iter.hasNext()) {
final String property = (String) iter.next();
for (final String property : propertyMap.keySet()) {
if (!"casServerUrlPrefix".equals(property)) {
log.debug("Attempting to set TicketValidator property " + property);
final String value = (String) propertyMap.get(property);
@ -461,22 +461,16 @@ public class CasLoginModule implements LoginModule {
* Removes all principals of the given type from the JAAS subject.
* @param clazz Type of principal to remove.
*/
private void removePrincipalsOfType(final Class clazz) {
final Iterator iter = this.subject.getPrincipals(clazz).iterator();
while (iter.hasNext()) {
this.subject.getPrincipals().remove(iter.next());
}
private void removePrincipalsOfType(final Class<? extends Principal> clazz) {
this.subject.getPrincipals().removeAll(this.subject.getPrincipals(clazz));
}
/**
* Removes all credentials of the given type from the JAAS subject.
* @param clazz Type of principal to remove.
*/
private void removeCredentialsOfType(final Class clazz) {
final Iterator iter = this.subject.getPrivateCredentials(clazz).iterator();
while (iter.hasNext()) {
this.subject.getPrivateCredentials().remove(iter.next());
}
private void removeCredentialsOfType(final Class<? extends Principal> clazz) {
this.subject.getPrivateCredentials().removeAll(this.subject.getPrivateCredentials(clazz));
}
/** Removes expired entries from the assertion cache. */

View File

@ -57,13 +57,13 @@ public class ServiceAndTicketCallbackHandler implements CallbackHandler {
}
public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
((NameCallback) callbacks[i]).setName(this.service);
} else if (callbacks[i] instanceof PasswordCallback) {
((PasswordCallback) callbacks[i]).setPassword(this.ticket.toCharArray());
for (final Callback callback : callbacks) {
if (callback instanceof NameCallback) {
((NameCallback) callback).setName(this.service);
} else if (callback instanceof PasswordCallback) {
((PasswordCallback) callback).setPassword(this.ticket.toCharArray());
} else {
throw new UnsupportedCallbackException(callbacks[i], "Callback not supported.");
throw new UnsupportedCallbackException(callback, "Callback not supported.");
}
}
}

View File

@ -19,6 +19,8 @@
package org.jasig.cas.client.jaas;
import java.security.Principal;
/**
* Strongly-typed wrapper for a ticket credential.
*
@ -27,7 +29,7 @@ package org.jasig.cas.client.jaas;
* @since 3.1.12
*
*/
public final class TicketCredential {
public final class TicketCredential implements Principal {
/** Hash code seed value */
private static final int HASHCODE_SEED = 17;
@ -43,10 +45,7 @@ public final class TicketCredential {
this.ticket = ticket;
}
/**
* @return Ticket identifier string.
*/
public String getTicket() {
public String getName() {
return this.ticket;
}

View File

@ -24,11 +24,7 @@ import org.apache.commons.logging.LogFactory;
import org.jasig.cas.client.util.CommonUtils;
import org.jasig.cas.client.util.XmlUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
/**
@ -65,6 +61,7 @@ public final class Cas20ProxyRetriever implements ProxyRetriever {
* Main Constructor.
*
* @param casServerUrl the URL to the CAS server (i.e. http://localhost/cas/)
* @param encoding the encoding to use.
*/
public Cas20ProxyRetriever(final String casServerUrl, final String encoding) {
CommonUtils.assertNotNull(casServerUrl, "casServerUrl cannot be null.");

View File

@ -21,8 +21,6 @@ package org.jasig.cas.client.proxy;
import java.util.TimerTask;
import org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter;
/**
* A {@link TimerTask} implementation which performs the
* actual 'cleaning' by calling {@link ProxyGrantingTicketStorage#cleanUp()}.

View File

@ -19,10 +19,9 @@
package org.jasig.cas.client.proxy;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -51,7 +50,7 @@ public final class ProxyGrantingTicketStorageImpl implements ProxyGrantingTicket
/**
* Map that stores the PGTIOU to PGT mappings.
*/
private final Map cache = Collections.synchronizedMap(new HashMap());
private final ConcurrentMap<String,ProxyGrantingTicketHolder> cache = new ConcurrentHashMap<String,ProxyGrantingTicketHolder>();
/**
* time, in milliseconds, before a {@link ProxyGrantingTicketHolder}
@ -83,15 +82,14 @@ public final class ProxyGrantingTicketStorageImpl implements ProxyGrantingTicket
* Its removed after retrieval.
*/
public String retrieve(final String proxyGrantingTicketIou) {
final ProxyGrantingTicketHolder holder = (ProxyGrantingTicketHolder) this.cache
.get(proxyGrantingTicketIou);
final ProxyGrantingTicketHolder holder = this.cache.get(proxyGrantingTicketIou);
if (holder == null) {
log.info("No Proxy Ticket found for [" + proxyGrantingTicketIou + "].");
return null;
}
this.cache.remove(holder);
this.cache.remove(proxyGrantingTicketIou);
if (log.isDebugEnabled()) {
log.debug("Returned ProxyGrantingTicket of [" + holder.getProxyGrantingTicket() + "]");
@ -99,10 +97,8 @@ public final class ProxyGrantingTicketStorageImpl implements ProxyGrantingTicket
return holder.getProxyGrantingTicket();
}
public void save(final String proxyGrantingTicketIou,
final String proxyGrantingTicket) {
final ProxyGrantingTicketHolder holder = new ProxyGrantingTicketHolder(
proxyGrantingTicket);
public void save(final String proxyGrantingTicketIou, final String proxyGrantingTicket) {
final ProxyGrantingTicketHolder holder = new ProxyGrantingTicketHolder(proxyGrantingTicket);
if (log.isDebugEnabled()) {
log.debug("Saving ProxyGrantingTicketIOU and ProxyGrantingTicket combo: [" + proxyGrantingTicketIou + ", " + proxyGrantingTicket + "]");
@ -115,16 +111,11 @@ public final class ProxyGrantingTicketStorageImpl implements ProxyGrantingTicket
* called regularly via an external thread or timer.
*/
public void cleanUp() {
synchronized (this.cache) {
for (final Iterator iter = this.cache.values().iterator(); iter
.hasNext();) {
final ProxyGrantingTicketHolder holder = (ProxyGrantingTicketHolder) iter.next();
if (holder.isExpired(this.timeout)) {
iter.remove();
}
for (final Map.Entry<String,ProxyGrantingTicketHolder> holder : this.cache.entrySet()) {
if (holder.getValue().isExpired(this.timeout)) {
this.cache.remove(holder.getKey());
}
}
}
}
private static final class ProxyGrantingTicketHolder {

View File

@ -40,12 +40,12 @@ public final class HashMapBackedSessionMappingStorage implements SessionMappingS
/**
* Maps the ID from the CAS server to the Session.
*/
private final Map MANAGED_SESSIONS = new HashMap();
private final Map<String,HttpSession> MANAGED_SESSIONS = new HashMap<String,HttpSession>();
/**
* Maps the Session ID to the key from the CAS Server.
*/
private final Map ID_TO_SESSION_KEY_MAPPING = new HashMap();
private final Map<String,String> ID_TO_SESSION_KEY_MAPPING = new HashMap<String,String>();
private final Log log = LogFactory.getLog(getClass());
@ -60,7 +60,7 @@ public final class HashMapBackedSessionMappingStorage implements SessionMappingS
log.debug("Attempting to remove Session=[" + sessionId + "]");
}
final String key = (String) ID_TO_SESSION_KEY_MAPPING.get(sessionId);
final String key = ID_TO_SESSION_KEY_MAPPING.get(sessionId);
if (log.isDebugEnabled()) {
if (key != null) {
@ -74,7 +74,7 @@ public final class HashMapBackedSessionMappingStorage implements SessionMappingS
}
public synchronized HttpSession removeSessionByMappingId(String mappingId) {
final HttpSession session = (HttpSession) MANAGED_SESSIONS.get(mappingId);
final HttpSession session = MANAGED_SESSIONS.get(mappingId);
if (session != null) {
removeBySessionById(session.getId());

View File

@ -39,7 +39,6 @@ import java.io.IOException;
* @since 3.1
*/
public final class SingleSignOutFilter extends AbstractConfigurationFilter {
private static Log log = LogFactory.getLog(SingleSignOutFilter.class);
private static final SingleSignOutHandler handler = new SingleSignOutHandler();

View File

@ -31,10 +31,12 @@ import org.jasig.cas.client.util.XmlUtils;
* Performs CAS single sign-out operations in an API-agnostic fashion.
*
* @author Marvin S. Addison
* @version $Revision$
* @version $Revision$ $Date$
* @since 3.1.12
*
*/
public class SingleSignOutHandler {
public final class SingleSignOutHandler {
/** Logger instance */
private final Log log = LogFactory.getLog(getClass());
@ -55,13 +57,6 @@ public class SingleSignOutHandler {
public SessionMappingStorage getSessionMappingStorage() {
return this.sessionMappingStorage;
}
/**
* @return Name of the parameter containing the authentication token.
*/
public String getArtifactParameterName() {
return artifactParameterName;
}
/**
* @param name Name of the authentication token parameter.
@ -69,13 +64,6 @@ public class SingleSignOutHandler {
public void setArtifactParameterName(final String name) {
this.artifactParameterName = name;
}
/**
* @return Name of parameter containing CAS logout request message.
*/
public String getLogoutParameterName() {
return logoutParameterName;
}
/**
* @param name Name of parameter containing CAS logout request message.

View File

@ -18,17 +18,9 @@
*/
/*
$Id$
Copyright (C) 2008-2009 Virginia Tech.
All rights reserved.
SEE LICENSE FOR MORE INFORMATION
Author: Middleware
Email: middleware@vt.edu
Version: $Revision$
Updated: $Date$
@author Marvin Addison
@version $Revision$ $Date$
@since 3.1.10
*/
package org.jasig.cas.client.ssl;

View File

@ -64,5 +64,4 @@ public class RegexHostnameVerifier implements HostnameVerifier {
public boolean verify(final String hostname, final SSLSession session) {
return pattern.matcher(hostname).matches();
}
}

View File

@ -66,11 +66,11 @@ public class WhitelistHostnameVerifier implements HostnameVerifier {
this.allowedHosts = allowedList.split(",\\s*");
}
/** {@inheritDoc} */
public boolean verify(final String hostname, final SSLSession session) {
for (int i = 0; i < this.allowedHosts.length; i++) {
if (hostname.equalsIgnoreCase(this.allowedHosts[i])) {
for (final String allowedHost : this.allowedHosts) {
if (hostname.equalsIgnoreCase(allowedHost)) {
return true;
}
}

View File

@ -67,7 +67,7 @@ public abstract class AbstractConfigurationFilter implements Filter {
log.info("Property [" + propertyName + "] loaded from ServletContext.getInitParameter with value [" + value2 + "]");
return value2;
}
InitialContext context = null;
InitialContext context;
try {
context = new InitialContext();
} catch (final NamingException e) {

View File

@ -22,7 +22,7 @@ package org.jasig.cas.client.util;
import org.jasig.cas.client.validation.Assertion;
/**
* Static holder that places Assertion in a threadlocal.
* Static holder that places Assertion in a ThreadLocal.
*
* @author Scott Battaglia
* @version $Revision: 11728 $ $Date: 2007-09-26 14:20:43 -0400 (Tue, 26 Sep 2007) $
@ -33,18 +33,22 @@ public class AssertionHolder {
/**
* ThreadLocal to hold the Assertion for Threads to access.
*/
private static final ThreadLocal threadLocal = new ThreadLocal();
private static final ThreadLocal<Assertion> threadLocal = new ThreadLocal<Assertion>();
/**
* Retrieve the assertion from the ThreadLocal.
*
* @return the Asssertion associated with this thread.
*/
public static Assertion getAssertion() {
return (Assertion) threadLocal.get();
return threadLocal.get();
}
/**
* Add the Assertion to the ThreadLocal.
*
* @param assertion the assertion to add.
*/
public static void setAssertion(final Assertion assertion) {
threadLocal.set(assertion);

View File

@ -228,41 +228,40 @@ public final class CommonUtils {
return encode ? response.encodeURL(service) : service;
}
final StringBuffer buffer = new StringBuffer();
final StringBuilder buffer = new StringBuilder();
synchronized (buffer) {
if (!serverName.startsWith("https://") && !serverName.startsWith("http://")) {
buffer.append(request.isSecure() ? "https://" : "http://");
if (!serverName.startsWith("https://") && !serverName.startsWith("http://")) {
buffer.append(request.isSecure() ? "https://" : "http://");
}
buffer.append(serverName);
buffer.append(request.getRequestURI());
if (CommonUtils.isNotBlank(request.getQueryString())) {
final int location = request.getQueryString().indexOf(artifactParameterName + "=");
if (location == 0) {
final String returnValue = encode ? response.encodeURL(buffer.toString()): buffer.toString();
if (LOG.isDebugEnabled()) {
LOG.debug("serviceUrl generated: " + returnValue);
}
return returnValue;
}
buffer.append(serverName);
buffer.append(request.getRequestURI());
buffer.append("?");
if (CommonUtils.isNotBlank(request.getQueryString())) {
final int location = request.getQueryString().indexOf(artifactParameterName + "=");
if (location == -1) {
buffer.append(request.getQueryString());
} else if (location > 0) {
final int actualLocation = request.getQueryString()
.indexOf("&" + artifactParameterName + "=");
if (location == 0) {
final String returnValue = encode ? response.encodeURL(buffer.toString()): buffer.toString();
if (LOG.isDebugEnabled()) {
LOG.debug("serviceUrl generated: " + returnValue);
}
return returnValue;
}
buffer.append("?");
if (location == -1) {
if (actualLocation == -1) {
buffer.append(request.getQueryString());
} else if (location > 0) {
final int actualLocation = request.getQueryString()
.indexOf("&" + artifactParameterName + "=");
if (actualLocation == -1) {
buffer.append(request.getQueryString());
} else if (actualLocation > 0) {
buffer.append(request.getQueryString().substring(0,
actualLocation));
}
} else if (actualLocation > 0) {
buffer.append(request.getQueryString().substring(0,
actualLocation));
}
}
}
@ -299,6 +298,7 @@ public final class CommonUtils {
* Contacts the remote URL and returns the response.
*
* @param constructedUrl the url to contact.
* @param encoding the encoding to use.
* @return the response.
*/
public static String getResponseFromServer(final URL constructedUrl, final String encoding) {
@ -310,6 +310,7 @@ public final class CommonUtils {
*
* @param constructedUrl the url to contact.
* @param hostnameVerifier Host name verifier to use for HTTPS connections.
* @param encoding the encoding to use.
* @return the response.
*/
public static String getResponseFromServer(final URL constructedUrl, final HostnameVerifier hostnameVerifier, final String encoding) {
@ -328,15 +329,13 @@ public final class CommonUtils {
}
String line;
final StringBuffer stringBuffer = new StringBuffer(255);
final StringBuilder stringBuffer = new StringBuilder(255);
synchronized (stringBuffer) {
while ((line = in.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
return stringBuffer.toString();
while ((line = in.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
return stringBuffer.toString();
} catch (final Exception e) {
LOG.error(e.getMessage(), e);
throw new RuntimeException(e);
@ -351,6 +350,7 @@ public final class CommonUtils {
* Contacts the remote URL and returns the response.
*
* @param url the url to contact.
* @param encoding the encoding to use.
* @return the response.
*/
public static String getResponseFromServer(final String url, String encoding) {

View File

@ -30,7 +30,6 @@ import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
/**
@ -57,7 +56,7 @@ public final class DelegatingFilter implements Filter {
/**
* The map of filters to delegate to and the criteria (as key).
*/
private final Map delegators;
private final Map<String,Filter> delegators;
/**
* The default filter to use if there is no match.
@ -70,25 +69,13 @@ public final class DelegatingFilter implements Filter {
*/
private final boolean exactMatch;
public DelegatingFilter(final String requestParameterName, final Map delegators, final boolean exactMatch) {
public DelegatingFilter(final String requestParameterName, final Map<String,Filter> delegators, final boolean exactMatch) {
this(requestParameterName, delegators, exactMatch, null);
}
public DelegatingFilter(final String requestParameterName, final Map delegators, final boolean exactMatch, final Filter defaultFilter) {
CommonUtils.assertNotNull(requestParameterName,
"requestParameterName cannot be null.");
CommonUtils.assertTrue(!delegators.isEmpty(),
"delegators cannot be empty.");
for (final Iterator iter = delegators.keySet().iterator(); iter
.hasNext();) {
final Object object = delegators.get(iter.next());
if (!Filter.class.isAssignableFrom(object.getClass())) {
throw new IllegalArgumentException(
"All value objects in the delegators map must be filters.");
}
}
public DelegatingFilter(final String requestParameterName, final Map<String,Filter> delegators, final boolean exactMatch, final Filter defaultFilter) {
CommonUtils.assertNotNull(requestParameterName, "requestParameterName cannot be null.");
CommonUtils.assertTrue(!delegators.isEmpty(), "delegators cannot be empty.");
this.requestParameterName = requestParameterName;
this.delegators = delegators;
@ -100,20 +87,14 @@ public final class DelegatingFilter implements Filter {
// nothing to do here
}
public void doFilter(final ServletRequest request,
final ServletResponse response, final FilterChain filterChain)
throws IOException, ServletException {
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) throws IOException, ServletException {
final String parameter = CommonUtils.safeGetParameter((HttpServletRequest) request, this.requestParameterName);
if (CommonUtils.isNotEmpty(parameter)) {
for (final Iterator iter = this.delegators.keySet().iterator(); iter
.hasNext();) {
final String key = (String) iter.next();
if ((parameter.equals(key) && this.exactMatch)
|| (parameter.matches(key) && !this.exactMatch)) {
final Filter filter = (Filter) this.delegators.get(key);
for (final String key : this.delegators.keySet()) {
if ((parameter.equals(key) && this.exactMatch) || (parameter.matches(key) && !this.exactMatch)) {
final Filter filter = this.delegators.get(key);
if (log.isDebugEnabled()) {
log.debug("Match found for parameter ["
+ this.requestParameterName + "] with value ["
@ -126,8 +107,7 @@ public final class DelegatingFilter implements Filter {
}
}
log.debug("No match found for parameter [" + this.requestParameterName
+ "] with value [" + parameter + "]");
log.debug("No match found for parameter [" + this.requestParameterName + "] with value [" + parameter + "]");
if (this.defaultFilter != null) {
this.defaultFilter.doFilter(request, response, filterChain);

View File

@ -54,7 +54,7 @@ public final class ErrorRedirectFilter implements Filter {
private final Log log = LogFactory.getLog(getClass());
private final List errors = new ArrayList();
private final List<ErrorHolder> errors = new ArrayList<ErrorHolder>();
private String defaultErrorRedirectPage;
@ -70,8 +70,7 @@ public final class ErrorRedirectFilter implements Filter {
} catch (final ServletException e) {
final Throwable t = e.getCause();
ErrorHolder currentMatch = null;
for (final Iterator iter = this.errors.iterator(); iter.hasNext();) {
final ErrorHolder errorHolder = (ErrorHolder) iter.next();
for (final ErrorHolder errorHolder : this.errors) {
if (errorHolder.exactMatch(t)) {
currentMatch = errorHolder;
break;

View File

@ -33,7 +33,6 @@ import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.Principal;
import java.util.Collection;
import java.util.Iterator;
/**
* Implementation of a filter that wraps the normal HttpServletRequest with a
@ -125,8 +124,9 @@ public final class HttpServletRequestWrapperFilter extends AbstractConfiguration
final Object value = this.principal.getAttributes().get(roleAttribute);
if (value instanceof Collection) {
for (final Iterator iter = ((Collection) value).iterator(); iter.hasNext();) {
if (rolesEqual(role, iter.next())) {
final Collection c = (Collection) value;
for (final Object o : c) {
if (rolesEqual(role, o)) {
log.debug("User [" + getRemoteUser() + "] is in role [" + role + "]: " + true);
return true;
}

View File

@ -122,7 +122,7 @@ public final class ReflectUtils {
}
/**
* Sets the given property on the target javabean using bean instrospection.
* Sets the given property on the target JavaBean using bean instrospection.
* @param propertyName Property to set.
* @param value Property value to set.
* @param target Target java bean on which to set property.
@ -131,21 +131,21 @@ public final class ReflectUtils {
try {
setProperty(propertyName, value, target, Introspector.getBeanInfo(target.getClass()));
} catch (final IntrospectionException e) {
throw new RuntimeException("Failed getting bean info on target javabean " + target, e);
throw new RuntimeException("Failed getting bean info on target JavaBean " + target, e);
}
}
/**
* Sets the given property on the target javabean using bean instrospection.
* Sets the given property on the target JavaBean using bean instrospection.
* @param propertyName Property to set.
* @param value Property value to set.
* @param target Target javabean on which to set property.
* @param info BeanInfo describing the target javabean.
* @param target Target JavaBean on which to set property.
* @param info BeanInfo describing the target JavaBean.
*/
public static void setProperty(final String propertyName, final Object value, final Object target, final BeanInfo info) {
try {
final PropertyDescriptor pd = getPropertyDescriptor(info, propertyName);
pd.getWriteMethod().invoke(target, new Object[] { value });
pd.getWriteMethod().invoke(target, value);
} catch (final InvocationTargetException e) {
throw new RuntimeException("Error setting property " + propertyName, e.getCause());
} catch (final Exception e) {

View File

@ -68,9 +68,9 @@ public final class XmlUtils {
* @param element the element to look for
* @return the list of text from the elements.
*/
public static List getTextForElements(final String xmlAsString,
public static List<String> getTextForElements(final String xmlAsString,
final String element) {
final List elements = new ArrayList(2);
final List<String> elements = new ArrayList<String>(2);
final XMLReader reader = getXmlReader();
final DefaultHandler handler = new DefaultHandler() {

View File

@ -92,7 +92,7 @@ public abstract class AbstractTicketValidationFilter extends AbstractCasFilter {
final Class verifierClass = Class.forName(className);
if (config != null) {
final Constructor cons = verifierClass.getConstructor(new Class[] {String.class});
verifier = (HostnameVerifier) cons.newInstance(new Object[] {config});
verifier = (HostnameVerifier) cons.newInstance(config);
} else {
verifier = (HostnameVerifier) verifierClass.newInstance();
}

View File

@ -28,7 +28,6 @@ import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
@ -67,7 +66,7 @@ public abstract class AbstractUrlBasedTicketValidator implements TicketValidator
/**
* A map containing custom parameters to pass to the validation url.
*/
private Map customParameters;
private Map<String,String> customParameters;
private String encoding;
@ -86,7 +85,7 @@ public abstract class AbstractUrlBasedTicketValidator implements TicketValidator
*
* @param urlParameters the map containing the parameters.
*/
protected void populateUrlAttributeMap(final Map urlParameters) {
protected void populateUrlAttributeMap(final Map<String,String> urlParameters) {
// nothing to do
}
@ -104,7 +103,7 @@ public abstract class AbstractUrlBasedTicketValidator implements TicketValidator
* @return the fully constructed URL.
*/
protected final String constructValidationUrl(final String ticket, final String serviceUrl) {
final Map urlParameters = new HashMap();
final Map<String,String> urlParameters = new HashMap<String,String>();
log.debug("Placing URL parameters in map.");
urlParameters.put("ticket", ticket);
@ -123,31 +122,30 @@ public abstract class AbstractUrlBasedTicketValidator implements TicketValidator
}
final String suffix = getUrlSuffix();
final StringBuffer buffer = new StringBuffer(urlParameters.size()*10 + this.casServerUrlPrefix.length() + suffix.length() +1);
final StringBuilder buffer = new StringBuilder(urlParameters.size()*10 + this.casServerUrlPrefix.length() + suffix.length() +1);
int i = 0;
synchronized (buffer) {
buffer.append(this.casServerUrlPrefix);
if (!this.casServerUrlPrefix.endsWith("/")) {
buffer.append("/");
}
buffer.append(suffix);
for (final Iterator iter = urlParameters.entrySet().iterator(); iter.hasNext();) {
final Map.Entry entry = (Map.Entry) iter.next();
final String key = (String) entry.getKey();
final String value = (String) entry.getValue();
if (value != null) {
buffer.append(i++ == 0 ? "?" : "&");
buffer.append(key);
buffer.append("=");
buffer.append(value);
}
}
return buffer.toString();
buffer.append(this.casServerUrlPrefix);
if (!this.casServerUrlPrefix.endsWith("/")) {
buffer.append("/");
}
buffer.append(suffix);
for (Map.Entry<String,String> entry : urlParameters.entrySet()) {
final String key = entry.getKey();
final String value = entry.getValue();
if (value != null) {
buffer.append(i++ == 0 ? "?" : "&");
buffer.append(key);
buffer.append("=");
buffer.append(value);
}
}
return buffer.toString();
}
/**
@ -218,7 +216,7 @@ public abstract class AbstractUrlBasedTicketValidator implements TicketValidator
this.renew = renew;
}
public final void setCustomParameters(final Map customParameters) {
public final void setCustomParameters(final Map<String,String> customParameters) {
this.customParameters = customParameters;
}

View File

@ -53,7 +53,7 @@ public interface Assertion extends Serializable {
*
* @return the map of attributes.
*/
Map getAttributes();
Map<String,Object> getAttributes();
/**
* The principal for which this assertion is valid.

View File

@ -23,8 +23,8 @@ import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import org.jasig.cas.client.util.CommonUtils;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
@ -47,7 +47,7 @@ public final class AssertionImpl implements Assertion {
private final Date validUntilDate;
/** Map of key/value pairs associated with this assertion. I.e. authentication type. */
private final Map attributes;
private final Map<String,Object> attributes;
/** The principal for which this assertion is valid for. */
private final AttributePrincipal principal;
@ -62,12 +62,12 @@ public final class AssertionImpl implements Assertion {
}
/**
* Creates a new Assrtion with the supplied Principal.
* Creates a new Assertion with the supplied Principal.
*
* @param principal the Principal to associate with the Assertion.
*/
public AssertionImpl(final AttributePrincipal principal) {
this(principal, new HashMap());
this(principal, Collections.<String, Object>emptyMap());
}
/**
@ -76,19 +76,19 @@ public final class AssertionImpl implements Assertion {
* @param principal the Principal to associate with the Assertion.
* @param attributes the key/value pairs for this attribute.
*/
public AssertionImpl(final AttributePrincipal principal, final Map attributes) {
public AssertionImpl(final AttributePrincipal principal, final Map<String,Object> attributes) {
this(principal, new Date(), null, attributes);
}
/**
* Creats a new Assertion with the supplied principal, Assertion attributes, and start and valid until dates.
* Creates a new Assertion with the supplied principal, Assertion attributes, and start and valid until dates.
*
* @param principal the Principal to associate with the Assertion.
* @param validFromDate when the assertion is valid from.
* @param validUntilDate when the assertion is valid to.
* @param attributes the key/value pairs for this attribute.
*/
public AssertionImpl(final AttributePrincipal principal, final Date validFromDate, final Date validUntilDate, final Map attributes) {
public AssertionImpl(final AttributePrincipal principal, final Date validFromDate, final Date validUntilDate, final Map<String,Object> attributes) {
this.principal = principal;
this.validFromDate = validFromDate;
this.validUntilDate = validUntilDate;
@ -106,7 +106,7 @@ public final class AssertionImpl implements Assertion {
return this.validUntilDate;
}
public Map getAttributes() {
public Map<String,Object> getAttributes() {
return this.attributes;
}

View File

@ -46,8 +46,7 @@ public final class Cas10TicketValidator extends AbstractCasProtocolUrlBasedTicke
}
try {
final BufferedReader reader = new BufferedReader(new StringReader(
response));
final BufferedReader reader = new BufferedReader(new StringReader(response));
reader.readLine();
final String name = reader.readLine();

View File

@ -127,7 +127,7 @@ public class Cas20ProxyReceivingTicketValidationFilter extends AbstractTicketVal
validator.setRenew(parseBoolean(getPropertyFromInitParams(filterConfig, "renew", "false")));
validator.setEncoding(getPropertyFromInitParams(filterConfig, "encoding", null));
final Map additionalParameters = new HashMap();
final Map<String,String> additionalParameters = new HashMap<String,String>();
final List params = Arrays.asList(RESERVED_INIT_PARAMS);
for (final Enumeration e = filterConfig.getInitParameterNames(); e.hasMoreElements();) {

View File

@ -50,15 +50,15 @@ public class Cas20ProxyTicketValidator extends Cas20ServiceTicketValidator {
}
protected void customParseResponse(final String response, final Assertion assertion) throws TicketValidationException {
final List proxies = XmlUtils.getTextForElements(response, "proxy");
final String[] proxiedList = (String[]) proxies.toArray(new String[proxies.size()]);
final List<String> proxies = XmlUtils.getTextForElements(response, "proxy");
final String[] proxiedList = proxies.toArray(new String[proxies.size()]);
// this means there was nothing in the proxy chain, which is okay
if (proxies == null || proxies.isEmpty() || this.acceptAnyProxy) {
if (proxies.isEmpty() || this.acceptAnyProxy) {
return;
}
if (allowedProxyChains.contains(proxiedList)) {
if (this.allowedProxyChains.contains(proxiedList)) {
return;
}

View File

@ -71,7 +71,7 @@ public class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTick
*
* @param urlParameters the Map containing the existing parameters to send to the server.
*/
protected final void populateUrlAttributeMap(final Map urlParameters) {
protected final void populateUrlAttributeMap(final Map<String,String> urlParameters) {
urlParameters.put("pgtUrl", encodeUrl(this.proxyCallbackUrl));
}
@ -97,7 +97,7 @@ public class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTick
}
final Assertion assertion;
final Map attributes = extractCustomAttributes(response);
final Map<String,Object> attributes = extractCustomAttributes(response);
if (CommonUtils.isNotBlank(proxyGrantingTicket)) {
final AttributePrincipal attributePrincipal = new AttributePrincipalImpl(principal, attributes, proxyGrantingTicket, this.proxyRetriever);
assertion = new AssertionImpl(attributePrincipal);
@ -123,21 +123,21 @@ public class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTick
* @param xml the XML to parse.
* @return the map of attributes.
*/
protected Map extractCustomAttributes(final String xml) {
protected Map<String,Object> extractCustomAttributes(final String xml) {
final int pos1 = xml.indexOf("<cas:attributes>");
final int pos2 = xml.indexOf("</cas:attributes>");
if (pos1 == -1) {
return Collections.EMPTY_MAP;
return Collections.emptyMap();
}
final String attributesText = xml.substring(pos1+16, pos2);
final Map attributes = new HashMap();
final Map<String,Object> attributes = new HashMap<String,Object>();
final BufferedReader br = new BufferedReader(new StringReader(attributesText));
String line;
final List attributeNames = new ArrayList();
final List<String> attributeNames = new ArrayList<String>();
try {
while ((line = br.readLine()) != null) {
final String trimmedLine = line.trim();
@ -152,8 +152,7 @@ public class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTick
//ignore
}
for (final Iterator iter = attributeNames.iterator(); iter.hasNext();) {
final String name = (String) iter.next();
for (final String name : attributeNames) {
attributes.put(name, XmlUtils.getTextForElement(xml, name));
}

View File

@ -23,7 +23,6 @@ import org.jasig.cas.client.util.CommonUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.Arrays;
/**
@ -35,26 +34,20 @@ import java.util.Arrays;
*/
public final class ProxyList {
private final List proxyChains;
private final List<String[]> proxyChains;
public ProxyList(final List proxyChains) {
public ProxyList(final List<String[]> proxyChains) {
CommonUtils.assertNotNull(proxyChains, "List of proxy chains cannot be null.");
// Assert that all entries in the list are String[]
for (final Iterator iter = proxyChains.iterator(); iter.hasNext();) {
CommonUtils.assertTrue(iter.next() instanceof String[], "Proxy chains must contain String[] items exclusively.");
}
this.proxyChains = proxyChains;
}
public ProxyList() {
this(new ArrayList());
this(new ArrayList<String[]>());
}
public boolean contains(String[] proxiedList) {
for (Iterator iter = this.proxyChains.iterator(); iter.hasNext();) {
if (Arrays.equals(proxiedList, (String[]) iter.next())) {
for (final String[] list : this.proxyChains) {
if (Arrays.equals(proxiedList, list)) {
return true;
}
}

View File

@ -40,7 +40,7 @@ public final class ProxyListEditor extends PropertyEditorSupport {
public void setAsText(final String text) throws IllegalArgumentException {
final BufferedReader reader = new BufferedReader(new StringReader(text));
final List proxyChains = new ArrayList();
final List<String[]> proxyChains = new ArrayList<String[]>();
try {
String line;

View File

@ -51,8 +51,8 @@ public final class Saml11TicketValidator extends AbstractUrlBasedTicketValidator
return "samlValidate";
}
protected void populateUrlAttributeMap(final Map urlParameters) {
final String service = (String) urlParameters.get("service");
protected void populateUrlAttributeMap(final Map<String, String> urlParameters) {
final String service = urlParameters.get("service");
urlParameters.remove("service");
urlParameters.remove("ticket");
urlParameters.put("TARGET", service);

View File

@ -40,6 +40,8 @@ public final class PublicTestHttpServer extends Thread {
public final String encoding;
private ServerSocket server;
private PublicTestHttpServer(String data, String encoding, String MIMEType, int port) throws UnsupportedEncodingException {
this(data.getBytes(encoding), encoding, MIMEType, port);
}
@ -66,10 +68,21 @@ public final class PublicTestHttpServer extends Thread {
return httpServer;
}
public void shutdown() {
System.out.println("Shutting down connection on port " + server.getLocalPort());
try {
this.server.close();
} catch (final Exception e) {
System.err.println(e);
}
httpServer = null;
}
public void run() {
try {
ServerSocket server = new ServerSocket(this.port);
this.server = new ServerSocket(this.port);
System.out.println("Accepting connections on port " + server.getLocalPort());
while (true) {

View File

@ -74,10 +74,10 @@ public class SerializationTests extends TestCase {
final SimplePrincipal simplePrincipal = new SimplePrincipal("simple");
final SimpleGroup simpleGroup = new SimpleGroup("group");
final AttributePrincipalImpl attributePrincipal =
new AttributePrincipalImpl("attr", Collections.singletonMap("LOA", "3"));
new AttributePrincipalImpl("attr", Collections.<String,Object>singletonMap("LOA", "3"));
final AssertionPrincipal assertionPrincipal = new AssertionPrincipal(
"assertion",
new AssertionImpl(attributePrincipal, Collections.singletonMap("authenticationMethod", "username")));
new AssertionImpl(attributePrincipal, Collections.<String,Object>singletonMap("authenticationMethod", "username")));
return new Object[] {
simplePrincipal,

View File

@ -28,7 +28,7 @@ import junit.framework.TestCase;
* @version $Revision: 11731 $ $Date: 2007-09-27 11:27:21 -0400 (Wed, 27 Sep 2007) $
* @since 3.0
*/
public abstract class AbstractTicketValidatorTests extends TestCase {
public abstract class AbstractTicketValidatorTests {
protected static final String CONST_CAS_SERVER_URL = "http://localhost:8085/";

View File

@ -21,9 +21,14 @@ package org.jasig.cas.client.validation;
import org.jasig.cas.client.PublicTestHttpServer;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import static org.junit.Assert.*;
/**
* Test cases for the {@link Cas10TicketValidator}.
*
@ -39,10 +44,17 @@ public final class Cas10TicketValidatorTests extends AbstractTicketValidatorTest
super();
}
protected void setUp() throws Exception {
@AfterClass
public static void classCleanUp() {
PublicTestHttpServer.instance().shutdown();
}
@Before
public void setUp() throws Exception {
this.ticketValidator = new Cas10TicketValidator(CONST_CAS_SERVER_URL);
}
@Test
public void testNoResponse() throws Exception {
PublicTestHttpServer.instance().content = "no\n\n"
.getBytes(PublicTestHttpServer.instance().encoding);
@ -55,6 +67,7 @@ public final class Cas10TicketValidatorTests extends AbstractTicketValidatorTest
}
}
@Test
public void testYesResponse() throws TicketValidationException,
UnsupportedEncodingException {
PublicTestHttpServer.instance().content = "yes\nusername\n\n"
@ -64,6 +77,7 @@ public final class Cas10TicketValidatorTests extends AbstractTicketValidatorTest
assertEquals(CONST_USERNAME, assertion.getPrincipal().getName());
}
@Test
public void testBadResponse() throws UnsupportedEncodingException {
PublicTestHttpServer.instance().content = "falalala\n\n"
.getBytes(PublicTestHttpServer.instance().encoding);

View File

@ -23,12 +23,17 @@ import org.jasig.cas.client.PublicTestHttpServer;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl;
import org.jasig.cas.client.proxy.ProxyRetriever;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
/**
* Test cases for the {@link Cas20ProxyTicketValidator}.
*
@ -45,8 +50,14 @@ public final class Cas20ProxyTicketValidatorTests extends
super();
}
protected void setUp() throws Exception {
final List list = new ArrayList();
@AfterClass
public static void classCleanUp() {
PublicTestHttpServer.instance().shutdown();
}
@Before
public void setUp() throws Exception {
final List<String[]> list = new ArrayList<String[]>();
list.add(new String[] {"proxy1", "proxy2", "proxy3"});
this.ticketValidator = new Cas20ProxyTicketValidator(CONST_CAS_SERVER_URL);
@ -58,13 +69,11 @@ public final class Cas20ProxyTicketValidatorTests extends
}
private ProxyGrantingTicketStorage getProxyGrantingTicketStorage() {
final ProxyGrantingTicketStorageImpl proxyGrantingTicketStorageImpl = new ProxyGrantingTicketStorageImpl();
return proxyGrantingTicketStorageImpl;
return new ProxyGrantingTicketStorageImpl();
}
private ProxyRetriever getProxyRetriever() {
final ProxyRetriever proxyRetriever = new ProxyRetriever() {
return new ProxyRetriever() {
/** Unique Id For serialization. */
private static final long serialVersionUID = 1L;
@ -73,10 +82,9 @@ public final class Cas20ProxyTicketValidatorTests extends
return "test";
}
};
return proxyRetriever;
}
@Test
public void testProxyChainWithValidProxy() throws TicketValidationException,
UnsupportedEncodingException {
final String USERNAME = "username";
@ -89,6 +97,7 @@ public final class Cas20ProxyTicketValidatorTests extends
assertEquals(USERNAME, assertion.getPrincipal().getName());
}
@Test
public void testProxyChainWithInvalidProxy() throws TicketValidationException,
UnsupportedEncodingException {
final String RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'><cas:authenticationSuccess><cas:user>username</cas:user><cas:proxyGrantingTicket>PGTIOU-84678-8a9d...</cas:proxyGrantingTicket><cas:proxies><cas:proxy>proxy7</cas:proxy><cas:proxy>proxy2</cas:proxy><cas:proxy>proxy3</cas:proxy></cas:proxies></cas:authenticationSuccess></cas:serviceResponse>";
@ -102,7 +111,8 @@ public final class Cas20ProxyTicketValidatorTests extends
// expected
}
}
@Test
public void testConstructionFromSpringBean() throws TicketValidationException,
UnsupportedEncodingException {
final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:cas20ProxyTicketValidator.xml");

View File

@ -24,6 +24,11 @@ import org.jasig.cas.client.PublicTestHttpServer;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl;
import org.jasig.cas.client.proxy.ProxyRetriever;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.UnsupportedEncodingException;
@ -34,8 +39,7 @@ import java.io.UnsupportedEncodingException;
* @version $Revision: 11737 $ $Date: 2007-10-03 09:14:02 -0400 (Tue, 03 Oct 2007) $
* @since 3.0
*/
public final class Cas20ServiceTicketValidatorTests extends
AbstractTicketValidatorTests {
public final class Cas20ServiceTicketValidatorTests extends AbstractTicketValidatorTests {
private Cas20ServiceTicketValidator ticketValidator;
@ -45,11 +49,13 @@ public final class Cas20ServiceTicketValidatorTests extends
super();
}
public Cas20ServiceTicketValidatorTests(Cas20ServiceTicketValidator ticketValidator) {
this.ticketValidator = ticketValidator;
@AfterClass
public static void classCleanUp() {
PublicTestHttpServer.instance().shutdown();
}
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
this.proxyGrantingTicketStorage = getProxyGrantingTicketStorage();
this.ticketValidator = new Cas20ServiceTicketValidator(CONST_CAS_SERVER_URL);
this.ticketValidator.setProxyCallbackUrl("test");
@ -59,13 +65,11 @@ public final class Cas20ServiceTicketValidatorTests extends
}
private ProxyGrantingTicketStorage getProxyGrantingTicketStorage() {
final ProxyGrantingTicketStorageImpl proxyGrantingTicketStorageImpl = new ProxyGrantingTicketStorageImpl();
return proxyGrantingTicketStorageImpl;
return new ProxyGrantingTicketStorageImpl();
}
private ProxyRetriever getProxyRetriever() {
final ProxyRetriever proxyRetriever = new ProxyRetriever() {
return new ProxyRetriever() {
/** Unique Id for serialization. */
private static final long serialVersionUID = 1L;
@ -74,10 +78,9 @@ public final class Cas20ServiceTicketValidatorTests extends
return "test";
}
};
return proxyRetriever;
}
@Test
public void testNoResponse() throws UnsupportedEncodingException {
final String RESPONSE = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'><cas:authenticationFailure code=\"INVALID_TICKET\">Ticket ST-1856339-aA5Yuvrxzpv8Tau1cYQ7 not recognized</cas:authenticationFailure></cas:serviceResponse>";
PublicTestHttpServer.instance().content = RESPONSE
@ -90,6 +93,7 @@ public final class Cas20ServiceTicketValidatorTests extends
}
}
@Test
public void testYesResponseButNoPgt() throws TicketValidationException,
UnsupportedEncodingException {
final String USERNAME = "username";
@ -102,8 +106,10 @@ public final class Cas20ServiceTicketValidatorTests extends
final Assertion assertion = this.ticketValidator.validate("test",
"test");
assertEquals(USERNAME, assertion.getPrincipal().getName());
}
@Test
public void testYesResponseWithPgt() throws TicketValidationException,
UnsupportedEncodingException {
final String USERNAME = "username";
@ -125,7 +131,8 @@ public final class Cas20ServiceTicketValidatorTests extends
assertEquals(USERNAME, assertion.getPrincipal().getName());
// assertEquals(PGT, assertion.getProxyGrantingTicketId());
}
@Test
public void testGetAttributes() throws TicketValidationException,
UnsupportedEncodingException {
final String USERNAME = "username";
@ -146,6 +153,7 @@ public final class Cas20ServiceTicketValidatorTests extends
//assertEquals(PGT, assertion.getProxyGrantingTicketId());
}
@Test
public void testInvalidResponse() throws Exception {
final String RESPONSE = "<root />";
PublicTestHttpServer.instance().content = RESPONSE

View File

@ -21,10 +21,15 @@ package org.jasig.cas.client.validation;
import org.jasig.cas.client.PublicTestHttpServer;
import org.jasig.cas.client.util.CommonUtils;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import static org.junit.Assert.*;
/**
* @author Scott Battaglia
* @version $Revision$ $Date$
@ -34,11 +39,18 @@ public final class Saml11TicketValidatorTests extends AbstractTicketValidatorTes
private Saml11TicketValidator validator;
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
this.validator = new Saml11TicketValidator(CONST_CAS_SERVER_URL);
this.validator.setTolerance(1000L);
}
@AfterClass
public static void classCleanUp() {
PublicTestHttpServer.instance().shutdown();
}
@Test
public void testValidationFailedResponse() throws UnsupportedEncodingException {
final String RESPONSE = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope\n" +
" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body><Response\n" +
@ -60,14 +72,14 @@ public final class Saml11TicketValidatorTests extends AbstractTicketValidatorTes
// expected
}
}
@Test
public void testValidationSuccessWithNoAttributes() throws UnsupportedEncodingException {
final Date now = new Date();
final Date before = new Date(now.getTime() - 5000);
final Date after = new Date(now.getTime() + 200000000);
final String RESPONSE = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body><Response xmlns=\"urn:oasis:names:tc:SAML:1.0:protocol\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\" xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" IssueInstant=\"" + CommonUtils.formatForUtcTime(now) + "\" MajorVersion=\"1\" MinorVersion=\"1\" Recipient=\"test\" ResponseID=\"_e1e2124c08ab456eab0bbab3e1c0c433\"><Status><StatusCode Value=\"samlp:Success\"></StatusCode></Status><Assertion xmlns=\"urn:oasis:names:tc:SAML:1.0:assertion\" AssertionID=\"_d2fd0d6e4da6a6d7d2ba5274ab570d5c\" IssueInstant=\"" + CommonUtils.formatForUtcTime(now) + "\" Issuer=\"testIssuer\" MajorVersion=\"1\" MinorVersion=\"1\"><Conditions NotBefore=\"" + CommonUtils.formatForUtcTime(before) + "\" NotOnOrAfter=\"" + CommonUtils.formatForUtcTime(after) + "\"><AudienceRestrictionCondition><Audience>test</Audience></AudienceRestrictionCondition></Conditions><AuthenticationStatement AuthenticationInstant=\"2008-06-19T14:34:44.426Z\" AuthenticationMethod=\"urn:ietf:rfc:2246\"><Subject><NameIdentifier>testPrincipal</NameIdentifier><SubjectConfirmation><ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:artifact</ConfirmationMethod></SubjectConfirmation></Subject></AuthenticationStatement></Assertion></Response></SOAP-ENV:Body></SOAP-ENV:Envelope>";
PublicTestHttpServer.instance().content = RESPONSE
.getBytes(PublicTestHttpServer.instance().encoding);
PublicTestHttpServer.instance().content = RESPONSE.getBytes(PublicTestHttpServer.instance().encoding);
try {
final Assertion a = this.validator.validate("test", "test");
assertEquals("testPrincipal", a.getPrincipal().getName());

View File

@ -48,20 +48,20 @@ public abstract class AbstractLogoutHandler implements LogoutHandler {
/** {@inheritDoc} */
public void logout(final HttpServletRequest request, final HttpServletResponse response) {
this.log.debug("Processing logout request from CAS server.");
log.debug("Processing logout request from CAS server.");
final Assertion assertion;
final HttpSession httpSession = request.getSession(false);
if (httpSession != null && (assertion = (Assertion) httpSession.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION)) != null) {
httpSession.removeAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
this.log.info("Successfully logged out " + assertion.getPrincipal());
log.info("Successfully logged out " + assertion.getPrincipal());
} else {
this.log.info("Session already ended.");
log.info("Session already ended.");
}
final String redirectUrl = constructRedirectUrl(request);
if (redirectUrl != null) {
this.log.debug("Redirecting to " + redirectUrl);
log.debug("Redirecting to " + redirectUrl);
CommonUtils.sendRedirect(response, redirectUrl);
}
}
@ -73,6 +73,6 @@ public abstract class AbstractLogoutHandler implements LogoutHandler {
* @return the url to redirect to. CAN be NULL.
*/
protected String constructRedirectUrl(final HttpServletRequest request) {
return redirectUrl;
return this.redirectUrl;
}
}

View File

@ -37,9 +37,11 @@ import org.jasig.cas.client.util.CommonUtils;
*
* @author Marvin S. Addison
* @version $Revision$
* @since 3.1.12
*
*/
public class AssertionCasRealmDelegate implements CasRealm {
/** Default role attribute name */
public static final String DEFAULT_ROLE_NAME = "role";
@ -63,7 +65,7 @@ public class AssertionCasRealmDelegate implements CasRealm {
public String[] getRoles(final Principal p) {
CommonUtils.assertTrue(p instanceof AttributePrincipal, "Expected instance of AttributePrincipal but got " + p.getClass());
final Collection roles = getRoleCollection(p);
final Collection<String> roles = getRoleCollection(p);
final String[] array = new String[roles.size()];
roles.toArray(array);
return array;
@ -80,7 +82,7 @@ public class AssertionCasRealmDelegate implements CasRealm {
* @param p the principal to check.
* @return the list of attribute values that matched this role, or an empty collection if they don't.
*/
private Collection getRoleCollection(final Principal p) {
private Collection<String> getRoleCollection(final Principal p) {
if (!(p instanceof AttributePrincipal)) {
return Collections.emptyList();
}
@ -92,9 +94,9 @@ public class AssertionCasRealmDelegate implements CasRealm {
}
if (attributes instanceof Collection) {
return (Collection) attributes;
return (Collection<String>) attributes;
}
return Arrays.asList(new Object[] {attributes});
return Arrays.asList(attributes.toString());
}
}

View File

@ -43,9 +43,11 @@ import org.jasig.cas.client.validation.TicketValidator;
*
* @author Marvin S. Addison
* @version $Revision$
* @since 3.1.12
*
*/
public class AuthenticatorDelegate {
public final class AuthenticatorDelegate {
/** Log instance */
private final Log log = LogFactory.getLog(getClass());
@ -63,7 +65,6 @@ public class AuthenticatorDelegate {
private CasRealm realm;
/**
* Performs CAS authentication on the given request and returns the principal
* determined by the configured {@link CasRealm} on success.
@ -157,13 +158,6 @@ public class AuthenticatorDelegate {
this.casServerLoginUrl = casServerLoginUrl;
}
/**
* @return the ticketValidator
*/
public TicketValidator getTicketValidator() {
return ticketValidator;
}
/**
* @param artifactParameterName the artifactParameterName to set
*/

View File

@ -27,6 +27,7 @@ import java.security.Principal;
*
* @author Marvin S. Addison
* @version $Revision$
* @since 3.1.12
*
*/
public interface CasRealm {

View File

@ -27,6 +27,7 @@ import javax.servlet.http.HttpServletResponse;
*
* @author Marvin S. Addison
* @version $Revision$
* @since 3.1.12
*
*/
public interface LogoutHandler {

View File

@ -43,6 +43,7 @@ import org.jasig.cas.client.util.CommonUtils;
*
* @author Middleware
* @version $Revision$
* @since 3.1.12
*
*/
public class PropertiesCasRealmDelegate implements CasRealm {
@ -54,7 +55,7 @@ public class PropertiesCasRealmDelegate implements CasRealm {
private String propertiesFilePath;
/** Map of usernames to roles */
private Map roleMap;
private Map<String, Set<String>> roleMap;
/**
* @param path Path to properties file container username/role data.
@ -76,15 +77,15 @@ public class PropertiesCasRealmDelegate implements CasRealm {
final Properties properties = new Properties();
try {
properties.load(new BufferedInputStream(new FileInputStream(file)));
} catch (IOException e) {
} catch (final IOException e) {
throw new IllegalStateException("Error loading users/roles from " + file, e);
}
roleMap = new HashMap(properties.size());
final Iterator keys = properties.keySet().iterator();
while (keys.hasNext()) {
final String user = (String) keys.next();
this.roleMap = new HashMap<String,Set<String>>(properties.size());
final Set<String> keys = new HashSet(properties.keySet());
for (final String user : keys) {
// Use TreeSet to sort roles
final Set roleSet = new HashSet();
final Set<String> roleSet = new HashSet<String>();
final String[] roles = properties.getProperty(user).split(",\\s*");
roleSet.addAll(Arrays.asList(roles));
roleMap.put(user, roleSet);
@ -93,7 +94,7 @@ public class PropertiesCasRealmDelegate implements CasRealm {
/** {@inheritDoc} */
public Principal authenticate(final Principal p) {
if (roleMap.containsKey(p.getName())) {
if (this.roleMap.containsKey(p.getName())) {
return p;
} else {
return null;
@ -102,7 +103,7 @@ public class PropertiesCasRealmDelegate implements CasRealm {
/** {@inheritDoc} */
public String[] getRoles(final Principal p) {
final Set roleSet = (Set) roleMap.get(p.getName());
final Set<String> roleSet = this.roleMap.get(p.getName());
final String[] roles = new String[roleSet.size()];
roleSet.toArray(roles);
return roles;
@ -110,7 +111,7 @@ public class PropertiesCasRealmDelegate implements CasRealm {
/** {@inheritDoc} */
public boolean hasRole(final Principal principal, final String role) {
final Set roles = (Set) roleMap.get(principal.getName());
final Set<String> roles = this.roleMap.get(principal.getName());
return roles != null && roles.contains(role);
}

View File

@ -46,7 +46,7 @@ public final class StaticUriLogoutHandler extends AbstractLogoutHandler {
}
/**
* Initalializes the component for use.
* Initializes the component for use.
*/
public void init() {
CommonUtils.assertNotNull(this.logoutUri, "logoutUri cannot be null.");

View File

@ -47,11 +47,11 @@ public class AssertionCasRealm extends AbstractCasRealm {
* @param name Name of the attribute in the principal that contains role data.
*/
public void setRoleAttributeName(final String name) {
delegate.setRoleAttributeName(name);
this.delegate.setRoleAttributeName(name);
}
/** {@inheritDoc} */
protected CasRealm getDelegate() {
return delegate;
return this.delegate;
}
}

View File

@ -54,6 +54,6 @@ public class Cas10CasAuthenticator extends AbstractCasAuthenticator {
super.start();
this.ticketValidator = new Cas10TicketValidator(getCasServerUrlPrefix());
lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);
this.log.info("Startup completed.");
log.info("Startup completed.");
}
}

View File

@ -36,6 +36,7 @@ import org.jasig.cas.client.tomcat.PropertiesCasRealmDelegate;
*
* @author Marvin S. Addison
* @version $Revision$
* @since 3.1.12
*
*/
public class PropertiesCasRealm extends AbstractCasRealm {
@ -46,19 +47,19 @@ public class PropertiesCasRealm extends AbstractCasRealm {
* @param path Path to properties file container username/role data.
*/
public void setPropertiesFilePath(final String path) {
delegate.setPropertiesFilePath(path);
this.delegate.setPropertiesFilePath(path);
}
/** {@inheritDoc} */
public void start() throws LifecycleException {
super.start();
delegate.readProperties();
this.delegate.readProperties();
this.log.info("Startup completed.");
}
/** {@inheritDoc} */
protected CasRealm getDelegate() {
return delegate;
return this.delegate;
}
}

View File

@ -58,6 +58,6 @@ public final class RegexUriLogoutValve extends AbstractLogoutValve {
/** {@inheritDoc} */
protected LogoutHandler getLogoutHandler() {
return logoutHandler;
return this.logoutHandler;
}
}

View File

@ -28,6 +28,7 @@ import org.jasig.cas.client.validation.TicketValidator;
*
* @author Marvin S. Addison
* @version $Revision$
* @since 3.1.12
*
*/
public class Saml11Authenticator extends AbstractAuthenticator {
@ -41,7 +42,6 @@ public class Saml11Authenticator extends AbstractAuthenticator {
/** SAML protocol clock drift tolerance in ms */
private int tolerance = -1;
/**
* @param ms SAML clock drift tolerance in milliseconds.
*/

View File

@ -39,6 +39,7 @@ import org.jasig.cas.client.session.SingleSignOutHandler;
*
* @author Marvin S. Addison
* @version $Revision$
* @since 3.1.12
*
*/
public class SingleSignOutValve extends AbstractLifecycleValve implements SessionListener {

View File

@ -58,6 +58,6 @@ public final class StaticUriLogoutValve extends AbstractLogoutValve {
/** {@inheritDoc} */
protected LogoutHandler getLogoutHandler() {
return logoutHandler;
return this.logoutHandler;
}
}

View File

@ -36,6 +36,7 @@ import org.jasig.cas.client.tomcat.PropertiesCasRealmDelegate;
*
* @author Marvin S. Addison
* @version $Revision$
* @since 3.1.12
*
*/
public class PropertiesCasRealm extends AbstractCasRealm {
@ -46,18 +47,18 @@ public class PropertiesCasRealm extends AbstractCasRealm {
* @param path Path to properties file container username/role data.
*/
public void setPropertiesFilePath(final String path) {
delegate.setPropertiesFilePath(path);
this.delegate.setPropertiesFilePath(path);
}
/** {@inheritDoc} */
protected void startInternal() throws LifecycleException {
super.startInternal();
delegate.readProperties();
this.delegate.readProperties();
}
/** {@inheritDoc} */
protected CasRealm getDelegate() {
return delegate;
return this.delegate;
}
}

View File

@ -34,9 +34,6 @@ import org.jasig.cas.client.tomcat.RegexUriLogoutHandler;
* @since 3.1.12
*/
public final class RegexUriLogoutValve extends AbstractLogoutValve {
/** Logger instance */
private final Log log = LogFactory.getLog(getClass());
private RegexUriLogoutHandler logoutHandler = new RegexUriLogoutHandler();
@ -56,6 +53,6 @@ public final class RegexUriLogoutValve extends AbstractLogoutValve {
/** {@inheritDoc} */
protected LogoutHandler getLogoutHandler() {
return logoutHandler;
return this.logoutHandler;
}
}

View File

@ -28,9 +28,11 @@ import org.jasig.cas.client.validation.TicketValidator;
*
* @author Marvin S. Addison
* @version $Revision$
* @since 3.1.12
*
*/
public final class Saml11Authenticator extends AbstractAuthenticator {
public static final String AUTH_METHOD = "SAML11";
private static final String NAME = Saml11Authenticator.class.getName();

View File

@ -41,7 +41,8 @@ import org.jasig.cas.client.session.SingleSignOutHandler;
* HTTP session.
*
* @author Marvin S. Addison
* @version $Revision$
* @version $Revision$ $Date$
* @since 3.1.12
*
*/
public class SingleSignOutValve extends ValveBase implements SessionListener {

View File

@ -20,8 +20,6 @@
package org.jasig.cas.client.tomcat.v7;
import org.apache.catalina.LifecycleException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.cas.client.tomcat.LogoutHandler;
import org.jasig.cas.client.tomcat.StaticUriLogoutHandler;
@ -35,9 +33,6 @@ import org.jasig.cas.client.tomcat.StaticUriLogoutHandler;
*/
public final class StaticUriLogoutValve extends AbstractLogoutValve {
/** Logger instance */
private final Log log = LogFactory.getLog(getClass());
private StaticUriLogoutHandler logoutHandler = new StaticUriLogoutHandler();
public void setRedirectUrl(final String redirectUrl) {
@ -56,6 +51,6 @@ public final class StaticUriLogoutValve extends AbstractLogoutValve {
/** {@inheritDoc} */
protected LogoutHandler getLogoutHandler() {
return logoutHandler;
return this.logoutHandler;
}
}

View File

@ -115,7 +115,7 @@ NwXMoqnmqmUUnosrspqmmmmmmUUnosrspqmmmmmmUUA1jJ
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>