/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@objectweb.org
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 * 
 */

package org.objectweb.jonas.rmifilters;

import java.util.Properties;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.InputStream;
import java.io.IOException;

import org.objectweb.security.propagation.SecurityReceiver;
import org.objectweb.security.propagation.SecuritySender;

import org.objectweb.security.context.SecurityContext;

import org.objectweb.jonas.common.Log;
import org.objectweb.util.monolog.api.Logger;
import org.objectweb.util.monolog.api.BasicLevel;


/**
 * This is the Utility class for RMI Security context propagation
 *
 * @author John Ellis
 * Contributor(s): 
 */
public class RMISecurityPropagationManager {
   
    // logger  for traces (used for security context)
    static private Logger logger = null;
 
    /**
     * Empty constructor
     */
    private RMISecurityPropagationManager () {
        if(logger == null)
            logger = Log.getLogger(Log.JONAS_SECURITY_PREFIX);
	init();
    }

    protected void init() {
	logger.log(BasicLevel.DEBUG, "entering");
   	Properties properties = new Properties();
   	String propertyPrefix = "jonas.security.SSHandler.";
   	try { 
	    InputStream in = ClassLoader.getSystemResourceAsStream("securitycontext.properties");
	    String senderClassName = null;
	    String receiverClassName = null;
	    if (in == null) {
		senderClassName = "org.objectweb.jonas.rmifilters.JonasSecuritySender";
		receiverClassName = "org.objectweb.jonas.rmifilters.JonasSecurityReceiver";
	    } else {
		properties.load(in);
		senderClassName = properties.getProperty(propertyPrefix + "sender");
		receiverClassName  = properties.getProperty(propertyPrefix + "receiver");
	    }
	    if (senderClassName != null && senderClassName.length() != 0) {
		try {
		    sender = (SecuritySender)Class.forName (senderClassName).newInstance();
		} catch (Exception e) {
		    e.printStackTrace();
		}
	    }
	    if (receiverClassName != null && receiverClassName.length() != 0) {
		try  {
		    receiver = (SecurityReceiver)Class.forName (receiverClassName).newInstance();
		} catch (Exception e) {
		    e.printStackTrace();
		}
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
   
    public static RMISecurityPropagationManager getInstance() {
	// CAUTION: Do not do log BEFORE 'new RMISecurityPropagationManager()' have been done
	if (unique == null) {
	    synchronized (syncro) {
		if (unique == null) {
		    unique = new RMISecurityPropagationManager();
		}            
	    }         
	}
 	return unique;
    }
   
    public void sendingRequest(ObjectOutput out) throws IOException {
	SecurityContext ctxOut = null;
	logger.log(BasicLevel.DEBUG, "entering");
	int nextId = getNextId();
      
	if (sender != null) {
	    ctxOut = sender.sending_request(nextId);
	}
	out.writeInt(nextId);
	out.writeObject(ctxOut);
    }
   
    public void sendingReply(ObjectOutput out) throws IOException {
	SecurityContext ctxOut = null;
	logger.log(BasicLevel.DEBUG, "entering");
	int nextId = getNextId();
      
	if (receiver != null) {
	    ctxOut = receiver.sending_reply(nextId);
	}
	out.writeInt(nextId);
	out.writeObject(ctxOut);
    }
   
    public void receivedRequest(ObjectInput in) throws IOException, ClassNotFoundException {
	int requestId = in.readInt();
	SecurityContext ctxIn = (SecurityContext)in.readObject();
 	logger.log(BasicLevel.DEBUG, "entering");     
	if (receiver != null) {
	    receiver.received_request(requestId, ctxIn);
	}      
    }
   
    public void receivedReply(ObjectInput in) throws IOException, ClassNotFoundException {
	int requestId = in.readInt();
	SecurityContext ctxIn = (SecurityContext)in.readObject();
   	logger.log(BasicLevel.DEBUG, "entering");       
	if (receiver != null) {
	    sender.received_reply(requestId, ctxIn);
	}      
    }

    protected synchronized int getNextId() {
	return nextId++;
    }
   
    private int nextId = 0;
      
    private static Object syncro = new Object(); 
    private static RMISecurityPropagationManager unique = null;
   
    private SecuritySender sender = null;
    private SecurityReceiver receiver = null;
}
