You are viewing a plain text version of this content. The canonical link for it is here.
Posted to scm@geronimo.apache.org by jg...@apache.org on 2006/10/27 03:45:31 UTC

svn commit: r468226 - in /geronimo/sandbox/gcache/server/src: main/java/org/apache/geronimo/gcache/command/ main/java/org/apache/geronimo/gcache/marshal/ main/java/org/apache/geronimo/gcache/transports/tcp/ main/java/org/apache/geronimo/gcache/util/ te...

Author: jgenender
Date: Thu Oct 26 18:45:30 2006
New Revision: 468226

URL: http://svn.apache.org/viewvc?view=rev&rev=468226
Log:
Auth code

Added:
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/AuthCommand.java   (with props)
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/HandShakeCommand.java   (with props)
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/PublicKeyCommand.java   (with props)
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPAuthenticationFilter.java   (with props)
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/util/CipherUtil.java   (with props)
    geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/command/AuthCommandTest.java   (with props)
    geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/util/
    geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/util/CipherUtilTest.java   (with props)
Modified:
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/BaseCommand.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/BulkSendCommand.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/CacheBaseCommand.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/CachePayloadBaseCommand.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/Command.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/CommandTypes.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/DiscoveryCommand.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/MessageAckCommand.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/PutSessionCommand.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/marshal/MarshalAware.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/Constants.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCacheNotifier.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCommandRequestDecoder.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCommandRequestEncoder.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCommandVisitor.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPMessageAckCommandFilter.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPSocketHandler.java
    geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPSocketTransportService.java
    geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/tcp/AbstractService.java
    geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/tcp/TCPEndpointTest.java

Added: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/AuthCommand.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/AuthCommand.java?view=auto&rev=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/AuthCommand.java (added)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/AuthCommand.java Thu Oct 26 18:45:30 2006
@@ -0,0 +1,110 @@
+/**
+ *
+ * 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.geronimo.gcache.command;
+
+import java.io.IOException;
+import java.security.PublicKey;
+
+import org.apache.geronimo.gcache.util.CipherUtil;
+import org.apache.mina.common.ByteBuffer;
+
+public class AuthCommand extends BaseCommand {
+    
+    private String userId;
+    private String password;
+    
+    private PublicKey publicKey;
+    
+    
+    @Override
+    public byte getCommandType() throws IOException {
+	return CommandTypes.AUTH_COMMAND;
+    }
+
+    public PublicKey getPublicKey() {
+        return publicKey;
+    }
+
+    public void setPublicKey(PublicKey publicKey) {
+        this.publicKey = publicKey;
+    }
+
+    public String getPassword() {
+        return password;
+    }
+
+    public void setPassword(String password) {
+        this.password = password;
+    }
+
+    public String getUserId() {
+        return userId;
+    }
+
+    public void setUserId(String userId) {
+        this.userId = userId;
+    }
+
+    @Override
+    public void readExternal(ByteBuffer buffer) throws Exception {
+	super.readExternal(buffer);
+	
+	int len = buffer.getInt();
+	if (len == -1){
+	    userId = null;
+	} else {
+	    byte decrypted[] = new byte[len];
+	    buffer.get(decrypted);
+	    userId = CipherUtil.RSADecrypt(decrypted);
+	}
+	
+	len = buffer.getInt();
+	if (len == -1){
+	    password = null;
+	} else {
+	    byte decrypted[] = new byte[len];
+	    buffer.get(decrypted);
+	    password = CipherUtil.RSADecrypt(decrypted);
+	}
+    }
+    
+    @Override
+    public void writeExternal(ByteBuffer buffer) throws Exception {
+	super.writeExternal(buffer);
+	
+	if (publicKey == null)
+	    throw new Exception("PublicKey not set on AuthCommand, cannot encrypt packet.");
+	
+	if (userId == null){
+	    buffer.putInt(-1);
+	} else {
+	    byte encrypted[] = CipherUtil.RSAEncrypt(userId, publicKey);
+	    buffer.putInt(encrypted.length);
+	    buffer.put(encrypted);
+	}
+	
+	if (password == null){
+	    buffer.putInt(-1);
+	} else {
+	    byte encrypted[] = CipherUtil.RSAEncrypt(password, publicKey);
+	    buffer.putInt(encrypted.length);
+	    buffer.put(encrypted);
+	}
+    }
+
+}

Propchange: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/AuthCommand.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/AuthCommand.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/AuthCommand.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/BaseCommand.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/BaseCommand.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/BaseCommand.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/BaseCommand.java Thu Oct 26 18:45:30 2006
@@ -100,14 +100,14 @@
      * This default implementation does nothing, subclasses will perform
      * whatever task this command is supposed to do.
      */
-    public void execute(CommandVisitor visitor) throws IOException {
+    public void execute(CommandVisitor visitor) throws Exception {
 	// nothing to do in the base
     }
 
     /**
      * @see org.apache.geronimo.gcache.marshal.MarshalAware.readExternal(ReadableByteChannel)
      */
-    public void readExternal(ByteBuffer buffer) throws IOException {
+    public void readExternal(ByteBuffer buffer) throws Exception {
 	// this is the root so no super impl, others should call super first
 	commandId = buffer.getLong();
     }
@@ -115,7 +115,7 @@
     /**
      * @see org.apache.geronimo.gcache.marshal.MarshalAware.writeExternal(WritableByteChannel)
      */
-    public void writeExternal(ByteBuffer buffer) throws IOException {
+    public void writeExternal(ByteBuffer buffer) throws Exception {
 	// this is the root so no super impl, others should call super first
 
 	if (commandId == 0) {
@@ -135,7 +135,7 @@
      * @return
      * @throws IOException
      */
-    public byte[] createPacket(boolean includeMagic) throws IOException {
+    public byte[] createPacket(boolean includeMagic) throws Exception {
 
 	ByteBuffer buffer = null;
 
@@ -187,7 +187,7 @@
 	}
     }
 
-    public byte[] marshal() throws IOException {
+    public byte[] marshal() throws Exception {
 	ByteBuffer buffer = null;
 	try {
 	    buffer = ByteBuffer.allocate(4096, true);

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/BulkSendCommand.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/BulkSendCommand.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/BulkSendCommand.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/BulkSendCommand.java Thu Oct 26 18:45:30 2006
@@ -45,18 +45,18 @@
     }
 
 
-    public void readExternal(ByteBuffer buffer) throws IOException{
+    public void readExternal(ByteBuffer buffer) throws Exception{
         super.readExternal(buffer);
 
         numberOfCommands = buffer.getInt();
     }
 
-    public void writeExternal(ByteBuffer buffer) throws IOException {
+    public void writeExternal(ByteBuffer buffer) throws Exception {
         super.writeExternal(buffer);
         buffer.putInt(numberOfCommands);
     }
 
-    public void execute(CommandVisitor visitor) throws IOException {
+    public void execute(CommandVisitor visitor) throws Exception {
 
         visitor.processBulkSend(this);
     }

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/CacheBaseCommand.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/CacheBaseCommand.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/CacheBaseCommand.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/CacheBaseCommand.java Thu Oct 26 18:45:30 2006
@@ -80,7 +80,7 @@
         return new ByteArray(key);
     }
 
-    public void readExternal(ByteBuffer buffer) throws IOException{
+    public void readExternal(ByteBuffer buffer) throws Exception{
         super.readExternal(buffer);
 
         //Process what we want read
@@ -89,7 +89,7 @@
         sessionId = readString(buffer);
     }
 
-    public void writeExternal(ByteBuffer buffer) throws IOException {
+    public void writeExternal(ByteBuffer buffer) throws Exception {
         super.writeExternal(buffer);
 
         //Process what we want to write

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/CachePayloadBaseCommand.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/CachePayloadBaseCommand.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/CachePayloadBaseCommand.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/CachePayloadBaseCommand.java Thu Oct 26 18:45:30 2006
@@ -29,14 +29,14 @@
     // this is the actual data that must be added to the distributed cache
     private byte[] payload = null;
 
-    public void readExternal(ByteBuffer buffer) throws IOException {
+    public void readExternal(ByteBuffer buffer) throws Exception {
 	super.readExternal(buffer);
 
 	// Process what we want to read
 	payload = readBytes(buffer);
     }
 
-    public void writeExternal(ByteBuffer buffer) throws IOException {
+    public void writeExternal(ByteBuffer buffer) throws Exception {
 	super.writeExternal(buffer);
 
 	// Process what we want to write

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/Command.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/Command.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/Command.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/Command.java Thu Oct 26 18:45:30 2006
@@ -32,5 +32,5 @@
 
     public byte getCommandType() throws IOException;
 
-    public void execute(CommandVisitor visitor) throws IOException;
+    public void execute(CommandVisitor visitor) throws Exception;
 }

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/CommandTypes.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/CommandTypes.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/CommandTypes.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/CommandTypes.java Thu Oct 26 18:45:30 2006
@@ -1,19 +1,31 @@
 package org.apache.geronimo.gcache.command;
 
 public class CommandTypes {
-    public static final byte PUT_ENTRY_COMMAND = 1;
-    public static final byte REMOVE_ENTRY_COMMAND = 2;
-    public static final byte CLEARCACHE_COMMAND = 3;
-    public static final byte MESSAGE_ACK_COMMAND = 4;
-    public static final byte BULK_SEND_COMMAND = 5;
-    public static final byte REMOVE_SESSION_COMMAND = 6;
-    public static final byte PUT_SESSION_COMMAND = 7;
-    public static final byte GET_CACHE_COMMAND = 8;
-    public static final byte DISCOVERY_COMMAND = 9;
+    public static final byte HAND_SHAKE_COMMAND = 1;
+    public static final byte AUTH_COMMAND = 2;
+    public static final byte PUBLIC_KEY_COMMAND = 3;
+    public static final byte PUT_ENTRY_COMMAND = 4;
+    public static final byte REMOVE_ENTRY_COMMAND = 5;
+    public static final byte CLEARCACHE_COMMAND = 6;
+    public static final byte MESSAGE_ACK_COMMAND = 7;
+    public static final byte BULK_SEND_COMMAND = 8;
+    public static final byte REMOVE_SESSION_COMMAND = 9;
+    public static final byte PUT_SESSION_COMMAND = 10;
+    public static final byte GET_CACHE_COMMAND = 11;
+    public static final byte DISCOVERY_COMMAND = 12;
 
     public static Command createCommand(int identifier) {
         Command command = null;
         switch (identifier) {
+            case(HAND_SHAKE_COMMAND):
+                command = new HandShakeCommand();
+                break;
+            case(AUTH_COMMAND):
+                command = new AuthCommand();
+                break;
+            case(PUBLIC_KEY_COMMAND):
+                command = new PublicKeyCommand();
+                break;
             case(PUT_ENTRY_COMMAND):
                 command = new PutEntryCommand();
                 break;

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/DiscoveryCommand.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/DiscoveryCommand.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/DiscoveryCommand.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/DiscoveryCommand.java Thu Oct 26 18:45:30 2006
@@ -43,14 +43,14 @@
     }
 
     @Override
-    public void readExternal(ByteBuffer buffer) throws IOException {
+    public void readExternal(ByteBuffer buffer) throws Exception {
 	super.readExternal(buffer);
         nodeName = readString(buffer);
         service = readString(buffer);
     }
 
     @Override
-    public void writeExternal(ByteBuffer buffer) throws IOException {
+    public void writeExternal(ByteBuffer buffer) throws Exception {
 	super.writeExternal(buffer);
         writeString(buffer, nodeName);
         writeString(buffer, service);

Added: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/HandShakeCommand.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/HandShakeCommand.java?view=auto&rev=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/HandShakeCommand.java (added)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/HandShakeCommand.java Thu Oct 26 18:45:30 2006
@@ -0,0 +1,78 @@
+/**
+ *
+ * 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.geronimo.gcache.command;
+
+import java.io.IOException;
+import java.security.PublicKey;
+import java.security.spec.InvalidKeySpecException;
+
+import org.apache.geronimo.gcache.util.CipherUtil;
+import org.apache.mina.common.ByteBuffer;
+
+public class HandShakeCommand extends BaseCommand {
+    
+    PublicKey publicKey = null;
+    
+    @Override
+    public byte getCommandType() throws IOException {
+	return CommandTypes.HAND_SHAKE_COMMAND;
+    }
+    
+    public PublicKey getPublicKey() {
+        return publicKey;
+    }
+
+    public void setPublicKey(PublicKey publicKey) {
+        this.publicKey = publicKey;
+    }
+
+    @Override
+    public void readExternal(ByteBuffer buffer) throws Exception {
+	super.readExternal(buffer);
+	
+	int len = buffer.getInt();
+	if (len == -1){
+	    publicKey = null;
+	    return;
+	}
+	
+	byte rawPublicKey[] = new byte[len];
+	buffer.get(rawPublicKey);
+	
+	try {
+	    publicKey = CipherUtil.bytesToPublicKey(rawPublicKey);
+	} catch (InvalidKeySpecException e) {
+	    throw new IOException(e.getMessage());
+	}
+    }
+
+    @Override
+    public void writeExternal(ByteBuffer buffer) throws Exception {
+	super.writeExternal(buffer);
+	if (publicKey == null){
+	    buffer.putInt(-1);
+	    return;
+	}
+	
+	byte rawPublicKey[] = publicKey.getEncoded();
+
+	buffer.putInt(rawPublicKey.length);
+	buffer.put(rawPublicKey);
+    }
+
+}

Propchange: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/HandShakeCommand.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/HandShakeCommand.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/HandShakeCommand.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/MessageAckCommand.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/MessageAckCommand.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/MessageAckCommand.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/MessageAckCommand.java Thu Oct 26 18:45:30 2006
@@ -39,7 +39,7 @@
         this.messageId = messageId;
     }
 
-    public void readExternal(ByteBuffer buffer) throws IOException {
+    public void readExternal(ByteBuffer buffer) throws Exception {
 
         super.readExternal(buffer);
 
@@ -47,7 +47,7 @@
 
     }
 
-    public void writeExternal(ByteBuffer buffer) throws IOException {
+    public void writeExternal(ByteBuffer buffer) throws Exception {
 
         super.writeExternal(buffer);
         buffer.putLong(messageId);

Added: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/PublicKeyCommand.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/PublicKeyCommand.java?view=auto&rev=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/PublicKeyCommand.java (added)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/PublicKeyCommand.java Thu Oct 26 18:45:30 2006
@@ -0,0 +1,32 @@
+/**
+ *
+ * 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.geronimo.gcache.command;
+
+import java.io.IOException;
+
+public class PublicKeyCommand extends HandShakeCommand {
+    //Same as the HandShake, but different type
+    //
+    //This just is a container as a response for a handshake event
+    //that sends back the key
+    @Override
+    public byte getCommandType() throws IOException {
+	return CommandTypes.PUBLIC_KEY_COMMAND;
+    }
+
+}

Propchange: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/PublicKeyCommand.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/PublicKeyCommand.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/PublicKeyCommand.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/PutSessionCommand.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/PutSessionCommand.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/PutSessionCommand.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/command/PutSessionCommand.java Thu Oct 26 18:45:30 2006
@@ -41,12 +41,12 @@
 	return CommandTypes.PUT_SESSION_COMMAND;
     }
 
-    public void readExternal(ByteBuffer buffer) throws IOException {
+    public void readExternal(ByteBuffer buffer) throws Exception {
 	super.readExternal(buffer);
 	entryCount = buffer.getInt();
     }
 
-    public void writeExternal(ByteBuffer buffer) throws IOException {
+    public void writeExternal(ByteBuffer buffer) throws Exception {
 	super.writeExternal(buffer);
 	buffer.putInt(entryCount);
     }

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/marshal/MarshalAware.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/marshal/MarshalAware.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/marshal/MarshalAware.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/marshal/MarshalAware.java Thu Oct 26 18:45:30 2006
@@ -43,9 +43,9 @@
      * method.
      * 
      * @param channel
-     * @throws IOException
+     * @throws Exception
      */
-    void readExternal(ByteBuffer buffer) throws IOException;
+    void readExternal(ByteBuffer buffer) throws Exception;
     
     /**
      * Write data into <code>channel</code> to save the state of the object.
@@ -53,7 +53,7 @@
      * readExternal method.
      * 
      * @param channel
-     * @throws IOException
+     * @throws Exception
      */
-    void writeExternal(ByteBuffer buffer) throws IOException;
+    void writeExternal(ByteBuffer buffer) throws Exception;
 }

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/Constants.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/Constants.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/Constants.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/Constants.java Thu Oct 26 18:45:30 2006
@@ -23,6 +23,9 @@
     public final static int HEADER_SIZE = MAGIC.length + 1 + 4;
     
     //Session attribute keys
+    public final static String AUTHENTICATED = "AUTHENTICATED";
+    public final static String AUTH_TASK = "AUTH_TASK";
     public final static String BULK_COUNT = "BULK_COUNT_";
     public final static String BULK_COMMAND_ID = "BULK_COMMAND_ID_";
+    public final static String REMOTE_PUBLIC_KEY = "REMOTE_PUBLIC_KEY";
 }

Added: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPAuthenticationFilter.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPAuthenticationFilter.java?view=auto&rev=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPAuthenticationFilter.java (added)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPAuthenticationFilter.java Thu Oct 26 18:45:30 2006
@@ -0,0 +1,215 @@
+/**
+ *
+ * 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.geronimo.gcache.transports.tcp;
+
+import java.security.PublicKey;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.geronimo.gcache.CacheInfoHolder;
+import org.apache.geronimo.gcache.command.AuthCommand;
+import org.apache.geronimo.gcache.command.HandShakeCommand;
+import org.apache.geronimo.gcache.command.PublicKeyCommand;
+import org.apache.geronimo.gcache.util.CipherUtil;
+import org.apache.mina.common.IoFilterAdapter;
+import org.apache.mina.common.IoSession;
+import org.apache.mina.common.IoFilter.NextFilter;
+
+import edu.emory.mathcs.backport.java.util.concurrent.ScheduledFuture;
+
+public class TCPAuthenticationFilter extends IoFilterAdapter {
+
+    private static final Log log = LogFactory
+            .getLog(TCPAuthenticationFilter.class);
+
+    public final static String NAME = "AuthenticationFilter";
+
+
+    private final String userId;
+    private final String password;
+
+    public TCPAuthenticationFilter(final String userId, final String password) {
+        this.userId = userId;
+        this.password = password;
+    }
+
+    @Override
+    public void sessionOpened(NextFilter nextFilter, IoSession sess) throws Exception {
+        //Start up the response timeout
+        ScheduledFuture task = ((TCPSocketHandler) sess.getHandler()).schedule(
+                new TimeoutTask(sess), 5000);
+        sess.setAttribute(Constants.AUTH_TASK, task);
+        nextFilter.sessionCreated(sess);
+    }
+
+    /**
+     * @Override public void sessionCreated(NextFilter nextFilter, IoSession sess)
+     * throws Exception {
+     * //Start up the response timeout
+     * ScheduledFuture task = ((TCPSocketHandler) sess.getHandler()).schedule(
+     * new TimeoutTask(sess), 5000);
+     * sess.setAttribute(Constants.AUTH_TASK, task);
+     * nextFilter.sessionCreated(sess);
+     * }
+     */
+
+    @Override
+    public void messageReceived(NextFilter nextFilter, IoSession sess,
+                                Object obj) throws Exception {
+
+        //If we have authenticated, continue on
+        if (sess.containsAttribute(Constants.AUTHENTICATED)) {
+            nextFilter.messageReceived(sess, obj);
+            return;
+        }
+
+        //Oh goody...someone might be authenticating
+
+        //If the session has a remote public key, then it's an Auth Command
+        if (sess.containsAttribute(Constants.REMOTE_PUBLIC_KEY)) {
+            handleAuth(sess, obj);
+            return;
+        }
+
+        //No Remote Public Key, so this should be a handshake
+        handleHandShake(sess, obj);
+
+        //Consume the message (don't pass it on)
+        nextFilter.messageReceived(sess, obj);
+    }
+
+    private void handleAuth(IoSession sess, Object obj) throws Exception {
+        if (!(obj instanceof AuthCommand)) {
+            //Nope...buh-bye...
+            log.error("Expected AuthCommand but got " + obj.getClass().getSimpleName() + " from " + sess.getRemoteAddress().toString());
+            sess.close();
+            return;
+        }
+
+        ScheduledFuture authTask = (ScheduledFuture) sess.getAttribute(Constants.AUTH_TASK);
+
+        //Cancel the timer
+        if (!authTask.cancel(false)) {
+            //Can't cancel because it's ran or is running...too late!
+            return;
+        }
+
+        //Pull and test the credentials
+        AuthCommand auth = (AuthCommand) obj;
+        String authUserId = auth.getUserId();
+        if (log.isDebugEnabled()) {
+            log.debug("User Id read was '" + authUserId + "'");
+        }
+        if (!userId.equals(authUserId)) {
+            log.error("Authentication failure for " + sess.getRemoteAddress().toString());
+            sess.close();
+            return;
+        }
+
+        String authPassword = auth.getPassword();
+        if (log.isDebugEnabled()) {
+            log.debug("Password read was '" + authPassword + "'");
+        }
+        if (!password.equals(authPassword)) {
+            log.error("Authentication failure for " + sess.getRemoteAddress().toString());
+            sess.close();
+            return;
+        }
+
+        //If we got here then authentication passed
+
+        //Clear the AUTH_TASK
+        sess.removeAttribute(Constants.AUTH_TASK);
+
+        //Register authentication
+        sess.setAttribute(Constants.AUTHENTICATED);
+
+        //Now add the client to the cache to start receiving events
+        CacheInfoHolder infoHolder = ((TCPSocketHandler) sess.getHandler()).getInfoHolder();
+        infoHolder.getEndpointManager().addEndpoint(new TCPEndpoint(sess));
+
+        //See if we need to send an Ack
+        TCPMessageAckCommandFilter filter = (TCPMessageAckCommandFilter) sess
+                .getFilterChain().get(TCPMessageAckCommandFilter.NAME);
+        if (filter != null) {
+            long commandId = auth.getCommandId();
+            filter.requestAck(commandId, sess);
+        }
+
+    }
+
+    private void handleHandShake(IoSession sess, Object obj) throws Exception {
+        ScheduledFuture handshakeTask = (ScheduledFuture) sess
+                .getAttribute(Constants.AUTH_TASK);
+
+        if (!(obj instanceof HandShakeCommand)) {
+            log.error("Expected HandShakeCommand but got " + obj.getClass().getSimpleName() + " from " + sess.getRemoteAddress().toString());
+            //Nope...buh-bye...
+            sess.close();
+            return;
+        }
+
+        //Cancel the timer
+        if (!handshakeTask.cancel(false)) {
+            //Can't cancel because it's ran or is running...too late!
+            return;
+        }
+
+        HandShakeCommand handShake = (HandShakeCommand) obj;
+        PublicKey key = handShake.getPublicKey();
+        if (key == null) {
+            throw new IllegalArgumentException(
+                    "Handshake did not contain a key");
+        }
+
+        //Store the remote's public key
+        sess.setAttribute(Constants.REMOTE_PUBLIC_KEY, key);
+
+        //Send out our public key
+        PublicKeyCommand keyCommand = new PublicKeyCommand();
+        keyCommand.setPublicKey(CipherUtil.publicKey);
+
+        sess.write(keyCommand);
+
+        //Now schedule a timeout for authorization
+        ScheduledFuture authTask = ((TCPSocketHandler) sess.getHandler()).schedule(
+                new TimeoutTask(sess), 5000);
+        sess.setAttribute(Constants.AUTH_TASK, authTask);
+
+
+    }
+
+    class TimeoutTask implements Runnable {
+
+        private IoSession sess;
+
+        public TimeoutTask(IoSession sess) {
+            this.sess = sess;
+        }
+
+        public void run() {
+            log.error("Timeout waiting for Handshake or Login from "
+                    + sess.getRemoteAddress().toString()
+                    + ", removing client.");
+            //Close the session, its no good since it cannot authenticate
+            sess.close();
+        }
+
+    }
+
+}

Propchange: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPAuthenticationFilter.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPAuthenticationFilter.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPAuthenticationFilter.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCacheNotifier.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCacheNotifier.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCacheNotifier.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCacheNotifier.java Thu Oct 26 18:45:30 2006
@@ -64,7 +64,7 @@
 	ByteBuffer buffer = null;
 	try {
 	    buffer = ByteBuffer.wrap(command.createPacket(true));
-	} catch (IOException e) {
+	} catch (Exception e) {
 	    log.error("Cannot marshal packet, cannot send to endpoints", e);
 	    return;
 	}

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCommandRequestDecoder.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCommandRequestDecoder.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCommandRequestDecoder.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCommandRequestDecoder.java Thu Oct 26 18:45:30 2006
@@ -59,6 +59,9 @@
 	in.getInt();
 	
 	Command command = CommandTypes.createCommand(commandIdentifier);
+	if (log.isDebugEnabled()){
+	    log.debug("Command is type " + command.getClass().getSimpleName());
+	}
 	
 	command.readExternal(in);
 	

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCommandRequestEncoder.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCommandRequestEncoder.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCommandRequestEncoder.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCommandRequestEncoder.java Thu Oct 26 18:45:30 2006
@@ -21,12 +21,17 @@
 import java.util.HashSet;
 import java.util.Set;
 
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.geronimo.gcache.command.AuthCommand;
 import org.apache.geronimo.gcache.command.BaseCommand;
 import org.apache.geronimo.gcache.command.BulkSendCommand;
 import org.apache.geronimo.gcache.command.ClearCacheCommand;
 import org.apache.geronimo.gcache.command.Command;
 import org.apache.geronimo.gcache.command.GetCacheCommand;
+import org.apache.geronimo.gcache.command.HandShakeCommand;
 import org.apache.geronimo.gcache.command.MessageAckCommand;
+import org.apache.geronimo.gcache.command.PublicKeyCommand;
 import org.apache.geronimo.gcache.command.PutEntryCommand;
 import org.apache.geronimo.gcache.command.PutSessionCommand;
 import org.apache.geronimo.gcache.command.RemoveEntryCommand;
@@ -37,15 +42,21 @@
 import org.apache.mina.filter.codec.demux.MessageEncoder;
 
 public class TCPCommandRequestEncoder implements MessageEncoder {
+    
+    private static Log log = LogFactory.getLog(TCPCommandRequestEncoder.class);
+    
     private static final Set TYPES;
 
     static
     {
         Set<Class> types= new HashSet<Class> ();
+        types.add( AuthCommand.class );
         types.add( BulkSendCommand.class );
         types.add( ClearCacheCommand.class );
         types.add( GetCacheCommand.class );
+        types.add( HandShakeCommand.class );
         types.add( MessageAckCommand.class );
+        types.add( PublicKeyCommand.class );
         types.add( PutEntryCommand.class );
         types.add( PutSessionCommand.class );
         types.add( RemoveEntryCommand.class );
@@ -55,6 +66,9 @@
     
     public void encode(IoSession sess, Object obj, ProtocolEncoderOutput out) throws Exception {
 	
+	if (log.isDebugEnabled()){
+	    log.debug("Sending " + obj.getClass().getSimpleName() + " to " + sess.getRemoteAddress().toString());
+	}
 	Command command = (Command)obj;
 	out.write(ByteBuffer.wrap(((BaseCommand)command).createPacket(true)));
     }

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCommandVisitor.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCommandVisitor.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCommandVisitor.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPCommandVisitor.java Thu Oct 26 18:45:30 2006
@@ -52,227 +52,225 @@
     private IoSession sess;
 
     public TCPCommandVisitor(CacheInfoHolder infoHolder, IoSession sess) {
-	this.sess = sess;
-	endpoint = new TCPEndpoint(sess);
-	this.infoHolder = infoHolder;
+        this.sess = sess;
+        endpoint = new TCPEndpoint(sess);
+        this.infoHolder = infoHolder;
     }
 
     public void processRemoveSession(RemoveSessionCommand command) {
 
-	Cache cache = infoHolder.getCache(command.getCacheName(), true);
+        Cache cache = infoHolder.getCache(command.getCacheName(), true);
 
-	// Be sure a session was sent
-	if (command.hasSession()) {
-	    cache.remove(command.getSessionId());
-	}
-
-	command.setAttachment(endpoint);
-	infoHolder.getCacheNotifier().notifyRemoveSession(command);
-	sendAck(command);
+        // Be sure a session was sent
+        if (command.hasSession()) {
+            cache.remove(command.getSessionId());
+        }
+
+        command.setAttachment(endpoint);
+        infoHolder.getCacheNotifier().notifyRemoveSession(command);
+        sendAck(command);
     }
 
     @SuppressWarnings("unchecked")
     public void processRemoveEntry(RemoveEntryCommand command) {
 
-	Cache cache = infoHolder.getCache(command.getCacheName(), true);
+        Cache cache = infoHolder.getCache(command.getCacheName(), true);
 
-	// Check if we are using sessions
-	if (command.hasSession()) {
+        // Check if we are using sessions
+        if (command.hasSession()) {
 
-	    Map sessionMap = null;
+            Map sessionMap = null;
 
-	    // We are so use the session maps that is stored
-	    Element element = cache.get(command.getSessionId());
-	    if (element != null) {
-		sessionMap = (Map) element.getObjectValue();
-	    } else {
-		sessionMap = Collections.synchronizedMap(new HashMap());
-	    }
+            // We are so use the session maps that is stored
+            Element element = cache.get(command.getSessionId());
+            if (element != null) {
+                sessionMap = (Map) element.getObjectValue();
+            } else {
+                sessionMap = Collections.synchronizedMap(new HashMap());
+            }
 
-	    sessionMap.remove(command.getHashableKey());
+            sessionMap.remove(command.getHashableKey());
 
-	    // Put the session away
-	    cache.put(new Element(command.getSessionId(), sessionMap));
+            // Put the session away
+            cache.put(new Element(command.getSessionId(), sessionMap));
 
-	} else {
+        } else {
 
-	    // No session map so store the value
-	    cache.remove(command.getHashableKey());
-	}
+            // No session map so store the value
+            cache.remove(command.getHashableKey());
+        }
 
-	command.setAttachment(endpoint);
-	infoHolder.getCacheNotifier().notifyRemove(command);
-	sendAck(command);
+        command.setAttachment(endpoint);
+        infoHolder.getCacheNotifier().notifyRemove(command);
+        sendAck(command);
 
     }
 
     public void processPutSession(PutSessionCommand command) {
-	Cache cache = infoHolder.getCache(command.getCacheName(), true);
+        Cache cache = infoHolder.getCache(command.getCacheName(), true);
 
-	// Place the raw session in the cache
-	try {
-	    cache.put(new Element(command.getSessionId(), command
-		    .getRawSessionFromPayload()));
-
-	    command.setAttachment(endpoint);
-	    infoHolder.getCacheNotifier().notifyPutSession(command);
-	    
-	    sendAck(command);
-	    
-	} catch (IOException e) {
-	    // TODO - What should we do on an IOException, ignore it or
-	    // remove the client?
-	    log.error(e);
-	}
+        // Place the raw session in the cache
+        try {
+            cache.put(new Element(command.getSessionId(), command
+                    .getRawSessionFromPayload()));
+
+            command.setAttachment(endpoint);
+            infoHolder.getCacheNotifier().notifyPutSession(command);
+
+            sendAck(command);
+
+        } catch (IOException e) {
+            // TODO - What should we do on an IOException, ignore it or
+            // remove the client?
+            log.error(e);
+        }
 
     }
 
-    @SuppressWarnings( { "unchecked" })
+    @SuppressWarnings({"unchecked"})
     public void processPutEntry(PutEntryCommand command) {
-	Cache cache = infoHolder.getCache(command.getCacheName(), true);
+        Cache cache = infoHolder.getCache(command.getCacheName(), true);
 
-	// Check if we are using sessions
-	if (command.hasSession()) {
+        // Check if we are using sessions
+        if (command.hasSession()) {
 
-	    Map sessionMap = null;
+            Map sessionMap = null;
 
-	    // We are so use the session maps that is stored
-	    Element element = cache.get(command.getSessionId());
-	    if (element != null) {
-		sessionMap = (Map) element.getObjectValue();
-	    } else {
-		sessionMap = Collections.synchronizedMap(new HashMap());
-	    }
-
-	    sessionMap.put(command.getHashableKey(), command.getRawPayload());
-	    // Put the session away
-	    cache.put(new Element(command.getSessionId(), sessionMap));
-
-	} else {
-
-	    // No session map so store the value
-	    cache.put(new Element(command.getHashableKey(), command
-		    .getRawPayload()));
-	}
-
-	command.setAttachment(endpoint);
-	infoHolder.getCacheNotifier().notifyPut(command);
-	sendAck(command);
+            // We are so use the session maps that is stored
+            Element element = cache.get(command.getSessionId());
+            if (element != null) {
+                sessionMap = (Map) element.getObjectValue();
+            } else {
+                sessionMap = Collections.synchronizedMap(new HashMap());
+            }
+
+            sessionMap.put(command.getHashableKey(), command.getRawPayload());
+            // Put the session away
+            cache.put(new Element(command.getSessionId(), sessionMap));
+
+        } else {
+
+            // No session map so store the value
+            cache.put(new Element(command.getHashableKey(), command
+                    .getRawPayload()));
+        }
+
+        command.setAttachment(endpoint);
+        infoHolder.getCacheNotifier().notifyPut(command);
+        sendAck(command);
     }
 
     public void processMessageAck(MessageAckCommand command) {
-	//This should never get called as the filters will handle it
+        //This should never get called as the filters will handle it
     }
 
     @SuppressWarnings("unchecked")
     public void processGetCache(GetCacheCommand command) {
-	Cache cache = infoHolder.getCache(command.getCacheName(), true);
+        Cache cache = infoHolder.getCache(command.getCacheName(), true);
+
+        IoSession sess = endpoint.getIoSession();
 
-	//Add the client endpoint
-	infoHolder.getEndpointManager().addEndpoint(endpoint);
-	IoSession sess = endpoint.getIoSession();
-
-	//Send a bulk command
-	BulkSendCommand bulk = new BulkSendCommand();
-	bulk.setNumberOfCommands(cache.getSize());
-
-	long commandId = bulk.getCommandId();
-
-	try {
-	    if (sess != null)
-		sess.write(bulk);
-
-	    for (Object key : (List<Object>) cache.getKeys()) {
-		Element element = cache.get(key);
-		Object payload = element.getValue();
-
-		BaseCommand newCommand = null;
-		// Test if we are sending a session or not
-		if (payload instanceof HashMap) {
-		    PutSessionCommand psc = new PutSessionCommand();
-		    psc.setCacheName(command.getCacheName());
-		    psc.setSessionId((String) key);
-		    psc.setPayloadFromSession((Map) payload);
-		    newCommand = psc;
-		} else {
-		    PutEntryCommand pec = new PutEntryCommand();
-		    pec.setCacheName(command.getCacheName());
-		    pec.setRawPayload((byte[]) payload);
-		    pec.setRawKey((byte[]) key);
-		    newCommand = pec;
-		}
-
-		//Set all the commands to the same commandId for a bulk send
-		newCommand.setCommandId(commandId);
-
-		//Send the packet.  If there is a failure just abort
-		if (sess != null) {
-		    sess.write(newCommand);
-		}
-	    }
-	    
-	    //We are returning a request there for we don't send an ack...
-	    //we request one
-	    requestAck(bulk);
-
-	} catch (IOException e) {
-	    // TODO - What should we do on an IOException, ignore it or
-	    // remove the client?
-	    log.error(e);
-	}
+        //Send a bulk command
+        BulkSendCommand bulk = new BulkSendCommand();
+        bulk.setNumberOfCommands(cache.getSize());
+
+        long commandId = bulk.getCommandId();
+
+        try {
+            if (sess != null)
+                sess.write(bulk);
+
+            for (Object key : (List<Object>) cache.getKeys()) {
+                Element element = cache.get(key);
+                Object payload = element.getValue();
+
+                BaseCommand newCommand = null;
+                // Test if we are sending a session or not
+                if (payload instanceof HashMap) {
+                    PutSessionCommand psc = new PutSessionCommand();
+                    psc.setCacheName(command.getCacheName());
+                    psc.setSessionId((String) key);
+                    psc.setPayloadFromSession((Map) payload);
+                    newCommand = psc;
+                } else {
+                    PutEntryCommand pec = new PutEntryCommand();
+                    pec.setCacheName(command.getCacheName());
+                    pec.setRawPayload((byte[]) payload);
+                    pec.setRawKey((byte[]) key);
+                    newCommand = pec;
+                }
+
+                //Set all the commands to the same commandId for a bulk send
+                newCommand.setCommandId(commandId);
+
+                //Send the packet.  If there is a failure just abort
+                if (sess != null) {
+                    sess.write(newCommand);
+                }
+            }
+
+            //We are returning a request there for we don't send an ack...
+            //we request one
+            requestAck(bulk);
+
+        } catch (IOException e) {
+            // TODO - What should we do on an IOException, ignore it or
+            // remove the client?
+            log.error(e);
+        }
     }
 
     public void processClearCache(ClearCacheCommand command) {
-	Cache cache = infoHolder.getCache(command.getCacheName(), true);
-	cache.removeAll();
+        Cache cache = infoHolder.getCache(command.getCacheName(), true);
+        cache.removeAll();
 
-	command.setAttachment(endpoint);
-	infoHolder.getCacheNotifier().notifyClearCache(command);
-	
-	sendAck(command);
+        command.setAttachment(endpoint);
+        infoHolder.getCacheNotifier().notifyClearCache(command);
+
+        sendAck(command);
     }
 
     public void processBulkSend(BulkSendCommand command) {
 
-	//Get the command count and set the attribute to count em down
-	int commandCount = command.getNumberOfCommands();
-	
-	if (sess == null)
-	    return;
-
-	//Setup the BulkCommand filter to process bulk commands
-	sess.setAttribute(Constants.BULK_COUNT + command.getCommandId(),
-		commandCount);
-	sess.setAttribute(Constants.BULK_COMMAND_ID + command.getCommandId());
-	
-	//Do not send an ack here, the filter will send it once all
-	//of the following commands have been received
-    }
-    
-    private void sendAck(BaseCommand command){
-	
-	if (sess == null)
-	    return;
-	
-	if (sess.getFilterChain().contains(TCPMessageAckCommandFilter.class)){
-	   MessageAckCommand ack = new MessageAckCommand();
-	   ack.setMessageId(command.getCommandId());
-	   sess.write(ack);
-	}
+        //Get the command count and set the attribute to count em down
+        int commandCount = command.getNumberOfCommands();
+
+        if (sess == null)
+            return;
+
+        //Setup the BulkCommand filter to process bulk commands
+        sess.setAttribute(Constants.BULK_COUNT + command.getCommandId(),
+                commandCount);
+        sess.setAttribute(Constants.BULK_COMMAND_ID + command.getCommandId());
+
+        //Do not send an ack here, the filter will send it once all
+        //of the following commands have been received
+    }
+
+    private void sendAck(BaseCommand command) {
+
+        if (sess == null)
+            return;
+
+        if (sess.getFilterChain().contains(TCPMessageAckCommandFilter.class)) {
+            MessageAckCommand ack = new MessageAckCommand();
+            ack.setMessageId(command.getCommandId());
+            sess.write(ack);
+        }
     }
 
     private void requestAck(BaseCommand command) {
 
-	if (sess == null)
-	    return;
-	
-	//See if we need to send an Ack
-	TCPMessageAckCommandFilter filter = (TCPMessageAckCommandFilter) sess
-		.getFilterChain().get(TCPMessageAckCommandFilter.NAME);
-	if (filter != null) {
-	    long commandId = command.getCommandId();
-	    filter.requestAck(commandId, sess);
-	}
+        if (sess == null)
+            return;
+
+        //See if we need to send an Ack
+        TCPMessageAckCommandFilter filter = (TCPMessageAckCommandFilter) sess
+                .getFilterChain().get(TCPMessageAckCommandFilter.NAME);
+        if (filter != null) {
+            long commandId = command.getCommandId();
+            filter.requestAck(commandId, sess);
+        }
     }
 
 }

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPMessageAckCommandFilter.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPMessageAckCommandFilter.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPMessageAckCommandFilter.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPMessageAckCommandFilter.java Thu Oct 26 18:45:30 2006
@@ -17,27 +17,22 @@
  */
 package org.apache.geronimo.gcache.transports.tcp;
 
-import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;
-import java.util.Timer;
 import java.util.TimerTask;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.geronimo.gcache.command.MessageAckCommand;
-import org.apache.mina.common.IdleStatus;
 import org.apache.mina.common.IoFilterAdapter;
 import org.apache.mina.common.IoSession;
 
 public class TCPMessageAckCommandFilter extends IoFilterAdapter {
 
-    private static final Log log = LogFactory
-	    .getLog(TCPMessageAckCommandFilter.class);
+    private static final Log log = LogFactory.getLog(TCPMessageAckCommandFilter.class);
 
     public final static String NAME = "MessageAckCommandFilter";
 
-    private final Timer timer = new Timer();
 
     public Map<Long, AckTask> waitingAcks = new HashMap<Long, AckTask>();
 
@@ -75,16 +70,10 @@
 	nextFilter.messageReceived(sess, obj);
     }
 
-    @Override
-    public void destroy() throws Exception {
-	//Shut down the timer.
-	timer.cancel();
-    }
-
     public void requestAck(long commandId, IoSession sess) {
 	AckTask task = new AckTask(commandId, sess);
-	timer.schedule(task, ackTimeout);
-
+	TCPSocketHandler handler = (TCPSocketHandler)sess.getHandler();
+	handler.schedule(task, ackTimeout);
     }
 
     class AckTask extends TimerTask {

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPSocketHandler.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPSocketHandler.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPSocketHandler.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPSocketHandler.java Thu Oct 26 18:45:30 2006
@@ -22,15 +22,35 @@
 import org.apache.mina.common.IoSession;
 import org.apache.mina.util.SessionLog;
 
+import edu.emory.mathcs.backport.java.util.concurrent.Executors;
+import edu.emory.mathcs.backport.java.util.concurrent.ScheduledFuture;
+import edu.emory.mathcs.backport.java.util.concurrent.ScheduledThreadPoolExecutor;
+import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+
 /**
  * This class is the main worker of the gcache functionality. Essentialy this 
  */
 public class TCPSocketHandler extends IoHandlerAdapter {
     
+    public final static int DEFAULT_THREAD_POOL_SIZE = 10;
     private final CacheInfoHolder infoHolder;
+    private final ScheduledThreadPoolExecutor scheduler;
     
     public TCPSocketHandler(final CacheInfoHolder infoHolder) {
+	this(infoHolder, DEFAULT_THREAD_POOL_SIZE);
+    }
+    
+    public TCPSocketHandler(final CacheInfoHolder infoHolder, int threadPoolSize) {
 	this.infoHolder = infoHolder;
+	scheduler = (ScheduledThreadPoolExecutor)Executors.newScheduledThreadPool(threadPoolSize);
+	
+	//Install the schedule purger to purge any cancelled tasks
+	//to prevent memory leaks
+	scheduler.scheduleWithFixedDelay(new SchedulePurger(), 10000, 10000, TimeUnit.MILLISECONDS);
+    }
+    
+    public CacheInfoHolder getInfoHolder() {
+        return infoHolder;
     }
 
     @Override
@@ -52,10 +72,31 @@
 	sess.close();
     }
 
+
     @Override
     public void sessionClosed(IoSession sess) throws Exception {
 	//Remove the client from the list
 	infoHolder.getEndpointManager().removeEndpoint(new TCPEndpoint(sess));
     }
+    
+    public void destroy(){
+	//Shut down the scheduler.
+	scheduler.shutdownNow();
+    }
+    
+    public ScheduledFuture schedule(Runnable task, long delay){
+	return scheduler.schedule(task, delay, TimeUnit.MILLISECONDS);
+    }
+    
+    /**
+     * Task to remove cancelled tasks from the scheduler
+     */
+    class SchedulePurger implements Runnable{
 
+	public void run() {
+	    scheduler.purge();
+	}
+	
+    }
+    
 }

Modified: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPSocketTransportService.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPSocketTransportService.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPSocketTransportService.java (original)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/transports/tcp/TCPSocketTransportService.java Thu Oct 26 18:45:30 2006
@@ -34,6 +34,8 @@
     private final static Log log = LogFactory.getLog(TCPSocketTransportService.class);
     
     public static final long DEFAULT_ACK_TIMEOUT = 10000;
+    public final static String DEFAULT_USERNAME = "system";
+    public final static String DEFAULT_PASSWORD = "manager";
     
     IoAcceptor acceptor = null; 
     private CacheInfoHolder info;
@@ -41,13 +43,31 @@
     private boolean requireMessageAck = false;
     private boolean enableLogging = false;
     private long ackTimeout = DEFAULT_ACK_TIMEOUT;
-    private TCPMessageAckCommandFilter messageAckCommandFilter = null;
+    private TCPSocketHandler handler = null;
+    private String userId = DEFAULT_USERNAME;
+    private String password = DEFAULT_PASSWORD;
 
     public TCPSocketTransportService(String uriString, CacheInfoHolder info) {
         this.info = info;
         this.uriString = uriString;
     }
 
+    public String getPassword() {
+        return password;
+    }
+
+    public void setPassword(String password) {
+        this.password = password;
+    }
+
+    public String getUserId() {
+        return userId;
+    }
+
+    public void setUserId(String userId) {
+        this.userId = userId;
+    }
+
     public boolean isRequireMessageAck() {
         return requireMessageAck;
     }
@@ -85,31 +105,36 @@
         SocketAcceptorConfig cfg = new SocketAcceptorConfig();
         cfg.setReuseAddress( true );
         
+	//If we requested logging, add that too
+        if (enableLogging){
+            cfg.getFilterChain().addLast( "logFilter", new LoggingFilter() );
+        }
+        
         //Add the filter to hande the GCache Codec
         cfg.getFilterChain().addLast( "protocolFilter", new ProtocolCodecFilter( new TCPCommandProtocolCodecFactory() ) );
         
+        //Add teh authentication filter
+	cfg.getFilterChain().addLast(TCPAuthenticationFilter.NAME, new TCPAuthenticationFilter(userId, password));
+	
         //Add the BulkCommandFilter for filtering when a BulkCommand is being read
         cfg.getFilterChain().addLast( TCPBulkCommandFilter.NAME, new TCPBulkCommandFilter() );
         
-        //If we require message acks, then set up the filter
+        //If we require message acks, then set up the message ack filter
 	if (requireMessageAck){
-	    messageAckCommandFilter = new TCPMessageAckCommandFilter(ackTimeout);
-	    cfg.getFilterChain().addLast(TCPMessageAckCommandFilter.NAME, messageAckCommandFilter);
+	    cfg.getFilterChain().addLast(TCPMessageAckCommandFilter.NAME, new TCPMessageAckCommandFilter(ackTimeout));
 	}        
 	
-        if (enableLogging){
-            cfg.getFilterChain().addLast( "logFilter", new LoggingFilter() );
-        }
-
-        acceptor.bind( inet, new TCPSocketHandler(info), cfg );
+	
+        handler = new TCPSocketHandler(info);
+        acceptor.bind( inet, handler, cfg );
     }
 
     public void stop() throws Exception {
 	
-	if (messageAckCommandFilter != null){
+	if (handler != null){
 	    try {
-		messageAckCommandFilter.destroy();
-		messageAckCommandFilter = null;
+		handler.destroy();
+		handler = null;
 	    } catch (Exception e) {
 		log.error(e);
 		//Ignore since there is not much that can be done

Added: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/util/CipherUtil.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/util/CipherUtil.java?view=auto&rev=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/util/CipherUtil.java (added)
+++ geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/util/CipherUtil.java Thu Oct 26 18:45:30 2006
@@ -0,0 +1,140 @@
+/**
+ *
+ * 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.geronimo.gcache.util;
+
+import java.security.InvalidKeyException;
+import java.security.KeyFactory;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.X509EncodedKeySpec;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.SecretKeySpec;
+
+public class CipherUtil {
+    private static final byte[] _3desData = { (byte) 0x76, (byte) 0x6F,
+	    (byte) 0xBA, (byte) 0x39, (byte) 0x31, (byte) 0x2F, (byte) 0x0D,
+	    (byte) 0x4A, (byte) 0xA3, (byte) 0x90, (byte) 0x55, (byte) 0xFE,
+	    (byte) 0x55, (byte) 0x65, (byte) 0x61, (byte) 0x13, (byte) 0x34,
+	    (byte) 0x82, (byte) 0x12, (byte) 0x17, (byte) 0xAC, (byte) 0x77,
+	    (byte) 0x39, (byte) 0x19 };
+
+    private static SecretKeySpec _key = new SecretKeySpec(_3desData, "DESede");
+    private static PrivateKey privateKey = null;
+    public static PublicKey publicKey = null;
+
+    static {
+	KeyPairGenerator keyGen;
+	try {
+	    keyGen = KeyPairGenerator.getInstance("RSA");
+	    keyGen.initialize(1024);
+	    KeyPair keypair = keyGen.genKeyPair();
+	    privateKey = keypair.getPrivate();
+	    publicKey = keypair.getPublic();
+	} catch (NoSuchAlgorithmException e) {
+	    throw new RuntimeException(e);
+	}
+    }
+    
+    public static PublicKey bytesToPublicKey(byte rawKey[]) throws InvalidKeySpecException{
+	X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(rawKey);
+	try {
+	    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
+	    PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
+	    
+	    return pubKey;
+	} catch (NoSuchAlgorithmException e) {
+	    throw new RuntimeException(e);
+	}
+    }
+    
+    public static byte[] RSAEncrypt(String text, PublicKey key) {
+	byte[] plaintext = text.getBytes();
+
+	try {
+	    // Get a RSA Cipher object
+	    Cipher cipher = Cipher.getInstance("RSA"); 
+	    
+	    // Set it into encryption mode
+	    cipher.init(Cipher.ENCRYPT_MODE, key);
+
+	    // Encrypt data
+	    return cipher.doFinal(plaintext);
+
+	} catch (Exception e) {
+	    throw new RuntimeException(e);
+	}
+    }
+    
+    public static String RSADecrypt(byte[] cipherText) throws InvalidKeyException {
+
+	try {
+
+	    Cipher cipher = Cipher.getInstance("RSA"); // Triple-DES encryption
+	    cipher.init(Cipher.DECRYPT_MODE, privateKey);
+
+	    // Decrypt data
+	    String plainText = new String(cipher.doFinal(cipherText));
+
+	    return plainText;
+
+	} catch (Exception e) {
+	    throw new InvalidKeyException(e.getMessage());
+	}
+    }
+    
+    public static byte[] TripleDESencrypt(String text) {
+	byte[] plaintext = text.getBytes();
+
+	try {
+	    // Get a 3DES Cipher object
+	    Cipher cipher = Cipher.getInstance("DESede"); // Triple-DES encryption
+	    // Set it into encryption mode
+	    cipher.init(Cipher.ENCRYPT_MODE, _key);
+
+	    // Encrypt data
+	    return cipher.doFinal(plaintext);
+
+	} catch (Exception e) {
+	    throw new RuntimeException(e);
+	}
+    }
+
+    public static String TripleDESdecrypt(byte[] cipherText) throws InvalidKeyException {
+
+	try {
+
+	    // Get a 3DES Cipher object
+	    Cipher cipher = Cipher.getInstance("DESede"); // Triple-DES encryption
+	    // Set it into decryption mode
+	    cipher.init(Cipher.DECRYPT_MODE, _key);
+
+	    // Decrypt data
+	    String plainText = new String(cipher.doFinal(cipherText));
+
+	    return plainText;
+
+	} catch (Exception e) {
+	    throw new InvalidKeyException(e.getMessage());
+	}
+    }
+}

Propchange: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/util/CipherUtil.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/util/CipherUtil.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/sandbox/gcache/server/src/main/java/org/apache/geronimo/gcache/util/CipherUtil.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/command/AuthCommandTest.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/command/AuthCommandTest.java?view=auto&rev=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/command/AuthCommandTest.java (added)
+++ geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/command/AuthCommandTest.java Thu Oct 26 18:45:30 2006
@@ -0,0 +1,46 @@
+/**
+ *
+ * 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.geronimo.gcache.command;
+
+import org.apache.geronimo.gcache.util.CipherUtil;
+import org.apache.mina.common.ByteBuffer;
+import org.testng.annotations.Test;
+
+public class AuthCommandTest {
+    
+    @Test
+    public void testAuthCommand() throws Exception{
+        AuthCommand command = (AuthCommand) CommandTypes.createCommand(CommandTypes.AUTH_COMMAND);
+        long commandId = command.getCommandId();
+        command.setUserId("test");
+        command.setPassword("secret");
+        command.setPublicKey(CipherUtil.publicKey);
+
+        //Convert the command to bytes
+        byte[] marshalled = command.marshal();
+
+        AuthCommand readCommand = new AuthCommand();
+        readCommand.readExternal(ByteBuffer.wrap(marshalled));
+        assert readCommand.getCommandId() == commandId;
+        assert readCommand.getUserId().equals("test");
+        assert readCommand.getPassword().equals("secret");
+        
+	
+    }
+
+}

Propchange: geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/command/AuthCommandTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/command/AuthCommandTest.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/command/AuthCommandTest.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/tcp/AbstractService.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/tcp/AbstractService.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/tcp/AbstractService.java (original)
+++ geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/tcp/AbstractService.java Thu Oct 26 18:45:30 2006
@@ -17,7 +17,6 @@
  */
 package org.apache.geronimo.gcache.transports.tcp;
 
-import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.net.InetSocketAddress;
@@ -28,10 +27,14 @@
 import net.sf.ehcache.CacheManager;
 
 import org.apache.geronimo.gcache.CacheInfoHolder;
+import org.apache.geronimo.gcache.command.AuthCommand;
 import org.apache.geronimo.gcache.command.BaseCommand;
 import org.apache.geronimo.gcache.command.Command;
 import org.apache.geronimo.gcache.command.CommandTypes;
-import org.apache.geronimo.gcache.transports.TransportService;
+import org.apache.geronimo.gcache.command.HandShakeCommand;
+import org.apache.geronimo.gcache.command.PublicKeyCommand;
+import org.apache.geronimo.gcache.command.MessageAckCommand;
+import org.apache.geronimo.gcache.util.CipherUtil;
 import org.apache.mina.common.ByteBuffer;
 import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
@@ -43,13 +46,13 @@
     protected Socket client;
     protected Socket client2;
     protected CacheInfoHolder info;
-    
+
     @BeforeClass
-    public void setUp() throws Exception{
+    public void setUp() throws Exception {
         CacheManager mgr = CacheManager.create();
         info = new CacheInfoHolder(mgr);
         info.setCacheNotifier(new TCPCacheNotifier());
-        
+
         URI uri = new URI(protocol);
 
         server = new TCPSocketTransportService(protocol, info);
@@ -58,43 +61,69 @@
         server.setEnableLogging(true);
 
         server.start();
-        
+
         //Create a client socket
         client = new Socket();
-        client.connect(new InetSocketAddress(uri.getHost(), uri.getPort()),2000);
-        
+        client.connect(new InetSocketAddress(uri.getHost(), uri.getPort()), 2000);
+        authenticate(client);
+
         //Create a second client socket
         client2 = new Socket();
-        client2.connect(new InetSocketAddress(uri.getHost(), uri.getPort()),2000);
+        client2.connect(new InetSocketAddress(uri.getHost(), uri.getPort()), 2000);
+        authenticate(client2);
     }
 
-    @AfterClass(alwaysRun=true)
-    public void shutdown() throws Exception{
+    @AfterClass(alwaysRun = true)
+    public void shutdown() throws Exception {
         server.stop();
-        
-        client.close();
-        client2.close();
+
+        if (client != null)
+            client.close();
+
+        if (client2 != null)
+            client2.close();
         info.getCacheManager().removalAll();
     }
-    
-    protected void sendCommand(Socket socket, BaseCommand command) throws IOException{
-	
-	byte bytes[] = command.createPacket(true);
-	
-	OutputStream out = socket.getOutputStream();
-	out.write(bytes);
-	out.flush();
-	
+
+    protected void authenticate(Socket socket) throws Exception {
+        HandShakeCommand command = new HandShakeCommand();
+        command.setPublicKey(CipherUtil.publicKey);
+
+        //Send the handshake
+        sendCommand(socket, command);
+
+        PublicKeyCommand keyCommand = (PublicKeyCommand) readCommand(socket);
+
+        AuthCommand auth = new AuthCommand();
+        auth.setUserId("system");
+        auth.setPassword("manager");
+        auth.setPublicKey(keyCommand.getPublicKey());
+
+        sendCommand(socket, auth);
+
+        //Get the ack
+        MessageAckCommand ackCommand = (MessageAckCommand) readCommand(socket);
+    }
+
+    protected void sendCommand(Socket socket, BaseCommand command) throws Exception {
+
+        byte bytes[] = command.createPacket(true);
+
+        OutputStream out = socket.getOutputStream();
+        out.write(bytes);
+        out.flush();
+
     }
-    
-    protected Command readCommand(Socket socket) throws IOException{
-	
-	byte recBuf[] = new byte[Constants.HEADER_SIZE];
-	
+
+    protected Command readCommand(Socket socket) throws Exception {
+
+        byte recBuf[] = new byte[Constants.HEADER_SIZE];
+
+//	socket.setSoTimeout(2000);
         InputStream is = socket.getInputStream();
         int read = is.read(recBuf);
         assert read == Constants.HEADER_SIZE;
-	ByteBuffer receiveHeader = ByteBuffer.wrap(recBuf);
+        ByteBuffer receiveHeader = ByteBuffer.wrap(recBuf);
 
         //Read the magic
         byte magic[] = new byte[Constants.MAGIC.length];
@@ -119,7 +148,7 @@
         //Create the command and unmarshal the data
         Command command = CommandTypes.createCommand(commandIdentifier);
         command.readExternal(ByteBuffer.wrap(commandBuffer.array()));
-        
+
         return command;
 
     }

Modified: geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/tcp/TCPEndpointTest.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/tcp/TCPEndpointTest.java?view=diff&rev=468226&r1=468225&r2=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/tcp/TCPEndpointTest.java (original)
+++ geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/tcp/TCPEndpointTest.java Thu Oct 26 18:45:30 2006
@@ -30,9 +30,7 @@
     
     @Test
     public void testJoinCluster() throws Exception{
-	
         assert 0 == info.getEndpointManager().size();
-        
 	GetCacheCommand command = new GetCacheCommand();
 	
 	command.setCacheName("Cache1");

Added: geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/util/CipherUtilTest.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/util/CipherUtilTest.java?view=auto&rev=468226
==============================================================================
--- geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/util/CipherUtilTest.java (added)
+++ geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/util/CipherUtilTest.java Thu Oct 26 18:45:30 2006
@@ -0,0 +1,33 @@
+/**
+ *
+ * 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.geronimo.gcache.transports.util;
+
+import org.apache.geronimo.gcache.util.CipherUtil;
+import org.testng.annotations.Test;
+
+public class CipherUtilTest {
+    @Test
+    public void testRSA() throws Exception{
+	
+	byte cipher[] = CipherUtil.RSAEncrypt("Test Me", CipherUtil.publicKey);
+	String result = CipherUtil.RSADecrypt(cipher);
+	
+	assert result.equals("Test Me");
+    }
+
+}

Propchange: geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/util/CipherUtilTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/util/CipherUtilTest.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/sandbox/gcache/server/src/test/java/org/apache/geronimo/gcache/transports/util/CipherUtilTest.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain