Java Code Examples for com.jfinal.kit.StrKit#isBlank()

The following examples show how to use com.jfinal.kit.StrKit#isBlank() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ResController.java    From jboot-admin with Apache License 2.0 6 votes vote down vote up
/**
 * 修改提交
 */
@Before({POST.class, ResValidator.class})
public void postUpdate() {
    Long pid = getParaToLong("pid");
    Res sysRes = getBean(Res.class, "res");

    if (StrKit.isBlank(sysRes.getIconCls())) {
        sysRes.setIconCls("");
    }

    sysRes.setPid(pid);
    sysRes.setLastUpdAcct(AuthUtils.getLoginUser().getName());
    sysRes.setLastUpdTime(new Date());
    sysRes.setNote("修改系统资源");

    if (!resService.update(sysRes)) {
        throw new BusinessException("修改失败,请重试");
    }

    renderJson(RestResult.buildSuccess());
}
 
Example 2
Source File: MsgInterceptor.java    From jfinal-weixin with Apache License 2.0 6 votes vote down vote up
/**
 * 检测签名
 */
private boolean checkSignature(Controller controller) {
	String signature = controller.getPara("signature");
	String timestamp = controller.getPara("timestamp");
	String nonce = controller.getPara("nonce");
	if (StrKit.isBlank(signature) || StrKit.isBlank(timestamp) || StrKit.isBlank(nonce)) {
		controller.renderText("check signature failure");
		return false;
	}
	
	if (SignatureCheckKit.me.checkSignature(signature, timestamp, nonce)) {
		return true;
	}
	else {
		logger.error("check signature failure: " +
				" signature = " + controller.getPara("signature") +
				" timestamp = " + controller.getPara("timestamp") +
				" nonce = " + controller.getPara("nonce"));
		
		return false;
	}
}
 
Example 3
Source File: PaymentKit.java    From jfinal-weixin with Apache License 2.0 6 votes vote down vote up
/**
 * 微信下单,map to xml
 * @param params 参数
 * @return String
 */
public static String toXml(Map<String, String> params) {
	StringBuilder xml = new StringBuilder();
	xml.append("<xml>");
	for (Entry<String, String> entry : params.entrySet()) {
		String key   = entry.getKey();
		String value = entry.getValue();
		// 略过空值
		if (StrKit.isBlank(value)) continue;
		xml.append("<").append(key).append(">");
			xml.append(entry.getValue());
		xml.append("</").append(key).append(">");
	}
	xml.append("</xml>");
	return xml.toString();
}
 
Example 4
Source File: NodeController.java    From zooadmin with MIT License 6 votes vote down vote up
public void modify() {
    ResultData result = new ResultData();
    String parentPath = getPara("parentPath");
    if (StrKit.isBlank(parentPath)) {
        parentPath = "/";
    }
    String nodeData = getPara("nodeData");
    try {
        ZkClient zkClient = getSessionAttr("zk-client");
        ZKPlugin zkPlugin = new ZKPlugin(zkClient);
        if (zkClient.exists(parentPath)) {
            zkPlugin.edit(parentPath, nodeData.getBytes());
            result.setMessage("数据修改成功");
        } else {
            result.setSuccess(false);
            result.setMessage("节点路径不存在失败");
        }
    } catch (Exception e) {
        result.setSuccess(false);
        result.setMessage("数据修改失败");
        log.error("数据修改失败,错误", e);
    }
    renderJson(result);
}
 
Example 5
Source File: ModelRedisPlugin.java    From jfinal-ext3 with Apache License 2.0 5 votes vote down vote up
/**
 * cacheName,
 * tables: tablename1,tablename2,tablename3...
 */
public ModelRedisPlugin(String cacheName, String tables) {
	if (StrKit.isBlank(cacheName)) {
		throw new IllegalArgumentException("cacheName can not be blank.");
	}
	if (StrKit.isBlank(tables)) {
		throw new IllegalArgumentException("tables can not be blank.");
	}
	
	this.cacheName = cacheName.trim();
	this.tables = tables.split(",");
}
 
