方枪枪的java世界

不要因为风雨飘落就停止了你的脚步,真正的得失就在你的心中。 做喜欢做的事,不轻言放弃!

03 一个简单的HttpServer_Command_CommandImpl

package com.tianhe.frm.http;

public interface Command
{
    public byte[] execute(String resource, char[] postData, String charset);
}


package com.tianhe.frm.http;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import com.tianhe.frm.context.GlobalConfig;
import com.tianhe.frm.utils.PropertiesUtil;
import com.tianhe.frm.utils.StringUtil;

public class CommandImpl implements Command
{
    private String DEFAULT_RESPONSE;
   
    private String resultConfig = "response.properties";
   
    private Properties resultMapping;
   
    public CommandImpl()
    {
        init(resultConfig);
    }
   
    private void init(String resultConfig2)
    {
        try
        {
            if (StringUtil.isNotEmpty(resultConfig))
            {
                this.resultMapping = PropertiesUtil.loadProperties(ProcessorImpl.class, resultConfig);
            }
           
            this.DEFAULT_RESPONSE = createDefaultResponse();
        }
        catch (Exception e)
        {
            System.err.println("ProcessorImpl.init failed, ignored!");
        }
    }
   
    protected String createDefaultResponse()
    {
        String defaultResponse = GlobalConfig.getString("ProcessorImpl.DEFAULT_RESPONSE",
                "request url[%REQUEST_URL%] is not configured in reponse config!");
        return defaultResponse;
    }
   
    public byte[] execute(String resource, char[] postData, String charset)
    {
        String resKey = resource;
        resKey = resKey.replace("=", "__");
        resKey = resKey.replace(":", "--");
        resKey = resKey.replace("\"", "");
       
        byte[] resVal = createResultData(resource, resKey, charset);
       
        return resVal;
    }
   
    protected byte[] createResultData(String resource, String resKey, String charset)
    {
        String resVal = resultMapping.getProperty(resKey);
        if (StringUtil.isEmpty(resVal))
        {
            resVal = DEFAULT_RESPONSE.replaceAll("%REQUEST_URL%", resource);
        }
       
        byte[] resData = null;
        try
        {
            // resVal = URLEncoder.encode(resVal, charset);
            resData = resVal.getBytes(charset);
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
       
        return resData;
    }
   
    public static void main(String[] args)
    {
        CommandImpl s = new CommandImpl();
        Properties p = s.resultMapping;
        for (Object key : p.keySet())
        {
            System.out.println(key + "<->" + p.getProperty(key.toString()));
        }
    }
}

posted on 2012-07-09 22:14 做强大的自己 阅读(179) 评论(0)  编辑  收藏 所属分类: Socket


只有注册用户登录后才能发表评论。


网站导航: