/** 
 * 
 * Copyright 2004 Hiram Chirino
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 * 
 **/
package org.codehaus.activemq.security.jassjacc;

import java.io.Serializable;
import java.security.Permission;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * Abstract class to make it easier to JMS Permissions.
 * 
 * @version $Revision: 1.1 $
 */
abstract public class AbstractJMSPermission extends Permission implements Serializable {
	
	private String action;
	private int cachedHashCode;
	private HashSet actions;	
	
	/**
	 * @param name
	 */
	public AbstractJMSPermission(String name, String action) {
		super(name);
		String listOfActions[]=normalize(action);
		this.actions = new HashSet( Arrays.asList(listOfActions) );
		if( !getValidSetOfActions().containsAll(actions) ) {
			throw new IllegalArgumentException("The action set ("+actions+") is invalid. Valid set of actions are: "+getValidSetOfActions());
		}		
		this.action=join(listOfActions);
	}

	abstract public Set getValidSetOfActions();

	static private String[] normalize(String action) {
		String[] strings = action.split(",", -1);
		Arrays.sort(strings);
		return strings;
	}
	
	static private String join(String action[]) {
		StringBuffer buff = new StringBuffer();
		for (int i = 0; i < action.length; i++) {
			if( i!=0 )
				buff.append(",");
			buff.append(action[i]);
		}
		return buff.toString();
	}

	/**
	 * @see java.security.Permission#hashCode()
	 */
	public int hashCode() {
		if (cachedHashCode == 0) {
            cachedHashCode = getName().hashCode() ^ action.hashCode();
        }
        return cachedHashCode;	
    }

	/**
	 * @see java.security.Permission#equals(java.lang.Object)
	 */
	public boolean equals(Object o) {
        if (o == null || !(o instanceof AbstractJMSPermission)) return false;

        AbstractJMSPermission other = (AbstractJMSPermission) o;
        return getName().equals(other.getName()) && action.equals(other.action);	
    }

	/**
	 * @see java.security.Permission#getActions()
	 */
	public String getActions() {
		return action;
	}

	/**
	 * @see java.security.Permission#implies(java.security.Permission)
	 */
	public boolean implies(Permission permission) {
       if (permission == null || !(permission instanceof AbstractJMSPermission)) return false;

       AbstractJMSPermission other = (AbstractJMSPermission) permission;
        return getName().equals(other.getName()) && other.actions.containsAll(this.actions);
	}
}

