com.digisky.outerproxy.server.OuterProxyHttpServerHandler.java Source code

Java tutorial

Introduction

Here is the source code for com.digisky.outerproxy.server.OuterProxyHttpServerHandler.java

Source

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project 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 com.digisky.outerproxy.server;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Random;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.multipart.FileUpload;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;

import com.alibaba.fastjson.JSONObject;
import com.digisky.locallog.LogMgr;
import com.digisky.outerproxy.processserver.ProcessServerManager;
import com.digisky.tools.XXTEA;

import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*;

public class OuterProxyHttpServerHandler extends SimpleChannelInboundHandler<Object> {

    private HttpRequest request;

    //defaut
    private static byte[] key = { (byte) 0x01, (byte) 0x82, (byte) 0x0D, (byte) 0xE0, (byte) 0xB0, (byte) 0x1A,
            (byte) 0x80, (byte) 0x85, (byte) 0x66, (byte) 0xD0, (byte) 0x81, (byte) 0x0A, (byte) 0xD4, (byte) 0x1C,
            (byte) 0xA5, (byte) 0xD3 };

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
        LogMgr.debug("channelRead0()", "channelRead0");
        if (msg instanceof HttpRequest) {
            HttpRequest request = this.request = (HttpRequest) msg;
            if (HttpHeaders.is100ContinueExpected(request)) {
                send100Continue(ctx);
            }
        }
        if (msg instanceof HttpContent) {
            String type = request.getUri().split("/")[1];
            if (type.equals("email_activate") == true) { // GET?
                String[] tmp = request.getUri().split("=");
                String acode = tmp[tmp.length - 1];
                LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + acode);
                ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"acode\":\"" + acode + "\"}");
                return;
            } else if (type.equals("email_pwd_reset") == true) { //?
                String[] tmp = request.getUri().split("=");
                String vcode = tmp[tmp.length - 1];
                LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + vcode);
                ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"vcode\":\"" + vcode + "\"}");
                return;
            }

            //email_active  email_pwd_reset, 
            //???
            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request);
            InterfaceHttpData postData = decoder.getBodyHttpData("val");
            if (postData instanceof FileUpload == false) {//outerProxy????
                ctx.close();
                return;
            }
            FileUpload binData = (FileUpload) postData;
            ByteBuf content = null;
            try {
                content = binData.getByteBuf();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //content??. , 0. ?(head)?id, json?, ?. ??, ???. 
            //?content?head
            int index = content.bytesBefore((byte) 0);
            if (index < 0) {
                LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "ellegal request.");
                ctx.channel().close();
                return;
            }
            byte[] head = new byte[index];
            content.readBytes(head);
            String strHead = new String(head);
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "head:" + strHead);
            JSONObject jo = JSONObject.parseObject(strHead);
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),
                    "jo::app_id:" + jo.getString("app_id") + " jo::version:" + jo.getString("version"));
            content.readByte();//0

            //?content?tail
            byte[] tail = new byte[content.readableBytes()];
            content.readBytes(tail);
            String sjsonmsg = null;
            if (jo.getString("version").equals("0")) { //?0
                byte[] bjsonmsg = XXTEA.decrypt(tail, key);
                int data_len = bjsonmsg.length;
                for (int i = bjsonmsg.length - 1; i != 0; --i) {
                    if (bjsonmsg[i] == 0) {
                        data_len--;
                        continue;
                    } else {
                        break;
                    }
                }
                try {
                    sjsonmsg = new String(bjsonmsg, 0, data_len, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else { //TODO?0, app_id. ???
                LogMgr.error(OuterProxyHttpServerHandler.class.getName(),
                        "?0, ??");
                ctx.close();
                return;
            }
            sjsonmsg = sjsonmsg.substring(sjsonmsg.indexOf('{'), sjsonmsg.indexOf('}') + 1);//?
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "sjson:" + sjsonmsg);

            //debug code
            //JSONObject jsonObj = JSONObject.parseObject(sjsonmsg);
            //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "tmp.get:" + jsonObj.getString("model"));

            /* debug code
            //b.getBytes(n+1, tail, 0, b.g-n-1);
            for(int i=0; i< tail.length; ++i) {
               System.out.print(String.format("%x ", tail[i]));
            }
            */

            //debug code
            //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "uri:" + request.getUri());
            //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"method:" + request.getMethod());
            //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"type:" + type);
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "json:" + sjsonmsg);

            //
            ProcessServerManager.getInstance().process(ctx.channel(), type, sjsonmsg);
        }
    }

    private static void send100Continue(ChannelHandlerContext ctx) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, CONTINUE);
        ctx.write(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        LogMgr.info(OuterProxyHttpServerHandler.class.getName(), "exceptionCaugt function called!");
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //      LogMgr.debug("", "channelActive called. peer ip_port:"
        //            + ctx.channel().remoteAddress());
    }

    //   private static void ResponseIllegalParameters(ChannelHandlerContext ctx) {
    //      return;
    //   }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) {
        LogMgr.debug("", "channelRegistered called. peer ip_port:" + ctx.channel().remoteAddress());
    }

    public void channelUnregistered(ChannelHandlerContext ctx) {
        LogMgr.debug("", "channelUnregistered called. peer ip_port:" + ctx.channel().remoteAddress());
    }

    public static void main(String[] args) {
        Random r = new Random();
        for (int i = 0; i < 16; ++i) {
            System.out.println(Integer.toHexString((r.nextInt() % 255)));
        }
    }
}