示例#1
0
文件: Lang.java 项目: flymichael/nutz
 /**
  * 根据一段字符串,生成一个List 对象。
  *
  * @param str 参照 JSON 标准的字符串,但是可以没有前后的中括号
  * @return List 对象
  */
 @SuppressWarnings("unchecked")
 public static List<Object> list4(String str) {
   if (null == str) return null;
   if ((str.length() > 0 && str.charAt(0) == '[') && str.endsWith("]"))
     return (List<Object>) Json.fromJson(str);
   return (List<Object>) Json.fromJson("[" + str + "]");
 }
示例#2
0
文件: Lang.java 项目: flymichael/nutz
 /**
  * 根据一段字符串,生成一个 Map 对象。
  *
  * @param str 参照 JSON 标准的字符串,但是可以没有前后的大括号
  * @return Map 对象
  */
 @SuppressWarnings("unchecked")
 public static Map<String, Object> map(String str) {
   if (null == str) return null;
   if ((str.length() > 0 && str.charAt(0) == '{') && str.endsWith("}"))
     return (Map<String, Object>) Json.fromJson(str);
   return (Map<String, Object>) Json.fromJson("{" + str + "}");
 }
示例#3
0
  @Test
  public void test() {
    Ioc ioc = new NutIoc(new JsonLoader("ioc.js"));
    Dao dao = ioc.get(NutDao.class, "rDao");
    dao.create(Teacher.class, true);
    TeacherAction action = ioc.get(TeacherAction.class);
    action.add("20092009", "张三", "123456", 1L, "*****@*****.**", "13333333333", Teacher.ROLE_ADMIN);
    action.add(
        "20102010", "李四", "123456", 1L, "*****@*****.**", "13333333333", Teacher.ROLE_NORMAL);
    action.add(
        "20132013", "王五", "123456", 2L, "*****@*****.**", "13333333333", Teacher.ROLE_ADMIN);

    action.mod("20092009", "张三", "123456", 1L, "*****@*****.**", "13333333333", Teacher.ROLE_ADMIN);
    action.mod(
        "20102010", "李四", "123456", 1L, "*****@*****.**", "13333333333", Teacher.ROLE_NORMAL);
    action.mod(
        "20132013", "王五", "123456", 2L, "*****@*****.**", "13333333333", Teacher.ROLE_ADMIN);

    System.out.println(Json.toJson(action.list(1L, "", 1, 10)));
    System.out.println(Json.toJson(action.list(1L, "张", 1, 10)));
    System.out.println(Json.toJson(action.list(1L, "10", 1, 10)));
    //        System.out.println(Json.toJson(action.login("20092009","123456")));
    //        System.out.println(Json.toJson(action.login("*****@*****.**","123456")));
    //        System.out.println(Json.toJson(action.login("*****@*****.**","12346")));

    //        action.del("20092009");
    //        action.del("20102010");
    //        action.del("20132013");
  }
示例#4
0
 public void find() {
   String tac = "01058001";
   int c = 0;
   IndexParser.init();
   HashMap<String, String[]> map = IndexParser.getTacMap();
   Iterator it = map.keySet().iterator();
   while (it.hasNext()) {
     String key = (String) it.next();
     Tac t = dao.getByTac(key);
     String[] str = map.get(key);
     if (null != t) {
       t.setTac(key);
       t.setHsmanNameEn(str[1]);
       t.setHsmanName(str[1]);
       t.setHstypeNameEn(str[2]);
       t.setHstypeName(str[2]);
       t.setModifytime(new Date());
       if (dao.update(t)) {
         System.out.println(" >> Update Success!");
       }
     } else {
       t = new Tac();
       t.setTac(key);
       t.setHsmanNameEn(str[1]);
       t.setHstypeNameEn(str[2]);
       System.out.println(" >> 添加数据:" + Json.toJson(t));
       t = dao.save(t);
       if (t.getId() > 0) {
         c++;
         System.out.println(Json.toJson(t));
       }
     }
   }
   System.out.println(" >> c:" + c);
 }
