⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 beepsession.java

📁 jxme的一些相关程序,主要是手机上程序开发以及手机和计算机通信的一些程序资料,程序编译需要Ant支持
💻 JAVA
字号:
/*
 * Copyright (c) 2001 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *       Sun Microsystems, Inc. for Project JXTA."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact Project JXTA at http://www.jxta.org.
 *
 * 5. Products derived from this software may not be called "JXTA",
 *    nor may "JXTA" appear in their name, without prior written
 *    permission of Sun.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL SUN MICROSYSTEMS OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of Project JXTA.  For more
 * information on Project JXTA, please see
 * <http://www.jxta.org/>.
 *
 * This license is based on the BSD license adopted by the Apache Foundation.
 *
 * $Id: BeepSession.java,v 1.3 2001/11/07 23:20:51 jice Exp $
 */

package net.jxta.impl.endpoint.beep;

import java.net.Socket;
import java.net.InetAddress;
import java.util.Iterator;

import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;

import org.apache.log4j.Category; import org.apache.log4j.Priority;

import org.beepcore.beep.core.Channel;
import org.beepcore.beep.core.SessionEvent;
import org.beepcore.beep.core.SessionEventListener;
import org.beepcore.beep.core.Session;
import org.beepcore.beep.lib.ChannelPool;
import org.beepcore.beep.lib.SharedChannel;
import org.beepcore.beep.transport.tcp.AutomatedTCPSessionCreator;
import org.beepcore.beep.transport.tcp.TCPSession;

import org.beepcore.beep.core.BEEPException;

import net.jxta.endpoint.EndpointAddress;

import net.jxta.impl.endpoint.Address;

/**
 *  The BeepSession manages an individual session that the TransportEndpoint has
 *  initiated or received from other peer.
 *
 **/
class BeepSession implements SessionEventListener {
    /**
     *  Our Log4J Category
     **/
    private static final Category LOG = Category.getInstance(BeepSession.class.getName());
    
    /**
     *  The time specified to the channel pool as to how long idle channels
     *  should live in miliseconds
     **/
    private static final int    CHANNEL_IDLE_TTL = 30 * 1000;
    
    /**
     *  Transport associated with this session
     **/
    private BeepTransport tpt;
    
    /**
     *  Destination address for this session
     **/
    private EndpointAddress     dst;
    
    /**
     *  The tcp host address of the DESTINATION
     **/
    private InetAddress         host;
    
    /**
     *  The tcp port address of the DESTINATION
     **/
    private int                 port = 0;
    
    /**
     *  The BEEP Session for this session.
     **/
    private Session             session;
    
    /**
     *  When we were last used. This may be used to LRU close sessions.
     **/
    private long                lastUsed;
    
    /**
     *  The pool of channels we use for messengers
     **/
    private ChannelPool         channels;
    
    /**
     * Constructor for a session we are initiating.
     *
     * @param tpt the transport associated with this session.
     * @param dest the destination address of this session.
     * @throws IOException Thrown if the session cannot be created.
     */
    BeepSession( BeepTransport tpt, EndpointAddress dest ) throws IOException {
        this.tpt = tpt;
        this.dst = (EndpointAddress) ((Address) dest).clone();
        
        try {
            String tmp = dst.getProtocolAddress();
            int portIndex = tmp.indexOf(":");
            if (portIndex == -1) {
                if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Port missing!" );
                throw new IllegalArgumentException( "Port missing!" );
            }
            port = Integer.valueOf(tmp.substring(portIndex + 1)).intValue();
            host = InetAddress.getByName(tmp.substring(0, portIndex));
            
            if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug(" using: " + host.toString() + ":" + port );
        } catch (Exception e) {
            if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "construct failed", e );
            throw new UndeclaredThrowableException( e );
        }
        
        try {
            session =
            AutomatedTCPSessionCreator.initiate( host, port, tpt.reg );
        } catch (BEEPException e) {
            if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Error connecting to " + host + ":" + port + "\n\t" + e.getMessage(), e );
            throw new IOException( "Connection Refused by " + host + ":" + port );
        }
        
