Java Code Examples for com.blade.kit.StringKit

The following examples show how to use com.blade.kit.StringKit. These examples are extracted from open source projects. 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 Project: squirrelAI   Source File: WechatApp.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取用户的备注名称
 *
 * @param id
 * @return
 */
public String getUserRemarkName(String id) {
    String name = "微信群消息";//一般值的是群聊消息
    for (int i = 0, len = this.MemberList.size(); i < len; i++) {
        JSONObject member = (JSONObject) this.MemberList.get(i);
        if (member.getString("UserName").equals(id)) {
            if (StringKit.isNotBlank(member.getString("RemarkName"))) {
                name = member.getString("RemarkName");
            } else {
                name = member.getString("NickName");
            }
            return name;
        }
    }
    return name;
}
 
Example 2
Source Project: tale   Source File: Theme.java    License: MIT License 6 votes vote down vote up
/**
 * 显示文章缩略图,顺序为:文章第一张图 -> 随机获取
 *
 * @return
 */
public static String show_thumb(Contents contents) {
    if (null == contents) {
        return "";
    }
    if (StringKit.isNotBlank(contents.getThumbImg())) {
        return contents.getThumbImg();
    }
    String content = article(contents.getContent());
    String img     = Commons.show_thumb(content);
    if (StringKit.isNotBlank(img)) {
        return img;
    }
    int cid  = contents.getCid();
    int size = cid % 20;
    size = size == 0 ? 1 : size;
    return "/templates/themes/default/static/img/rand/" + size + ".jpg";
}
 
Example 3
Source Project: tale   Source File: TaleUtils.java    License: MIT License 6 votes vote down vote up
/**
 * markdown转换为html
 *
 * @param markdown
 * @return
 */
public static String mdToHtml(String markdown) {
    if (StringKit.isBlank(markdown)) {
        return "";
    }

    List<Extension> extensions = Arrays.asList(TablesExtension.create());
    Parser          parser     = Parser.builder().extensions(extensions).build();
    Node            document   = parser.parse(markdown);
    HtmlRenderer    renderer   = HtmlRenderer.builder().extensions(extensions).build();
    String          content    = renderer.render(document);
    content = Commons.emoji(content);

    // 支持网易云音乐输出
    if (TaleConst.BCONF.getBoolean("app.support_163_music", true) && content.contains("[mp3:")) {
        content = content.replaceAll("\\[mp3:(\\d+)\\]", "<iframe frameborder=\"no\" border=\"0\" marginwidth=\"0\" marginheight=\"0\" width=350 height=106 src=\"//music.163.com/outchain/player?type=2&id=$1&auto=0&height=88\"></iframe>");
    }
    // 支持gist代码输出
    if (TaleConst.BCONF.getBoolean("app.support_gist", true) && content.contains("https://gist.github.com/")) {
        content = content.replaceAll("&lt;script src=\"https://gist.github.com/(\\w+)/(\\w+)\\.js\">&lt;/script>", "<script src=\"https://gist.github.com/$1/$2\\.js\"></script>");
    }

    return content;
}
 
Example 4
Source Project: tale   Source File: ThemeController.java    License: MIT License 6 votes vote down vote up
/**
 * 主题设置页面
 *
 * @param request
 * @return
 */
@GetRoute(value = "setting")
public String setting(Request request) {
    String currentTheme = Commons.site_theme();
    String key          = "theme_" + currentTheme + "_options";

    String              option = optionsService.getOption(key);
    Map<String, Object> map    = new HashMap<>();
    try {
        if (StringKit.isNotBlank(option)) {
            map = JsonKit.toAson(option);
        }
        request.attribute("theme_options", map);
    } catch (Exception e) {
        log.error("解析主题设置出现异常", e);
    }
    request.attribute("theme_options", map);
    return this.render("setting");
}
 
Example 5
Source Project: tale   Source File: ArticleController.java    License: MIT License 6 votes vote down vote up
/**
 * 发布文章操作
 *
 * @return
 */
@PostRoute(value = "publish")
@JSON
public RestResponse publishArticle(@Valid Contents contents) {
    Users users = this.user();
    contents.setType(Types.ARTICLE);
    contents.setAuthorId(users.getUid());
    if (StringKit.isBlank(contents.getCategories())) {
        contents.setCategories("默认");
    }

    try {
        Integer cid = contentsService.publish(contents);
        siteService.cleanCache(Types.C_STATISTICS);
        return RestResponse.ok(cid);
    } catch (Exception e) {
        String msg = "文章发布失败";
        if (e instanceof TipException) {
            msg = e.getMessage();
        } else {
            log.error(msg, e);
        }
        return RestResponse.fail(msg);
    }
}
 