示例#5
0
  @SuppressWarnings("unchecked")
  protected Profile authLogin() throws Exception {
    String presp;
    try {
      Response response = authenticationStrategy.executeFeed(PROFILE_URL);
      presp =
          response.getResponseBodyAsString(
              Constants.ENCODING); // callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} );
      if (presp != null) {
        presp = presp.trim().intern();
        if (presp.startsWith("callback(") && presp.endsWith(");")) {
          presp = presp.substring(presp.indexOf("{"), presp.indexOf("}") + 1);
          Map<String, String> map = (Map<String, String>) Json.fromJson(presp);
          if (map.get("openid") != null) {
            Profile p = new Profile();
            p.setValidatedId(map.get("openid")); // QQ定义的
            p.setProviderId(getProviderId());
            userProfile = p;

            try {
              Map<String, String> params = new HashMap<String, String>();
              params.put("format", "json");
              params.put("openid", map.get("openid"));
              params.put("oauth_consumer_key", config.get_consumerKey());
              response =
                  authenticationStrategy.executeFeed(
                      "https://graph.qq.com/user/get_user_info", "GET", params, null, null);
              presp = response.getResponseBodyAsString(Constants.ENCODING);
              Map<String, Object> user_info = (Map<String, Object>) Json.fromJson(presp);
              if ((Integer) user_info.get("ret") == 0) { // 获取成功
                if (user_info.get("nickname") != null)
                  p.setDisplayName(user_info.get("nickname").toString());
                if (user_info.get("figureurl") != null)
                  p.setProfileImageURL(user_info.get("figureurl").toString());
                if (user_info.get("gender") != null)
                  p.setGender(user_info.get("gender").toString());
              }

              // TODO 尝试获取Email等详细信息

            } catch (Throwable e) {
              e.printStackTrace();
            }

            return p;
          }
        }
      }

      throw new SocialAuthException("QQ Error : " + presp);
    } catch (Exception e) {
      throw new SocialAuthException("Error while getting profile from " + PROFILE_URL, e);
    }
  }
示例#6
0
 public static String getErrorMsg(int res) {
   Map<String, Object> map = new HashMap<String, Object>();
   switch (res) {
     case -1:
       map.put("errcode", -1);
       map.put("errmsg", "来源未通过验证");
       break;
     case 1:
       map.put("errcode", 1);
       map.put("errmsg", "操作成功");
       break;
     case 2:
       map.put("errcode", 2);
       map.put("errmsg", "操作失败");
       break;
     case 3:
       map.put("errcode", 3);
       map.put("errmsg", "参数错误");
       break;
     case 4:
       map.put("errcode", 4);
       map.put("errmsg", "内容未发布");
       break;
     case 5:
       map.put("errcode", 5);
       map.put("errmsg", "未读取到内容");
       break;
     default:
       map.put("errcode", 0);
       map.put("errmsg", "系统错误");
       break;
   }
   return Json.toJson(map);
 }
示例#7
0
 @SecurityMapping(
     title = "支付方式列表",
     value = "/seller/payment.htm*",
     rtype = "seller",
     rname = "支付方式",
     rcode = "payment_seller",
     rgroup = "交易管理")
 @RequestMapping("/seller/payment.htm")
 public ModelAndView payment(HttpServletRequest request, HttpServletResponse response) {
   ModelAndView mv =
       mv =
           new JModelAndView(
               "user/default/usercenter/payment.html",
               configService.getSysConfig(),
               this.userConfigService.getUserConfig(),
               0,
               request,
               response);
   String store_payment = this.configService.getSysConfig().getStore_payment();
   if (store_payment != null && !store_payment.equals("")) {
     Map map = Json.fromJson(HashMap.class, store_payment);
     mv.addObject("map", map);
     mv.addObject("paymentTools", paymentTools);
   }
   return mv;
 }
 @SecurityMapping(
     title = "楼层模板右侧商品列表保存",
     value = "/admin/goods_floor_list_goods_save.htm*",
     rtype = "admin",
     rname = "首页楼层",
     rcode = "goods_floor",
     rgroup = "商品")
 @RequestMapping("/admin/goods_floor_list_goods_save.htm")
 public String goods_floor_list_goods_save(
     HttpServletRequest request,
     HttpServletResponse response,
     String list_title,
     String id,
     String ids) {
   GoodsFloor obj = this.goodsfloorService.getObjById(CommUtil.null2Long(id));
   String[] id_list = ids.split(",");
   Map map = new HashMap();
   map.put("list_title", list_title);
   for (int i = 0; i < id_list.length; i++) {
     if (!id_list[i].equals("")) {
       map.put("goods_id" + i, id_list[i]);
     }
   }
   // System.out.println(Json.toJson(map, JsonFormat.compact()));
   obj.setGf_list_goods(Json.toJson(map, JsonFormat.compact()));
   this.goodsfloorService.update(obj);
   return "redirect:goods_floor_template.htm?id=" + obj.getId();
 }