        constructorCommon();
    }
    
    /**
     *  Constructor for a session we are accepting.
     *
     *  @param  tpt the transport associated with this session.
     *  @param  session the incoming session.
     *
     **/
    BeepSession( BeepTransport tpt, Session session ) {
        this.tpt = tpt;
        this.session = session;
        
        dst = new Address();
        dst.setProtocolName( tpt.getProtocolName() );
        
        if( session instanceof TCPSession ) {
            Socket socket = ((TCPSession) session).getSocket();
            
            host = socket.getInetAddress();
            port = socket.getPort();
            
            dst.setProtocolAddress( host.getHostAddress() + ":" + Integer.toString(port) );
        }
        
        constructorCommon();
    }
    
    /**
     *  Common stuff used by constructors. Also needed if we decide to
     *  support reactivating sessions.
     **/
    private void constructorCommon() {
        updateLastUsed();
        
        channels = new ChannelPool( session, CHANNEL_IDLE_TTL );
        
        session.registerForEvent( this, SessionEvent.SESSION_CLOSED_EVENT_CODE );
        session.registerForEvent( this, SessionEvent.SESSION_TERMINATED_EVENT_CODE );
    }
    
    /**
     *  Update the time of last use for this session.
     **/
    void updateLastUsed( ) {
        lastUsed = System.currentTimeMillis();
    }
    
    /**
     *  Return the time of last use for this session.
     *
     *  @return long the time this session was last used.
     **/
    long getLastUsed( ) {
        return lastUsed;
    }
    
    /**
     *  Returns true if the session is still active.
     *
     *  @return boolean true if the session is active otherwise false.
     **/
    boolean isActive() {
        int state;
        
        if( null == session )
            state = Session.SESSION_STATE_CLOSED;
        else
            state = session.getState();
        
        return (state == Session.SESSION_STATE_ACTIVE);
    }
    
    /**
     *  Return the destination endpoint addresss associated with this session.
     *
     *  @return EndpointAddress the destination address of this session.
     **/
    EndpointAddress getDestEndpoint() {
        return (EndpointAddress) ((Address) dst).clone();
    }
    
    /**
     *  Return the source endpoint addresss associated with this session.
     *
     *  @return EndpointAddress the destination address of this session.
     **/
    EndpointAddress getSrcEndpoint() {
        return tpt.getPublicAddress();
    }
    
    /**
     *  Get a channel for sending messages on.
     *
     *  @return Channel a channel for messages.
     **/
    Channel getNewChannel() {
        Channel channel;
        
        updateLastUsed( );
        
        try {
            channel = channels.getSharedChannel( JxtaBeepProfile.JXTA_URI );
        } catch( BEEPException caught ) {
            throw new RuntimeException( "BEEPException - no docs, didnt know what to do" );
        }
        
        return channel;
    }
    
    /**
     *  Release a channel once its no longer neeeded
     *
     *  @param channel channel being given up.
     **/
    void releaseChannel( Channel channel ) {
        
        SharedChannel mine = (SharedChannel) channel;
        
        mine.release();
    }
    
    /**
     *  Close down the session.
     **/
    void close() {
        // Cleanup
        
        channels = null;
        
        // Close the Session
        try {
            session.close();
        } catch (BEEPException e) {
            if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Error closing session (" + e.getMessage() + ")");
            return;
        }
        
        session = null;
    }
    
    /**
     *  Event Listener for BEEP Session Events.
     * @param sessionEvent The session event we have just been sent.
     */
    public void receiveEvent( SessionEvent sessionEvent) {
        int event = sessionEvent.getEvent();
        
        switch( event ) {
            case SessionEvent.GREETING_SENT_EVENT_CODE :
                if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Session : " + session.toString() + " GREETING_SENT_EVENT_CODE" );
                break;
                
            case SessionEvent.GREETING_RECEIVED_EVENT_CODE :
                if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Session : " + session.toString() + " GREETING_RECEIVED_EVENT_CODE" );
                break;
                
            case SessionEvent.CHANNEL_OPENED_EVENT_CODE :
                if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Session : " + session.toString() + " CHANNEL_OPENED_EVENT_CODE" );
                break;
                
            case SessionEvent.CHANNEL_CLOSED_EVENT_CODE :
                if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Session : " + session.toString() + " CHANNEL_CLOSED_EVENT_CODE" );
                break;
                
            case SessionEvent.SESSION_CLOSED_EVENT_CODE :
                // we have to make sure we are not being called on a session we already closed
                if( session != null )  {
                    if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Session : " + session.toString() + " SESSION_CLOSED_EVENT_CODE" );
                    synchronized( tpt.activeSessions ) {
                        for( Iterator eachSession = tpt.activeSessions.values().iterator();
                        eachSession.hasNext(); ) {
                            if( this == eachSession.next() ) {
                                eachSession.remove( );
                                break;
                            }
                        }
                    }
                    session = null;
                    channels = null;
                }
                break;
                
            case SessionEvent.SESSION_TERMINATED_EVENT_CODE :
                // we have to make sure we are not being called on a session we already closed
                if( session != null )  {
                    if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Session : " + session.toString() + " SESSION_TERMINATED_EVENT_CODE" );
                    synchronized( tpt.activeSessions ) {
                        for( Iterator eachSession = tpt.activeSessions.values().iterator();
                        eachSession.hasNext(); ) {
                            if( this == eachSession.next() ) {
                                eachSession.remove( );
                                break;
                            }
                        }
                    }
                    session = null;
                    channels = null;
                }
                break;
                
            case SessionEvent.UNKNOWN_EVENT_CODE :
                if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Session : " + session.toString() + " UNKNOWN_EVENT_CODE" );
                break;
                
            default :
                if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Session : " + session.toString() + "UNKNOWN EVENT CODE - " + event );
                break;
        }
        
    }
    
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -