Commits

Ning Sun committed 39ff740

add encode and decode on protocol interface

  • Participants
  • Parent commits e347350

Comments (0)

Files changed (13)

             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-compiler-plugin</artifactId>
+                <version>2.3.2</version>
                 <configuration>
                     <source>1.6</source>
                     <target>1.6</target>

File src/main/java/info/sunng/soldat/Protocol.java

  * @author Sun Ning <classicning@gmail.com>
  * 
  */
-public interface Protocol {
+public interface Protocol<I, O> {
 
     /**
      *
      */
     public boolean isMessageCompleted(byte[] buffer);
     
+    /**
+     * 
+     * @param buffer
+     * @return 
+     */
+    public I encode(byte[] buffer);
+    
+    /**
+     * 
+     * @param data
+     * @return 
+     */
+    public byte[] decode(O data);
+    
 }

File src/main/java/info/sunng/soldat/engines/PacketReader.java

                     logger.trace("packet read complete");
                 }
 
-                client.setInput(clientBuffer.toBytes());
+                Object encodedObject = client.getProtocol()
+                        .encode(clientBuffer.toBytes());
+                client.setInput(encodedObject);
                 
                 return client.getRead();
             }

File src/main/java/info/sunng/soldat/engines/PacketWriter.java

      * @return
      */
     public int write () throws IOException {
-        ByteBuffer buffer = (ByteBuffer)client.getOutput();
+        Object o = client.getOutput();
+        ByteBuffer buffer = ByteBuffer.wrap(client.getProtocol().decode(o));
         int write = 0;
         if(logger.isTraceEnabled()){
             logger.trace("packet begin to write");

File src/main/java/info/sunng/soldat/examples/echoserver/EchoHandler.java

 import info.sunng.soldat.HandleAdapter;
 import info.sunng.soldat.SoldatException;
 import info.sunng.soldat.engines.SoldatEngine;
-import java.io.UnsupportedEncodingException;
-import java.nio.ByteBuffer;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 
     @Override
     public void onMessageComplete(Client client) {
-        try {
-            byte[] request = (byte[])client.getInput();
-            String content = new String(request, "UTF-8");
-            if (logger.isDebugEnabled()){
-                logger.debug(content);
-            }
-            if (content.trim().equals("shutdown")) {
-                try {
-                    engine.shutdown();
-                } catch(SoldatException e) {}
-            } else if (content.trim().equals("bye")) {
-                // TODO
-            } else {
-                ByteBuffer response = ByteBuffer.wrap(content.getBytes("UTF-8"));
-                client.setOutput(response);
-            }
-        } catch (UnsupportedEncodingException e) {}
+        String content = (String)client.getInput();
+        if (logger.isDebugEnabled()){
+            logger.debug(content);
+        }
+        if (content.trim().equals("shutdown")) {
+            try {
+                engine.shutdown();
+            } catch(SoldatException e) {}
+        } else if (content.trim().equals("bye")) {
+            // TODO
+        } else {
+            client.setOutput(content);
+        }
     }
 
 }

File src/main/java/info/sunng/soldat/examples/echoserver/EchoProtocol.java

 package info.sunng.soldat.examples.echoserver;
 
 import info.sunng.soldat.Protocol;
-import java.nio.ByteBuffer;
+import java.nio.charset.Charset;
 
 /**
  *
  * @author Sun Ning
  *
  */
-public class EchoProtocol implements Protocol {
+public class EchoProtocol implements Protocol<String, String> {
 
     @Override
     public boolean isMessageCompleted(byte[] buffer) {
 
         int len = buffer.length;
-        System.out.println(new String(buffer));
 
         if (len < 2) {
             return false;
 
     }
 
+    @Override
+    public String encode(byte[] buffer) {
+        return new String(buffer, Charset.defaultCharset());
+    }
+
+    @Override
+    public byte[] decode(String data) {
+        return data.getBytes(Charset.defaultCharset());
+    }
+
 }

File src/main/java/info/sunng/soldat/examples/http/HttpProtocol.java

 package info.sunng.soldat.examples.http;
 
 import info.sunng.soldat.Protocol;
-import java.nio.ByteBuffer;
+import java.nio.charset.Charset;
 
 /**
  *
  * @author Sun Ning
  *
  */
-public class HttpProtocol implements Protocol {
+public class HttpProtocol implements Protocol<HttpMessage, String> {
 
     public HttpProtocol() {
         
         }
     }
 
+    @Override
+    public HttpMessage encode(byte[] buffer) {
+        return new HttpMessage(buffer);
+    }
+
+    @Override
+    public byte[] decode(String data) {
+        return data.getBytes(Charset.defaultCharset());
+    }
+
 }
 

File src/main/java/info/sunng/soldat/examples/http/HttpServerHandler.java

 import java.io.IOException;
 import java.io.PrintWriter;
 import java.io.StringWriter;
-import java.io.UnsupportedEncodingException;
-import java.nio.ByteBuffer;
 import java.util.Map;
 
 /**
     @Override
     public void onMessageComplete(Client client) {
 
-        byte[] requestBuffer = (byte[])client.getInput();
-        HttpMessage message  = new HttpMessage(requestBuffer);
+        HttpMessage message  = (HttpMessage)client.getInput();
         client.setAttachment(message);
 
         Map<String, String> headers = message.getHeaders();
         out.println(responseBody);
         out.println();
         
-        try {
-            client.setOutput(ByteBuffer.wrap(s.toString().getBytes("utf8")));
-        } catch (UnsupportedEncodingException ex) {
-            // ignore
-        }
+        client.setOutput(s.toString());
     }
 
     @Override

File src/main/java/info/sunng/soldat/examples/timeserver/TimeClient.java

-/*
- *  Copyright (c) 2010 Sun Ning <classicning@gmail.com>
- *  All rights reserved.
- * 
- *  Redistribution and use in source and binary forms, with or without
- *  modification, are permitted provided that the following conditions are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *  * Neither the name of the project nor the
- *    names of its contributors may be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- * 
- *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- *  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- *  DISCLAIMED. IN NO EVENT SHALL Sun Ning BE LIABLE FOR ANY
- *  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- */
-
-package info.sunng.soldat.examples.timeserver;
-
-import info.sunng.soldat.Client;
-import info.sunng.soldat.HandleAdapter;
-import info.sunng.soldat.Soldat;
-import info.sunng.soldat.SoldatException;
-import info.sunng.soldat.engines.SimpleConnectorEngine;
-import info.sunng.soldat.engines.SoldatEngine;
-import java.io.UnsupportedEncodingException;
-import java.net.InetSocketAddress;
-import java.nio.ByteBuffer;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- *
- * @author Sun Ning
- *
- */
-public class TimeClient {
-
-    /**
-     * 
-     * @param args
-     */
-    public static void main(String[] args) throws Exception {
-        final int port = 8705;
-
-        SoldatEngine engine = new SimpleConnectorEngine(
-                new InetSocketAddress(port), SoldatEngine.TransportType.UDP);
-        final Soldat s = new Soldat(engine);
-        s.setHandler(new HandleAdapter() {
-
-            @Override
-            public void onMessageComplete(Client client) {
-                try {
-                    ByteBuffer buffer = (ByteBuffer)client.getInput();
-                    System.out.println(new String(buffer.array(), "UTF-8"));
-                } catch (UnsupportedEncodingException ex) {
-                    Logger.getLogger(TimeClient.class.getName()).log(Level.SEVERE, null, ex);
-                }
-            }
-
-        });
-
-        s.setProtocol(new TimeProtocol());
-
-        Thread t = new Thread(new Runnable() {
-
-            @Override
-            public void run() {
-                try {
-                    s.start();
-                } catch (SoldatException ex) {
-                    Logger.getLogger(TimeClient.class.getName()).log(Level.SEVERE, null, ex);
-                }
-            }
-        });
-
-        t.start();
-
-        s.sendMessage(ByteBuffer.wrap(("Sunn\r\n").getBytes("UTF-8")), null);
-        
-        t.join();
-
-        
-
-    }
-
-}

File src/main/java/info/sunng/soldat/examples/timeserver/TimeHandler.java

-/*
- *  Copyright (c) 2010 Sun Ning <classicning@gmail.com>
- *  All rights reserved.
- * 
- *  Redistribution and use in source and binary forms, with or without
- *  modification, are permitted provided that the following conditions are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *  * Neither the name of the project nor the
- *    names of its contributors may be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- * 
- *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- *  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- *  DISCLAIMED. IN NO EVENT SHALL Sun Ning BE LIABLE FOR ANY
- *  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- */
-
-package info.sunng.soldat.examples.timeserver;
-
-import info.sunng.soldat.Client;
-import info.sunng.soldat.HandleAdapter;
-import java.nio.ByteBuffer;
-import java.util.Date;
-
-/**
- *
- * @author Sun Ning
- *
- */
-public class TimeHandler extends HandleAdapter {
-
-    @Override
-    public void onMessageComplete(Client client) {
-        try {
-            String data = new Date().toString()+"\r\n";
-            ByteBuffer buffer = ByteBuffer.wrap(data.getBytes("UTF-8"));
-            client.setOutput(buffer);
-        } catch (Exception e) {
-            
-        }
-    }
-
-}

File src/main/java/info/sunng/soldat/examples/timeserver/TimeProtocol.java

-/*
- *  Copyright (c) 2010 Sun Ning <classicning@gmail.com>
- *  All rights reserved.
- * 
- *  Redistribution and use in source and binary forms, with or without
- *  modification, are permitted provided that the following conditions are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *  * Neither the name of the project nor the
- *    names of its contributors may be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- * 
- *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- *  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- *  DISCLAIMED. IN NO EVENT SHALL Sun Ning BE LIABLE FOR ANY
- *  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- */
-
-package info.sunng.soldat.examples.timeserver;
-
-import info.sunng.soldat.examples.echoserver.*;
-import info.sunng.soldat.Protocol;
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-
-/**
- *
- * @author Sun Ning
- *
- */
-public class TimeProtocol implements Protocol {
-
-    @Override
-    public boolean isMessageCompleted(byte[] buffer) {
-
-        int length = buffer.length;
-
-        if (length < 2) {
-            return false;
-        } else {
-            char l1 = (char)buffer[length - 2];
-            char l2 = (char)buffer[length - 1];
-            return l1 == '\r' && l2 == '\n';
-        }
-
-//        buffer.rewind();
-//
-//        char l1 =0, l2=0;
-//        while (buffer.hasRemaining()) {
-//            l1 = l2;
-//            l2 = buffer.getChar();
-//        }
-
-    }
-
-}

File src/main/java/info/sunng/soldat/examples/timeserver/TimeServer.java

-/*
- *  Copyright (c) 2010 Sun Ning <classicning@gmail.com>
- *  All rights reserved.
- * 
- *  Redistribution and use in source and binary forms, with or without
- *  modification, are permitted provided that the following conditions are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *  * Neither the name of the project nor the
- *    names of its contributors may be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- * 
- *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- *  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- *  DISCLAIMED. IN NO EVENT SHALL Sun Ning BE LIABLE FOR ANY
- *  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- */
-
-package info.sunng.soldat.examples.timeserver;
-
-import info.sunng.soldat.Soldat;
-import info.sunng.soldat.SoldatException;
-import info.sunng.soldat.engines.SingleThreadAcceptorEngine;
-import info.sunng.soldat.engines.SoldatEngine;
-import java.net.InetSocketAddress;
-
-/**
- *
- * @author Sun Ning
- *
- */
-public class TimeServer {
-
-    public static void main (String[] args) throws Exception {
-        Thread serverThread = new Thread(new Runnable(){
-            @Override
-            public void run(){
-                try {
-                    InetSocketAddress addr = new InetSocketAddress(8705);
-                    final Soldat s = new Soldat(new SingleThreadAcceptorEngine(
-                            addr, SoldatEngine.TransportType.UDP));
-                    s.setHandler(new TimeHandler());
-                    s.setProtocol(new TimeProtocol());
-                    s.start();
-                } catch (SoldatException ex) {
-                    ex.printStackTrace();
-                }
-            }
-        });
-
-        serverThread.start();
-        serverThread.join();
-    }
-
-}

File src/main/resources/log4j.properties

-log4j.rootLogger=DEBUG, CONSOLE
+log4j.rootLogger=INFO, CONSOLE
 log4j.addivity.org.apache=true
 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout