Search in sources :

Example 1 with HongsExpedient

use of app.hongs.HongsExpedient in project HongsCORE by ihongs.

the class Loop method next.

@Override
public Map next() {
    // 判断是否到达末尾
    if (!hasNext()) {
        this.close();
        return null;
    }
    il = null;
    // 获取当前字段类型
    try {
        // getMetaData();
        getTypeDict();
    } catch (HongsException ex) {
        this.close();
        throw ex.toExpedient();
    }
    // 获取行内每列数据
    try {
        int i = 0;
        Map<String, Object> row = new LinkedHashMap();
        if (ib) {
            for (Map.Entry<String, Class> et : td.entrySet()) {
                // row.put(et.getKey() , rs.getObject(++ i, et.getState()));
                Dict.put(row, rs.getObject(++i, et.getValue()), (Object[]) et.getKey().split("\\."));
            }
        } else {
            for (Map.Entry<String, Class> et : td.entrySet()) {
                // row.put(et.getKey() , rs.getString(++ i /* No Type */ ));
                Dict.put(row, rs.getString(++i), (Object[]) et.getKey().split("\\."));
            }
        }
        return row;
    } catch (SQLException ex) {
        this.close();
        throw new HongsExpedient(0x10a6, ex);
    }
}
Also used : HongsException(app.hongs.HongsException) SQLException(java.sql.SQLException) HongsExpedient(app.hongs.HongsExpedient) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap)

Example 2 with HongsExpedient

use of app.hongs.HongsExpedient in project HongsCORE by ihongs.

the class ActionHelper method getRequestPart.

/**
 * 解析 multipart/form-data 数据, 处理上传
 * @return
 */
final Map getRequestPart() {
    CoreConfig conf = CoreConfig.getInstance();
    // 是否仅登录用户可上传
    if (conf.getProperty("core.upload.auth.needs", false) && null == getSessibute(Cnst.UID_SES)) {
        throw new HongsExpedient(0x1100, "Multipart is not supported");
    }
    String x;
    Set<String> allowTypes = null;
    x = conf.getProperty("fore.upload.allow.types", null);
    if (x != null) {
        allowTypes = new HashSet(Arrays.asList(x.split(",")));
    }
    Set<String> denyTypes = null;
    x = conf.getProperty("fore.upload.deny.types", null);
    if (x != null) {
        denyTypes = new HashSet(Arrays.asList(x.split(",")));
    }
    Set<String> allowExtns = null;
    x = conf.getProperty("fore.upload.allow.extns", null);
    if (x != null) {
        allowExtns = new HashSet(Arrays.asList(x.split(",")));
    }
    Set<String> denyExtns = null;
    x = conf.getProperty("fore.upload.deny.extns", null);
    if (x != null) {
        denyExtns = new HashSet(Arrays.asList(x.split(",")));
    }
    try {
        Map rd = new HashMap();
        Map ud = new HashMap();
        for (Part part : request.getParts()) {
            long size = part.getSize();
            String name = part.getName();
            String type = part.getContentType();
            String subn = part.getSubmittedFileName();
            String extn = subn;
            // 无类型的普通参数已在外部处理
            if (name == null || type == null || extn == null) {
                continue;
            }
            // 在修改的操作中表示将其置为空
            if (size == 0) {
                if (null == request.getParameter(name)) {
                    Dict.setParam(rd, null, name);
                }
                continue;
            }
            // 检查类型
            int pos = type.indexOf(',');
            if (pos != -1) {
                type = type.substring(0, pos);
            }
            if (allowTypes != null && !allowTypes.contains(type)) {
                throw new HongsExpedient(0x1100, "Type '" + type + "' is not allowed");
            }
            if (denyTypes != null && denyTypes.contains(type)) {
                throw new HongsExpedient(0x1100, "Type '" + type + "' is denied");
            }
            // 检查扩展
            pos = extn.lastIndexOf('.');
            if (pos == -1) {
                extn = extn.substring(1 + pos);
            } else {
                extn = "";
            }
            if (allowExtns != null && !allowExtns.contains(extn)) {
                throw new HongsExpedient(0x1100, "Type '" + extn + "' is not allowed");
            }
            if (denyExtns != null && denyExtns.contains(extn)) {
                throw new HongsExpedient(0x1100, "Type '" + extn + "' is denied");
            }
            /**
             * 临时存储文件
             * 不再需要暂存
             * 可以直接利用 Part 继续向下传递
             */
            /*
            String id = Core.getUniqueId();
            String temp = path + File.separator + id + ".tmp";
            String tenp = path + File.separator + id + ".tnp";
            subn = subn.replaceAll("[\\r\\n\\\\/]", ""); // 清理非法字符: 换行和路径分隔符
            subn = subn + "\r\n" + type + "\r\n" + size; // 拼接存储信息: 名称和类型及大小
            try (
                InputStream      xmin = part.getInputStream();
                FileOutputStream mout = new FileOutputStream(temp);
                FileOutputStream nout = new FileOutputStream(tenp);
            ) {
                byte[] nts = subn.getBytes("UTF-8");
                byte[] buf = new byte[1024];
                int    cnt ;
                while((cnt = xmin.read(buf)) != -1) {
                    mout.write(buf, 0, cnt);
                }
                nout.write(nts);
            }
            Dict.setParam( rd , id , name );
            */
            Dict.setValue(ud, part, name, null);
            Dict.setParam(rd, part, name);
        }
        // 记录在应用里以便有需要时候还可读取原始值
        setAttribute(Cnst.UPLOAD_ATTR, ud);
        return rd;
    } catch (IllegalStateException e) {
        // 上传受限, 如大小超标
        throw new HongsExpedient(0x1100, e);
    } catch (ServletException e) {
        throw new HongsExpedient(0x1110, e);
    } catch (IOException e) {
        throw new HongsExpedient(0x1110, e);
    }
}
Also used : CoreConfig(app.hongs.CoreConfig) HashMap(java.util.HashMap) HongsExpedient(app.hongs.HongsExpedient) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) Part(javax.servlet.http.Part) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 3 with HongsExpedient

use of app.hongs.HongsExpedient in project HongsCORE by ihongs.

the class ActionDriver method doFinish.

private void doFinish(Core core, ActionHelper hlpr, HttpServletRequest req) {
    try {
        if (0 < Core.DEBUG && 8 != (8 & Core.DEBUG)) {
            /**
             * 提取必要的客户相关标识
             * 以便判断用户和模拟登录
             */
            req = hlpr.getRequest();
            HttpSession ses = req.getSession(false);
            Object uid = hlpr.getSessibute(Cnst.UID_SES);
            String mem;
            if (ses == null) {
                mem = "-";
            } else {
                mem = ses.getId();
            }
            if (uid != null) {
                mem += " " + uid;
            }
            long time = System.currentTimeMillis() - Core.ACTION_TIME.get();
            StringBuilder sb = new StringBuilder("...");
            sb.append("\r\n\tACTION_NAME : ").append(Core.ACTION_NAME.get()).append("\r\n\tACTION_TIME : ").append(Core.ACTION_TIME.get()).append("\r\n\tACTION_LANG : ").append(Core.ACTION_LANG.get()).append("\r\n\tACTION_ZONE : ").append(Core.ACTION_ZONE.get()).append("\r\n\tMethod      : ").append(req.getMethod()).append("\r\n\tMember      : ").append(mem).append("\r\n\tObjects     : ").append(core.toString()).append("\r\n\tRuntime     : ").append(Tool.humanTime(time));
            /**
             * 显示请求报头及输入输出
             * 这对调试程序非常有帮助
             */
            CoreConfig cf = CoreConfig.getInstance();
            if (cf.getProperty("core.debug.action.request", false)) {
                Map rd = null;
                try {
                    rd = hlpr.getRequestData();
                } catch (HongsExpedient ex) {
                    CoreLogger.debug(ex.getMessage());
                }
                if (rd != null && !rd.isEmpty()) {
                    sb.append("\r\n\tRequest     : ").append(Tool.indent(Data.toString(rd)).substring(1));
                }
            }
            if (cf.getProperty("core.debug.action.results", false)) {
                Map xd = hlpr.getResponseData();
                if (xd == null) {
                    xd = (Map) req.getAttribute(Cnst.RESP_ATTR);
                }
                if (xd != null && !xd.isEmpty()) {
                    sb.append("\r\n\tResults     : ").append(Tool.indent(Data.toString(xd)).substring(1));
                }
            }
            if (cf.getProperty("core.debug.action.session", false) && ses != null) {
                Map map = new HashMap();
                Enumeration<String> nms = ses.getAttributeNames();
                while (nms.hasMoreElements()) {
                    String nme = nms.nextElement();
                    map.put(nme, ses.getAttribute(nme));
                }
                if (!map.isEmpty()) {
                    sb.append("\r\n\tSession     : ").append(Tool.indent(Data.toString(map)).substring(1));
                }
            }
            if (cf.getProperty("core.debug.action.context", false)) {
                Map map = new HashMap();
                Enumeration<String> nms = req.getAttributeNames();
                while (nms.hasMoreElements()) {
                    String nme = nms.nextElement();
                    map.put(nme, req.getAttribute(nme));
                }
                if (!map.isEmpty()) {
                    sb.append("\r\n\tContext     : ").append(Tool.indent(Data.toString(map)).substring(1));
                }
            }
            if (cf.getProperty("core.debug.action.headers", false)) {
                Map map = new HashMap();
                Enumeration<String> nms = req.getHeaderNames();
                while (nms.hasMoreElements()) {
                    String nme = nms.nextElement();
                    map.put(nme, req.getHeader(nme));
                }
                if (!map.isEmpty()) {
                    sb.append("\r\n\tHeaders     : ").append(Tool.indent(Data.toString(map)).substring(1));
                }
            }
            if (cf.getProperty("core.debug.action.cookies", false)) {
                Map map = new HashMap();
                Cookie[] cks = req.getCookies();
                for (Cookie cke : cks) {
                    map.put(cke.getName(), cke.getValue());
                }
                if (!map.isEmpty()) {
                    sb.append("\r\n\tCookies     : ").append(Tool.indent(Data.toString(map)).substring(1));
                }
            }
            CoreLogger.debug(sb.toString());
        }
        // 删除上传的临时文件
        Map<String, List<Part>> ud = Synt.asMap(hlpr.getAttribute(Cnst.UPLOAD_ATTR));
        if (ud != null) {
            for (List<Part> pa : ud.values()) {
                for (Part pr : pa) {
                    try {
                        pr.delete();
                    } catch (IOException ex) {
                        CoreLogger.error(ex);
                    }
                }
            }
        }
    } finally {
        // 销毁此周期内的对象
        try {
            core.close();
        } catch (Error e) {
            CoreLogger.error(e);
        } catch (Exception e) {
            CoreLogger.error(e);
        }
        req.removeAttribute(Core.class.getName());
        Core.THREAD_CORE.remove();
        Core.ACTION_TIME.remove();
        Core.ACTION_ZONE.remove();
        Core.ACTION_LANG.remove();
        Core.ACTION_NAME.remove();
    }
}
Also used : Cookie(javax.servlet.http.Cookie) CoreConfig(app.hongs.CoreConfig) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) HongsExpedient(app.hongs.HongsExpedient) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) Part(javax.servlet.http.Part) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) Core(app.hongs.Core)

