001/*
002 *   Licensed to the Apache Software Foundation (ASF) under one
003 *   or more contributor license agreements.  See the NOTICE file
004 *   distributed with this work for additional information
005 *   regarding copyright ownership.  The ASF licenses this file
006 *   to you under the Apache License, Version 2.0 (the
007 *   "License"); you may not use this file except in compliance
008 *   with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 *   Unless required by applicable law or agreed to in writing,
013 *   software distributed under the License is distributed on an
014 *   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *   KIND, either express or implied.  See the License for the
016 *   specific language governing permissions and limitations
017 *   under the License.
018 *
019 */
020package org.apache.mina.example.imagine.step1.server;
021
022import org.apache.mina.core.service.IoHandlerAdapter;
023import org.apache.mina.core.session.IoSession;
024import org.apache.mina.example.imagine.step1.ImageRequest;
025import org.apache.mina.example.imagine.step1.ImageResponse;
026import org.slf4j.Logger;
027import org.slf4j.LoggerFactory;
028
029import java.awt.Color;
030import java.awt.Font;
031import java.awt.Graphics;
032import java.awt.image.BufferedImage;
033
034/**
035 * server-side {@link org.apache.mina.core.service.IoHandler}
036 *
037 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
038 */
039
040public class ImageServerIoHandler extends IoHandlerAdapter {
041
042    private final static String characters = "mina rocks abcdefghijklmnopqrstuvwxyz0123456789";
043
044    public static final String INDEX_KEY = ImageServerIoHandler.class.getName() + ".INDEX";
045
046    private static Logger LOGGER = LoggerFactory.getLogger(ImageServerIoHandler.class);
047
048    /**
049     * Called when the session is opened, which will come after the session created.
050     * 
051     * @see org.apache.mina.core.service.IoHandlerAdapter#sessionOpened(org.apache.mina.core.session.IoSession)
052     */
053    public void sessionOpened(IoSession session) throws Exception {
054        session.setAttribute(INDEX_KEY, 0);
055    }
056
057    /**
058     * This method will be called whenever an exception occurs.  For this handler,
059     * the logger will generate a warning message.
060     * 
061     * @see org.apache.mina.core.service.IoHandlerAdapter#exceptionCaught(org.apache.mina.core.session.IoSession, java.lang.Throwable)
062     */
063    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
064        LOGGER.warn(cause.getMessage(), cause);
065    }
066
067    /**
068     * Handle incoming messages.
069     * 
070     * @see org.apache.mina.core.service.IoHandlerAdapter#messageReceived(org.apache.mina.core.session.IoSession, java.lang.Object)
071     */
072    public void messageReceived(IoSession session, Object message) throws Exception {
073        ImageRequest request = (ImageRequest) message;
074        String text1 = generateString(session, request.getNumberOfCharacters());
075        String text2 = generateString(session, request.getNumberOfCharacters());
076        BufferedImage image1 = createImage(request, text1);
077        BufferedImage image2 = createImage(request, text2);
078        ImageResponse response = new ImageResponse(image1, image2);
079        session.write(response);
080    }
081
082    /**
083     * Create an image using the specified request and the text.  
084     *
085     * @param request
086     *  Determines the height and width of the image
087     * @param text
088     *  The text that is placed in the image
089     * @return
090     *  a BufferedImage representing the text.
091     */
092    private BufferedImage createImage(ImageRequest request, String text) {
093        BufferedImage image = new BufferedImage(request.getWidth(), request.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
094        Graphics graphics = image.createGraphics();
095        graphics.setColor(Color.YELLOW);
096        graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
097        Font serif = new Font("serif", Font.PLAIN, 30);
098        graphics.setFont(serif);
099        graphics.setColor(Color.BLUE);
100        graphics.drawString(text, 10, 50);
101        return image;
102    }
103
104    /**
105     * Generate a string based on the 'characters' field in this class.  The
106     * characters that make up the string are based on the session 
107     * attribute "INDEX_KEY"
108     *
109     * @param session
110     *  The {@link IoSession} object that will provide the INDEX_KEY attribute
111     * @param length
112     *  The length that the String will be
113     * @return
114     *  The generated String
115     */
116    private String generateString(IoSession session, int length) {
117        Integer index = (Integer) session.getAttribute(INDEX_KEY);
118        StringBuffer buffer = new StringBuffer(length);
119        while (buffer.length() < length) {
120            buffer.append(characters.charAt(index));
121            index++;
122            if (index >= characters.length()) {
123                index = 0;
124            }
125        }
126        session.setAttribute(INDEX_KEY, index);
127        return buffer.toString();
128    }
129
130}