directory-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From nik...@apache.org
Subject svn commit: r448325 - in /directory/trunks/mina/example: ./ src/main/java/org/apache/mina/example/chat/ src/main/java/org/apache/mina/example/chat/client/
Date Wed, 20 Sep 2006 20:19:20 GMT
Author: niklas
Date: Wed Sep 20 13:19:20 2006
New Revision: 448325

URL: http://svn.apache.org/viewvc?view=rev&rev=448325
Log:
Initial check in of chat server and client example contributed by Pablo Pita Leira (DIRMINA-227).

Added:
    directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/
    directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/ChatCommand.java
  (with props)
    directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/ChatProtocolHandler.java
  (with props)
    directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/Main.java   (with
props)
    directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/SpringMain.java
  (with props)
    directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/
    directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/ChatClientSupport.java
  (with props)
    directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/SwingChatClient.java
  (with props)
    directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/SwingChatClientHandler.java
  (with props)
    directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/package.html
    directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/package.html
    directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/serverContext.xml
  (with props)
Modified:
    directory/trunks/mina/example/pom.xml

Modified: directory/trunks/mina/example/pom.xml
URL: http://svn.apache.org/viewvc/directory/trunks/mina/example/pom.xml?view=diff&rev=448325&r1=448324&r2=448325
==============================================================================
--- directory/trunks/mina/example/pom.xml (original)
+++ directory/trunks/mina/example/pom.xml Wed Sep 20 13:19:20 2006
@@ -17,12 +17,24 @@
     </dependency>
 
     <dependency>
+      <groupId>org.apache.mina</groupId>
+      <artifactId>mina-integration-spring</artifactId>
+      <version>${pom.version}</version>
+    </dependency>
+    
+    <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>nlog4j</artifactId>
       <version>1.2.25</version>
       <scope>provided</scope>
     </dependency>
 
+    <dependency>
+      <groupId>org.springframework</groupId>
+      <artifactId>spring-context</artifactId>
+      <version>1.2.8</version>
+    </dependency>
+        
     <dependency>
       <groupId>commons-net</groupId>
       <artifactId>commons-net</artifactId>

Added: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/ChatCommand.java
URL: http://svn.apache.org/viewvc/directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/ChatCommand.java?view=auto&rev=448325
==============================================================================
--- directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/ChatCommand.java
(added)
+++ directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/ChatCommand.java
Wed Sep 20 13:19:20 2006
@@ -0,0 +1,67 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.mina.example.chat;
+
+/**
+ * Encapsulates a chat command. Use {@link #valueOf(String)} to create an
+ * instance given a command string.
+ * 
+ * @author The Apache Directory Project (mina-dev@directory.apache.org)
+ * @version $Rev$, $Date$
+ */
+public class ChatCommand
+{
+    public static final int LOGIN = 0;
+
+    public static final int QUIT = 1;
+
+    public static final int BROADCAST = 2;
+
+    private final int num;
+
+    private ChatCommand( int num )
+    {
+        this.num = num;
+    }
+
+    public int toInt()
+    {
+        return num;
+    }
+
+    public static ChatCommand valueOf( String s )
+    {
+        s = s.toUpperCase();
+        if( "LOGIN".equals( s ) )
+        {
+            return new ChatCommand( LOGIN );
+        }
+        if( "QUIT".equals( s ) )
+        {
+            return new ChatCommand( QUIT );
+        }
+        if( "BROADCAST".equals( s ) )
+        {
+            return new ChatCommand( BROADCAST );
+        }
+
+        throw new IllegalArgumentException( "Unrecognized command: " + s );
+    }
+}

Propchange: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/ChatCommand.java
------------------------------------------------------------------------------
    svn:keywords = Id

