SlideShare a Scribd company logo
1 of 36
Download to read offline
RAPID NETWORK APPLICATION DEVELOPMENT
          WITH APACHE MINA

Trustin Lee
Principal Software Engineer
Red Hat, Inc.
TS-4814
Learn how to build:
scalable, stable, maintainable and manageable
network applications utilizing any protocol
with Apache MINA




                               2008 JavaOneSM Conference | java.sun.com/javaone |   2
Agenda
Before the adventure...
  Presenter
  Introduction
  Core Components
  Management
  Future
  Summary




                          2008 JavaOneSM Conference | java.sun.com/javaone |   3
Presenter
Who is Trustin Lee?
 Founder of Netty framework
 Cofounder and VP of Apache MINA
 JBoss Remoting project lead
 Wrote Java™ New I/O API (NIO)-based massive network
 applications
  • Distributed SMS gateway – 10M msgs / day
  • OSGi-based asynchronous RPC server with Hessian protocol
 Didn't write a book yet! ;)


                                                 2008 JavaOneSM Conference | java.sun.com/javaone |   4
Agenda
What, Why and How?
 Presenter
 Introduction
 Core Components
 Management
 Future
 Summary




                     2008 JavaOneSM Conference | java.sun.com/javaone |   5
Introduction
What is Apache MINA?
 A Java open-source network application framework
 Abstract API
  • Event-driven
  • Asynchronous
  • Unit-testable
 Implementations
  • Sockets & datagrams – Java NIO & APR via Tomcat Native
  • Serial ports – RXTX.org
  • In-VM pipes
  • <Your favorite transports here: SCTP, multicast, Infiniband...>


                                                    2008 JavaOneSM Conference | java.sun.com/javaone |   6
Introduction
Why should I use it?
  Maintainable and reusable
  • Networking engine – MINA I/O service
  • Protocol codec – MINA codec framework
  • Your business logic
  Extensible
   • Runtime modification of application behavior using 'filters'
  Manageable
  • Introspection of connections and services via JMX™ API
  Unit-testable
   • Abstract API
   • Out-of-the-box mock objects

                                                     2008 JavaOneSM Conference | java.sun.com/javaone |   7
Introduction                    Remote Peer
What does it look like?
                                I/O Service
  Performs actual I/O


  Filters events & requests   I/O Filter Chain
                                 I/O Filter #1
                                 I/O Filter #2

                                 I/O Filter #3

  A connection
                                     I/O Session
  <Your protocol logic>        I/O Handler
                                    2008 JavaOneSM Conference | java.sun.com/javaone |   8
Agenda
Let’s learn by looking at examples!
  Presenter
  Introduction
  Core Components
  Management
  Future
  Summary




                                      2008 JavaOneSM Conference | java.sun.com/javaone |   9
IoSession & IoBuffer
Writing a message was never easier than this.
  // Build a string to send.
  CharsetEncoder = ...;
  IoSession session = ...;
  IoBuffer buffer = IoBuffer.allocate(16);
  buffer.setAutoExpand(true)
        .putString(quot;It is quot;, encoder)
        .putString(new Date().toString(), encoder)
        .putString(quot; now.rnquot;, encoder).flip();

  // Asynchronous write request.
  session.write(buffer);




                                       2008 JavaOneSM Conference | java.sun.com/javaone |   10
IoSession
Connection, Socket, Channel...
 Abstracts a underlying transport’s connection away
 Provides asynchronous operations to I/O service
  • Write, close...
  • All asynchronous
  • Returns IoFuture (WriteFuture, CloseFuture...)
     • A set of IoFutureListener can be added for notification

 Provides I/O statistics
  • Read bytes, written bytes, last I/O time...




                                                         2008 JavaOneSM Conference | java.sun.com/javaone |   11
IoBuffer
Why don’t you just use NIO ByteBuffer?
 Rich binary & text manipulation methods
  • Unsigned value, enum, string, Java Object...
 On-demand automatic expansion and shrinkage
 More control over allocation mechanism
 More extensible than ByteBuffer
  • provides all methods in ByteBuffer
  • provides easy wrap · unwrap methods




                                                   2008 JavaOneSM Conference | java.sun.com/javaone |   12
