星期天寫了點蛋疼的東西(2)

續上篇,蛋疼(1)

package org.J.v;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.J.c.Action;
import org.J.c.RenderType;
import org.J.conf.JFrameConstants;
import org.J.conf.JFrameLogger;
import org.J.m.JModel;
import org.J.res.Encoding;


/**
* 只實現了JSP 顯示器,其他的用到的,可以隨意實現View藉口
* 1.普通返回指向頁面 ([a-zA-Z]|$)+
* 2.重定向
      重定向到 想同 namespace other action r:([a-zA-Z]|$)+
            重定向到 不同 namespace other action r:/([a-zA-Z]|$)+    
* 3.轉發
*      轉發到     想同 namespace other action d:([a-zA-Z]|$)+
*      轉發到     不同 namespace other action d:/([a-zA-Z]|$)+
* r:redirect 重定向    response.sendRedirect(view);
* r(1)> return 'r:action1'
* r(2)> return 'r:/action1'
* d:dispatcher request.getRequestDispatcher(view).forward(request,response);
* d(1)> return 'd:action1' 指向本命名空間下的action1
* d(2)> return 'd:/test/action2' 指向命名空間根目錄的action2
*
* 表達式中的/代表 需要寫'相對的'絕對路徑
* 例如 有如下目錄
* WebContent/ac1
* WebContent/portal/ac2
* WebContent/portal/main/ac3
* WebContent/portal/sub1/ac4
* WebContent/portal/sub1/ac5
*
* 從ac3到ac5的轉發就要寫 d:/portal/sub1/ac5
* 其中,包括2部分內容,一個就是url頭'd:/',一個就是指向的具體路徑 portal/sub1/ac5,即ac5的actionKey
*/


@SuppressWarnings({"serial", "unchecked"})
public class Render {
  
  /**項目編譯後,文件所在目錄*/
  final static String appCompileFouder=JFrameConstants.cla***esourcePath;
  /**全局設置的頁面存放路徑*/
  final static String webViewRootPath=JFrameConstants.viewRoot.replace("\\", "/");
  
  static RenderType renderType;
  /**
    * 這個參數改爲一個ActionContextRequire對象
    * 然後把有用的信息封裝進去
    * 避免和org.J.c.Action 巨耦合
    * @param ac
    * @return
    */

  public static final View renderFilter(Action ac,Object result){
    /**調試輸出若干Action信息**/
    JFrameLogger.ActionConsoleView(ac);
    sysoAppInfo();
    org.J.annotation.action.Action action=ac.getMethod().getAnnotation(org.J.annotation.action.Action.class);
    if(action!=null){
        renderType=action.renderType();
      if(renderType.equals(RenderType.jsp)){
        return new JspRender(ac,result);
      }else if(renderType.equals(RenderType.json)){
        return new JsonRender(ac,result);
      }
    }else{
//      action:execute
    }
    return null;
  }

  private static void sysoAppInfo() {
    JFrameLogger.logger.debug(String.format("app appCompileFouder '%s':",appCompileFouder));
    JFrameLogger.logger.debug(String.format("app web root '%s':",webViewRootPath));
  }
  
  static class JspRender extends View{
    
    public JspRender(Action ac,Object result){
      this(ac);
      this.actionResultObj=result;
      if(result instanceof String){
        this.view=(String)result;
      }
    }
    public JspRender(Action ac){
      this.actionInstance =ac;
      this.request=ac.getHttpServletRequest();
      this.response=ac.getHttpServletResponse();
    }
    
    @Override
    public View handlerAfterAction() {
      for (Enumeration<String> attrs = request.getAttributeNames(); attrs.hasMoreElements();) {
        String key = attrs.nextElement();
        Object value = request.getAttribute(key);
        if (value instanceof JModel) {
          request.setAttribute(key, handleModel((JModel)value));
        }
        else if (value instanceof List) {
          List temp = (List)value;
          if (temp.size() > 0) {
            Object o = temp.get(0);
            if (o instanceof JModel)
              request.setAttribute(key, handleModelList((List<JModel>)value));
          }
        }
        else if (value instanceof JModel[]) {
          this.request.setAttribute(key, handleModelArray((JModel[])value));
        }
      }
      return this;
    }