Added: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/ChatProtocolHandler.java
URL: http://svn.apache.org/viewvc/directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/ChatProtocolHandler.java?view=auto&rev=448325
==============================================================================
--- directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/ChatProtocolHandler.java
(added)
+++ directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/ChatProtocolHandler.java
Wed Sep 20 13:19:20 2006
@@ -0,0 +1,151 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.mina.example.chat;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.apache.mina.common.IoHandler;
+import org.apache.mina.common.IoHandlerAdapter;
+import org.apache.mina.common.IoSession;
+import org.apache.mina.util.SessionLog;
+
+/**
+ * {@link IoHandler} implementation of a simple chat server protocol.
+ * 
+ * @author The Apache Directory Project (mina-dev@directory.apache.org)
+ * @version $Rev$, $Date$
+ */
+public class ChatProtocolHandler extends IoHandlerAdapter
+{
+    private Set sessions = Collections.synchronizedSet( new HashSet() );
+    private Set users = Collections.synchronizedSet( new HashSet() );
+
+	public void exceptionCaught( IoSession session, Throwable cause )
+    {
+        SessionLog.error( session, "", cause );
+        // Close connection when unexpected exception is caught.
+        session.close();
+    }
+
+	public void messageReceived( IoSession session, Object message )
+    {
+        String theMessage = ( String ) message;
+        String[] result = theMessage.split( " ", 2 );
+        String theCommand = result[ 0 ];
+
+        try
+        {
+
+            ChatCommand command = ChatCommand.valueOf( theCommand );
+            String user = ( String ) session.getAttribute( "user" );
+
+            switch( command.toInt() )
+            {
+
+            case ChatCommand.QUIT:
+                session.write( "QUIT OK" );
+                session.close();
+                break;
+            case ChatCommand.LOGIN:
+
+                if( user != null )
+                {
+                    session.write( "LOGIN ERROR user " + user
+                            + " already logged in." );
+                    return;
+                }
+
+                if( result.length == 2 )
+                {
+                    user = result[ 1 ];
+                }
+                else
+                {
+                    session.write( "LOGIN ERROR invalid login command." );
+                    return;
+                }
+
+                // check if the username is already used
+                if( users.contains( user ) )
+                {
+                    session.write( "LOGIN ERROR the name " + user + " is already used." );
+                    return;
+                }
+
+                sessions.add( session );
+                session.setAttribute( "user", user );
+
+                // Allow all users
+                users.add( user );
+                session.write( "LOGIN OK" );
+                broadcast( "The user " + user + " has joined the chat session." );
+                break;
+
+            case ChatCommand.BROADCAST:
+
+                if( result.length == 2 )
+                {
+                    broadcast( user + ": " + result[ 1 ] );
+                }
+                break;
+            default:
+                SessionLog.info( session, "Unhandled command: " + command );
+                break;
+            }
+
+        }
+        catch( IllegalArgumentException e )
+        {
+            SessionLog.debug( session, e.getMessage() );
+        }
+    }
+
+    public void broadcast(String message)
+    {
+        synchronized( sessions )
+        {
+            Iterator iter = sessions.iterator();
+            while( iter.hasNext() )
+            {
+                IoSession s = ( IoSession ) iter.next();
+                if( s.isConnected() )
+                {
+                    s.write( "BROADCAST OK " + message );
+                }
+            }
+        }
+	}
+
+	public void sessionClosed( IoSession session ) throws Exception
+    {
+        String user = ( String ) session.getAttribute( "user" );
+        users.remove( user );
+        sessions.remove( session );
+        broadcast( "The user " + user + " has left the chat session." );
+    }
+
+	public boolean isChatUser( String name )
+    {
+        return users.contains( name );
+    }
+}

Propchange: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/ChatProtocolHandler.java
------------------------------------------------------------------------------
    svn:keywords = Id