Example 6
Source File: JbootController.java    From jboot with Apache License 2.0 5 votes vote down vote up
private BigInteger toBigInteger(String value, BigInteger defaultValue) {
    try {
        if (StrKit.isBlank(value)) {
            return defaultValue;
        }
        value = value.trim();
        if (value.startsWith("N") || value.startsWith("n")) {
            return BigInteger.ZERO.subtract(new BigInteger(value));
        }
        return new BigInteger(value);
    } catch (Exception e) {
        throw new ActionException(400, RenderManager.me().getRenderFactory().getErrorRender(400), "Can not parse the parameter \"" + value + "\" to BigInteger value.");
    }
}
 
Example 7
Source File: IndexController.java    From zooadmin with MIT License 5 votes vote down vote up
public void dologin() {
    ResultData result = new ResultData();
    String addr = getPara("addr");
    String password = getPara("password");
    String pwd = PropKit.use("user.properties").get("root");
    if (StrKit.isBlank(password) || !password.equals(pwd)) {
        result.setSuccess(false);
        result.setMessage("请输入正确的密码登陆!");
        renderJson(result);
    } else {
        if (StrKit.notBlank(addr)) {
            try {
                ZKPlugin zkPlugin = new ZKPlugin(addr);
                if (getSessionAttr("zk-client") == null) {
                    setSessionAttr("zk-client", zkPlugin.getClient());
                    setSessionAttr("addr", addr);
                }
            } catch (Exception e) {
                log.error("ZKPlugin error.", e);
                result.setSuccess(false);
                result.setMessage("连接到ZooKeeper失败,请复核!");
            }

        } else {
            result.setSuccess(false);
            result.setMessage("ZooKeeper 地址不能为空!");
        }
        renderJson(result);
    }
}
 
Example 8
Source File: HtmlToJson.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取转换后的JSON 数组 有多级子节点
 *
 * @return
 */
public String get() {
    if (StrKit.isBlank(html)) {
        return null;
    }
    Document document = null;
    try {
        //判断是否需要绝对路径URL
        if (needAbsUrl) {
            document = Jsoup.parseBodyFragment(html, params.getBaseUri());
        } else {
            document = Jsoup.parseBodyFragment(html);
        }
    } finally {
        if (document == null) {
            return null;
        }
    }
    //以前使用Element元素会把无标签包裹的textNode节点给抛弃,这里改为选用Node节点实现
    //Node节点可以将一段html的所有标签和无标签文本区分 都转为Node
    List<Node> nodes = document.body().childNodes();
    //如果获取的Node为空 直接返回Null不处理
    if (nodes.isEmpty()) {
        return null;
    }
    //整个HTML转为JSON其实是转为一个JSON数组传递给前端html2wxml组件模板 循环解析
    JSONArray array = new JSONArray();
    JSONObject jsonObject = null;
    String tag = null;
    for (Node node : nodes) {
        tag = node.nodeName().toLowerCase();
        jsonObject = convertNodeToJsonObject(node, tag, "pre".equals(tag));
        if (jsonObject != null) {
            array.add(jsonObject);
        }
    }
    return array.toJSONString();
}
 
Example 9
Source File: JFinalConfigExt.java    From jfinal-ext3 with Apache License 2.0 5 votes vote down vote up
/**
 * 获取数据源
 * @return
 */
private String[] getDataSource() {
	String ds = this.getProperty("db.ds", "");
	if (StrKit.isBlank(ds)) {
		return (new String[0]);
	}
	if (ds.contains(",")) {
		new IllegalArgumentException("Cannot use ,in ds");
	}
	return ds.split(",");
}
 
Example 10
Source File: JFinalConfigExt.java    From jfinal-ext3 with Apache License 2.0 5 votes vote down vote up
private String getRedisCacheTables(String cache) {
	String cts = this.getProperty(String.format(REDIS_TABLES_TEMPLATE, cache), "");
	if (StrKit.isBlank(cts)) {
		return "";
	}
	if (cts.contains(",")) {
		new IllegalArgumentException("Cannot use ,in reids.*.tables");
	}
	return cts;
}
 
Example 11
Source File: JFinalConfigExt.java    From jfinal-ext3 with Apache License 2.0 5 votes vote down vote up
/**
 * 获取 AppName
 * @return
 */
protected String getAppName() {
	String appName = this.getProperty("app.name", "");
	if (StrKit.isBlank(appName)) {
		throw new IllegalArgumentException("Please Set Your App Name in Your cfg file");
	}
	return appName;
}
 