示例#9
0
  // @RequestMapping(value = "queryAllRoleList", method = { RequestMethod.POST })
  public String queryAllRoleList(HttpServletRequest request, HttpServletResponse response) {
    int page = Integer.parseInt(request.getParameter("page")); // 当前页数
    int rows = Integer.parseInt(request.getParameter("rows")); // 每页多少行
    int startNum = page * rows - rows; // 分页查询开始位置
    String roleJsonStr = "";
    Datagrid datagrid = new Datagrid();
    int roleTotalCount = roleService.queryRoleTotalCount(); // 统计角色数量
    List<Role> roleList = roleService.quryAllRoleList(startNum, rows); // 查询角色列表
    datagrid.setRows(roleList);
    datagrid.setTotal(roleTotalCount);
    try {
      // 将查询的角色集合list转换成json格式字符串
      roleJsonStr = Json.toJson(datagrid); // JsonUtils.objectToJackson(datagrid, Datagrid.class);
      PrintWriter out = response.getWriter();
      out.print(roleJsonStr);
      out.flush();
      out.close();
      request.setAttribute("roleJsonStr", roleJsonStr);
    } catch (Exception e) {
      log.error("处理json数据报错:" + e.getStackTrace());
    }
    log.info(roleJsonStr);

    return null;
  }
示例#10
0
  // @RequestMapping(value="getRoleByRoleName",method={RequestMethod.POST})
  public String getRoleByRoleName(
      HttpServletRequest request, HttpServletResponse response, String roleName) {
    int page = Integer.parseInt(request.getParameter("page")); // 当前页数
    int rows = Integer.parseInt(request.getParameter("rows")); // 每页多少行
    int startNum = page * rows - rows; // 分页查询开始位置

    List<Role> roles = roleService.getRoleByRoleName(roleName, startNum, rows);
    int rolesTotalCountByRoleName = roleService.getRolesTotalCountByRoleName(roleName);
    Datagrid datagrid = new Datagrid();
    datagrid.setRows(roles);
    datagrid.setTotal(rolesTotalCountByRoleName);
    String rolesJsonStr = "";
    try {
      rolesJsonStr =
          Json.toJson(
              datagrid); // JsonUtils.objectToJackson(datagrid, Datagrid.class);// 将对象转换成json字符串
      PrintWriter out = response.getWriter();
      out.print(rolesJsonStr);
      out.flush();
      out.close();
    } catch (Exception e) {
      log.error("处理json数据报错:" + e.getStackTrace());
    }
    return null;
  }
示例#11
0
  @SuppressWarnings({"unchecked"})
  public void init() throws FileNotFoundException {

    File config = Files.findFile("auth.json");
    if (null == config) {
      log.error("Can not find path:[classpath:auth.json]");
      throw new FileNotFoundException("[classpath:auth.json]");
    }

    FileReader reader = new FileReader(config);
    authMap = new LinkedHashMap<String, Integer>();
    authMap = Json.fromJson(authMap.getClass(), reader);
    log.info("Get url mapping:[" + authMap + "]");
    patternMap = new LinkedHashMap<String, Pattern>();
    if (!authMap.isEmpty()) {
      for (String url : authMap.keySet()) {
        patternMap.put(url, Pattern.compile(url));
      }
    }

    excludePaths = new HashSet<String>();
    Collections.addAll(
        excludePaths, PropertiesReader.getProperties("doe.url.pass").trim().split(","));
    //          System.out.println(Json.toJson(excludePaths));
  }
示例#12
0
 @SecurityMapping(title = "直通车商品加载", value = "/seller/ztc_goods.htm*", rtype = "seller", rname = "竞价直通车", rcode = "ztc_seller", rgroup = "促销管理")
 @RequestMapping({ "/seller/ztc_goods.htm" })
 public void ztc_goods(HttpServletRequest request, HttpServletResponse response, String goods_name) {
     Map params = new HashMap();
     params.put("goods_name", "%" + goods_name.trim() + "%");
     params.put("goods_status", Integer.valueOf(0));
     params.put("user_id", SecurityUserHolder.getCurrentUser().getId());
     params.put("ztc_status", Integer.valueOf(0));
     List<Goods> goods_list = this.goodsService
             .query("select obj from Goods obj where obj.goods_name like :goods_name and obj.goods_store.user.id=:user_id and obj.ztc_status=:ztc_status and obj.goods_status=:goods_status  order by obj.addTime desc",
                     params, -1, -1);
     List maps = new ArrayList();
     for (Goods goods : goods_list) {
         Map map = new HashMap();
         map.put("goods_name", goods.getGoods_name());
         map.put("goods_id", goods.getId());
         maps.add(map);
     }
     response.setContentType("text/plain");
     response.setHeader("Cache-Control", "no-cache");
     response.setCharacterEncoding("UTF-8");
     try {
         PrintWriter writer = response.getWriter();
         writer.print(Json.toJson(maps, JsonFormat.compact()));
     } catch (IOException e) {
         e.printStackTrace();
     }
 }
