View Javadoc

1   /*
2    *   Licensed to the Apache Software Foundation (ASF) under one
3    *   or more contributor license agreements.  See the NOTICE file
4    *   distributed with this work for additional information
5    *   regarding copyright ownership.  The ASF licenses this file
6    *   to you under the Apache License, Version 2.0 (the
7    *   "License"); you may not use this file except in compliance
8    *   with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *   Unless required by applicable law or agreed to in writing,
13   *   software distributed under the License is distributed on an
14   *   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *   KIND, either express or implied.  See the License for the
16   *   specific language governing permissions and limitations
17   *   under the License.
18   *
19   */
20  package org.apache.mina.example.imagine.step3.server;
21  
22  import java.awt.Color;
23  import java.awt.Font;
24  import java.awt.Graphics;
25  import java.awt.image.BufferedImage;
26  
27  import javax.management.MBeanServer;
28  import javax.management.ObjectName;
29  
30  import org.apache.mina.core.service.IoHandlerAdapter;
31  import org.apache.mina.core.session.IoSession;
32  import org.apache.mina.example.imagine.step1.ImageRequest;
33  import org.apache.mina.example.imagine.step1.ImageResponse;
34  import org.apache.mina.integration.jmx.IoSessionMBean;
35  import org.slf4j.Logger;
36  import org.slf4j.LoggerFactory;
37  
38  /**
39   * server-side {@link org.apache.mina.core.service.IoHandler}
40   *
41   * @author The Apache MINA Project (dev@mina.apache.org)
42   * @version $Rev$, $Date$
43   */
44  
45  public class ImageServerIoHandler extends IoHandlerAdapter {
46  
47      private final static String characters = "mina rocks abcdefghijklmnopqrstuvwxyz0123456789";
48  
49      public static final String INDEX_KEY = ImageServerIoHandler.class.getName() + ".INDEX";
50  
51      private Logger logger = LoggerFactory.getLogger(this.getClass());
52  
53      private MBeanServer mBeanServer;
54      
55      /**
56       * Creates a new instance of ImageServerIoHandler.  For this step, we pass in a reference
57       * to the MBeanServer.  This instance will be used to register new IoSession objects
58       * so that the JMX subsystem can report statistics on the sessions.
59       *
60       * @param mBeanServer
61       *  The JMX MBeanServer that will register the sessions
62       */
63      public ImageServerIoHandler( MBeanServer mBeanServer ) {
64          this.mBeanServer = mBeanServer;
65      }
66      
67      /**
68       * This method is called first when a new connection to the server is made.  In here we will set
69       * up the JMX session MBean.
70       * 
71       * @see org.apache.mina.core.service.IoHandlerAdapter#sessionCreated(org.apache.mina.core.session.IoSession)
72       */
73      public void sessionCreated( IoSession session ) throws Exception
74      {
75          // create a session MBean in order to load into the MBeanServer and allow
76          // this session to be managed by the JMX subsystem.
77          IoSessionMBean sessionMBean = new IoSessionMBean( session );
78          
79          // create a JMX ObjectName.  This has to be in a specific format.  
80          ObjectName sessionName = new ObjectName( session.getClass().getPackage().getName() + 
81              ":type=session,name=" + session.getClass().getSimpleName() + "-" + session.getId());
82          
83          // register the bean on the MBeanServer.  Without this line, no JMX will happen for
84          // this session
85          mBeanServer.registerMBean( sessionMBean, sessionName );
86      }
87  
88      /**
89       * Called when the session is opened, which will come after the session created.
90       * 
91       * @see org.apache.mina.core.service.IoHandlerAdapter#sessionOpened(org.apache.mina.core.session.IoSession)
92       */
93      public void sessionOpened(IoSession session) throws Exception {
94          
95          // set the index to zero.  This is used to determine how the build the
96          // string that is sent to the client.
97          session.setAttribute(INDEX_KEY, 0);
98      }
99  
100     /**
101      * This method will be called whenever an exception occurs.  For this handler,
102      * the logger will generate a warning message.
103      * 
104      * @see org.apache.mina.core.service.IoHandlerAdapter#exceptionCaught(org.apache.mina.core.session.IoSession, java.lang.Throwable)
105      */
106     public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
107         logger.warn(cause.getMessage(), cause);
108     }
109 
110     /**
111      * Handle incoming messages.
112      * 
113      * @see org.apache.mina.core.service.IoHandlerAdapter#messageReceived(org.apache.mina.core.session.IoSession, java.lang.Object)
114      */
115     public void messageReceived(IoSession session, Object message) throws Exception {
116         ImageRequest request = (ImageRequest) message;
117         String text1 = generateString(session, request.getNumberOfCharacters());
118         String text2 = generateString(session, request.getNumberOfCharacters());
119         BufferedImage image1 = createImage(request, text1);
120         BufferedImage image2 = createImage(request, text2);
121         ImageResponse response = new ImageResponse(image1, image2);
122         session.write(response);
123     }
124 
125     /**
126      * Create an image using the specified request and the text.  
127      *
128      * @param request
129      *  Determines the height and width of the image
130      * @param text
131      *  The text that is placed in the image
132      * @return
133      *  a BufferedImage representing the text.
134      */
135     private BufferedImage createImage(ImageRequest request, String text) {
136         BufferedImage image = new BufferedImage(request.getWidth(), request.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
137         Graphics graphics = image.createGraphics();
138         graphics.setColor(Color.YELLOW);
139         graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
140         Font serif = new Font("serif", Font.PLAIN, 30);
141         graphics.setFont(serif);
142         graphics.setColor(Color.BLUE);
143         graphics.drawString(text, 10, 50);
144         return image;
145     }
146 
147     /**
148      * Generate a string based on the 'characters' field in this class.  The
149      * characters that make up the string are based on the session 
150      * attribute "INDEX_KEY"
151      *
152      * @param session
153      *  The {@link IoSession} object that will provide the INDEX_KEY attribute
154      * @param length
155      *  The length that the String will be
156      * @return
157      *  The generated String
158      */
159     private String generateString(IoSession session, int length) {
160         Integer index = (Integer) session.getAttribute(INDEX_KEY);
161         StringBuffer buffer = new StringBuffer(length);
162         while (buffer.length() < length) {
163             buffer.append(characters.charAt(index));
164             index++;
165             if (index >= characters.length()) {
166                 index = 0;
167             }
168         }
169         session.setAttribute(INDEX_KEY, index);
170         return buffer.toString();
171     }
172 
173 }