    private Map<String,Object> handleModel(JModel model){
      return model.getAttrsInSession();
    }
    
    private List<Map<String, Object>> handleModelList(List<JModel> list) {
      List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(list.size());
      for (JModel model : list)
        result.add(model.getAttrsInSession());
      return result;
    }
    
    private List<Map<String, Object>> handleModelArray(JModel[] array) {
      List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(array.length);
      for (JModel model : array)
        result.add(model.getAttrsInSession());
      return result;
    }
    
    /**
     * 目前只支持返回Map 或者 url
     * @return
     */

    ReturnInfo getReturnInfo(){
      ReturnInfo result=null;
      if(actionResultObj!=null){
        result=new ReturnInfo();
      }
      //普通返回路徑
      if(actionResultObj instanceof String){
        String urlStemp=(String)actionResultObj;
        if(urlStemp.toLowerCase().startsWith("r:")==false&&urlStemp.toLowerCase().startsWith("d:")==false
          &&urlStemp.toLowerCase().startsWith("r:/")==false&&urlStemp.toLowerCase().startsWith("d:/")==false){
          result.setDip(RenderDip.Normal);
        }else if(urlStemp.toLowerCase().startsWith("r:")==true&&urlStemp.toLowerCase().startsWith("r:/")==false){
          result.setDip(RenderDip.redirect);
        }else if(urlStemp.toLowerCase().startsWith("r:")==false&&urlStemp.toLowerCase().startsWith("r:/")==true){
          result.setDip(RenderDip.redirect$);
        }else if(urlStemp.toLowerCase().startsWith("d:")==true&&urlStemp.toLowerCase().startsWith("d:/")==false){
          result.setDip(RenderDip.dispatcher);
        }else if(urlStemp.toLowerCase().startsWith("d:")==false&&urlStemp.toLowerCase().startsWith("d:/")==true){
          result.setDip(RenderDip.dispatcher$);
        }
        JFrameLogger.logger.debug(String.format("in getReturnInfo 返回 :%s",result.getDip()));
      }else if(actionResultObj instanceof Map){
        Map<String,Object> mapStemp=((Map<String,Object>)actionResultObj);
        for(Entry<String, Object> entry : mapStemp.entrySet()){
          this.request.setAttribute(entry.getKey(),entry.getValue());
        }
        result.setDip(RenderDip.Normal);
      }
      return result;
    }
    
    @Override
    public void render() {
      if(appCompileFouder.contains(webViewRootPath)){
        String temp=appCompileFouder.substring(0,appCompileFouder.indexOf(webViewRootPath)+webViewRootPath.length());
        ReturnInfo returnInfo= getReturnInfo();
        /**同一space下轉發*/
        if(returnInfo.getDip().equals(RenderDip.Normal)){
          //磁盤存放頁面路徑
          String diskFile=temp+(this.actionInstance.getNamespace().substring(1)+View.gen+this.view+"."+renderType);
          JFrameLogger.logger.debug("智能ABC="+diskFile);
          //request.getRequestDispatcher需要的相對路徑
          String fowardFile=View.gen+(this.actionInstance.getNamespace().substring(1)+View.gen+this.view+"."+renderType);
          JFrameLogger.logger.debug(String.format(Locale.getDefault(),"返回文件是 路徑是 '%s':",fowardFile));
          file=new File(diskFile);
          if(file.exists()){
            try {
              JFrameLogger.logger.debug(String.format("目標地址:%s",fowardFile));
              request.getRequestDispatcher(fowardFile).forward(request,response);
            } catch (ServletException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }else{
            JFrameLogger.logger.debug(String.format("GOTO 404 Page 不存在 %s",fowardFile));
          }
        }
        /**同族轉發**/
        else if(returnInfo.getDip().equals(RenderDip.dispatcher)){
          
        }
        /**跨族轉發**/
        else if(returnInfo.getDip().equals(RenderDip.dispatcher$)){
          
        }
        /**國內重定向**/
        else if(returnInfo.getDip().equals(RenderDip.redirect)){
          
        }
        /**跨國重定向**/
        else if(returnInfo.getDip().equals(RenderDip.redirect$)){
          
        }
      }
    }
    
  }
  