示例#13
0
  @Override
  public View match(ActionContext actionContext) {

    if (!enable) {
      return null;
    }
    String sessionID = SessionUtil.getSessionId(actionContext.getRequest());
    String path = actionContext.getRequest().getServletPath();

    log.info("Auth for PATH:[" + path + "]");
    System.out.println("excludePaths:" + Json.toJson(excludePaths));
    if (excludePaths.contains(path)) {
      log.info("[pass] path:[" + path + "]");
      return null;
    }

    if (sessionID == null || sessionID.trim().equals("")) {
      handleResponse(actionContext.getRequest(), actionContext.getResponse());
      return new VoidView();
    }
    for (String url : patternMap.keySet()) {
      Matcher matcher = patternMap.get(url).matcher(path);
      if (matcher.find()) {
        int auth = authMap.get(url);
        log.debug("Path:{" + url + "] auth:[" + auth + ']');
        Integer sessionAuth =
            (Integer) SessionUtil.getFromSession("role", actionContext.getRequest());
        if (sessionAuth == null || sessionAuth > auth) {
          handleResponse(actionContext.getRequest(), actionContext.getResponse());
          return new VoidView();
        } else {
          log.info("[pass] path:[" + path + "]");
          return null;
        }
      }
    }

    // not find matcher

    int auth = PropertiesReader.getPropertiesInt("doe.defaultrole");
    Integer sessionAuth = (Integer) SessionUtil.getFromSession("role", actionContext.getRequest());
    log.info("sessionAuth: " + sessionAuth);
    if (sessionAuth == null || (sessionAuth >= auth && !path.equals("/"))) {
      handleResponse(actionContext.getRequest(), actionContext.getResponse());
      return new VoidView();
    } else if (sessionAuth == auth && path.equals("/")) {
      try {
        actionContext
            .getResponse()
            .sendRedirect(actionContext.getRequest().getContextPath() + studentligin);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
      return new VoidView();
    } else {
      log.info("[pass] path:[" + path + "]");
      return null;
    }
  }
示例#14
0
 public void handle(Message msg, Session sess) throws IOException {
   Email email = Json.fromJson(Email.class, msg.getBodyString());
   try {
     email.send();
   } catch (EmailException e) {
     e.printStackTrace();
   }
 }
示例#15
0
 public static void main(String ars[]) {
   //        String salt=getSalt(60);
   //        System.out.println(salt);
   //        String pass=Encrypt("test", "UCUeqU");
   //        System.out.println("加密:"+pass);
   //        String y=Decrypt(pass,"UCUeqU");
   //        System.out.println("解密:"+y);
   Map<String, String> s1 = new HashMap<String, String>();
   s1.put("a", "a");
   s1.put("a1", "a1");
   s1.put("b", "b");
   s1.put("b2", "b2");
   s1.put("b1", "b1");
   Map<String, String> s2 = new HashMap<String, String>();
   s2.put("b1", "b1");
   s2.put("b2", "b2");
   s2.put("b", "b");
   s2.put("a1", "a1");
   s2.put("a", "a");
   SortHashtable sortHashtable = new SortHashtable();
   String ss1 = Json.toJson(s1, JsonFormat.full());
   String ss2 = Json.toJson(s2, JsonFormat.compact());
   LinkedHashMap map1 = Json.fromJson(LinkedHashMap.class, ss1);
   // map1.remove("a");
   LinkedHashMap map2 = Json.fromJson(LinkedHashMap.class, ss2);
   // map2.remove("a");
   System.out.println(
       Base64.encodeToString(
           Json.toJson(sortHashtable.sortByValue(map1), JsonFormat.compact()).getBytes(), true));
   System.out.println(
       Base64.encodeToString(
           Json.toJson(sortHashtable.sortByValue(map1), JsonFormat.compact()).getBytes(), false));
   System.out.println(Json.toJson(sortHashtable.sortByValue(map2), JsonFormat.compact()));
 }
示例#16
0
  public NutMap wx_minfo(String info, HttpServletRequest req) throws Exception {
    String uri = myWxApi.getCompleteUri(req); // 获取完整uri,否则jsticket无法使用
    Logs.get().debugf("request url=%s", uri);

    String decinfo = BlueDes.decrypt(info);
    HashMap<String, String> minfo = Json.fromJson(HashMap.class, decinfo);

    return wx_init(uri, minfo);
  }
示例#17
0
  /**
   * 它将对象序列化成 JSON 字符串,并写入 HTTP 响应
   *
   * @param resp 响应对象
   * @param obj 数据对象
   * @param format JSON 的格式化方式
   * @throws IOException 写入失败
   */
  public static void write(HttpServletResponse resp, Object obj, JsonFormat format)
      throws IOException {
    resp.setHeader("Cache-Control", "no-cache");
    resp.setContentType("text/plain");

    // by mawm 改为直接采用resp.getWriter()的方式直接输出!
    Json.toJson(resp.getWriter(), obj, format);

    resp.flushBuffer();
  }
示例#18
0
 @At("/saveMenuOperations")
 @Ok("json")
 public Map<String, Object> saveMenuOperations(
     HttpServletRequest request, @Param("optIds") String menuIds, @Param("menuId") Long menuId) {
   Long[] mIds = Json.fromJson(Long[].class, menuIds);
   boolean re = operationService.saveMenuOperations(menuId, mIds);
   Map<String, Object> reMap = new HashMap<String, Object>();
   reMap.put("success", re);
   return reMap;
 }
示例#19
0
 /** 分页 */
 public void list() {
   TbRole entity = new TbRole();
   Page<TbRole> pageInfo = new Page<TbRole>();
   pageInfo.setStart(1);
   pageInfo.setPageSize(20);
   pageInfo.setPageNo(1);
   pageInfo.setOrderFiled("id");
   pageInfo.setOrderDirection("desc");
   Page<TbRole> page = roleService.findByPage(entity, pageInfo);
   log.info("page:" + Json.toJson(page));
 }
示例#20
0
 @At
 @Ok("raw")
 public String tree(@Param("id") String id, HttpSession session) throws Exception {
   Sys_user user = (Sys_user) session.getAttribute("userSession");
   id = Strings.sNull(id);
   List array = new ArrayList();
   if ("".equals(id)) {
     Map<String, Object> jsonroot = new HashMap<String, Object>();
     jsonroot.put("id", "");
     jsonroot.put("pId", "0");
     jsonroot.put("name", "机构列表");
     jsonroot.put("icon", Globals.APP_BASE_NAME + "/images/icons/icon042a1.gif");
     array.add(jsonroot);
   }
   Criteria cri = Cnd.cri();
   if (user.getSysrole()) // 判断是否为系统管理员角色
   {
     cri.where().and("id", "like", id + "____");
     cri.getOrderBy().asc("location");
     cri.getOrderBy().asc("id");
   } else {
     if ("".equals(id)) {
       cri.where().and("id", "=", user.getUnitid());
       cri.getOrderBy().asc("location");
       cri.getOrderBy().asc("id");
     } else {
       cri.where().and("id", "like", id + "____");
       cri.getOrderBy().asc("location");
       cri.getOrderBy().asc("id");
     }
   }
   List<Sys_unit> unitlist = daoCtl.list(dao, Sys_unit.class, cri);
   int i = 0;
   for (Sys_unit u : unitlist) {
     String pid = u.getId().substring(0, u.getId().length() - 4);
     int num =
         daoCtl.getRowCount(dao, Sys_unit.class, Cnd.wrap("id like '" + u.getId() + "____'"));
     if (i == 0 || "".equals(pid)) pid = "0";
     Map<String, Object> obj = new HashMap<String, Object>();
     obj.put("id", u.getId());
     obj.put("pId", pid);
     obj.put("name", u.getName());
     obj.put("url", "javascript:view(\"" + u.getId() + "\")");
     obj.put("isParent", num > 0 ? true : false);
     obj.put("target", "_self");
     array.add(obj);
     i++;
   }
   return Json.toJson(array);
 }
示例#21
0
  @At
  @Ok("->:/private/sys/unitSort.html")
  public void sort(@Param("id") String id, HttpServletRequest req, HttpSession session)
      throws Exception {
    Sys_user user = (Sys_user) session.getAttribute("userSession");
    Condition c;
    if (user.getSysrole()) // 判断是否为系统管理员角色
    {
      c = Cnd.where("id", "is not", null).asc("location,id");
    } else {
      c = Cnd.where("id", "like", user.getUnitid() + "%'").asc("location,id");
    }
    List<Sys_unit> list = daoCtl.list(dao, Sys_unit.class, c);
    List<Object> array = new ArrayList<Object>();
    Map<String, Object> jsonroot = new HashMap<String, Object>();
    jsonroot.put("id", "");
    jsonroot.put("pId", "0");
    jsonroot.put("name", "机构列表");
    jsonroot.put("open", true);
    jsonroot.put("childOuter", false);
    jsonroot.put("icon", Globals.APP_BASE_NAME + "/images/icons/icon042a1.gif");
    array.add(jsonroot);
    for (int i = 0; i < list.size(); i++) {
      Map<String, Object> jsonobj = new HashMap<String, Object>();
      Sys_unit obj = list.get(i);
      jsonobj.put("id", obj.getId());
      String p = obj.getId().substring(0, obj.getId().length() - 4);
      jsonobj.put("pId", p == "" ? "0" : p);
      jsonobj.put("name", obj.getName());
      jsonobj.put("childOuter", false);
      if (obj.getId().length() < 12) {
        jsonobj.put("open", true);
      } else {
        jsonobj.put("open", false);
      }
      array.add(jsonobj);
    }

    req.setAttribute("str", Json.toJson(array));
  }
 public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
     throws Exception {
   HttpServletRequest req = (HttpServletRequest) request;
   HttpServletResponse resp = (HttpServletResponse) response;
   if ("GET".equals(req.getMethod()) && !Strings.isBlank(req.getParameter("token"))) {
     String token = req.getParameter("token");
     try {
       token = Toolkit._3DES_decode(CrossScreen.csKEY, Toolkit.hexstr2bytearray(token));
       NutMap map = Json.fromJson(NutMap.class, token);
       Long t = map.getLong("t", -1);
       if (System.currentTimeMillis() - t > timeout * 1000) {
         resp.sendError(403); // TODO 提示token已经过期
         return false;
       }
       Integer uid = (Integer) map.get("uid");
       if (uid != null) {
         // 有登陆用户
         Toolkit.doLogin(new CrossScreenUserToken(uid), uid);
         if (sysLogService == null) {
           try {
             sysLogService = Mvcs.ctx().getDefaultIoc().get(SysLogService.class);
           } catch (Throwable e) {
           }
         }
         sysLogService.async(SysLog.c("method", "用户登陆", null, uid, "用户通过跨屏二维码登陆"));
       }
       resp.sendRedirect(map.getString("url"));
       return false;
     } catch (Exception e) {
       log.debug("bad token?", e);
       resp.sendError(502);
       return false;
     }
   } else {
     resp.sendError(403);
     return false;
   }
 }
 @SecurityMapping(
     title = "楼层模板商品分类保存",
     value = "/admin/goods_floor_class_save.htm*",
     rtype = "admin",
     rname = "首页楼层",
     rcode = "goods_floor",
     rgroup = "商品")
 @RequestMapping("/admin/goods_floor_class_save.htm")
 public String goods_floor_class_save(
     HttpServletRequest request,
     HttpServletResponse response,
     String id,
     String ids,
     String gf_name) {
   GoodsFloor obj = this.goodsfloorService.getObjById(CommUtil.null2Long(id));
   obj.setGf_name(gf_name);
   List gf_gc_list = new ArrayList();
   String[] id_list = ids.split(",pid:");
   for (String t_id : id_list) {
     String[] c_id_list = t_id.split(",");
     Map map = new HashMap();
     for (int i = 0; i < c_id_list.length; i++) {
       String c_id = c_id_list[i];
       if (c_id.indexOf("cid") < 0) {
         map.put("pid", c_id);
       } else {
         map.put("gc_id" + i, c_id.substring(4));
       }
     }
     map.put("gc_count", c_id_list.length - 1);
     if (!map.get("pid").toString().equals("")) gf_gc_list.add(map);
   }
   // System.out.println(Json.toJson(gf_gc_list, JsonFormat.compact()));
   obj.setGf_gc_list(Json.toJson(gf_gc_list, JsonFormat.compact()));
   this.goodsfloorService.update(obj);
   return "redirect:goods_floor_template.htm?id=" + id;
 }
示例#24
0
  @ResponseBody
  @RequestMapping(value = "/event")
  public String event(String message) throws Exception {
    message = new String(message.getBytes("iso-8859-1"), "gbk");
    logger.info("message:{}", message);
    ExecuteResult e = new ExecuteResult("0", "");

    if (StringUtils.isNotBlank(message)) {
      try {
        HwpaeventBean event = Json.fromJson(HwpaeventBean.class, message);
        hwpaeventService.insert(event);
        logger.debug("eventlog save finish");
        e.setResult("1");
        e.setMessage("ok");
      } catch (Exception e1) {
        logger.info(e1.getMessage(), e1);
        e.setMessage("proccess_failed");
      }
    } else {
      e.setMessage("message_invalid");
    }

    return JsonUtil.toJson(e);
  }
示例#25
0
  @SuppressWarnings("unchecked")
  protected Profile authLogin() throws Exception {
    String presp;

    try {
      Response response = authenticationStrategy.executeFeed(PROFILE_URL);
      presp = response.getResponseBodyAsString(Constants.ENCODING);
      System.out.println(response.getStatus());
    } catch (Exception e) {
      throw new SocialAuthException("Error while getting profile from " + PROFILE_URL, e);
    }
    try {
      // System.out.println("User Profile : " + presp);
      Map<String, Object> data = Json.fromJson(Map.class, presp);
      if (!data.containsKey("id")) throw new SocialAuthException("Error: " + presp);
      if (userProfile == null) userProfile = new Profile();
      userProfile.setValidatedId(data.get("id").toString());
      userProfile.setProviderId(getProviderId());
      return userProfile;

    } catch (Exception ex) {
      throw new ServerDataException("Failed to parse the user profile json : " + presp, ex);
    }
  }
示例#26
0
 public String toString() {
   return "/*AnnotationIocLoader*/\n" + Json.toJson(map);
 }
示例#27
0
 /** 插入角色和权限的关系 */
 public void updateRoleRight() {
   Long[] rightIds = {4L, 5L, 1L};
   log.info("rightIds:" + Json.toJson(rightIds));
   roleService.updateRoleRight(5L, rightIds);
   log.info("insert RoleRight success.");
 }
示例#28
0
 @Override
 public Map cast(String src, Class<?> toType, String... args) throws FailToCastObjectException {
   return (Map) Json.fromJson(Lang.inr(src));
 }
  @SecurityMapping(
      title = "楼层模板右下方广告保存",
      value = "/admin/goods_floor_right_adv_save.htm*",
      rtype = "admin",
      rname = "首页楼层",
      rcode = "goods_floor",
      rgroup = "商品")
  @RequestMapping("/admin/goods_floor_right_adv_save.htm")
  public String goods_floor_right_adv_save(
      HttpServletRequest request,
      HttpServletResponse response,
      String type,
      String id,
      String adv_url,
      String adv_id) {
    GoodsFloor obj = this.goodsfloorService.getObjById(CommUtil.null2Long(id));
    Map map = new HashMap();
    if (type.equals("user")) {
      // 模板广告图片
      String uploadFilePath = ConfigContants.UPLOAD_IMAGE_MIDDLE_NAME;
      String saveFilePathName =
          TytsmsStringUtils.generatorImagesFolderServerPath(request)
              + uploadFilePath
              + File.separator
              + "advert";
      Map json_map = new HashMap();
      try {
        map = CommUtil.saveFileToServer(configService, request, "img", saveFilePathName, "", null);
        if (map.get("fileName") != "") {
          Accessory acc = new Accessory();
          acc.setName(CommUtil.null2String(map.get("fileName")));
          acc.setExt(CommUtil.null2String(map.get("mime")));
          acc.setSize(BigDecimal.valueOf(CommUtil.null2Double(map.get("fileSize"))));
          acc.setPath(uploadFilePath + "/advert");
          acc.setWidth(CommUtil.null2Int(map.get("width")));
          acc.setHeight(CommUtil.null2Int(map.get("height")));
          acc.setAddTime(new Date());
          this.accessoryService.save(acc);
          json_map.put("acc_id", acc.getId());
        }

      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      json_map.put("acc_url", adv_url);
      json_map.put("adv_id", "");
      System.out.println(Json.toJson(json_map, JsonFormat.compact()));
      obj.setGf_right_adv(Json.toJson(json_map, JsonFormat.compact()));
    }
    if (type.equals("adv")) {
      Map json_map = new HashMap();
      json_map.put("acc_id", "");
      json_map.put("acc_url", "");
      json_map.put("adv_id", adv_id);
      System.out.println(Json.toJson(json_map, JsonFormat.compact()));
      obj.setGf_right_adv(Json.toJson(json_map, JsonFormat.compact()));
    }
    this.goodsfloorService.update(obj);
    return "redirect:goods_floor_template.htm?id=" + obj.getId();
  }
示例#30
0
  @SuppressWarnings("unchecked")
  private void pojo2Json(Object obj) throws IOException {
    if (null == obj) return;
    /*
     * Default
     */
    Class<?> type = obj.getClass();
    JsonEntity jen = Json.getEntity(Mirror.me(type));
    Method toJsonMethod = jen.getToJsonMethod();
    if (toJsonMethod != null) {
      try {
        if (toJsonMethod.getParameterTypes().length == 0) {
          writer.append(String.valueOf(toJsonMethod.invoke(obj)));
        } else {
          writer.append(String.valueOf(toJsonMethod.invoke(obj, format)));
        }
        return;
      } catch (Exception e) {
        throw Lang.wrapThrow(e);
      }
    }
    List<JsonEntityField> fields = jen.getFields();
    appendBraceBegin();
    increaseFormatIndent();
    ArrayList<Pair> list = new ArrayList<Pair>(fields.size());
    for (JsonEntityField jef : fields) {
      if (jef.isIgnore()) continue;
      String name = jef.getName();
      try {
        Object value = jef.getValue(obj);

        // 判断是否应该被忽略
        if (!this.isIgnore(name, value)) {
          Mirror mirror = null;
          // 以前曾经输出过 ...
          if (null != value) {
            // zozoh: 循环引用的默认行为,应该为 null,以便和其他语言交换数据
            mirror = Mirror.me(value);
            if (mirror.isPojo()) {
              if (memo.contains(value)) value = null;
            }
          }
          // 如果是强制输出为字符串的
          if (null != value && jef.isForceString()) {
            // 数组
            if (value.getClass().isArray()) {
              String[] ss = new String[Array.getLength(value)];
              for (int i = 0; i < ss.length; i++) {
                ss[i] = Array.get(value, i).toString();
              }
              value = ss;
            }
            // 集合
            else if (value instanceof Collection) {
              Collection col = (Collection) Mirror.me(value).born();
              for (Object ele : (Collection) value) {
                col.add(ele.toString());
              }
              value = col;
            }
            // 其他统统变字符串
            else {
              value = value2string(jef, value);
            }
          } else if (jef.hasDataFormat() && null != value && value instanceof Date) {
            value = jef.getDataFormat().format((Date) value);
          } else if (jef.hasDataFormat() && null != value && mirror.isNumber()) {
            value = jef.getDataFormat().format(value);
          }

          // 加入输出列表 ...
          list.add(new Pair(name, value));
        }
      } catch (FailToGetValueException e) {
      }
    }
    writeItem(list);
  }