/** Create by tanliansheng on 2015年10月29日 */
@ControllerBind(controllerKey = "/admin/user", viewPath = "/ftl/admin/user")
public class UserAdminController extends Controller {

  private static final Logger LOG = Logger.getLogger(UserAdminController.class);

  public void index() {

    int pageNo = getParaToInt("pageNo", 1);
    int pageSize = getParaToInt("pageSize", 10);

    Page<User> userPage =
        User.dao.paginate(
            pageNo,
            pageSize,
            "select u.username,u.is_locked,u.id,r.name,r.description ",
            "from system_user u "
                + "LEFT JOIN system_user_role ur on ur.user_id = u.id "
                + "LEFT JOIN system_role r on r.id = ur.role_id ");

    TablePage tp = new TablePage(pageNo, pageSize, userPage.getTotalRow(), userPage.getTotalPage());

    setAttr("page", userPage);
    setAttr("pageStr", tp.toString());

    render("index.html");
  }

  public void update() {
    int id = getParaToInt("id", 0);
    if (id > 0) {
      setAttr("user", User.dao.findByUserId(id));
      render("update.html");
    }
  }
}
public class ConfigPlugin implements IPlugin {

  static String suffix = "txt";

  protected final Logger logger = Logger.getLogger(getClass());

  private final List<String> includeResources = Lists.newArrayList();

  private final List<String> excludeResources = Lists.newArrayList();

  private boolean reload = true;

  public ConfigPlugin(String... includeResources) {
    if (includeResources != null) {
      for (String includeResource : includeResources) {
        this.includeResources.add(includeResource);
      }
    }
  }

  public ConfigPlugin excludeResource(String... resource) {
    if (includeResources != null) {
      for (String excludeResource : excludeResources) {
        excludeResources.add(excludeResource);
      }
    }
    return this;
  }

  public ConfigPlugin addResource(String resource) {
    includeResources.add(resource);
    return this;
  }

  public ConfigPlugin reload(boolean reload) {
    this.reload = reload;
    return this;
  }

  public static void setSuffix(String suffix) {
    ConfigPlugin.suffix = suffix;
  }

  @Override
  public boolean start() {
    ConfigKit.init(includeResources, excludeResources, reload);
    return true;
  }

  @Override
  public boolean stop() {
    return true;
  }
}
Exemple #3
0
/** ActionException. */
public class ActionException extends RuntimeException {

  private static final long serialVersionUID = 1998063243843477017L;
  private static final Logger log = Logger.getLogger(ActionException.class);
  private int errorCode;
  private Render errorRender;

  public ActionException(final int errorCode, final Render errorRender) {
    if (errorRender == null)
      throw new IllegalArgumentException("The parameter errorRender can not be null.");

    this.errorCode = errorCode;

    if (errorRender instanceof com.jfinal.render.ErrorRender) {
      this.errorRender = errorRender;
    } else {
      this.errorRender =
          new Render() {
            public Render setContext(
                HttpServletRequest req, HttpServletResponse res, String viewPath) {
              errorRender.setContext(req, res, viewPath);
              res.setStatus(errorCode); // important
              return this;
            }

            public void render() {
              errorRender.render();
            }
          };
    }
  }

  public ActionException(int errorCode, String errorView) {
    if (StrKit.isBlank(errorView))
      throw new IllegalArgumentException("The parameter errorView can not be blank.");

    this.errorCode = errorCode;
    this.errorRender = RenderFactory.me().getErrorRender(errorCode, errorView);
  }

  public ActionException(int errorCode, Render errorRender, String errorMessage) {
    this(errorCode, errorRender);
    log.warn(errorMessage);
  }

  public int getErrorCode() {
    return errorCode;
  }

  public Render getErrorRender() {
    return errorRender;
  }
}
Exemple #4
0
public class ThreadParamInit extends Thread {

  private static Logger log = Logger.getLogger(ThreadParamInit.class);

  public static String cacheStart_role = "role_";
  public static String cacheStart_permission = "permission_";
  public static String cacheStart_user = "******";
  public static String cacheStart_branch = "branch_";
  public static String cacheStart_apartment = "apartment_";
  public static String cacheStart_position = "position_";
  public static String cacheStart_operator = "operator_";
  public static String cacheStart_dict = "dict_";
  public static String cacheStart_dict_child = "dict_child_";
  public static String cacheStart_etype = "etype_";
  public static String cacheStart_etype_child = "etype_child_";

  @Override
  public void run() {
    cacheAll();
  }

  public static synchronized void cacheAll() {}
}
/** 角色 */
@Control(controllerKey = "/role")
public class RoleController extends BaseController {

  private static final Logger LOG = Logger.getLogger(RoleController.class);

  public void index() {
    List<SysRolesModel> role = SysRolesModel.dao.allRoles();
    List<SysMenusModel> menu = SysMenusModel.dao.allMenus();
    setAttr("rolesJson", JsonKit.toJson(role));
    setAttr("menusJson", JsonKit.toJson(menu));
    render("tissue/role_mgr");
  }

  public void list() {
    setAttr(DATA, SysRolesModel.dao.getRoleByParent(getUser().getInt("roleID")));
    setAttr(RESULT, true);
    renderJson();
  }

  public void add() {
    SysRolesModel menu = getModelWithOutModelName(SysRolesModel.class, true);
    if (menu.save()) {
      setAttr(MESSAGE, "新增成功!");
      setAttr("id", menu.get("id"));
      setAttr(RESULT, true);
      DisplayTool.removeCache(DisplayTool.ROLE_KEY);
    } else {
      setAttr(RESULT, false);
      setAttr(MESSAGE, "新增失败!");
    }
    renderJson();
  }

  public void update() {
    SysRolesModel role = getModelWithOutModelName(SysRolesModel.class, true);
    if (role.get("id") != null && role.update()) {
      setAttr(RESULT, true);
      setAttr(MESSAGE, "更新成功!");
      DisplayTool.removeCache(DisplayTool.ROLE_KEY);
    } else {
      setAttr(RESULT, false);
      setAttr(MESSAGE, "更新失败!");
    }
    renderJson();
  }

  public void del() {
    Integer id = getParaToInt("id");
    if (id != null && SysRolesModel.dao.deleteById(id)) {
      setAttr(RESULT, true);
      setAttr(MESSAGE, "删除成功!");
    } else {
      setAttr(RESULT, false);
      setAttr(MESSAGE, "删除失败!");
    }
    renderJson();
  }

  public void roleMenu() {
    Integer id = getParaToInt("id");
    if (id != null) {
      setAttr(RESULT, true);
      setAttr(DATA, SysRoleMenuModel.dao.getRoleMenus(id));
    } else {
      setAttr(RESULT, false);
      setAttr(MESSAGE, "参数错误,获取数据失败!");
    }
    renderJson();
  }

  public void menuChecked() {
    Boolean checked = getParaToBoolean("checked");
    SysRoleMenuModel roleMenu = getModelWithOutModelName(SysRoleMenuModel.class, true);
    if (checked != null && roleMenu.get("roleID") != null && roleMenu.get("menuID") != null) {
      setAttr(RESULT, true);
      SysRoleMenuModel.dao.changeRoleMenu(roleMenu, checked);
      setAttr(MESSAGE, "修改成功!");
    } else {
      setAttr(RESULT, false);
      setAttr(MESSAGE, "参数错误,获取数据失败!");
    }
    renderJson();
  }
}
// @Controller(controllerKey = "/buyer/collect")
@Before(LoginInteceptor.class)
public class CollectController extends BaseController {
  private static Logger log = Logger.getLogger(CollectController.class);
  // 查询用户的收藏(默认查询的是用户收藏的商品)
  public void collectlist() {
    Member member = Member.dao.findById(getUserIds());
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("userId", member.getStr("id"));
    Integer pageNum = getParaToInt("pageNum");
    Integer pageSize = getParaToInt("pageSize");
    if (pageNum == null || pageNum.intValue() < 1) {
      pageNum = 1; // 默认第一页
    }
    if (pageSize == null || pageSize.intValue() < 0) {
      pageSize = 10; // 默认每页显示10条
    } else if (pageSize.intValue() > 100) {
      pageSize = 10; // 最大100条
    }
    Page<Collect> collects = Collect.dao.findGoodsCollectByUserId(pageNum, pageSize, params);
    setAttr("collects", collects);
    setAttr("param", paramsToStr(params));
    render("");
  }

  // 删除用户收藏(商品)
  public void deleteGoodsCollect() {
    Collect.dao.deleteById(getPara("collect_id"));
    redirect("/buyer/collect/collectlist");
  }

  // 查询用户收藏(店铺)
  public void storecollect() {
    Member member = Member.dao.findById(getUserIds());
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("userId", member.getStr("id"));
    Integer pageNum = getParaToInt("pageNum");
    Integer pageSize = getParaToInt("pageSize");
    if (pageNum == null || pageNum.intValue() < 1) {
      pageNum = 1; // 默认第一页
    }
    if (pageSize == null || pageSize.intValue() < 0) {
      pageSize = 10; // 默认每页显示10条
    } else if (pageSize.intValue() > 100) {
      pageSize = 10; // 最大100条
    }
    Page<Collect> collects = Collect.dao.findStoreCollectByUserId(pageNum, pageSize, params);
    setAttr("collects", collects);
    setAttr("param", paramsToStr(params));
    render("");
  }

  // 删除用户收藏(店铺)
  public void deleteStoreCollect() {
    Collect.dao.deleteById(getPara("collect_id"));
    redirect("/buyer/collect/storecollect");
  }

  // 添加收藏
  @ClearInterceptor
  public void saveCollect() {
    Member member = Member.dao.findById(getUserIds());
    Collect collect =
        Collect.dao.findByCollect(getPara("collect_type"), getPara("collect"), member.getStr("id"));
    if (collect == null) {
      new Collect()
          .set("user_id", member.getStr("id"))
          .set("id", ToolUtil.getUuidByJdk(true))
          .set("collect", getPara("collect"))
          .set("collect_type", getPara("collect_type"))
          .save();
      setAttr("massege", true);
    } else { // 已经收藏
      setAttr("massege", false);
    }
    setAttr("collect_type", getPara("collect_type"));
    render("/store/shoucangDialog.html");
  }

  @ClearInterceptor
  public void islogin() {
    JSONObject result = new JSONObject();
    // 验证是否登陆
    if (StringUtil.isBlank(getUserIds())) {
      result.put("isLogin", false);
      result.put("error", "请先登录");
      renderJson(result.toString());
      return;
    }
    result.put("isLogin", true);
    renderJson(result.toString());
  }
}
Exemple #7
0
public class ConfigKit {

  protected static final Logger LOG = Logger.getLogger(ConfigKit.class);

  private static List<String> includeResources;

  private static List<String> excludeResources;

  private static Map<String, String> map = Maps.newHashMap();

  private static Map<String, String> testMap = Maps.newHashMap();

  private static Map<String, Long> lastmodifies = new HashMap<String, Long>();

  private static boolean reload = true;

  /**
   * @param includeResources
   * @param excludeResources
   * @param reload
   */
  static void init(List<String> includeResources, List<String> excludeResources, boolean reload) {
    ConfigKit.includeResources = includeResources;
    ConfigKit.excludeResources = excludeResources;
    ConfigKit.reload = reload;
    for (final String resource : includeResources) {
      LOG.debug("include :" + resource);
      File[] propertiesFiles = null;
      propertiesFiles =
          new File(PathKit.getRootClassPath())
              .listFiles(
                  new FileFilter() {

                    @Override
                    public boolean accept(File pathname) {
                      return Pattern.compile(resource).matcher(pathname.getName()).matches();
                    }
                  });
      for (File file : propertiesFiles) {
        String fileName = file.getAbsolutePath();
        LOG.debug("fileName:" + fileName);
        if (fileName.endsWith("-test." + ConfigPlugin.getSuffix())) {
          continue;
        }
        boolean excluded = false;
        for (String exclude : excludeResources) {
          if (Pattern.compile(exclude).matcher(file.getName()).matches()) {
            excluded = true;
          }
        }
        if (excluded) {
          continue;
        }
        lastmodifies.put(fileName, new File(fileName).lastModified());
        map = ResourceKit.readProperties(fileName);
        testMap = ResourceKit.readProperties(testFileName(fileName));
      }
    }
    LOG.debug("map" + map);
    LOG.debug("testMap" + testMap);
    LOG.info("config init success!");
  }

  private static String testFileName(String fileName) {
    return fileName.substring(0, fileName.indexOf("." + ConfigPlugin.getSuffix()))
        + "-test."
        + ConfigPlugin.getSuffix();
  }

  public static String getStr(String key, String defaultVal) {
    if (testMap == null || map == null) {
      throw new RuntimeException(" please start ConfigPlugin first~");
    }
    if (reload) {
      checkFileModify();
    }
    String val = testMap.get(key);
    if (val == null || "".equals(val.trim())) {
      val = map.get(key);
    }
    return val == null ? defaultVal : val + "";
  }

  private static void checkFileModify() {
    Set<String> filenames = lastmodifies.keySet();
    for (String filename : filenames) {
      File file = new File(filename);
      if (lastmodifies.get(filename) != file.lastModified()) {
        LOG.info(filename + " changed, reload.");
        init(includeResources, excludeResources, reload);
      }
    }
  }

  public static String getStr(String key) {
    return getStr(key, "");
  }

  public static long getLong(String key) {
    return getLong(key, 0);
  }

  public static long getLong(String key, long defaultVal) {
    String val = getStr(key).trim();
    if ("".equals(val)) {
      return defaultVal;
    }
    return Long.parseLong(val);
  }

  public static int getInt(String key, int defaultVal) {
    String val = getStr(key).trim();
    if ("".equals(val)) {
      return defaultVal;
    }
    return Integer.parseInt(val);
  }

  public static int getInt(String key) {
    return getInt(key, 0);
  }

  public static void set(String key, String val) {
    // TODO
    throw new RuntimeException("I do not know how to do it now..");
  }
}
public class BigwheelController extends BaseController {
  private static Logger log = Logger.getLogger(AppraiseController.class);