Example 12
Source File: HexKit.java    From jfinal-ext3 with Apache License 2.0 5 votes vote down vote up
public static byte[] HexStringToBytes(String hexString) {
	if (StrKit.isBlank(hexString)) {
		return null;
	}
	hexString = hexString.toUpperCase();
	int length = hexString.length() / 2;
	char[] hexChars = hexString.toCharArray();
	byte[] data = new byte[length];
	for (int i = 0; i < length; i++) {
		int pos = i * 2;
		data[i] = (byte) (c2b(hexChars[pos]) << 4 | c2b(hexChars[pos + 1]));
	}
	return data;
}
 
Example 13
Source File: GlobalSyncRedis.java    From jfinal-ext3 with Apache License 2.0 5 votes vote down vote up
/**
 * Get cache from memory.
 * @param name
 * @return
 */
public static Cache getSyncCache(String name) {
	if (StrKit.isBlank(name) || !GlobalSyncRedis.caches.containsKey(name)) {
		return Redis.use();
	}
	return GlobalSyncRedis.caches.get(name);
}
 
Example 14
Source File: GlobalSyncRedis.java    From jfinal-ext3 with Apache License 2.0 5 votes vote down vote up
/**
 * remove cache from memory.
 * @param name
 */
public static void removeSyncCache(String name) {
	if (StrKit.isBlank(name)) {
		return;
	}
	if (GlobalSyncRedis.caches.containsKey(name)) {
		GlobalSyncRedis.caches.remove(name);
	}
}
 
Example 15
Source File: DataDirective.java    From jboot-admin with Apache License 2.0 5 votes vote down vote up
@Override
public void exec(Env env, Scope scope, Writer writer) {
    if (exprList.length() > 2) {
        throw new ParseException("Wrong number parameter of #date directive, two parameters allowed at most", location);
    }

    typeCode = getParam(0, scope);
    if (StrKit.isBlank(typeCode)) {
        throw new ParseException("typeCode is null", location);
    }

    if (exprList.length() > 1) {
        code = getParam(1,scope);
    }



    List<Data> list = dataApi.getListByTypeOnUse(typeCode);

    if (StrKit.isBlank(code)) {
        write(writer, "");
    } else {
        for (Data data : list) {
            if(code.equals(data.getCode())) {
                write(writer,data.getCodeDesc());
            }
        }
    }
}
 
Example 16
Source File: WeixinPayController.java    From jfinal-weixin with Apache License 2.0 4 votes vote down vote up
public void index() throws DocumentException {
	// openId,采用 网页授权获取 access_token API:SnsAccessTokenApi获取
	String openId = "";

	// 统一下单文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
	
	Map<String, String> params = new HashMap<String, String>();
	params.put("appid", appid);
	params.put("mch_id", partner);
	params.put("body", "JFinal2.0极速开发");
	params.put("out_trade_no", "977773682111");
	params.put("total_fee", "1");
	
	String ip = IpKit.getRealIp(getRequest());
	if (StrKit.isBlank(ip)) {
		ip = "127.0.0.1";
	}
	
	params.put("spbill_create_ip", ip);
	params.put("trade_type", TradeType.JSAPI.name());
	params.put("nonce_str", System.currentTimeMillis() / 1000 + "");
	params.put("notify_url", notify_url);
	params.put("openid", openId);

	String sign = PaymentKit.createSign(params, paternerKey);
	params.put("sign", sign);
	String xmlResult = PaymentApi.pushOrder(params);
	
	System.out.println(xmlResult);
	
	Document doc = DocumentHelper.parseText(xmlResult);
	Element root = doc.getRootElement();
	String return_code = root.elementText("return_code");
	String result_code = root.elementText("result_code");
	
	// 
	
	String return_msg = root.elementText("return_msg");
	String prepay_id = root.elementText("prepay_id");
	
	Map<String, String> packageParams = new HashMap<String, String>();
	packageParams.put("appId", appid);
	packageParams.put("timeStamp", System.currentTimeMillis() / 1000 + "");
	packageParams.put("nonceStr", System.currentTimeMillis() + "");
	packageParams.put("package", "prepay_id=" + prepay_id);
	packageParams.put("signType", "MD5");
	String packageSign = PaymentKit.createSign(packageParams, paternerKey);
	packageParams.put("paySign", packageSign);
	
	String jsonStr = JsonUtils.toJson(packageParams);
	setAttr("json", jsonStr);
	System.out.println(jsonStr);
	render("/jsp/pay.jsp");
}
 
Example 17
Source File: AppServiceImplGenerator.java    From jboot-admin with Apache License 2.0 4 votes vote down vote up
public static void doGenerate() {
    AppServiceImplGeneratorConfig config = Jboot.config(AppServiceImplGeneratorConfig.class);

    System.out.println(config.toString());

    if (StrKit.isBlank(config.getModelpackage())) {
        System.err.println("jboot.admin.serviceimpl.ge.modelpackage 不可为空");
        System.exit(0);
    }

    if (StrKit.isBlank(config.getServicepackage())) {
        System.err.println("jboot.admin.serviceimpl.ge.servicepackage 不可为空");
        System.exit(0);
    }

    if (StrKit.isBlank(config.getServiceimplpackage())) {
        System.err.println("jboot.admin.serviceimpl.ge.serviceimplpackage 不可为空");
        System.exit(0);
    }

    String modelPackage = config.getModelpackage();
    String servicepackage = config.getServicepackage();
    String serviceimplpackage = config.getServiceimplpackage();

    System.out.println("start generate...");
    System.out.println("generate dir:" + servicepackage);

    DataSource dataSource = CodeGenHelpler.getDatasource();

    AppMetaBuilder metaBuilder = new AppMetaBuilder(dataSource);

    if (StrKit.notBlank(config.getRemovedtablenameprefixes())) {
        metaBuilder.setRemovedTableNamePrefixes(config.getRemovedtablenameprefixes().split(","));
    }

    if (StrKit.notBlank(config.getExcludedtableprefixes())) {
        metaBuilder.setSkipPre(config.getExcludedtableprefixes().split(","));
    }

    List<TableMeta> tableMetaList = metaBuilder.build();
    CodeGenHelpler.excludeTables(tableMetaList, config.getExcludedtable());

    new AppJbootServiceImplGenerator(servicepackage , modelPackage, serviceimplpackage).generate(tableMetaList);

    System.out.println("service generate finished !!!");

}
 
Example 18
Source File: LoginController.java    From my_curd with Apache License 2.0 4 votes vote down vote up
/**
 * 登录表单提交地址
 */
public void action() {
    String username = getPara("username");
    String password = getPara("password");

    /* username password 无效 */
    if (StrKit.isBlank(username)) {
        setAttr("errMsg", "请填写用户名。");
        render("login.ftl");
        return;
    }
    if (StrKit.isBlank(password)) {
        setAttr("errMsg", "请填写密码。");
        render("login.ftl");
        return;
    }
    SysUser sysUser = SysUser.dao.findByUsername(username);
    if (sysUser == null) {
        setAttr("errMsg", username + " 用户不存在。");
        render("login.ftl");
        return;
    }

    // 密码错误 n 次 锁定 m 分钟
    BaseCache<String, AtomicInteger> retryCache = CacheContainer.getLoginRetryLimitCache();
    AtomicInteger retryTimes = retryCache.getCache(username);
    if (retryTimes.get() >= LoginRetryLimitCache.RETRY_LIMIT) {
        setAttr("username", username);
        setAttr("errMsg", " 账号已被锁定, " + LoginRetryLimitCache.LOCK_TIME + "分钟后可自动解锁。 ");
        render("login.ftl");
        return;
    }
    password = HashKit.sha1(password);
    if (!sysUser.getPassword().equals(password)) {
        int nowRetryTimes = retryTimes.incrementAndGet();  // 错误次数 加 1
        setAttr("username", username);
        if ((LoginRetryLimitCache.RETRY_LIMIT - nowRetryTimes) == 0) {
            setAttr("errMsg", " 账号已被锁定, " + LoginRetryLimitCache.LOCK_TIME + "分钟后可自动解锁。 ");
        } else {
            setAttr("errMsg", " 密码错误, 再错误 "
                    + (LoginRetryLimitCache.RETRY_LIMIT - nowRetryTimes) + " 次账号将被锁定" + LoginRetryLimitCache.LOCK_TIME + "分钟。");
        }
        render("login.ftl");
        return;
    }
    retryCache.put(username, new AtomicInteger()); // 密码正确缓存数清0

    if (sysUser.getUserState().equals("1")) {
        setAttr("errMsg", username + " 用户被禁用,请联系管理员。");
        render("login.ftl");
        return;
    }

    /* username password 有效 */

    // 如果选中了记住密码且cookie信息不存在,生成新的cookie 信息
    String remember = getPara("remember");
    if ("on".equals(remember) && getCookie(USERNAME_KEY) == null) {
        setCookie(USERNAME_KEY, username, 60 * 60 * 24);  // 1天
        setCookie(PASSWORD_KEY, password, 60 * 60 * 24);
    }

    sysUser.setLastLoginTime(new Date());
    sysUser.update();

    afterLogin(sysUser);

    // 登录日志
    redirect("/dashboard");
}
 