Example 6
Source Project: tale   Source File: IndexController.java    License: MIT License 6 votes vote down vote up
/**
 * 系统备份
 *
 * @return
 */
@Route(value = "backup", method = HttpMethod.POST)
@JSON
public RestResponse backup(@Param String bk_type, @Param String bk_path,
                           Request request) {
    if (StringKit.isBlank(bk_type)) {
        return RestResponse.fail("请确认信息输入完整");
    }

    try {
        BackResponse backResponse = siteService.backup(bk_type, bk_path, "yyyyMMddHHmm");
        new Logs(LogActions.SYS_BACKUP, null, request.address(), this.getUid()).save();
        return RestResponse.ok(backResponse);
    } catch (Exception e) {
        String msg = "备份失败";
        if (e instanceof TipException) {
            msg = e.getMessage();
        } else {
            log.error(msg, e);
        }
        return RestResponse.fail(msg);
    }
}
 
Example 7
Source Project: tale   Source File: MetasService.java    License: MIT License 6 votes vote down vote up
/**
 * 保存项目
 *
 * @param type
 * @param name
 * @param mid
 */
public void saveMeta(String type, String name, Integer mid) {
    if (StringKit.isNotBlank(type) && StringKit.isNotBlank(name)) {
        Metas metas = new Metas().where("type", type).and("name", name).find();
        if (null != metas) {
            throw new TipException("已经存在该项");
        } else {
            if (null != mid) {
                metas = new Metas();
                metas.setMid(mid);
                metas.setName(name);
                metas.update();
            } else {
                metas = new Metas();
                metas.setType(type);
                metas.setName(name);
                metas.save();
            }
        }
    }
}
 
Example 8
Source Project: tale   Source File: OptionsService.java    License: MIT License 6 votes vote down vote up
/**
 * 保存配置
 *
 * @param key   配置key
 * @param value 配置值
 */
public void saveOption(String key, String value) {
    if (StringKit.isNotBlank(key) && StringKit.isNotBlank(value)) {
        Options options = new Options();
        options.setName(key);

        long count = options.count();
        if (count == 0) {
            options = new Options();
            options.setName(key);
            options.setValue(value);
            options.save();
        } else {
            options = new Options();
            options.setValue(value);
            options.update(key);
        }
    }
}
 
Example 9
Source Project: blade   Source File: XssMiddleware.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean before(RouteContext context) {
    if (xssOption.isExclusion(context.uri())) {
        return true;
    }

    this.filterHeaders(context.headers());
    this.filterParameters(context.parameters());

    if (context.contentType().toLowerCase().contains("json")) {
        String body = context.bodyToString();
        if (StringKit.isNotEmpty(body)) {
            String filterBody = stripXSS(body);
            context.body(new StringBody(filterBody));
        }
    }
    return true;
}
 
Example 10
Source Project: blade   Source File: DynamicContext.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean isJarPackage(String packageName) {
    if (StringKit.isBlank(packageName)) {
        return false;
    }
    try {
        packageName = packageName.replace(".", "/");
        Enumeration<URL> dirs = DynamicContext.class.getClassLoader().getResources(packageName);
        if (dirs.hasMoreElements()) {
            String url = dirs.nextElement().toString();
            return url.indexOf(".jar!") != -1 || url.indexOf(".zip!") != -1;
        }
    } catch (Exception e) {
        log.error("", e);
    }
    return false;
}
 
Example 11
Source Project: blade   Source File: RouteActionArguments.java    License: Apache License 2.0 6 votes vote down vote up
private static String getDefaultValue(String defaultValue, Type argType) {
    if (argType.equals(String.class)) {
        if (StringKit.isNotEmpty(defaultValue)) {
            return defaultValue;
        }
        return null;
    }
    if ("".equals(defaultValue) && ReflectKit.isBasicType(argType)) {

        if (argType.equals(int.class) || argType.equals(long.class)
                || argType.equals(double.class) || argType.equals(float.class)
                || argType.equals(short.class) || argType.equals(byte.class)) {

            return "0";
        }

        if (argType.equals(boolean.class)) {
            return "false";
        }
        return "";
    }
    return defaultValue;
}
 
Example 12
Source Project: blade   Source File: PathRegexBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private PathBuilderMeta rowToPath(String row) {
    if (!row.contains(":")) {
        return PathBuilderMeta.builder()
                .name(row)
                .type(PathBuilderMeta.PathTypeEnum.COMMON)
                .build();
    }
    String[] itemPath = row.split(":");
    if (StringKit.isBlank(itemPath[0])) {
        return PathBuilderMeta.builder()
                .name(itemPath[1])
                .regex(PATH_VARIABLE_REPLACE)
                .type(PathBuilderMeta.PathTypeEnum.PARAM)
                .build();
    } else {
        return PathBuilderMeta.builder()
                .name(itemPath[0])
                .regex("(" + itemPath[1] + ")")
                .type(PathBuilderMeta.PathTypeEnum.REGEX)
                .build();
    }
}
 
Example 13
Source Project: blade   Source File: Blade.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get banner text
 *
 * @return return blade start banner text
 */
public String bannerText() {
    if (null != bannerText) return bannerText;
    String bannerPath = environment.get(ENV_KEY_BANNER_PATH, null);

    if (StringKit.isEmpty(bannerPath) || Files.notExists(Paths.get(bannerPath))) {
        return null;
    }

    try {
        BufferedReader bufferedReader = Files.newBufferedReader(Paths.get(bannerPath));
        bannerText = bufferedReader.lines().collect(Collectors.joining("\r\n"));
    } catch (Exception e) {
        log.error("Load Start Banner file error", e);
    }
    return bannerText;
}
 
Example 14
Source Project: squirrelAI   Source File: WechatApp.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取UUID:uuid是唯一的识别码
 */
public String getUUID() {

    HttpRequest request =
            HttpRequest.get(WechatInterface.UUID_URL, true, "appid", "wx782c26e4c19acffb", "fun", "new", "lang", "zh_CN", "_", DateKit.getCurrentUnixTime());
    // LOGGER.info 记录信息
    LOGGER.info("[*] " + request);

    String res = request.body();
    //res 为UUID
    request.disconnect();

    //如果返回的uuid信息不等于空
    if (StringKit.isNotBlank(res)) {
        //将登陆信息赋值给code
        String code = Matchers.match("window.QRLogin.code = (\\d+);", res);
        //如果登陆信息不等于空,那么微信登陆成功,否则反馈错误状态码
        if (null != code) {
            if (code.equals("200")) {
                this.Uuid = Matchers.match("window.QRLogin.uuid = \"(.*)\";", res);
                return this.Uuid;
            } else {
                LOGGER.info("[*] 错误的状态码: %s"+ code);
            }
        }
    }
    return null;
}
 
Example 15
Source Project: squirrelAI   Source File: WechatApp.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 登陆微信
 */
public boolean login() {

    HttpRequest request = HttpRequest.get(this.REDIRECT_URL);
    LOGGER.info("[*] " + request);
    String res = request.body();
    this.Cookie = CookieUtil.getCookie(request);
    request.disconnect();

    if (StringKit.isBlank(res)) {
        return false;
    }

    this.SKEY = Matchers.match("<skey>(\\S+)</skey>", res);
    this.WXSID = Matchers.match("<wxsid>(\\S+)</wxsid>", res);
    this.WXUIN = Matchers.match("<wxuin>(\\S+)</wxuin>", res);
    this.PASS_TICKET = Matchers.match("<pass_ticket>(\\S+)</pass_ticket>", res);

    LOGGER.info("[*] skey[%s]"+ this.SKEY);
    LOGGER.info("[*] wxsid[%s]"+ this.WXSID);
    LOGGER.info("[*] wxuin[%s]"+ this.WXUIN);
    LOGGER.info("[*] pass_ticket[%s]"+ this.PASS_TICKET);

    this.BaseRequest = new JSONObject();
    BaseRequest.put("Uin", this.WXUIN);
    BaseRequest.put("Sid", this.WXSID);
    BaseRequest.put("Skey", this.SKEY);
    BaseRequest.put("DeviceID", this.DEVICEID);

    return true;
}
 
Example 16
Source Project: squirrelAI   Source File: WechatApp.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 微信状态通知
 */
public boolean wxStatusNotify() {

    String Url = this.BASE_URL + WechatInterface.WXSTATUS_CODE + this.PASS_TICKET;

    JSONObject body = new JSONObject();
    body.put("BaseRequest", BaseRequest);
    body.put("Code", 3);
    body.put("FromUserName", this.User.getString("UserName"));
    body.put("ToUserName", this.User.getString("UserName"));
    body.put("ClientMsgId", DateKit.getCurrentUnixTime());

    HttpRequest request = HttpRequest.post(Url)
            .header("Content-Type", "application/json;charset=utf-8")
            .header("Cookie", this.Cookie)
            .send(body.toString());

    LOGGER.info("[*] " + request);
    String res = request.body();
    request.disconnect();

    if (StringKit.isBlank(res)) {
        return false;
    }

    try {
        JSONObject jsonObject = (JSONObject) JSON.parse(res);
        JSONObject BaseResponse = (JSONObject) jsonObject.get("BaseResponse");
        if (null != BaseResponse) {
            int ret = BaseResponse.getInt("Ret", -1);
            return ret == 0;
        }
    } catch (Exception e) {
    }
    return false;
}
 
Example 17
Source Project: squirrelAI   Source File: WechatApp.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 发送消息
 */
private void webwxsendmsg(String content, String to) {

    String url = this.BASE_URL + "/webwxsendmsg?lang=zh_CN&pass_ticket=" + this.PASS_TICKET;

    JSONObject body = new JSONObject();

    String clientMsgId = DateKit.getCurrentUnixTime() + StringKit.getRandomNumber(5);
    JSONObject Msg = new JSONObject();
    Msg.put("Type", 1);
    Msg.put("Content", content);
    Msg.put("FromUserName", User.getString("UserName"));
    Msg.put("ToUserName", to);
    Msg.put("LocalID", clientMsgId);
    Msg.put("ClientMsgId", clientMsgId);

    body.put("BaseRequest", this.BaseRequest);
    body.put("Msg", Msg);

    HttpRequest request = HttpRequest.post(url)
            .header("Content-Type", "application/json;charset=utf-8")
            .header("Cookie", this.Cookie)
            .send(body.toString());

    LOGGER.info("[*] " + request);
    request.body();
    request.disconnect();
}
 
Example 18
Source Project: tale   Source File: JetTag.java    License: MIT License 5 votes vote down vote up
public static void social(JetTagContext ctx, String name) throws IOException {
    String value = Commons.site_option("social_" + name);
    if (StringKit.isNotBlank(value)) {
        value = ctx.getBodyContent();
    }
    ctx.getWriter().print(value.toString());
}
 
Example 19
Source Project: tale   Source File: Theme.java    License: MIT License 5 votes vote down vote up
/**
 * 当前文章的分类列表
 *
 * @return
 * @since b1.3.0
 */
public static List<String> category_list() {
    Contents contents = current_article();
    if (null != contents && StringKit.isNotBlank(contents.getCategories())) {
        return Arrays.asList(contents.getCategories().split(","));
    }
    return Collections.emptyList();
}
 
Example 20
Source Project: tale   Source File: Theme.java    License: MIT License 5 votes vote down vote up
/**
 * 当前文章的标签列表
 *
 * @return
 * @since b1.3.0
 */
public static List<String> tag_list() {
    Contents contents = current_article();
    if (null != contents && StringKit.isNotBlank(contents.getTags())) {
        return Arrays.asList(contents.getTags().split(","));
    }
    return Collections.emptyList();
}
 
Example 21
Source Project: tale   Source File: Theme.java    License: MIT License 5 votes vote down vote up
/**
 * 显示分类
 *
 * @param categories
 * @return
 */
public static String show_categories(String categories) throws UnsupportedEncodingException {
    if (StringKit.isNotBlank(categories)) {
        String[]     arr  = categories.split(",");
        StringBuffer sbuf = new StringBuffer();
        for (String c : arr) {
            sbuf.append("<a href=\"/category/" + URLEncoder.encode(c, "UTF-8") + "\">" + c + "</a>");
        }
        return sbuf.toString();
    }
    return show_categories("默认");
}
 
Example 22
Source Project: tale   Source File: Theme.java    License: MIT License 5 votes vote down vote up
/**
 * 显示标签
 *
 * @param split 每个标签之间的分隔符
 * @return
 */
public static String show_tags(String split) throws UnsupportedEncodingException {
    Contents contents = current_article();
    if (StringKit.isNotBlank(contents.getTags())) {
        String[]     arr  = contents.getTags().split(",");
        StringBuffer sbuf = new StringBuffer();
        for (String c : arr) {
            sbuf.append(split).append("<a href=\"/tag/" + URLEncoder.encode(c, "UTF-8") + "\">" + c + "</a>");
        }
        return split.length() > 0 ? sbuf.substring(split.length() - 1) : sbuf.toString();
    }
    return "";
}
 
Example 23
Source Project: tale   Source File: Theme.java    License: MIT License 5 votes vote down vote up
/**
 * 显示文章内容,转换markdown为html
 *
 * @param value
 * @return
 */
public static String article(String value) {
    if (StringKit.isNotBlank(value)) {
        value = value.replace("<!--more-->", "\r\n");
        return TaleUtils.mdToHtml(value);
    }
    return "";
}
 
Example 24
Source Project: tale   Source File: Theme.java    License: MIT License 5 votes vote down vote up
/**
 * 返回主题设置选项
 *
 * @param key
 * @return
 */
public static String theme_option(String key, String defaultValue) {
    String option = theme_option(key);
    if (StringKit.isBlank(option)) {
        return defaultValue;
    }
    return option;
}
 
Example 25
Source Project: tale   Source File: Theme.java    License: MIT License 5 votes vote down vote up
/**
 * 返回主题设置选项
 *
 * @param key
 * @return
 */
public static String theme_option(String key) {
    String theme = Commons.site_theme();
    return TaleConst.OPTIONS.get("theme_" + theme + "_options")
            .filter(StringKit::isNotBlank)
            .map((String json) -> {
                Ason ason = JsonKit.toAson(json);
                if (!ason.containsKey(key)) {
                    return "";
                }
                return ason.getString(key);
            })
            .orElse("");
}
 
Example 26
Source Project: tale   Source File: TaleUtils.java    License: MIT License 5 votes vote down vote up
/**
 * 提取html中的文字
 *
 * @param html
 * @return
 */
public static String htmlToText(String html) {
    if (StringKit.isNotBlank(html)) {
        return html.replaceAll("(?s)<[^>]*>(\\s*<[^>]*>)*", " ");
    }
    return "";
}
 
Example 27
Source Project: tale   Source File: TaleUtils.java    License: MIT License 5 votes vote down vote up
/**
 * 判断是否是合法路径
 *
 * @param slug
 * @return
 */
public static boolean isPath(String slug) {
    if (StringKit.isNotBlank(slug)) {
        if (slug.contains("/") || slug.contains(" ") || slug.contains(".")) {
            return false;
        }
        Matcher matcher = SLUG_REGEX.matcher(slug);
        return matcher.find();
    }
    return false;
}
 
Example 28
Source Project: tale   Source File: TaleUtils.java    License: MIT License 5 votes vote down vote up
public static String getFileKey(String name) {
    String prefix = "/upload/" + DateKit.toString(new Date(), "yyyy/MM");
    String dir    = UP_DIR + prefix;
    if (!Files.exists(Paths.get(dir))) {
        new File(dir).mkdirs();
    }
    return prefix + "/" + com.blade.kit.UUID.UU32() + "." + StringKit.fileExt(name);
}
 
Example 29
Source Project: tale   Source File: IndexController.java    License: MIT License 5 votes vote down vote up
/**
 * 保存个人信息
 */
@Route(value = "profile", method = HttpMethod.POST)
@JSON
public RestResponse saveProfile(@Param String screen_name, @Param String email, Request request) {
    Users users = this.user();
    if (StringKit.isNotBlank(screen_name) && StringKit.isNotBlank(email)) {
        Users temp = new Users();
        temp.setScreen_name(screen_name);
        temp.setEmail(email);
        temp.update(users.getUid());
        new Logs(LogActions.UP_INFO, JsonKit.toString(temp), request.address(), this.getUid()).save();
    }
    return RestResponse.ok();
}
 
Example 30
Source Project: tale   Source File: IndexController.java    License: MIT License 5 votes vote down vote up
/**
 * 修改密码
 */
@Route(value = "password", method = HttpMethod.POST)
@JSON
public RestResponse upPwd(@Param String old_password, @Param String password, Request request) {
    Users users = this.user();
    if (StringKit.isBlank(old_password) || StringKit.isBlank(password)) {
        return RestResponse.fail("请确认信息输入完整");
    }

    if (!users.getPassword().equals(EncryptKit.md5(users.getUsername() + old_password))) {
        return RestResponse.fail("旧密码错误");
    }
    if (password.length() < 6 || password.length() > 14) {
        return RestResponse.fail("请输入6-14位密码");
    }

    try {
        Users  temp = new Users();
        String pwd  = EncryptKit.md5(users.getUsername() + password);
        temp.setPassword(pwd);
        temp.update(users.getUid());
        new Logs(LogActions.UP_PWD, null, request.address(), this.getUid()).save();
        return RestResponse.ok();
    } catch (Exception e) {
        String msg = "密码修改失败";
        if (e instanceof TipException) {
            msg = e.getMessage();
        } else {
            log.error(msg, e);
        }
        return RestResponse.fail(msg);
    }
}