  static class HtmlRender extends View{
    private static final String contentType = "text/html;charset=" + Encoding.UTF8;
    
    private String text;
    
    public HtmlRender(String text) {
      this.text = text;
    }
    public HtmlRender(Action ac){
      this.actionInstance =ac;
      this.request=ac.getHttpServletRequest();
      this.response=ac.getHttpServletResponse();
    }
    public HtmlRender(Action ac,Object result){
      this(ac);
      if(result instanceof String){
        this.text=(String)result;
      }
    }
    @Override
    public View handlerAfterAction() {

      return null;
    }

    @Override
    public void render() {
      PrintWriter writer = null;
      try {
        response.setHeader("Pragma", "no-cache");
                    response.setHeader("Cache-Control", "no-cache");
                    response.setDateHeader("Expires", 0);
        response.setContentType(contentType);
                    writer = response.getWriter();
                    writer.write(text);
                    writer.flush();
      } catch (IOException e) {
        throw new RenderException(e);
      }
      finally {
        writer.close();
      }
    }
    
  }
  
  
  static class JsonRender extends View{
    
    private static final String contentType="application/json;charset=" + Encoding.UTF8;
    
    private String jsonString;
    public JsonRender(){}
    public JsonRender(Action ac,Object result){
      this(ac);
      if(result instanceof String){
        jsonString=(String)result;
      }
    }
    public JsonRender(Action ac){
      this.actionInstance =ac;
      this.request=ac.getHttpServletRequest();
      this.response=ac.getHttpServletResponse();
    }
    public JsonRender(String viewPath){ this.view = viewPath;}
    public JsonRender(String viewPath,String json){ this.view = viewPath; this.jsonString = json ;}
    PrintWriter writer;
    @Override
    public View handlerAfterAction() {
      return this;
    }
    @Override
    public void render() {
      try {
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType(contentType);
        writer = response.getWriter();
                    writer.write(jsonString);
                    writer.flush();
      } catch (IOException e) {
        throw new RenderException(e);
      }
    }
    
  }
  
  /**
    * 1.普通返回指向頁面 ([a-zA-Z]|$)+
     * 2.重定向
         *      重定向到 想同 namespace other action r:([a-zA-Z]|$)+
     *        重定向到 不同 namespace other action r:/([a-zA-Z]|$)+    
    * 3.轉發
     *      轉發到     想同 namespace other action d:([a-zA-Z]|$)+
     *      轉發到     不同 namespace other action d:/([a-zA-Z]|$)+
    * @author Gelopa
    *
    */

  static enum RenderDip{
    Normal,
    redirect,
    redirect$,
    dispatcher,
    dispatcher$
  }

  /**
    * 數據返回使者
    * @author Gelopa
    *
    */

  static class ReturnInfo {
    RenderDip dip;
    RenderType renderType;
    HttpServletRequest request;
    public RenderDip getDip() {
      return dip;
    }
    public void setDip(RenderDip dip) {
      this.dip = dip;
    }
    public HttpServletRequest getRequest() {
      return request;
    }
    public void setRequest(HttpServletRequest request) {
      this.request = request;
    }
    public RenderType getRenderType() {
      return renderType;
    }
    public void setRenderType(RenderType renderType) {
      this.renderType = renderType;
    }
    
  }
  
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章