Example 19
Source File: SearchSql.java    From my_curd with Apache License 2.0 4 votes vote down vote up
/**
 * searchParams中key的格式为OPERATOR_FIELDNAME
 */
public static Map<String, SearchFilter> parse(Map<String, Object> searchParams) {
    Map<String, SearchFilter> filters = new HashMap<>();

    for (Map.Entry<String, Object> entry : searchParams.entrySet()) {
        // 过滤掉空值
        String key = entry.getKey();
        Object value = entry.getValue();
        if (StrKit.isBlank((String) value)) {
            continue;
        }

        // 拆分operator与field

        String[] names = key.split("_");
        if (names.length < 2) {
            throw new IllegalArgumentException(key + " is not a valid search filter name");
        }

        // field 中可能有查询条件
        String filedName;
        StringBuilder filedNameTemp = new StringBuilder();
        for (int i = 1; i < names.length; i++) {
            filedNameTemp.append(names[i]).append("_");
        }
        if (filedNameTemp.substring(filedNameTemp.length() - 1).equals("_")) {
            filedNameTemp = new StringBuilder(filedNameTemp.substring(0, filedNameTemp.length() - 1));
        }
        filedName = filedNameTemp.toString();

        // 查询条件
        Operator operator = Operator.valueOf(names[0]);

        // 创建searchFilter
        SearchFilter filter = new SearchFilter(filedName, operator, value);

        filters.put(key, filter);
    }

    return filters;
}
 
Example 20
Source File: AppModelGenerator.java    From jboot-admin with Apache License 2.0 3 votes vote down vote up
public static void doGenerate() {
    AppModelGeneratorConfig config = Jboot.config(AppModelGeneratorConfig.class);

    System.out.println(config.toString());

    if (StrKit.isBlank(config.getModelpackage())) {
        System.err.println("jboot.admin.model.ge.modelpackage 不可为空");
        System.exit(0);
    }

    String modelPackage = config.getModelpackage();
    String baseModelPackage = modelPackage + ".base";

    String modelDir = PathKit.getWebRootPath() + "/src/main/java/" + modelPackage.replace(".", "/");
    String baseModelDir = PathKit.getWebRootPath() + "/src/main/java/" + baseModelPackage.replace(".", "/");

    System.out.println("start generate...");
    System.out.println("generate dir:" + modelDir);

    DataSource dataSource = CodeGenHelpler.getDatasource();

    AppMetaBuilder metaBuilder = new AppMetaBuilder(dataSource);

    if (StrKit.notBlank(config.getRemovedtablenameprefixes())) {
        metaBuilder.setRemovedTableNamePrefixes(config.getRemovedtablenameprefixes().split(","));
    }

    if (StrKit.notBlank(config.getExcludedtableprefixes())) {
        metaBuilder.setSkipPre(config.getExcludedtableprefixes().split(","));
    }

    List<TableMeta> tableMetaList = metaBuilder.build();
    CodeGenHelpler.excludeTables(tableMetaList, config.getExcludedtable());

    new JbootBaseModelGenerator(baseModelPackage, baseModelDir).generate(tableMetaList);
    new JbootModelGenerator(modelPackage, baseModelPackage, modelDir).generate(tableMetaList);

    System.out.println("entity generate finished !!!");

}