IoHandler
Let’s write back what’s received.
  public class EchoHandler implements IoHandler {
    public void messageReceived(IoSession s, Object msg)
    {
      IoBuffer buffer = (IoBuffer) msg;
      s.write(buffer.duplicate());
    }

      public void exceptionCaught(IoSession s, Throwable e)
      {
        s.close();
      }

      public   void   sessionOpened(IoSession s) {}
      public   void   messageSent(IoSession s, Object msg) {}
      public   void   sessionIdle(IoSession s, IdleStatus stat) {}
      public   void   sessionClosed(IoSession s) {}
  }


                                              2008 JavaOneSM Conference | java.sun.com/javaone |   13
IoService
IoAcceptor is for the server side.
  public class Main {
    public static void main(String[] args) ...
    {
      IoAcceptor acceptor = new NioSocketAcceptor();
      acceptor.setHandler(new EchoHandler());
      acceptor.bind(new InetSocketAddress(8080));
      ...
      acceptor.unbind(new InetSocketAddress(8080));
    }
  }




                                     2008 JavaOneSM Conference | java.sun.com/javaone |   14
IoService
IoConnector is for the client side.
  public class Main {
    public static void main(String[] args) ...
    {
      IoConnector connector = new NioSocketConnector();
      connector.setHandler(new MyHandler());
      ConnectFuture future = connector.connect(
          new InetSocketAddress(quot;example.comquot;, 8080));

          IoSession session = future.await().getSession();

          session.write(...).await();         // WriteFuture
          session.close().await();            // CloseFuture
      }
  }



                                        2008 JavaOneSM Conference | java.sun.com/javaone |   15
IoService
Switching to a different transport was never easier than this.

  IoAcceptor acceptor = new NioSocketAcceptor();
  IoAcceptor acceptor = new AprSocketAcceptor();
  ...

  IoConnector connector      = new NioSocketConnector();
  IoConnector connector      = new SerialConnector();
  ...
  connector.connect(new      InetSocketAddress(...));
  connector.connect(new      SerialAddress(...));
  ...




                                            2008 JavaOneSM Conference | java.sun.com/javaone |   16
IoFilterChain & IoFilter
Imagine hot-deployable Servlet filters.
  // Enable logging.
  acceptor.getFilterChain().addLast(
          quot;loggerquot;, new LoggingFilter());

  // Enable SSL.
  acceptor.getFilterChain().addLast(
          quot;sslquot;, new SslFilter());

  // Enable compression for an individual session.
  session.getFilterChain().addBefore(
          quot;sslquot;, quot;compressorquot;,
          new CompressionFilter());

  // Zap all of them.
  session.getFilterChain().clear();

                                          2008 JavaOneSM Conference | java.sun.com/javaone |   17
IoFilter
One-stop solution for cross-cutting concerns:
  Logging
  Overload prevention
  Failure injection
  On-demand profiler
  Remote peer blacklisting
  Keep-alive · timeout
  More to come – whatever you want to intercept!



                                          2008 JavaOneSM Conference | java.sun.com/javaone |   18
Protocol Codecs
Why do we need a protocol codec?
 It is a bad idea to implement a protocol only with IoBuffers.
  • Packet fragmentation and assembly
  • Separation of concerns
 Codecs are often reusable – MINA provides:
  • Text line codec
  • Object stream codec
  • HTTP codec
 MINA also provides reusable components to build a codec.
 • Solutions for packet fragmentation and assembly issue
 • Finite state machine framework dedicated to codec construction
 • Support for multi-layered protocol (e.g. Kerberos)

                                               2008 JavaOneSM Conference | java.sun.com/javaone |   19
Protocol Codecs
What does it look like with a protocol codec?
                                    Remote Peer


                                   I/O Service
        POJO → IoBuffer
                                 I/O Filter Chain
       ProtocolCodecFactory
        ProtocolEncoder
                                ProtocolCodecFilter
        ProtocolDecoder

        IoBuffer → POJO
                                       I/O Session
                                   I/O Handler

                                         2008 JavaOneSM Conference | java.sun.com/javaone |   20
Protocol Codecs
Echo server redux – TextLineProtocolCodecFactory kicks in!
  public class EchoHandler extends IoHandlerAdapter
  {
    public void messageReceived(IoSession s, Object m)
    {
      s.write((String) m);
    }
    ...
  }
  ...
  acceptor.getFilterChain().addLast(
        quot;codecquot;, new ProtocolCodecFilter(
                         new TextLineCodecFactory()));
  ...




                                       2008 JavaOneSM Conference | java.sun.com/javaone |   21
Protocol Codecs
Custom AJAX-ready HTTP server in 10 minutes!?
  public class HttpHandler extends IoHandlerAdapter {
    public void messageReceived(IoSession s, Object msg)
    {
      HttpRequest req = (HttpRequest) msg;
      MutableHttpResponse res = new DefaultHttpResponse();
      IoBuffer content = ...;
      res.setContent(content);
      res.normalize(req);
      s.write(res);
    }
  }
  ...
  acceptor.getFilterChain().addLast(
         quot;codecquot;, new ProtocolCodecFilter(
                new HttpProtocolCodecFactoryFactory()));
  ...



                                        2008 JavaOneSM Conference | java.sun.com/javaone |   22
Thread Models
It’s as easy as inserting an IoFilter.
  // Single thread model by default.
  ...

  // One thread pool – suitable for typical servers.
  //// Place CPU-bound tasks first,
  acceptor.getFilterChain().addLast(quot;compressionquot;, ...);
  acceptor.getFilterChain().addLast(quot;codecquot;, ...);

  //// And then thread pool.
  acceptor.getFilterChain().addLast(
         “executor”, new ExecutorFilter(
                new OrderedThreadPoolExecutor(16)));

  //// Use UnorderedThreadPoolExecutor or your favorite
  //// Executor instance if you don't want event ordering.



                                         2008 JavaOneSM Conference | java.sun.com/javaone |   23
Agenda
JMX integration – brain-dead easy!
 Presenter
 Introduction
 Core Components
 Management
 Future
 Summary




                                     2008 JavaOneSM Conference | java.sun.com/javaone |   24
Management
IoService, IoSession and IoFilter are exposed as JMX MBean.

  MBeanServer mbs = ...;

  mbs.registerMBean(new IoServiceMBean(acceptor),
                    new ObjectName(...));

  mbs.registerMBean(new IoSessionMBean(session),
                    new ObjectName(...));

  mbs.registerMBean(new IoFilterMBean(executorFilter),
                    new ObjectName(...));




                                       2008 JavaOneSM Conference | java.sun.com/javaone |   25
Management
What you can do in runtime with MINA MBeans:
 Monitor various performance counters
 Adjust all socket parameters
 Start · stop an IoService
 Modify an IoSession based on OGNL expression
 • Find all session originating from '192.168.0.x' and close them all!
 Insertion and removal of an IoFilter
  • Enable or disable whatever on demand!
     • Logging
     • Profiling
     • Changing thread model


                                                    2008 JavaOneSM Conference | java.sun.com/javaone |   26
2008 JavaOneSM Conference | java.sun.com/javaone |   27
2008 JavaOneSM Conference | java.sun.com/javaone |   28
2008 JavaOneSM Conference | java.sun.com/javaone |   29
2008 JavaOneSM Conference | java.sun.com/javaone |   30
Agenda
A lot more to come!
 Presenter
 Introduction
 Core Components
 Management
 Future
 Summary




                      2008 JavaOneSM Conference | java.sun.com/javaone |   31
Future
Major tasks ahead:
 Zero copy I/O
  • Looking for better alternative to IoBuffer
 IoConnector improvements
  • Proxy support – patch pending
  • Automatic reconnection
 Better documentation
 Protocol codec generator
  • Rapid legacy & new protocol implementation
 Tools based on a protocol codec implementation
  • Protocol analyzing proxy
  • Intelligent L7 switch & firewall
                                                 2008 JavaOneSM Conference | java.sun.com/javaone |   32
Agenda
So, what’s the verdict?
  Presenter
  Introduction
  Core Components
  Management
  Future
  Summary




                          2008 JavaOneSM Conference | java.sun.com/javaone |   33
Summary
Apache MINA is designed exactly for:
 Any kind of network applications
  • Stable
  • Scalable
  • Extensible
  • Manageable
  • Unit-testable
 Simple, complex, text, binary, legacy and evolving protocols
 You got to try it now! ;)




                                           2008 JavaOneSM Conference | java.sun.com/javaone |   34
For More Information
Vibrant community – that's what we are.
              MINA.apache.org
 WWW –
              users@mina.apache.org
 E-mail –
              trustin@apache.org (me)


 Please talk to me right after this session.




                                               2008 JavaOneSM Conference | java.sun.com/javaone |   35
Trustin Lee
Principal Software Engineer
Red Hat, Inc.
TS-4814




                              2008 JavaOneSM Conference | java.sun.com/javaone |   36

More Related Content

What's hot

Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
priyank09
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
knight1128
 
Jersey framework
Jersey frameworkJersey framework
Jersey framework
knight1128
 
Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능
knight1128
 

What's hot (20)

Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in Java
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
JVM
JVMJVM
JVM
 
Jersey framework
Jersey frameworkJersey framework
Jersey framework
 
Maximize the power of OSGi
Maximize the power of OSGiMaximize the power of OSGi
Maximize the power of OSGi
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 
Commons Pool and DBCP
Commons Pool and DBCPCommons Pool and DBCP
Commons Pool and DBCP
 
Java adv
Java advJava adv
Java adv
 
How to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsHow to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applications
 
What`s new in Java 7
What`s new in Java 7What`s new in Java 7
What`s new in Java 7
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class (DeepSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (DeepSec Edition)Java Deserialization Vulnerabilities - The Forgotten Bug Class (DeepSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (DeepSec Edition)
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitter
 
Java RMI
Java RMIJava RMI
Java RMI
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능
 
OSGi Presentation
OSGi PresentationOSGi Presentation
OSGi Presentation
 
nullcon 2010 - Software Fuzzing with Wireplay
nullcon 2010 - Software Fuzzing with Wireplaynullcon 2010 - Software Fuzzing with Wireplay
nullcon 2010 - Software Fuzzing with Wireplay
 

Viewers also liked

Apache Mina
Apache MinaApache Mina
Apache Mina
lake xie
 
Building High Performance Scalable TCP/IP Servers with Apache MINA
Building High Performance Scalable TCP/IP Servers with Apache MINABuilding High Performance Scalable TCP/IP Servers with Apache MINA
Building High Performance Scalable TCP/IP Servers with Apache MINA
elliando dias
 

Viewers also liked (7)

Mina2
Mina2Mina2
Mina2
 
Apache Mina
Apache MinaApache Mina
Apache Mina
 
Apache MINA: The high-performance protocol construction toolkit.
Apache MINA: The high-performance protocol construction toolkit.Apache MINA: The high-performance protocol construction toolkit.
Apache MINA: The high-performance protocol construction toolkit.
 
Introduction to Apache MINA
Introduction to Apache MINAIntroduction to Apache MINA
Introduction to Apache MINA
 
NIO 2
NIO 2NIO 2
NIO 2
 
Nio sur Netty par Mouhcine Moulou - 3 avril 2014
Nio sur Netty par Mouhcine Moulou - 3 avril 2014Nio sur Netty par Mouhcine Moulou - 3 avril 2014
Nio sur Netty par Mouhcine Moulou - 3 avril 2014
 
Building High Performance Scalable TCP/IP Servers with Apache MINA
Building High Performance Scalable TCP/IP Servers with Apache MINABuilding High Performance Scalable TCP/IP Servers with Apache MINA
Building High Performance Scalable TCP/IP Servers with Apache MINA
 

Similar to Rapid Network Application Development with Apache MINA

Similar to Rapid Network Application Development with Apache MINA (20)

NIO-Grizly.pdf
NIO-Grizly.pdfNIO-Grizly.pdf
NIO-Grizly.pdf
 
What is Java? Presentation On Introduction To Core Java By PSK Technologies
What is Java? Presentation On Introduction To Core Java By PSK TechnologiesWhat is Java? Presentation On Introduction To Core Java By PSK Technologies
What is Java? Presentation On Introduction To Core Java By PSK Technologies
 
Java one 2010
Java one 2010Java one 2010
Java one 2010
 
Open Source XMPP for Cloud Services
Open Source XMPP for Cloud ServicesOpen Source XMPP for Cloud Services
Open Source XMPP for Cloud Services
 
Socket.io
Socket.ioSocket.io
Socket.io
 
Java EE 6 & Spring: A Lover's Quarrel
Java EE 6 & Spring: A Lover's QuarrelJava EE 6 & Spring: A Lover's Quarrel
Java EE 6 & Spring: A Lover's Quarrel
 
Faster & Greater Messaging System HornetQ zzz
Faster & Greater Messaging System HornetQ zzzFaster & Greater Messaging System HornetQ zzz
Faster & Greater Messaging System HornetQ zzz
 
Java Cloud and Container Ready
Java Cloud and Container ReadyJava Cloud and Container Ready
Java Cloud and Container Ready
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
Java EE 7 - Overview and Status
Java EE 7  - Overview and StatusJava EE 7  - Overview and Status
Java EE 7 - Overview and Status
 
Tuning and development with SIP Servlets on Mobicents
Tuning and development with SIP Servlets on MobicentsTuning and development with SIP Servlets on Mobicents
Tuning and development with SIP Servlets on Mobicents
 
It pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_enIt pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_en
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Owin and Katana
Owin and KatanaOwin and Katana
Owin and Katana
 
Windows Azure Interoperability
Windows Azure InteroperabilityWindows Azure Interoperability
Windows Azure Interoperability
 
ASML_FlightRecorderMeetsJava.pdf
ASML_FlightRecorderMeetsJava.pdfASML_FlightRecorderMeetsJava.pdf
ASML_FlightRecorderMeetsJava.pdf
 
Windows Server 2008 for Developers - Part 2
Windows Server 2008 for Developers - Part 2Windows Server 2008 for Developers - Part 2
Windows Server 2008 for Developers - Part 2
 
Java ee 7 New Features
Java ee 7   New FeaturesJava ee 7   New Features
Java ee 7 New Features
 
Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applications
 
Pure Java RAD and Scaffolding Tools Race
Pure Java RAD and Scaffolding Tools RacePure Java RAD and Scaffolding Tools Race
Pure Java RAD and Scaffolding Tools Race
 

More from trustinlee

WebSocket 기반 쌍방향 메시징
WebSocket 기반 쌍방향 메시징WebSocket 기반 쌍방향 메시징
WebSocket 기반 쌍방향 메시징
trustinlee
 

More from trustinlee (8)

WebSocket 기반 쌍방향 메시징
WebSocket 기반 쌍방향 메시징WebSocket 기반 쌍방향 메시징
WebSocket 기반 쌍방향 메시징
 
사용자 경험 극대화를 위한 웹 서버 아키텍처
사용자 경험 극대화를 위한 웹 서버 아키텍처사용자 경험 극대화를 위한 웹 서버 아키텍처
사용자 경험 극대화를 위한 웹 서버 아키텍처
 
APIviz – Java API Visualizer
APIviz – Java API VisualizerAPIviz – Java API Visualizer
APIviz – Java API Visualizer
 
Apache MINA를 사용한 네트워크 어플리케이션 개발
Apache MINA를 사용한 네트워크 어플리케이션 개발Apache MINA를 사용한 네트워크 어플리케이션 개발
Apache MINA를 사용한 네트워크 어플리케이션 개발
 
자바 네트워킹 기초에서 응용까지
자바 네트워킹 기초에서 응용까지자바 네트워킹 기초에서 응용까지
자바 네트워킹 기초에서 응용까지
 
JBoss Middleware 및 Remoting 프로젝트 소개
JBoss Middleware 및 Remoting 프로젝트 소개JBoss Middleware 및 Remoting 프로젝트 소개
JBoss Middleware 및 Remoting 프로젝트 소개
 
오픈 소스 프로젝트 참여를 통한 개발자 커리어 관리
오픈 소스 프로젝트 참여를 통한 개발자 커리어 관리오픈 소스 프로젝트 참여를 통한 개발자 커리어 관리
오픈 소스 프로젝트 참여를 통한 개발자 커리어 관리
 
오픈 소스 소개
오픈 소스 소개오픈 소스 소개
오픈 소스 소개
 

Recently uploaded

Recently uploaded (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

Rapid Network Application Development with Apache MINA

  • 1. RAPID NETWORK APPLICATION DEVELOPMENT WITH APACHE MINA Trustin Lee Principal Software Engineer Red Hat, Inc. TS-4814
  • 2. Learn how to build: scalable, stable, maintainable and manageable network applications utilizing any protocol with Apache MINA 2008 JavaOneSM Conference | java.sun.com/javaone | 2
  • 3. Agenda Before the adventure... Presenter Introduction Core Components Management Future Summary 2008 JavaOneSM Conference | java.sun.com/javaone | 3
  • 4. Presenter Who is Trustin Lee? Founder of Netty framework Cofounder and VP of Apache MINA JBoss Remoting project lead Wrote Java™ New I/O API (NIO)-based massive network applications • Distributed SMS gateway – 10M msgs / day • OSGi-based asynchronous RPC server with Hessian protocol Didn't write a book yet! ;) 2008 JavaOneSM Conference | java.sun.com/javaone | 4
  • 5. Agenda What, Why and How? Presenter Introduction Core Components Management Future Summary 2008 JavaOneSM Conference | java.sun.com/javaone | 5
  • 6. Introduction What is Apache MINA? A Java open-source network application framework Abstract API • Event-driven • Asynchronous • Unit-testable Implementations • Sockets & datagrams – Java NIO & APR via Tomcat Native • Serial ports – RXTX.org • In-VM pipes • <Your favorite transports here: SCTP, multicast, Infiniband...> 2008 JavaOneSM Conference | java.sun.com/javaone | 6
  • 7. Introduction Why should I use it? Maintainable and reusable • Networking engine – MINA I/O service • Protocol codec – MINA codec framework • Your business logic Extensible • Runtime modification of application behavior using 'filters' Manageable • Introspection of connections and services via JMX™ API Unit-testable • Abstract API • Out-of-the-box mock objects 2008 JavaOneSM Conference | java.sun.com/javaone | 7
  • 8. Introduction Remote Peer What does it look like? I/O Service Performs actual I/O Filters events & requests I/O Filter Chain I/O Filter #1 I/O Filter #2 I/O Filter #3 A connection I/O Session <Your protocol logic> I/O Handler 2008 JavaOneSM Conference | java.sun.com/javaone | 8
  • 9. Agenda Let’s learn by looking at examples! Presenter Introduction Core Components Management Future Summary 2008 JavaOneSM Conference | java.sun.com/javaone | 9
  • 10. IoSession & IoBuffer Writing a message was never easier than this. // Build a string to send. CharsetEncoder = ...; IoSession session = ...; IoBuffer buffer = IoBuffer.allocate(16); buffer.setAutoExpand(true) .putString(quot;It is quot;, encoder) .putString(new Date().toString(), encoder) .putString(quot; now.rnquot;, encoder).flip(); // Asynchronous write request. session.write(buffer); 2008 JavaOneSM Conference | java.sun.com/javaone | 10
  • 11. IoSession Connection, Socket, Channel... Abstracts a underlying transport’s connection away Provides asynchronous operations to I/O service • Write, close... • All asynchronous • Returns IoFuture (WriteFuture, CloseFuture...) • A set of IoFutureListener can be added for notification Provides I/O statistics • Read bytes, written bytes, last I/O time... 2008 JavaOneSM Conference | java.sun.com/javaone | 11
  • 12. IoBuffer Why don’t you just use NIO ByteBuffer? Rich binary & text manipulation methods • Unsigned value, enum, string, Java Object... On-demand automatic expansion and shrinkage More control over allocation mechanism More extensible than ByteBuffer • provides all methods in ByteBuffer • provides easy wrap · unwrap methods 2008 JavaOneSM Conference | java.sun.com/javaone | 12
  • 13. IoHandler Let’s write back what’s received. public class EchoHandler implements IoHandler { public void messageReceived(IoSession s, Object msg) { IoBuffer buffer = (IoBuffer) msg; s.write(buffer.duplicate()); } public void exceptionCaught(IoSession s, Throwable e) { s.close(); } public void sessionOpened(IoSession s) {} public void messageSent(IoSession s, Object msg) {} public void sessionIdle(IoSession s, IdleStatus stat) {} public void sessionClosed(IoSession s) {} } 2008 JavaOneSM Conference | java.sun.com/javaone | 13
  • 14. IoService IoAcceptor is for the server side. public class Main { public static void main(String[] args) ... { IoAcceptor acceptor = new NioSocketAcceptor(); acceptor.setHandler(new EchoHandler()); acceptor.bind(new InetSocketAddress(8080)); ... acceptor.unbind(new InetSocketAddress(8080)); } } 2008 JavaOneSM Conference | java.sun.com/javaone | 14
  • 15. IoService IoConnector is for the client side. public class Main { public static void main(String[] args) ... { IoConnector connector = new NioSocketConnector(); connector.setHandler(new MyHandler()); ConnectFuture future = connector.connect( new InetSocketAddress(quot;example.comquot;, 8080)); IoSession session = future.await().getSession(); session.write(...).await(); // WriteFuture session.close().await(); // CloseFuture } } 2008 JavaOneSM Conference | java.sun.com/javaone | 15
  • 16. IoService Switching to a different transport was never easier than this. IoAcceptor acceptor = new NioSocketAcceptor(); IoAcceptor acceptor = new AprSocketAcceptor(); ... IoConnector connector = new NioSocketConnector(); IoConnector connector = new SerialConnector(); ... connector.connect(new InetSocketAddress(...)); connector.connect(new SerialAddress(...)); ... 2008 JavaOneSM Conference | java.sun.com/javaone | 16
  • 17. IoFilterChain & IoFilter Imagine hot-deployable Servlet filters. // Enable logging. acceptor.getFilterChain().addLast( quot;loggerquot;, new LoggingFilter()); // Enable SSL. acceptor.getFilterChain().addLast( quot;sslquot;, new SslFilter()); // Enable compression for an individual session. session.getFilterChain().addBefore( quot;sslquot;, quot;compressorquot;, new CompressionFilter()); // Zap all of them. session.getFilterChain().clear(); 2008 JavaOneSM Conference | java.sun.com/javaone | 17
  • 18. IoFilter One-stop solution for cross-cutting concerns: Logging Overload prevention Failure injection On-demand profiler Remote peer blacklisting Keep-alive · timeout More to come – whatever you want to intercept! 2008 JavaOneSM Conference | java.sun.com/javaone | 18
  • 19. Protocol Codecs Why do we need a protocol codec? It is a bad idea to implement a protocol only with IoBuffers. • Packet fragmentation and assembly • Separation of concerns Codecs are often reusable – MINA provides: • Text line codec • Object stream codec • HTTP codec MINA also provides reusable components to build a codec. • Solutions for packet fragmentation and assembly issue • Finite state machine framework dedicated to codec construction • Support for multi-layered protocol (e.g. Kerberos) 2008 JavaOneSM Conference | java.sun.com/javaone | 19
  • 20. Protocol Codecs What does it look like with a protocol codec? Remote Peer I/O Service POJO → IoBuffer I/O Filter Chain ProtocolCodecFactory ProtocolEncoder ProtocolCodecFilter ProtocolDecoder IoBuffer → POJO I/O Session I/O Handler 2008 JavaOneSM Conference | java.sun.com/javaone | 20
  • 21. Protocol Codecs Echo server redux – TextLineProtocolCodecFactory kicks in! public class EchoHandler extends IoHandlerAdapter { public void messageReceived(IoSession s, Object m) { s.write((String) m); } ... } ... acceptor.getFilterChain().addLast( quot;codecquot;, new ProtocolCodecFilter( new TextLineCodecFactory())); ... 2008 JavaOneSM Conference | java.sun.com/javaone | 21
  • 22. Protocol Codecs Custom AJAX-ready HTTP server in 10 minutes!? public class HttpHandler extends IoHandlerAdapter { public void messageReceived(IoSession s, Object msg) { HttpRequest req = (HttpRequest) msg; MutableHttpResponse res = new DefaultHttpResponse(); IoBuffer content = ...; res.setContent(content); res.normalize(req); s.write(res); } } ... acceptor.getFilterChain().addLast( quot;codecquot;, new ProtocolCodecFilter( new HttpProtocolCodecFactoryFactory())); ... 2008 JavaOneSM Conference | java.sun.com/javaone | 22
  • 23. Thread Models It’s as easy as inserting an IoFilter. // Single thread model by default. ... // One thread pool – suitable for typical servers. //// Place CPU-bound tasks first, acceptor.getFilterChain().addLast(quot;compressionquot;, ...); acceptor.getFilterChain().addLast(quot;codecquot;, ...); //// And then thread pool. acceptor.getFilterChain().addLast( “executor”, new ExecutorFilter( new OrderedThreadPoolExecutor(16))); //// Use UnorderedThreadPoolExecutor or your favorite //// Executor instance if you don't want event ordering. 2008 JavaOneSM Conference | java.sun.com/javaone | 23
  • 24. Agenda JMX integration – brain-dead easy! Presenter Introduction Core Components Management Future Summary 2008 JavaOneSM Conference | java.sun.com/javaone | 24
  • 25. Management IoService, IoSession and IoFilter are exposed as JMX MBean. MBeanServer mbs = ...; mbs.registerMBean(new IoServiceMBean(acceptor), new ObjectName(...)); mbs.registerMBean(new IoSessionMBean(session), new ObjectName(...)); mbs.registerMBean(new IoFilterMBean(executorFilter), new ObjectName(...)); 2008 JavaOneSM Conference | java.sun.com/javaone | 25
  • 26. Management What you can do in runtime with MINA MBeans: Monitor various performance counters Adjust all socket parameters Start · stop an IoService Modify an IoSession based on OGNL expression • Find all session originating from '192.168.0.x' and close them all! Insertion and removal of an IoFilter • Enable or disable whatever on demand! • Logging • Profiling • Changing thread model 2008 JavaOneSM Conference | java.sun.com/javaone | 26
  • 27. 2008 JavaOneSM Conference | java.sun.com/javaone | 27
  • 28. 2008 JavaOneSM Conference | java.sun.com/javaone | 28
  • 29. 2008 JavaOneSM Conference | java.sun.com/javaone | 29
  • 30. 2008 JavaOneSM Conference | java.sun.com/javaone | 30
  • 31. Agenda A lot more to come! Presenter Introduction Core Components Management Future Summary 2008 JavaOneSM Conference | java.sun.com/javaone | 31
  • 32. Future Major tasks ahead: Zero copy I/O • Looking for better alternative to IoBuffer IoConnector improvements • Proxy support – patch pending • Automatic reconnection Better documentation Protocol codec generator • Rapid legacy & new protocol implementation Tools based on a protocol codec implementation • Protocol analyzing proxy • Intelligent L7 switch & firewall 2008 JavaOneSM Conference | java.sun.com/javaone | 32
  • 33. Agenda So, what’s the verdict? Presenter Introduction Core Components Management Future Summary 2008 JavaOneSM Conference | java.sun.com/javaone | 33
  • 34. Summary Apache MINA is designed exactly for: Any kind of network applications • Stable • Scalable • Extensible • Manageable • Unit-testable Simple, complex, text, binary, legacy and evolving protocols You got to try it now! ;) 2008 JavaOneSM Conference | java.sun.com/javaone | 34
  • 35. For More Information Vibrant community – that's what we are. MINA.apache.org WWW – users@mina.apache.org E-mail – trustin@apache.org (me) Please talk to me right after this session. 2008 JavaOneSM Conference | java.sun.com/javaone | 35
  • 36. Trustin Lee Principal Software Engineer Red Hat, Inc. TS-4814 2008 JavaOneSM Conference | java.sun.com/javaone | 36