  /**
   * \ // Object[][] prizeArr = new Object[][]{ // //id,min,max,prize【奖项】,v【中奖率】 // //外面的转盘转动 // //
   * {1,1,14,"一等奖",1}, // // {2,346,364,"一等奖",1}, // // {3,16,44,"不要灰心",10}, // //
   * {4,46,74,"神马也没有",10}, // // {5,76,104,"祝您好运",10}, // // {6,106,134,"二等奖",2}, // //
   * {7,136,164,"再接再厉",10}, // // {8,166,194,"神马也没有",10}, // // {9,196,224,"运气先攒着",10}, // //
   * {10,226,254,"三等奖",5}, // // {11,256,284,"要加油哦",10}, // // {12,286,314,"神马也没有",10}, // //
   * {13,316,344,"谢谢参与",10} // // //里面的指针转动 // {1,1,14,"一等奖",1}, // {2,346,364,"一等奖",1}, //
   * {3,16,44,"不要灰心",10}, // {4,46,74,"神马也没有",10}, // {5,76,104,"祝您好运",10}, // {6,106,134,"二等奖",2},
   * // {7,136,164,"再接再厉",10}, // {8,166,194,"神马也没有",10}, // {9,196,224,"运气先攒着",10}, //
   * {10,226,254,"三等奖",5}, // {11,256,284,"要加油哦",10}, // {12,286,314,"神马也没有",10}, //
   * {13,316,344,"谢谢参与",10} // };
   */
  public void award() {
    JSONObject json = new JSONObject();
    Member member = Member.dao.findById(getUserIds());
    String storeId = getPara("storeId");
    String programId = getPara("programId");
    ActiveProgram activeProgram = ActiveProgram.dao.findById(programId);
    // 查询是否中奖
    Integer prizeCount =
        ActivePrizeInfo.dao.prizeCount(
            member.getStr("id"), DateUtil.format(new Date(), "yyyyMMdd") + "%", storeId, programId);
    if (prizeCount > 0) {
      json.put("msg", "你已中奖,今天不能在抽奖了");
      json.put("isRight", false);
      renderJson(json.toString());
      return;
    }

    // 查询是否超过限制
    // String time = "";

    Integer count =
        ActivePrizeInfo.dao.findCountBydate(
            member.getStr("id"),
            storeId,
            activeProgram.getStr("activetype_id"),
            programId,
            DateUtil.format(new Date(), "yyyyMMdd") + "%");
    if (count >= activeProgram.getInt("repeat_prize_count")) {
      json.put("msg", "你的抽奖次数已经用完!");
      json.put("isRight", false);
      renderJson(json.toString());
      return;
    }

    List<ActiveProgramItem> activeProgramItems =
        ActiveProgramItem.dao.findActiveProgramItem(programId);
    // 封装

    List<Object[]> prizeArr = new ArrayList<Object[]>();

    Integer totalCount = 0; // 计算总数
    for (int i = 0; i < activeProgramItems.size(); i++) {
      totalCount += activeProgramItems.get(i).getInt("item_count");
    }

    // 设置未中奖信息
    double cal_isPrize = totalCount / (double) activeProgram.getInt("partake_num"); // 中奖概率
    Object[] result_ = new Object[6];
    result_[0] = "-1";
    result_[1] = 31;
    result_[2] = 89;
    result_[3] = "你未中奖";
    result_[4] = (int) ((1 - cal_isPrize) * 100);
    result_[5] = "";
    prizeArr.add(result_);

    // 设置中奖信息
    for (int i = 0; i < activeProgramItems.size(); i++) {
      ActiveProgramItem item = activeProgramItems.get(i);
      if (totalCount == 0) continue;
      double cal = item.getInt("item_count") / (double) activeProgram.getInt("partake_num"); // 每次概率
      if (item.getInt("px") == 1) {
        Object[] r1 = new Object[6];
        r1[0] = item.get("id");
        r1[1] = 1;
        r1[2] = 29;
        r1[3] = item.get("name");
        r1[4] = (int) (cal * 100);
        r1[5] = item.get("active_prize_item_id");
        prizeArr.add(r1);

        Object[] r2 = new Object[6];
        r2[0] = item.get("id");
        r2[1] = 331;
        r2[2] = 359;
        r2[3] = item.get("name");
        r2[4] = (int) (cal * 100);
        r2[5] = item.get("active_prize_item_id");
        prizeArr.add(r2);
      } else {
        Object[] result = new Object[6];
        result[0] = item.get("id");
        result[1] = 360 - (item.getInt("px") - 1) * 60 - 30 + 1;
        result[2] = 360 - (item.getInt("px") - 2) * 60 - 30 - 1;
        result[3] = item.getStr("name");
        result[4] = (int) (cal * 100);
        result[5] = item.get("active_prize_item_id");
        prizeArr.add(result);
      }
    }
    Object result[] = award(prizeArr); // 抽奖后返回角度和奖品等级
    // 1 得到奖项 更新数量
    String itemId = (String) result[3]; // 判断是否中奖
    String provavilit = (String) result[4]; // 奖项类型ID

    // 1.更新奖品数量
    if (StringUtil.isNotBlank(itemId) && !"-1".equals(itemId)) {
      ActiveProgramItem.dao.updateCount(itemId); // 更新数量
    }

    Store store = Store.dao.findById(activeProgram.get("store_id"));

    ActivePrizeItem item = ActivePrizeItem.dao.findById(provavilit);

    ActivePrizeInfo info = new ActivePrizeInfo();
    info.set("id", ToolUtil.getUuidByJdk(true))
        .set("user_id", member.get("id"))
        .set("store_id", activeProgram.get("store_id"))
        .set("store_name", store.get("name"))
        .set("active_type_id", activeProgram.get("activetype_id"))
        .set("active_program_id", activeProgram.get("id"))
        .set("active_program_name", activeProgram.get("name"))
        .set("active_program_item_id", itemId)
        .set("prize_code", "JL" + GenerateUtils.consumCode())
        .set("status", 1)
        .set("loose_time", activeProgram.get("end_time"))
        .set("prize_time", DateUtil.format(new Date(), "yyyyMMddHHmmss"))
        .set("prize_item_name", item != null ? item.get("item_name") : "");
    ActivePrizeInfo.dao.saveInfo(info, item, member.getStr("id"));

    json.put("angle", result[0]);
    json.put("msg", result[2]);
    json.put("isRight", true);
    renderJson(json.toString());
  }

  // 抽奖并返回角度和奖项
  public Object[] award(List<Object[]> prizeArr) {
    // 概率数组
    Integer obj[] = new Integer[prizeArr.size()];
    for (int i = 0; i < prizeArr.size(); i++) {
      obj[i] = (Integer) prizeArr.get(i)[4];
    }
    Integer prize = getRand(obj); // 根据概率获取奖项id
    // 旋转角度
    int angle =
        new Random().nextInt((Integer) prizeArr.get(prize)[2] - (Integer) prizeArr.get(prize)[1])
            + (Integer) prizeArr.get(prize)[1];
    String msg = (String) prizeArr.get(prize)[3]; // 提示信息
    String prizeId = (String) prizeArr.get(prize)[0]; // 提示信息
    return new Object[] {angle, prize, msg, prizeId, prizeArr.get(prize)[5]};
  }

  // 根据概率获取奖项
  public Integer getRand(Integer obj[]) {
    Integer result = null;
    try {
      int sum = 0; // 概率数组的总概率精度
      for (int i = 0; i < obj.length; i++) {
        sum += obj[i];
      }
      for (int i = 0; i < obj.length; i++) { // 概率数组循环
        int randomNum = new Random().nextInt(sum); // 随机生成1到sum的整数
        if (randomNum < obj[i]) { // 中奖
          result = i;
          break;
        } else {
          sum -= obj[i];
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
}
/**
 * 采购入库单
 *
 * @author 熊涛 2013.9.25
 */
@RouteBind(path = "/ckjhcheck")
@Before({ManagerPowerInterceptor.class})
public class CkjhcheckController extends BaseController {
  public static Logger log = Logger.getLogger(CkjhcheckController.class);
  private static String navTabId = "ckjhcheck";
  private String supplierCodePara = null;
  private byte[] lock = new byte[0];

  @Override
  public void index() {
    select();
    render("index.html");
  }

  public void list() {
    supplierCodePara = getPara();
    select();
    render("list.html");
  }

  private void select() {
    StringBuffer whee = new StringBuffer();
    List<Object> param = new ArrayList<Object>();
    String startTime = getPara("startTime");
    if (startTime != null && !"".equals(startTime.trim())) {
      whee.append(" and UNIX_TIMESTAMP(p.OrderDate) >= UNIX_TIMESTAMP(?)");
      param.add(startTime);
    }
    setAttr("startTime", startTime);
    String endTime = getPara("endTime");
    if (endTime != null && !"".equals(endTime.trim())) {
      whee.append(" and UNIX_TIMESTAMP(p.OrderDate) <= UNIX_TIMESTAMP(?)");
      param.add(endTime);
    }
    setAttr("endTime", endTime);
    String supplierCode = getPara("supplier.supplierCode");
    if (supplierCodePara != null) supplierCode = supplierCodePara;
    if (supplierCode != null && !"".equals(supplierCode.trim())) {
      whee.append(" and p.SupplierCode = ?");
      param.add(Long.parseLong(supplierCode));
    }
    setAttr("supplierCode", supplierCode);
    setAttr("supplierName", getPara("supplier.supplierName"));

    String storeCd = getPara("store.StoreCode");
    if (storeCd != null && !"".equals(storeCd.trim())) {
      whee.append(" and p.StoreCode = ?");
      param.add(Long.parseLong(storeCd));
    }
    setAttr("StoreCode", storeCd);
    setAttr("StoreName", getPara("store.StoreName"));
    String sql = " from ckjhcheck p  left join  jbsupplier b on p.SupplierCode = b.supplierCode ";
    sql += " left join  jbstore c on p.StoreCode = c.StoreCode ";
    sql += " left join  employee d on d.usr_no = p.EmpCode ";
    sql += " left join  partment e on e.deptCode = p.deptCode ";
    sql += " left join  types t on t.id=p.inoutTypeNo and t.function='入库类型'";
    sql += " where 1=1 ";
    setAttr(
        "page",
        Db.paginate(
            getParaToInt("pageNum", 1),
            getParaToInt("numPerPage", 10),
            "select p.id,p.OrderCode 订单号, p.OrderDate 进货日期,p.remark 备注, t.name 入库类型,p.BillOrderNo 采购单号,p.CKAmount 入库金额, p.payAmount 已付金额,p.checkflag 审核, b.supplierName 供应商,c.StoreName 订货仓库,d.usr_name 业务员, e.`name` 部门 ",
            sql + whee.toString(),
            param.toArray()));
    setAttr(
        "collist",
        new String[] {
          "订单号", "进货日期", "供应商", "业务员", "部门", "收货日期", "订货仓库", "入库类型", "采购单号", "入库金额", "已付金额", "审核",
          "备注"
        });
  }

  // 采购入库
  public void cgInStore() {
    Ckjhcheck ckjhcheck = new Ckjhcheck();
    Jbsupplier jbsupplier = new Jbsupplier();
    Jbstore jbstore = new Jbstore();
    List<Object> param = new ArrayList<Object>();
    // 采购入库单号
    String ordCdNw = null;
    synchronized (lock) {
      ordCdNw = BsUtil.getMaxOrdNo("OrderCode", "PK", "ckjhcheck");
    }
    ckjhcheck.set("OrderCode", ordCdNw);
    String obj = getPara();
    Cgorder cgOrd = new Cgorder();
    cgOrd = Cgorder.dao.findFirst("select * from cgorder where orderCode = ?", new Object[] {obj});
    jbsupplier =
        Jbsupplier.dao.findFirst(
            "select * from jbsupplier where supplierCode = ?", cgOrd.getStr("supplierCode"));
    jbstore =
        Jbstore.dao.findFirst(
            "select * from jbstore where StoreCode = ?", cgOrd.getStr("StoreCode"));
    // ckjhcheck.set("OrderCode", ordCdNw);
    ckjhcheck.set("OrderDate", cgOrd.getDate("DeliveryDate"));
    ckjhcheck.set("supplierCode", cgOrd.getStr("supplierCode"));
    ckjhcheck.set("StoreCode", cgOrd.getStr("StoreCode"));
    // ckjhcheck.set("InOutTypeNo", "52");
    ckjhcheck.set("BillOrderNo", cgOrd.getStr("orderCode"));
    ckjhcheck.set("deptCode", cgOrd.getStr("deptcode"));
    ckjhcheck.set("Empcode", cgOrd.getStr("Empcode"));
    ckjhcheck.set("Operator", cgOrd.getStr("Operator"));
    ckjhcheck.set("CheckFlag", 0);
    ckjhcheck.set("SettleTypeFlag", 0);
    StringBuffer whee = new StringBuffer();
    whee.append(" and a.orderCode = ?");
    param.add(obj);
    String sql =
        "select a.id,b.GoodsCode 商品编号,b.GoodsName 商品名称,b.Model 商品规格,b.BaseUnit 基本单位,b.BRefPrice 原价,a.Discount 折扣, a.Quantity 数量,";
    sql += " a.TaxRate 税率,a.TaxAmount 税额,a.Amount 税后金额";
    String sqlSelect = " from cgorderdetail a";
    sqlSelect += " left join jbgoods b on a.GoodsCode = b.GoodsCode where 1=1 ";
    Page<Record> redLst =
        Db.paginate(
            getParaToInt("pageNum", 1),
            getParaToInt("numPerPage", 20),
            sql,
            sqlSelect + whee.toString(),
            param.toArray());
    int size = redLst.getList().size();
    // 不足10条,补足10条显示
    if (size < 10) {
      for (int i = 0; i < 10 - size; i++) {
        redLst.getList().add(new Record());
      }
    }
    setAttr("page", redLst);
    setAttr(
        "collist",
        new String[] {
          "商品编号", "商品名称", "商品规格", "基本单位", "原价", "折扣%", "单价", "数量", "税率%", "折后金额", "税后金额"
        });
    setAttr("ckjhcheck", ckjhcheck);
    setAttr("store", jbstore);
    setAttr("supplier", jbsupplier);
    setAttr(InOutTypeNoSelectTarget.targetName, new InOutTypeNoSelectTarget());
    setAttr(PartmentSelectTarget.targetName, new PartmentSelectTarget());
    setAttr(EmployeeSelectTarget.targetName, new EmployeeSelectTarget());
    render("add.html");
  }

  public void add() {
    Ckjhcheck ckjhcheck = new Ckjhcheck();
    Jbsupplier jbsupplier = new Jbsupplier();
    Jbstore jbstore = new Jbstore();
    // 采购入库单号
    String ordCdNw = null;
    // 不是采购订单导入
    Long id = getParaToLong(0, 0L);
    List<Object> param = new ArrayList<Object>();
    StringBuffer whee = new StringBuffer();
    whee.append(" and a.OrderCode = ?");
    if (id != 0) { // 修改
      ckjhcheck = Ckjhcheck.dao.findById(id);
      jbsupplier =
          Jbsupplier.dao.findFirst(
              "select * from jbsupplier where supplierCode = ?", ckjhcheck.getStr("SupplierCode"));
      jbstore =
          Jbstore.dao.findFirst(
              "select * from jbstore where StoreCode = ?", ckjhcheck.getStr("StoreCode"));
      param.add(ckjhcheck.get("orderCode"));
    } else {
      synchronized (lock) {
        ordCdNw = BsUtil.getMaxOrdNo("OrderCode", "PK", "ckjhcheck");
      }
      ckjhcheck.set("OrderCode", ordCdNw);
      param.add(ordCdNw);
      // 赋值当前时间
      Date dt = new Date();
      SimpleDateFormat ckDate = new SimpleDateFormat("yyyy-MM-dd");
      ckjhcheck.set("orderdate", ckDate.format(dt));
      // 赋值制单人
      Record m = getCurrentUser();
      ckjhcheck.set("operator", m.getStr("usr_name"));
    }
    String sql =
        "select a.id,b.GoodsCode 商品编号,b.GoodsName 商品名称,b.Model 商品规格,b.BaseUnit 基本单位,b.BRefPrice 原价,a.Discount 折扣, a.Quantity 数量,";
    sql += " a.TaxRate 税率,a.TaxAmount 税额,a.Amount 金额";
    String sqlSelect = " from ckjhcheckdetail a";
    sqlSelect += " left join jbgoods b on a.GoodsCode = b.GoodsCode where 1=1 ";
    Page<Record> redLst =
        Db.paginate(
            getParaToInt("pageNum", 1),
            getParaToInt("numPerPage", 20),
            sql,
            sqlSelect + whee.toString(),
            param.toArray());
    int size = redLst.getList().size();
    // 不足10条,补足10条显示
    if (size < 10) {
      for (int i = 0; i < 10 - size; i++) {
        redLst.getList().add(new Record());
      }
    }
    setAttr("page", redLst);
    setAttr(
        "collist",
        new String[] {"商品编号", "商品名称", "商品规格", "单位", "原价", "折扣%", "数量", "订单金额", "税率%", "税额", "金额"});
    setAttr("ckjhcheck", ckjhcheck);
    setAttr("store", jbstore);
    setAttr("supplier", jbsupplier);
    setAttr(InOutTypeNoSelectTarget.targetName, new InOutTypeNoSelectTarget());
    setAttr(PartmentSelectTarget.targetName, new PartmentSelectTarget());
    setAttr(EmployeeSelectTarget.targetName, new EmployeeSelectTarget());
    render("add.html");
  }

  public void save() {
    try {
      boolean settleTypeFlag = false;
      Jhpay jhpay = null;
      Ckjhcheck m = getModel(Ckjhcheck.class, "ckjhcheck");
      Jbsupplier supplier = getModel(Jbsupplier.class, "supplier");
      Jbstore store = getModel(Jbstore.class, "store");
      m.set("SupplierCode", supplier.getStr("supplierCode"));
      m.set("StoreCode", store.getStr("StoreCode"));
      Double amount = Double.parseDouble(getPara("amount"));
      m.set("CKAmount", amount);
      if (getPara("typeFlg") != null && getParaToInt("typeFlg") == 1) {
        m.set("SettleTypeFlag", getParaToInt("typeFlg"));
        settleTypeFlag = true;
      }
      if (m.getLong("id") != null) {
        m.update();
      } else {
        m.save();
      }
      // 当面付模式
      if (settleTypeFlag) {
        jhpay =
            Jhpay.dao.findFirst("select * from jhpay where BillOrderNo = ?", m.getStr("OrderDate"));
        if (jhpay == null) {
          // 生成付款单信息
          jhpay = new Jhpay();
          synchronized (lock) {
            String ordCdNw = BsUtil.getMaxOrdNo("OrderCode", "CF", "jhpay");
            jhpay.set("OrderCode", ordCdNw);
          }
          jhpay.set(
              "OrderDate",
              DateUtil.string2Date(
                  DateUtil.date2String(new Date(), DateUtil.FORMAT_DATE), DateUtil.FORMAT_DATE));
          jhpay.set("SupplierCode", m.get("SupplierCode"));
          jhpay.set("DeptCode", m.get("DeptCode"));
          jhpay.set("EmpCode", m.get("EmpCode"));
          jhpay.set("PayType", BsUtil.DIR_PAY);
          jhpay.set("BankNo", supplier.get("BankNo"));
          jhpay.set("Amount", amount);
          jhpay.set("BillOrderNo", m.get("OrderCode"));
          Record man = getCurrentUser();
          jhpay.set("checkman", man.getStr("usr_name"));
          jhpay.set("CheckDate", new Date());
          jhpay.set("CheckFlag", 1);
          jhpay.save();
          Jhpaydetail jhpaydetail = new Jhpaydetail();
          jhpaydetail.set("OrderCode", m.get("OrderCode"));
          jhpaydetail.set("PayOrderNo", jhpay.get("OrderCode"));
          jhpaydetail.set("CollateType", "采购入库单");
          jhpaydetail.set("NowCollated", amount);
          jhpaydetail.set("Adjust", 0);
          jhpaydetail.set("Amount", amount);
        }
      }
      String orderCode = m.get("OrderCode");
      // 保存明细
      int size = 0;
      // 通过【新建商品明细】按钮新追加记录
      String[] index = getParaValues("lineId");
      size =
          Db.queryLong(
                  "select count(*)  from ckjhcheckdetail where orderCode = '" + orderCode + "'")
              .intValue();
      if (!(index == null || index.length == 0)) {
        size = size + index.length;
      }
      // 不足10条,补足10条显示并保存
      if (size < 10) {
        size = 10;
      }
      for (int i = 0; i < size; i++) {
        Ckjhcheckdetail md = getModel(Ckjhcheckdetail.class, "ckjhcheckDetail" + i);
        Jbgoods goods = getModel(Jbgoods.class, "goods" + i);
        if (goods.getStr("GoodsCode") != null) {
          md.set("GoodsCode", goods.get("GoodsCode"));
          Ckjhcheckdetail tmp = Ckjhcheckdetail.dao.findById(md.getLong("id"));
          if (tmp != null) {
            md.set("price", goods.get("BRefPrice"));
            md.update();
          } else {
            md.set("ordercode", orderCode);
            md.set("price", goods.get("BRefPrice"));
            md.save();
          }
        }
      }
      toDwzJson(200, "保存成功!", navTabId, "closeCurrent");
    } catch (Exception e) {
      log.error("保存仓库分类异常", e);
      toDwzJson(300, "保存异常!");
    }
  }

  public void del() {
    Long id = getParaToLong(0, 0L);
    try {
      if (id != null) {
        Ckjhcheck r = Ckjhcheck.dao.findById(id);
        Ckjhcheck.dao.deleteById(id);
        Db.update("delete from ckjhcheckdetail where OrderCode=?", r.getStr("OrderCode"));
      }
      toDwzJson(200, "删除成功!", navTabId);
    } catch (Exception e) {
      toDwzJson(300, "删除失败!");
    }
  }

  // 审核
  @Before(Tx.class)
  public void review() throws Exception {
    Long id = getParaToLong(0, 0L);
    try {
      if (id != null) {
        Ckjhcheck r = Ckjhcheck.dao.findById(id);
        /*
         * if (r.getInt("SettleTypeFlag") == 2) { toDwzJson(300,
         * "已清货不能审核!", navTabId); return; }
         */
        if (r.getInt("CheckFlag") == null || r.getInt("CheckFlag") != 1) {
          // 登录人即审核者
          Record m = getCurrentUser();
          r.set("checkman", m.getStr("usr_name"));
          r.set("CheckDate", new Date());
          r.set("CheckFlag", 1);
          r.update();
          // 审核后更新库存表及供应商表应付款
          CkjhDbProc oracleDbK =
              new CkjhDbProc(
                  r.getStr("StoreCode"), r.getStr("orderCode"), r.getStr("SupplierCode"), 1);
          Db.execute(oracleDbK);
        }
        toDwzJson(200, "审核通过!", navTabId);
      }
    } catch (Exception e) {
      toDwzJson(300, "审核失败!" + e.getMessage());
      throw e;
    }
  }

  // 未审核
  @Before(Tx.class)
  public void unreview() throws Exception {
    Long id = getParaToLong(0, 0L);
    try {
      if (id != null) {
        Ckjhcheck r = Ckjhcheck.dao.findById(id);
        /*
         * if (r.getInt("SettleTypeFlag") == 2) { toDwzJson(300,
         * "已清货不能反审核!", navTabId); return; }
         */
        if (r.getInt("CheckFlag") != null && r.getInt("CheckFlag") != 0) {
          // 登录人即审核者
          Record m = getCurrentUser();
          r.set("CheckFlag", 0);
          r.set("checkman", m.getStr("usr_name"));
          r.set("CheckDate", new Date());
          r.update();
          // 审核后更新库存表及供应商表应付款
          CkjhDbProc oracleDbK =
              new CkjhDbProc(
                  r.getStr("StoreCode"), r.getStr("orderCode"), r.getStr("SupplierCode"), 2);
          Db.execute(oracleDbK);
        }
        toDwzJson(200, "反审核通过!", navTabId);
      }
    } catch (Exception e) {
      toDwzJson(300, "删除失败!");
      throw e;
    }
  }
}
Exemple #10
0
/**
 * 工单model
 *
 * @author 陈宇佳
 */
@SuppressWarnings("unused")
@TableBind(tableName = "com_order")
public class Order extends BaseModel<Order> {

  private static final long serialVersionUID = -3474341426070972713L;

  private static Logger log = Logger.getLogger(Order.class);

  public static final Order dao = new Order();

  /**
   * @描述 查询Reports 分页
   *
   * @param pageNumber
   * @param pageSize
   * @param where
   * @param orderby
   * @param paras
   * @return
   */
  public Page<Record> findReportsByUserId(
      int pageNumber, int pageSize, String where, String orderby, Object... paras) {
    return Db.paginate(
        pageNumber,
        pageSize,
        getSql("order.findOfferQueryBySelect"),
        getSql("order.findOfferQueryByFrom") + getWhere(where) + orderby,
        paras);
  }

  /**
   * @描述 查询Report 详细内容
   *
   * @param where
   * @param paras
   * @return
   */
  public Record findReportById(String where, Object... paras) {
    return Db.findFirst(
        getSql("order.findOrderInfoBySelect")
            + blank
            + getSql("order.findOrderInfoByFrom")
            + getWhere(where),
        paras);
  }

  /**
   * @描述 查询Operates 分页
   *
   * @param pageNumber
   * @param pageSize
   * @param where
   * @param orderby
   * @param paras
   * @return
   */
  public Page<Record> findOperatesByUserId(
      int pageNumber, int pageSize, String where, String orderby, Object... paras) {
    return Db.paginate(
        pageNumber,
        pageSize,
        getSql("order.findOfferQueryBySelect"),
        getSql("order.findOfferQueryByFrom") + getWhere(where) + orderby,
        paras);
  }

  public List<Record> findOperatesByUserId(String where, String orderby, Object... paras) {
    return Db.find(
        getSql("order.findOfferQueryBySelect")
            + getSql("order.findOfferQueryByFrom")
            + getWhere(where)
            + orderby,
        paras);
  }

  /**
   * @描述 查询Operate 详细内容
   *
   * @param where
   * @param paras
   * @return
   */
  public Record findOperateById(String where, Object... paras) {
    return Db.findFirst(
        getSql("order.findOrderInfoBySelect")
            + blank
            + getSql("order.findOrderInfoByFrom")
            + getWhere(where),
        paras);
  }

  /**
   * @描述 查询Orders 主页 分页
   *
   * @param pageNumber
   * @param pageSize
   * @param where
   * @param orderby
   * @param paras
   * @return
   */
  public Page<Record> findIndexOrders(
      int pageNumber, int pageSize, String where, String orderby, Object... paras) {
    return Db.paginate(
        pageNumber,
        pageSize,
        getSql("order.findOfferQueryBySelect"),
        getSql("order.findOfferQueryByFrom") + getWhere(where) + orderby,
        paras);
  }

  /**
   * @描述 查询Orders 管理员 不分页
   *
   * @param where
   * @param orderby
   * @param paras
   * @return
   */
  public List<Record> findAdminOrders(String where, String orderby, Object... paras) {
    return Db.find(
        getSql("order.findOfferQueryBySelect")
            + getSql("order.findOfferQueryByFrom")
            + getWhere(where)
            + orderby,
        paras);
  }

  public List<Record> exporter(String where, String orderby, Object... paras) {
    return Db.find(getSql("order.exporter") + getWhere(where) + orderby, paras);
  }

  public List<Record> exporterWithComments(String where, String orderby, Object... paras) {
    return Db.find(getSql("order.exporterWithComments") + getWhere(where) + orderby, paras);
  }

  /**
   * @描述 查询order 管理员
   *
   * @param where
   * @param paras
   * @return
   */
  public Record query(String where, Object... paras) {

    return Db.findFirst(
        getSql("order.findOfferQueryBySelect")
            + getSql("order.findOfferQueryByFrom")
            + getWhere(where),
        paras);
  }

  /**
   * 获得所有故障类型(弃用)
   *
   * @return
   */
  @Deprecated
  public List<Record> getAllType() {
    return Db.find("select * from com_type");
  }

  /**
   * @描述 如果attr,如description的长度超过30(随机,由Random决定),则后面用...代替。
   *
   * @param page
   * @param paras
   */
  public void format(Page<Record> page, String... paras) {
    for (Record record : page.getList()) {
      for (String attr : paras) {
        record.set(
            attr, StringUtils.abbreviate(record.getStr(attr), (new Random().nextInt(2) + 35)));
      }
    }
  }

  public void format(List<Record> list, String... paras) {
    for (Record record : list) {
      for (String attr : paras) {
        record.set(
            attr, StringUtils.abbreviate(record.getStr(attr), (new Random().nextInt(2) + 35)));
      }
    }
  }

  /**
   * 根据status获取Order。
   *
   * @param paras
   * @return
   */
  public List<Order> findOrderByStatus(Object... paras) {
    return find("select * from com_order where status=?", paras);
  }

  /**
   * 根据条件获取Order。
   *
   * @param where
   * @param paras
   * @return
   */
  public Page<Record> findExceptionOrders(
      int pageNumber, int pageSize, String where, Object... paras) {
    return Db.paginate(
        pageNumber,
        pageSize,
        getSql("order.findOrderInfoBySelect"),
        getSql("order.findOrderInfoByFrom") + getWhere(where),
        paras);
  }
}
/**
 * 用于动态生成JFinal的SQL查询语句
 *
 * @author Lims
 * @date 2015年9月18日
 * @version 1.1
 */
public class QueryCondition {

  static Logger log = Logger.getLogger(QueryCondition.class);

  // 用于接收SQL语句
  private ThreadLocal<String> sql = new ThreadLocal<String>();

  // 用于接收参数数组
  private ThreadLocal<ArrayList<Object>> paramList = new ThreadLocal<ArrayList<Object>>();

  // 用于存放设置的条件
  private ThreadLocal<Map<String, Object[]>> conditionMap =
      new ThreadLocal<Map<String, Object[]>>();

  // 用于存放需要排除的字段
  private ThreadLocal<Map<String, String>> excludeFieldMap = new ThreadLocal<Map<String, String>>();

  /** 构造方法(表示没有设置查询类型的字段全部按照等于来处理) */
  public QueryCondition() {
    conditionMap.set(new HashMap<String, Object[]>());
    excludeFieldMap.set(new HashMap<String, String>());
  }

  /**
   * 构造方法(设置后表示字段所有的查询方式按照设置类型来处理,除非后面针对字段的重新设置)
   *
   * @param type 查询类型
   */
  public QueryCondition(String type) {
    Map<String, Object[]> map = new HashMap<String, Object[]>();
    map.put("GLOBALTYPE", new String[] {type});
    conditionMap.set(map);
    excludeFieldMap.set(new HashMap<String, String>());
  }

  /**
   * ************************************************************************* 设置字段的查询类型
   *
   * @param queryType 查询类型
   * @param filedName 字段名称数组
   */
  public void setFiledQuery(String queryType, String... filedName) {
    if (StringUtils.isNotBlank(queryType) && !JFinalExtKit.isNullOrEmpty(filedName)) {
      Map<String, Object[]> map = conditionMap.get();
      map.put(queryType, filedName);
      conditionMap.set(map);
    }
  }

  /**
   * ************************************************************************* 设置需要排除的字段
   * setexcludeField
   *
   * @param filedName 参数说明
   */
  public void setExcludeField(String... filedName) {
    if (!JFinalExtKit.isNullOrEmpty(filedName)) {
      Map<String, String> map = excludeFieldMap.get();
      for (String str : filedName) {
        map.put(str, str);
      }
      excludeFieldMap.set(map);
    }
  }

  /**
   * 查询空值或者不为空值的情况 setNullFieldQuery
   *
   * @param queryType 参数说明
   * @param filedName 字段名
   */
  public void setNullOrNotNullFieldQuery(String queryType, String... filedName) {
    if (StringUtils.isNotBlank(queryType) && !JFinalExtKit.isNullOrEmpty(filedName)) {
      if (!QueryType.NOT_EMPTY.equals(queryType) && !QueryType.EMPTY.equals(queryType)) {
        log.error("空值或者非空查询的类型只能为:EMPTY、NOT_EMPTY");
        throw new RuntimeException("空值或者非空查询的类型只能为:EMPTY、NOT_EMPTY");
      }
      Map<String, Object[]> map = conditionMap.get();
      map.put(queryType, filedName);
      conditionMap.set(map);
    }
  }

  /**
   * ************************************************************************* 传值查询
   * 注:如果queryType为in或者not in那么filedValue必须为一个list对象
   *
   * @param queryType 查询类型
   * @param fieldName 字段名称
   * @param filedValue 字段值
   */
  public void setValueQuery(String queryType, String fieldName, Object filedValue) {
    if (StringUtils.isNotBlank(queryType)
        && StringUtils.isNotBlank(fieldName)
        && !JFinalExtKit.isNullOrEmpty(filedValue)) {
      Object[] param = new Object[2];
      param[0] = fieldName; // 字段名
      param[1] = filedValue; // 字段值
      Map<String, Object[]> map = conditionMap.get();
      map.put(queryType + "#" + fieldName, param); // 避免类型重复被覆盖掉就加上字段名
      conditionMap.set(map);
    }
  }

  /**
   * ************************************************************************* 用于生成SQL条件语句不带别名
   *
   * @param modelClass 必须继承于Model
   */
  public void modelToCondition(Model<?> modelClass) {
    modelToCondition(modelClass, null);
  }

  /**
   * ************************************************************************* 用于生成SQL条件语句不带别名
   *
   * @param recordClass 必须是一个Record类
   */
  public void recordToCondition(Record recordClass) {
    recordToCondition(recordClass, null);
  }

  /**
   * ************************************************************************* 用于生成SQL条件语句带别名
   *
   * @param modelClass 必须继承于Model
   * @param alias 别名
   */
  public void modelToCondition(Model<?> modelClass, String alias) {
    alias = StringUtils.isNotBlank(alias) ? alias + "." : "";
    if (modelClass != null) {
      // 所有的字段
      String[] fieldNames = modelClass.getAttrNames();
      // 字段名和值的map集合
      Map<String, Object> valueMap = JFinalExtKit.modelToMap(modelClass);

      // 构建查询条件
      buildCondition(alias, fieldNames, valueMap);
    } else {
      if (!conditionMap.get().isEmpty()) {
        buildCondition(alias, new String[] {}, new HashMap<String, Object>());
      } else {
        sql.set("");
        paramList.set(new ArrayList<Object>());
      }
    }
  }

  /**
   * ************************************************************************* 用于生成SQL条件语句不带别名
   *
   * @param recordClass 必须是一个Record类
   * @param alias 别名
   */
  public void recordToCondition(Record recordClass, String alias) {
    // 别名
    alias = StringUtils.isNotBlank(alias) ? alias + "." : "";
    if (recordClass != null) {
      // 所有的字段
      String[] fieldNames = recordClass.getColumnNames();
      // 字段名和值的map集合
      Map<String, Object> valueMap = JFinalExtKit.recordToMap(recordClass);

      // 构建查询条件
      buildCondition(alias, fieldNames, valueMap);
    } else {
      if (!conditionMap.get().isEmpty()) {
        buildCondition(alias, new String[] {}, new HashMap<String, Object>());
      } else {
        sql.set("");
        paramList.set(new ArrayList<Object>());
      }
    }
  }

  /**
   * ************************************************************************* 构建条件语句
   *
   * @param alias 别名
   * @param fieldNames 所有查询的字段名称
   * @param valueMap 所有的值的map
   */
  private void buildCondition(String alias, String[] fieldNames, Map<String, Object> valueMap) {
    try {
      // 构建条件前先清空变量
      sql.set("");
      paramList.set(new ArrayList<Object>());
      // 用于存放参数列表
      ArrayList<Object> paramArrayList = new ArrayList<Object>();
      StringBuilder sb = new StringBuilder();
      // 所有的字段名称
      Map<String, String> usedFieldMap = new HashMap<String, String>();
      if (!conditionMap.get().isEmpty()) {
        for (Entry<String, Object[]> map : conditionMap.get().entrySet()) {
          String queryType = map.getKey();
          Object[] array = map.getValue();
          if (queryType.indexOf("#") > 0) { // 传值查询
            String fieldQueryType = queryType.split("#")[0];
            String fieldName = array[0] != null ? array[0].toString() : "";
            Object fieldValue = array[1];

            // 将设置过的字段保存到数组中
            usedFieldMap.put(fieldName, fieldName);
            // 构建SQL语句
            buildSQL(sb, fieldQueryType, fieldName, fieldValue, alias, paramArrayList);
          } else { // 字段查询
            if (!"GLOBALTYPE".equals(queryType)) {
              for (Object field : array) {
                String filedName = field != null ? field.toString() : "";
                if (!excludeFieldMap.get().containsKey(filedName)) {
                  Object fieldValue = valueMap.get(filedName);

                  if (QueryType.EMPTY.equals(queryType) || QueryType.NOT_EMPTY.equals(queryType)) {
                    fieldValue = null;
                  }
                  // 将设置过的字段保存到数组中
                  usedFieldMap.put(filedName, filedName);
                  // 构建查询语句
                  buildSQL(sb, queryType, filedName, fieldValue, alias, paramArrayList);
                }
              }
            }
          }
        }
      }
      // 对没有设置条件的字段进行查询类型设置
      String queryType = QueryType.EQUAL;
      if (conditionMap.get().containsKey("GLOBALTYPE")) {
        String[] typeArray = (String[]) conditionMap.get().get("GLOBALTYPE");
        queryType = typeArray[0];
      }
      // 对未使用过的字段进行build
      for (String field : fieldNames) {
        if (!usedFieldMap.containsKey(field)) {
          Object fieldValue = valueMap.get(field);
          // 构建查询语句
          buildSQL(sb, queryType, field, fieldValue, alias, paramArrayList);
        }
      }

      // 合并传入的参数到参数对象中
      sql.set(sb.toString());
      paramList.set(paramArrayList);
      conditionMap.set(new HashMap<String, Object[]>()); // 清空本次的条件map
      excludeFieldMap.set(new HashMap<String, String>()); // 清空本次的排除字段
    } catch (Exception e) {
      log.error("Conditions构建SQL语句出现错误,请仔细检查!", e);
      e.printStackTrace();
    }
  }

  /**
   * ************************************************************************* 构建SQL语句
   *
   * @param sb 用于拼接SQL语句
   * @param queryType 查询类型
   * @param fieldName 字段名称
   * @param fieldValue 字段值
   * @param alias 别名
   */
  @SuppressWarnings("rawtypes")
  private void buildSQL(
      StringBuilder sb,
      String queryType,
      String fieldName,
      Object fieldValue,
      String alias,
      ArrayList<Object> params) {
    // 非空的时候进行设置
    if (!JFinalExtKit.isNullOrEmpty(fieldValue) && !JFinalExtKit.isNullOrEmpty(fieldName)) {
      if (QueryType.EQUAL.equals(queryType)) {
        sb.append(" and " + alias + fieldName + " = ? ");
        params.add(fieldValue);
      } else if (QueryType.NOT_EQUAL.equals(queryType)) {
        sb.append(" and " + alias + fieldName + " <> ? ");
        params.add(fieldValue);
      } else if (QueryType.LESS_THEN.equals(queryType)) {
        sb.append(" and " + alias + fieldName + " < ? ");
        params.add(fieldValue);
      } else if (QueryType.LESS_EQUAL.equals(queryType)) {
        sb.append(" and " + alias + fieldName + " <= ? ");
        params.add(fieldValue);
      } else if (QueryType.GREATER_THEN.equals(queryType)) {
        sb.append(" and " + alias + fieldName + " > ? ");
        params.add(fieldValue);
      } else if (QueryType.GREATER_EQUAL.equals(queryType)) {
        sb.append(" and " + alias + fieldName + " >= ? ");
        params.add(fieldValue);
      } else if (QueryType.FUZZY.equals(queryType)) {
        sb.append(" and " + alias + fieldName + " like ? ");
        params.add("%" + fieldValue + "%");
      } else if (QueryType.FUZZY_LEFT.equals(queryType)) {
        sb.append(" and " + alias + fieldName + " like ? ");
        params.add("%" + fieldValue);
      } else if (QueryType.FUZZY_RIGHT.equals(queryType)) {
        sb.append(" and " + alias + fieldName + " like ? ");
        params.add(fieldValue + "%");
      } else if (QueryType.IN.equals(queryType)) {
        try {
          List list = (List) fieldValue;
          StringBuffer instr = new StringBuffer();
          sb.append(" and " + alias + fieldName + " in (");
          for (Object obj : list) {
            instr.append(StringUtils.isNotBlank(instr) ? ",?" : "?");
            params.add(obj);
          }
          sb.append(instr + ") ");
        } catch (Exception e) {
          throw new RuntimeException(
              "使用IN条件的时候传入的值必须是个List对象,否则将会转换出错!例如将 in('1','2','3')中的'1','2','3'分为三个分别添加到List中做为值传入.",
              e);
        }
      } else if (QueryType.NOT_IN.equals(queryType)) {
        try {
          List list = (List) fieldValue;
          StringBuffer instr = new StringBuffer();
          sb.append(" and " + alias + fieldName + " not in (");
          for (Object obj : list) {
            instr.append(StringUtils.isNotBlank(instr) ? ",?" : "?");
            params.add(obj);
          }
          sb.append(instr + ") ");
        } catch (Exception e) {
          throw new RuntimeException(
              "使用NOT IN条件的时候传入的值必须是个List对象,否则将会转换出错!例如将 not in('1','2','3')中的'1','2','3'分为三个分别添加到List中做为值传入.",
              e);
        }
      }
    } else {
      if (QueryType.EMPTY.equals(queryType)) {
        sb.append(" and " + alias + fieldName + " is null ");
      } else if (QueryType.NOT_EMPTY.equals(queryType)) {
        sb.append(" and " + alias + fieldName + " is not null ");
      }
    }
  }

  /**
   * 获取sql语句
   *
   * @return 封装好的sql语句
   */
  public String getSql() {
    return sql.get();
  }

  /**
   * 查询条件的值
   *
   * @return List<Object> 查询条件的值
   */
  public List<Object> getParamList() {
    return paramList.get();
  }
}
Exemple #12
0
/** Created by ZaoSheng on 2015/5/24. */
public abstract class JFinalConfig extends com.jfinal.config.JFinalConfig {
  private static final Logger LOG = Logger.getLogger(JFinalConfig.class);
  private static final List<String> controlPackage = new ArrayList<String>();
  private static final List<String> basePackage = new ArrayList<String>();

  /** Scan control */
  public abstract void controlSscan(List<String> controlPackage);

  /** Scan basePackage */
  public abstract void componentSscan(List<String> basePackage);

  /**
   * 设置数据源
   *
   * @return IDataSourceProvider
   */
  public abstract IDataSourceProvider setDataSource();

  /**
   * controller
   *
   * @param me
   */
  @Override
  public void configRoute(Routes me) {

    //        String path = this.getClass().getClassLoader().getResource("").getPath();
    controlSscan(controlPackage); // 获取需要扫描的包

    // 扫描器
    Scan driven = new Scan();
    for (String pake : controlPackage) {
      Set<Class<?>> clazzs = driven.getClasses(pake);
      /*System.out.println("pake: " + pake);*/
      for (Class<?> clazz : clazzs) {
        //            	System.out.println(clazz.getSuperclass());
        LOG.info(clazz.getName());
        Class<?> superclass = clazz.getSuperclass();
        Class<?> jfClz = com.jfinal.core.Controller.class;
        if (superclass == jfClz || superclass.getSuperclass() == jfClz) {
          C con = clazz.getAnnotation(C.class);
          if (null != con) {
            me.add(con.value(), (Class<? extends Controller>) clazz);
          }
        }
      }
    }
  }

  /**
   * model
   *
   * @param me
   */
  @Override
  public void configPlugin(Plugins me) {

    componentSscan(basePackage);

    IDataSourceProvider iDataSourceProvider = setDataSource();
    try {
      me.add((IPlugin) iDataSourceProvider);
    } catch (Exception e) {
      throw new RuntimeException("is not IPlugin type");
    }
    ActiveRecordPlugin arp = new ActiveRecordPlugin(iDataSourceProvider);

    addActiveRecord(arp); // 加入附加的活动记录
    Scan driven = new Scan();
    for (String pake : basePackage) {
      Set<Class<?>> clazzs = driven.getClasses(pake);

      for (Class<?> clazz : clazzs) {
        LOG.info(clazz.getName());
        Class superClass = clazz.getSuperclass();
        Class<?> jfClz = com.jfinal.plugin.activerecord.Model.class;
        if (superClass == jfClz || superClass.getSuperclass() == jfClz) {
          M model = clazz.getAnnotation(M.class);
          if (null != model) {
            arp.addMapping(model.value(), model.id(), (Class<? extends Model<?>>) clazz);
          }
        }
      }
    }
    me.add(arp);
  }

  /**
   * 这里进行附加的活动记录的添加,
   *
   * @param arp 活动记录插件
   */
  public void addActiveRecord(ActiveRecordPlugin arp) {
    // arp.setShowSql(true);//设置是sql显示开关
  }

  /**
   * Interceptors
   *
   * @param me
   */
  @Override
  public void configInterceptor(Interceptors me) {}

  @Override
  public void configHandler(Handlers me) {}
}
Exemple #13
0
/**
 * Redis插件
 *
 * @author june 2015年3月2日 下午3:02:57
 */
public class RedisPlugin implements IPlugin {

  /** 集群连接池 */
  private static ShardedJedisPool shardedJedisPool;
  /** 配置文件路径 */
  private String configurationFileName = "redis";

  private final Logger logger = Logger.getLogger(getClass());

  public RedisPlugin() {}

  public RedisPlugin(String configurationFileName) {
    this.configurationFileName = configurationFileName;
  }

  @Override
  public boolean start() {
    createShardedJedisPool();
    RedisKit.init(shardedJedisPool);
    logger.info("初始化redis插件成功");
    return true;
  }

  /** 初始化连接池 */
  private void createShardedJedisPool() {
    ResourceBundle bundle = ResourceBundle.getBundle(configurationFileName);
    if (bundle == null) {
      throw new IllegalArgumentException(configurationFileName + " is not found!");
    }
    JedisPoolConfig config = new JedisPoolConfig();
    config.setMaxTotal(Integer.valueOf(bundle.getString("redis.pool.maxTotal")));
    config.setMaxIdle(Integer.valueOf(bundle.getString("redis.pool.maxIdle")));
    config.setMaxWaitMillis(Long.valueOf(bundle.getString("redis.pool.maxWait")));
    config.setTestOnBorrow(Boolean.valueOf(bundle.getString("redis.pool.testOnBorrow")));
    config.setTestOnReturn(Boolean.valueOf(bundle.getString("redis.pool.testOnReturn")));
    List<JedisShardInfo> list = createJedisShardInfoList(bundle);
    shardedJedisPool = new ShardedJedisPool(config, list);
  }
  /**
   * 构建redis集群配置信息
   *
   * @param bundle
   * @return
   */
  private List<JedisShardInfo> createJedisShardInfoList(ResourceBundle bundle) {
    List<JedisShardInfo> list = new LinkedList<JedisShardInfo>();
    String defaultRedisPort = bundle.getString("redis.port");
    for (int i = 0; i < 10; i++) {
      if (!bundle.containsKey("redis" + (i == 0 ? "" : i) + ".ip")) {
        continue;
      }
      String redisIp = bundle.getString("redis" + (i == 0 ? "" : i) + ".ip");
      String redisPort = bundle.getString("redis" + (i == 0 ? "" : i) + ".port");
      if (StringUtils.isEmpty(redisPort)) {
        redisPort = defaultRedisPort;
      }
      if (StringUtils.isNotEmpty(redisIp) && StringUtils.isNotEmpty(redisPort)) {
        JedisShardInfo jedisShardInfo = new JedisShardInfo(redisIp, redisPort);
        logger.info("初始化redis,redis" + (i == 0 ? "" : i) + ".ip:" + redisIp + ",端口:" + redisPort);
        list.add(jedisShardInfo);
      }
    }
    return list;
  }

  @Override
  public boolean stop() {
    if (shardedJedisPool != null) {
      shardedJedisPool.destroy();
    }
    return true;
  }
}