Added: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/Main.java
URL: http://svn.apache.org/viewvc/directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/Main.java?view=auto&rev=448325
==============================================================================
--- directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/Main.java (added)
+++ directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/Main.java Wed
Sep 20 13:19:20 2006
@@ -0,0 +1,68 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.mina.example.chat;
+
+import java.net.InetSocketAddress;
+
+import org.apache.mina.common.DefaultIoFilterChainBuilder;
+import org.apache.mina.common.IoAcceptor;
+import org.apache.mina.common.IoAcceptorConfig;
+import org.apache.mina.filter.LoggingFilter;
+import org.apache.mina.filter.codec.ProtocolCodecFilter;
+import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
+import org.apache.mina.transport.socket.nio.SocketAcceptor;
+import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;
+
+/**
+ * (<b>Entry point</b>) Chat server
+ * 
+ * @author The Apache Directory Project (mina-dev@directory.apache.org)
+ * @version $Rev$, $Date$
+ */
+public class Main
+{
+    /** Choose your favorite port number. */
+    private static final int PORT = 1234;
+    
+    public static void main( String[] args ) throws Exception
+    {
+        IoAcceptor acceptor = new SocketAcceptor();
+        IoAcceptorConfig config = new SocketAcceptorConfig();
+        DefaultIoFilterChainBuilder chain = config.getFilterChain();
+        
+        chain.addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory() ) );
+        
+        addLogger( chain );
+        
+        // Bind
+        acceptor.bind(
+                new InetSocketAddress( PORT ),
+                new ChatProtocolHandler(),
+                config );
+
+        System.out.println( "Listening on port " + PORT );
+    }
+    
+    private static void addLogger( DefaultIoFilterChainBuilder chain ) throws Exception
+    {
+        chain.addLast( "logger", new LoggingFilter() );
+        System.out.println( "Logging ON" );
+    }
+}

Propchange: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/Main.java
------------------------------------------------------------------------------
    svn:keywords = Id

Added: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/SpringMain.java
URL: http://svn.apache.org/viewvc/directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/SpringMain.java?view=auto&rev=448325
==============================================================================
--- directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/SpringMain.java
(added)
+++ directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/SpringMain.java
Wed Sep 20 13:19:20 2006
@@ -0,0 +1,45 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.mina.example.chat;
+
+import org.springframework.context.support.ClassPathXmlApplicationContext;
+
+/**
+ * (<b>Entry point</b>) Chat server which uses Spring and the serverContext.xml
+ * file to set up MINA and the server handler.
+ * 
+ * @author The Apache Directory Project (mina-dev@directory.apache.org)
+ * @version $Rev$, $Date$
+ */
+public class SpringMain
+{
+
+    public static void main( String[] args ) throws Exception
+    {
+        new ClassPathXmlApplicationContext( getApplicationContext() );
+        System.out.println( "Listening ..." );
+    }
+
+    public static String getApplicationContext()
+    {
+        return "org/apache/mina/example/chat/serverContext.xml";
+    }
+
+}

Propchange: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/SpringMain.java
------------------------------------------------------------------------------
    svn:keywords = Id

Added: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/ChatClientSupport.java
URL: http://svn.apache.org/viewvc/directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/ChatClientSupport.java?view=auto&rev=448325
==============================================================================
--- directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/ChatClientSupport.java
(added)
+++ directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/ChatClientSupport.java
Wed Sep 20 13:19:20 2006
@@ -0,0 +1,89 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.mina.example.chat.client;
+
+import java.io.IOException;
+import java.net.SocketAddress;
+
+import org.apache.mina.common.ConnectFuture;
+import org.apache.mina.common.IoHandler;
+import org.apache.mina.common.IoSession;
+import org.apache.mina.transport.socket.nio.SocketConnector;
+
+/**
+ * A simple chat client for a given user.
+ * 
+ * @author The Apache Directory Project (mina-dev@directory.apache.org)
+ * @version $Rev$, $Date$
+ */
+public class ChatClientSupport
+{
+    private final IoHandler handler;
+    private final String name;
+    private IoSession session;
+
+    public ChatClientSupport( String name, IoHandler handler )
+    {
+        if( name == null )
+        {
+            throw new IllegalArgumentException( "Name can not be null" );
+        }
+        this.name = name;
+        this.handler = handler;
+    }
+
+    public void connect( SocketConnector connector, SocketAddress address )
+            throws IOException
+    {
+        if( session != null && session.isConnected() )
+        {
+            throw new IllegalStateException( "Already connected. Disconnect first." );
+        }
+        
+        ConnectFuture future1 = connector.connect( address, handler );
+        future1.join();
+        session = future1.getSession();
+    }
+
+    public void login()
+    {
+        session.write( "LOGIN " + name );
+    }
+
+    public void broadcast( String message )
+    {
+        session.write( "BROADCAST " + message );
+    }
+
+    public void quit()
+    {
+        if( session != null )
+        {
+            if( session.isConnected() )
+            {
+                session.write( "QUIT" );
+                // Wait until the chat ends.
+                session.getCloseFuture().join();
+            }
+            session.close();
+        }
+    }
+
+}

Propchange: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/ChatClientSupport.java
------------------------------------------------------------------------------
    svn:keywords = Id

Added: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/SwingChatClient.java
URL: http://svn.apache.org/viewvc/directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/SwingChatClient.java?view=auto&rev=448325
==============================================================================
--- directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/SwingChatClient.java
(added)
+++ directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/SwingChatClient.java
Wed Sep 20 13:19:20 2006
@@ -0,0 +1,309 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.mina.example.chat.client;
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+
+import javax.swing.AbstractAction;
+import javax.swing.BorderFactory;
+import javax.swing.Box;
+import javax.swing.BoxLayout;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollBar;
+import javax.swing.JTextArea;
+import javax.swing.JTextField;
+import javax.swing.border.EmptyBorder;
+
+import org.apache.mina.example.chat.client.SwingChatClientHandler.Callback;
+import org.apache.mina.transport.socket.nio.SocketConnector;
+
+/**
+ * Simple chat client based on Swing & MINA that implements the chat protocol.
+ *  
+ * @author The Apache Directory Project (mina-dev@directory.apache.org)
+ * @version $Rev$, $Date$
+ */
+public class SwingChatClient extends JFrame implements Callback
+{
+	private JTextField inputText;
+	private JButton loginButton;
+	private JButton quitButton;
+	private JButton closeButton;
+	private JTextField serverField;
+	private JTextField nameField;
+	private JTextArea area;
+	private JScrollBar scroll;
+
+	private ChatClientSupport client;
+	private SwingChatClientHandler handler;
+    private SocketConnector connector;
+
+	public SwingChatClient()
+    {
+        super( "Chat Client based on Apache MINA" );
+        
+        connector = new SocketConnector();
+        
+        loginButton = new JButton( new LoginAction() );
+        loginButton.setText( "Connect" );
+        quitButton = new JButton( new LogoutAction() );
+        quitButton.setText( "Disconnect" );
+        closeButton = new JButton( new QuitAction() );
+        closeButton.setText( "Quit" );
+        inputText = new JTextField( 30 );
+        inputText.setAction( new BroadcastAction() );
+        area = new JTextArea( 10, 50 );
+        area.setLineWrap( true );
+        area.setEditable( false );
+        scroll = new JScrollBar();
+        scroll.add( area );
+        nameField = new JTextField( 10 );
+        nameField.setEditable( false );
+        serverField = new JTextField( 10 );
+        serverField.setEditable( false );
+
+        JPanel h = new JPanel();
+        h.setLayout( new BoxLayout( h, BoxLayout.LINE_AXIS ) );
+        h.setBorder( BorderFactory.createEmptyBorder( 10, 10, 10, 10 ) );
+        JLabel nameLabel = new JLabel( "Name: " );
+        JLabel serverLabel = new JLabel( "Server: " );
+        h.add( nameLabel );
+        h.add( Box.createRigidArea( new Dimension( 10, 0 ) ) );
+        h.add( nameField );
+        h.add( Box.createRigidArea( new Dimension( 10, 0 ) ) );
+        h.add( Box.createHorizontalGlue() );
+        h.add( Box.createRigidArea( new Dimension( 10, 0 ) ) );
+        h.add( serverLabel );
+        h.add( Box.createRigidArea( new Dimension( 10, 0 ) ) );
+        h.add( serverField );
+
+        JPanel p = new JPanel();
+        p.setLayout( new BoxLayout( p, BoxLayout.LINE_AXIS ) );
+        p.setBorder( new EmptyBorder( 10, 10, 10, 10 ) );
+
+        JPanel left = new JPanel();
+        left.setLayout( new BoxLayout( left, BoxLayout.PAGE_AXIS ) );
+        left.add( area );
+        left.add( Box.createRigidArea( new Dimension( 0, 5 ) ) );
+        left.add( Box.createHorizontalGlue() );
+        left.add( inputText );
+
+        JPanel right = new JPanel();
+        right.setLayout( new BoxLayout( right, BoxLayout.PAGE_AXIS ) );
+        right.add( loginButton );
+        right.add( Box.createRigidArea( new Dimension( 0, 5 ) ) );
+        right.add( quitButton );
+        right.add( Box.createHorizontalGlue() );
+        right.add( Box.createRigidArea( new Dimension( 0, 25 ) ) );
+        right.add( closeButton );
+
+        p.add( left );
+        p.add( Box.createRigidArea( new Dimension( 10, 0 ) ) );
+        p.add( right );
+
+        getContentPane().add( h, BorderLayout.NORTH );
+        getContentPane().add( p );
+
+        closeButton.addActionListener( new ActionListener()
+        {
+            public void actionPerformed( ActionEvent e )
+            {
+                dispose();
+            }
+        } );
+        setLoggedOut();
+        setDefaultCloseOperation( EXIT_ON_CLOSE );
+    }
+	
+	public class LoginAction extends AbstractAction
+    {
+        public void actionPerformed( ActionEvent e )
+        {
+
+            String value = JOptionPane.showInputDialog( SwingChatClient.this,
+                    "Specify server address (default: localhost:1234)" ); // "localhost";
+            if( value == null || value.length() == 0 )
+            {
+                value = "localhost:1234";
+            }
+            SocketAddress address = parseSocketAddress( value );
+            String name = JOptionPane.showInputDialog( SwingChatClient.this,
+                            "Specify name for chat session with no spaces (default: userN)"
);
+            if( name == null || name.length() == 0 )
+            {
+                name = "user" + Math.round( Math.random() * 10 );
+            }
+            name = name.trim();
+            handler = new SwingChatClientHandler( SwingChatClient.this );
+            client = new ChatClientSupport( name, handler );
+            nameField.setText( name );
+            serverField.setText( value );
+            try
+            {
+                client.connect( connector, address );
+                area.setText( "" );
+            }
+            catch( Exception ex )
+            {
+                JOptionPane.showMessageDialog( SwingChatClient.this,
+                        "Could not connect to " + value + ". " );
+            }
+        }
+    }
+    
+	private class LogoutAction extends AbstractAction
+    {
+        public void actionPerformed( ActionEvent e )
+        {
+            try
+            {
+                client.quit();
+                setLoggedOut();
+            }
+            catch( Exception e1 )
+            {
+                JOptionPane.showMessageDialog( SwingChatClient.this,
+                        "Session could not be closed." );
+            }
+        }
+    }
+	
+	private class BroadcastAction extends AbstractAction
+    {
+        public void actionPerformed( ActionEvent e )
+        {
+            client.broadcast( inputText.getText() );
+            inputText.setText( "" );
+        }
+    }
+	
+	private class QuitAction extends AbstractAction
+    {
+        public void actionPerformed( ActionEvent e )
+        {
+            if( client != null )
+            {
+                client.quit();
+            }
+            SwingChatClient.this.dispose();
+        }
+    }
+	
+    private void setLoggedOut()
+    {
+        inputText.setEnabled( false );
+        quitButton.setEnabled( false );
+        loginButton.setEnabled( true );
+    }
+
+    private void setLoggedIn()
+    {
+        inputText.setEnabled( true );
+        quitButton.setEnabled( true );
+        loginButton.setEnabled( false );
+    }
+
+    private void append( String text )
+    {
+        area.append( text );
+    }
+
+	private void notifyError( String message )
+    {
+        JOptionPane.showMessageDialog( this, message );
+    }
+
+	private SocketAddress parseSocketAddress( String s )
+    {
+        s = s.trim();
+        int colonIndex = s.indexOf( ":" );
+        if( colonIndex > 0 )
+        {
+            String host = s.substring( 0, colonIndex );
+            int port = parsePort( s.substring( colonIndex + 1 ) );
+            return new InetSocketAddress( host, port );
+        }
+        else
+        {
+            int port = parsePort( s.substring( colonIndex + 1 ) );
+            return new InetSocketAddress( port );
+        }
+    }
+
+	private int parsePort( String s )
+    {
+        try
+        {
+            return Integer.parseInt( s );
+        }
+        catch( NumberFormatException nfe )
+        {
+            throw new IllegalArgumentException( "Illegal port number: " + s );
+        }
+    }    
+	
+	public void connected()
+    {
+        client.login();
+    }
+
+    public void disconnected()
+    {
+        setLoggedOut();
+    }
+
+    public void error( String message )
+    {
+        notifyError( message + "\n" );
+    }
+
+    public void loggedIn()
+    {
+        setLoggedIn();
+        append( "You have joined the chat session.\n" );
+    }
+
+    public void loggedOut()
+    {
+        append( "You have left the chat session.\n" );
+        setLoggedOut();
+    }
+
+    public void messageReceived( String message )
+    {
+        append( message + "\n" );
+    }
+
+    public static void main( String[] args )
+    {
+        SwingChatClient client = new SwingChatClient();
+        client.pack();
+        client.setVisible( true );
+    }
+}

Propchange: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/SwingChatClient.java
------------------------------------------------------------------------------
    svn:keywords = Id

Added: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/SwingChatClientHandler.java
URL: http://svn.apache.org/viewvc/directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/SwingChatClientHandler.java?view=auto&rev=448325
==============================================================================
--- directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/SwingChatClientHandler.java
(added)
+++ directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/SwingChatClientHandler.java
Wed Sep 20 13:19:20 2006
@@ -0,0 +1,117 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.mina.example.chat.client;
+
+import org.apache.mina.common.IoFilter;
+import org.apache.mina.common.IoHandler;
+import org.apache.mina.common.IoHandlerAdapter;
+import org.apache.mina.common.IoSession;
+import org.apache.mina.example.chat.ChatCommand;
+import org.apache.mina.filter.LoggingFilter;
+import org.apache.mina.filter.codec.ProtocolCodecFilter;
+import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
+
+/**
+ * {@link IoHandler} implementation of the client side of the simple chat protocol.
+ * 
+ * @author The Apache Directory Project (mina-dev@directory.apache.org)
+ * @version $Rev$, $Date$
+ */
+public class SwingChatClientHandler extends IoHandlerAdapter
+{
+    
+    public interface Callback
+    {
+        void connected();
+        void loggedIn();
+        void loggedOut();
+        void disconnected();
+        void messageReceived( String message );
+        void error( String message );
+    }
+    
+    private static IoFilter LOGGING_FILTER = new LoggingFilter();
+    private static IoFilter CODEC_FILTER = new ProtocolCodecFilter(
+            new TextLineCodecFactory() );
+
+    private final Callback callback;
+
+    public SwingChatClientHandler( Callback callback )
+    {
+        this.callback = callback;
+    }
+
+    public void sessionCreated( IoSession session ) throws Exception
+    {
+        session.getFilterChain().addLast( "codec", CODEC_FILTER );
+        session.getFilterChain().addLast( "logger", LOGGING_FILTER );
+    }
+
+    public void sessionOpened( IoSession session ) throws Exception
+    {
+        callback.connected();
+    }
+
+    public void messageReceived( IoSession session, Object message )
+            throws Exception
+    {
+        String theMessage = ( String ) message;
+        String[] result = theMessage.split( " ", 3 );
+        String status = result[ 1 ];
+        String theCommand = result[ 0 ];
+        ChatCommand command = ChatCommand.valueOf( theCommand );
+
+        if( "OK".equals( status ) )
+        {
+
+            switch( command.toInt() )
+            {
+
+            case ChatCommand.BROADCAST:
+                if( result.length == 3 )
+                {
+                    callback.messageReceived( result[ 2 ] );
+                }
+                break;
+            case ChatCommand.LOGIN:
+                callback.loggedIn();
+                break;
+
+            case ChatCommand.QUIT:
+                callback.loggedOut();
+                break;
+            }
+
+        }
+        else
+        {
+            if( result.length == 3 )
+            {
+                callback.error( result[ 2 ] );
+            }
+        }
+    }
+
+    public void sessionClosed( IoSession session ) throws Exception
+    {
+        callback.disconnected();
+    }
+
+}

Propchange: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/SwingChatClientHandler.java
------------------------------------------------------------------------------
    svn:keywords = Id

Added: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/package.html
URL: http://svn.apache.org/viewvc/directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/package.html?view=auto&rev=448325
==============================================================================
--- directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/package.html
(added)
+++ directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/client/package.html
Wed Sep 20 13:19:20 2006
@@ -0,0 +1,8 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+</head>
+<body>
+Swing based chat client.
+</body>
+</html>

Added: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/package.html
URL: http://svn.apache.org/viewvc/directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/package.html?view=auto&rev=448325
==============================================================================
--- directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/package.html
(added)
+++ directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/package.html
Wed Sep 20 13:19:20 2006
@@ -0,0 +1,8 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+</head>
+<body>
+Chat server which demonstates using the text line codec and Spring integration.
+</body>
+</html>

Added: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/serverContext.xml
URL: http://svn.apache.org/viewvc/directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/serverContext.xml?view=auto&rev=448325
==============================================================================
--- directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/serverContext.xml
(added)
+++ directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/serverContext.xml
Wed Sep 20 13:19:20 2006
@@ -0,0 +1,76 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
+<beans>
+
+<!-- 
+        Classic Spring approach : define each bean, then do the call to bind in code
+
+        <bean id="acceptor" class="org.apache.mina.transport.socket.nio.SocketAcceptor"
/>
+        <bean id="address" class="java.net.InetSocketAddress">
+            <constructor-arg>
+                <value>1234</value>
+            </constructor-arg>
+        </bean>
+         <bean id="chatHandler" class="server.ChatProtocolHandler" />
+--> 
+
+   <!-- MINA IoAcceptorFactoryBean approach -->
+   <!-- This makes it possible to specify java.net.SocketAddress values 
+        (e.g. :1234 below) as Strings.
+        They will be converted into java.net.InetSocketAddress objects by Spring.  -->
+   <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
+     <property name="customEditors">
+       <map>
+         <entry key="java.net.SocketAddress">
+           <bean class="org.apache.mina.integration.spring.InetSocketAddressEditor"/>
+         </entry>
+       </map>
+     </property>
+   </bean>
+ 
+   <!-- The IoHandler implementation -->
+   <bean id="chatHandler" class="org.apache.mina.example.chat.ChatProtocolHandler" />
+     
+   <bean id="filterChainBuilder" 
+         class="org.apache.mina.integration.spring.DefaultIoFilterChainBuilderFactoryBean">
+     <property name="filters">
+       <list>
+
+         <!-- Thread pool where threads will be named IoWorker-1, IoWorker-2, etc -->
+		 <!--
+         <bean class="org.apache.mina.filter.ThreadPoolFilter">
+           <constructor-arg value="IoWorker"/>
+           <property name="maximumPoolSize" value="10"/>
+         </bean>
+         -->
+         <bean class="org.apache.mina.filter.codec.ProtocolCodecFilter" >
+          <constructor-arg>
+           	<bean class="org.apache.mina.filter.codec.textline.TextLineCodecFactory" />
+           </constructor-arg>
+         </bean>
+         <bean class="org.apache.mina.filter.LoggingFilter"/>
+       </list>
+     </property>
+   </bean>
+
+   <bean id="ioAcceptor" class="org.apache.mina.integration.spring.IoAcceptorFactoryBean">
+     <property name="target">
+       <bean class="org.apache.mina.transport.socket.nio.SocketAcceptor"/>
+     </property>
+     <property name="bindings">
+       <list>
+         <bean class="org.apache.mina.integration.spring.Binding">
+           <property name="address" value=":1234"/>
+           <property name="handler" ref="chatHandler"/>
+           <property name="serviceConfig">
+             <bean class="org.apache.mina.transport.socket.nio.SocketAcceptorConfig">
+               <property name="filterChainBuilder" ref="filterChainBuilder"/>
+               <property name="reuseAddress" value="true"/>
+             </bean>
+           </property>
+         </bean>
+       </list>
+     </property>
+   </bean>
+        
+</beans>
\ No newline at end of file

Propchange: directory/trunks/mina/example/src/main/java/org/apache/mina/example/chat/serverContext.xml
------------------------------------------------------------------------------
    svn:keywords = Id



Mime
View raw message