Example 4 with HongsExpedient

use of app.hongs.HongsExpedient in project HongsCORE by ihongs.

the class ActionHelper method getRequestData.

/**
 * 获取请求数据
 *
 * 不同于 request.getParameterMap,
 * 该方法会将带"[]"的拆成子List, 将带"[xxx]"的拆成子Map, 并逐级递归.
 * 也可以解析用"." 连接的参数, 如 a.b.c 与上面的 a[b][c] 是同样效果.
 * 故请务必注意参数中的"."和"[]"符号.
 * 如果Content-Type为"multipart/form-data", 则使用 apache-common-fileupload 先将文件存入临时目录.
 *
 * @return 请求数据
 */
public Map<String, Object> getRequestData() {
    if (this.request != null && this.requestData == null) {
        String ct = this.request.getContentType();
        if (ct == null) {
            ct = "application/x-www-form-urlencode";
        } else {
            ct = ct.split(";", 2)[0];
        }
        try {
            Map ad, rd;
            // 可用属性传递
            ad = this.getRequestAttr();
            if (ct.startsWith("multipart/")) {
                // 处理上传文件
                rd = this.getRequestPart();
            } else if (ct.endsWith("/json")) {
                // 处理JSON数据
                rd = this.getRequestJson();
            } else {
                rd = null;
            }
            requestData = parseParam(request.getParameterMap());
            // 深度整合数据
            if (rd != null) {
                Dict.putAll(requestData, rd);
            }
            if (ad != null) {
                Dict.putAll(requestData, ad);
            }
        } catch (HongsError er) {
            throw new HongsExpedient(0x1100, er);
        } finally {
            // 防止解析故障后再调用又出错
            if (this.requestData == null) {
                this.requestData = new HashMap();
            }
        }
    }
    return this.requestData;
}
Also used : HongsError(app.hongs.HongsError) HashMap(java.util.HashMap) HongsExpedient(app.hongs.HongsExpedient) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with HongsExpedient

use of app.hongs.HongsExpedient in project HongsCORE by ihongs.

the class ActsAction method service.

/**
 * 服务方法
 * Servlet Mapping: *.act<br/>
 * 注意: 不支持请求URI的路径中含有"."(句点), 且必须区分大小写;
 * 其目的是为了防止产生多种形式的请求路径, 影响动作过滤, 产生安全隐患.
 *
 * @param req
 * @param rsp
 * @throws javax.servlet.ServletException
 */
@Override
public void service(HttpServletRequest req, HttpServletResponse rsp) throws ServletException {
    String act = ActionDriver.getRecentPath(req);
    Core core = ActionDriver.getActualCore(req);
    ActionHelper helper = core.get(ActionHelper.class);
    Core.THREAD_CORE.set(core);
    if (act == null || act.length() == 0) {
        senderr(helper, 0x1104, null, "Action URI can not be empty.", "");
        return;
    }
    // 去掉根和扩展名
    act = act.substring(1);
    int pos = act.lastIndexOf('.');
    if (pos != -1)
        act = act.substring(0, pos);
    // 获取并执行动作
    try {
        ActionRunner runner = new ActionRunner(helper, act);
        runner.doAction();
    } catch (ClassCastException ex) {
        // 类型转换失败按 400 错误处理
        senderr(helper, new HongsException(0x1100, ex));
    } catch (HongsException ex) {
        senderr(helper, ex);
    } catch (HongsExpedient ex) {
        senderr(helper, ex);
    } catch (HongsError ex) {
        senderr(helper, ex);
    }
}
Also used : ActionRunner(app.hongs.action.ActionRunner) HongsError(app.hongs.HongsError) HongsException(app.hongs.HongsException) ActionHelper(app.hongs.action.ActionHelper) HongsExpedient(app.hongs.HongsExpedient) Core(app.hongs.Core)

Aggregations

HongsExpedient (app.hongs.HongsExpedient)11 HongsException (app.hongs.HongsException)7 Map (java.util.Map)7 HashMap (java.util.HashMap)5 Core (app.hongs.Core)4 HongsError (app.hongs.HongsError)4 CoreConfig (app.hongs.CoreConfig)3 ActionHelper (app.hongs.action.ActionHelper)2 FormSet (app.hongs.action.FormSet)2 NaviMap (app.hongs.action.NaviMap)2 IOException (java.io.IOException)2 HashSet (java.util.HashSet)2 Set (java.util.Set)2 ServletException (javax.servlet.ServletException)2 Part (javax.servlet.http.Part)2 CoreLocale (app.hongs.CoreLocale)1 ActionRunner (app.hongs.action.ActionRunner)1 Color (java.awt.Color)1 File (java.io.File)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1