com.blade.kit.StringKit Java Examples

The following examples show how to use com.blade.kit.StringKit. 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: MetasService.java    From tale with 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 #2
Source File: TaleUtils.java    From tale with 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 #3
Source File: ThemeController.java    From tale with 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 #4
Source File: DynamicContext.java    From blade with 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 #5
Source File: Theme.java    From tale with 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 #6
Source File: ArticleController.java    From tale with 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 #7
Source File: RouteActionArguments.java    From blade with 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 #8
Source File: IndexController.java    From tale with 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 #9
Source File: XssMiddleware.java    From blade with 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 File: WechatApp.java    From squirrelAI with 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 #11
Source File: Blade.java    From blade with 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 #12
Source File: PathRegexBuilder.java    From blade with 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 File: OptionsService.java    From tale with 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 #14
Source File: Ason.java    From blade with Apache License 2.0 5 votes vote down vote up
public Short getShort(String key) {
    String val = getString(key);
    if (StringKit.isNotBlank(val)) {
        return Short.parseShort(val);
    }
    return null;
}
 
Example #15
Source File: RouteActionArguments.java    From blade with Apache License 2.0 5 votes vote down vote up
private static Object getPathParam(ParamStruct paramStruct) {
    Type      argType   = paramStruct.argType;
    PathParam pathParam = paramStruct.pathParam;
    String    paramName = paramStruct.paramName;
    Request   request   = paramStruct.request;

    String name = StringKit.isEmpty(pathParam.name()) ? paramName : pathParam.name();
    String val  = request.pathString(name);
    if (StringKit.isBlank(val)) {
        val = pathParam.defaultValue();
    }
    return ReflectKit.convert(argType, val);
}
 
Example #16
Source File: WechatApp.java    From squirrelAI with 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 #17
Source File: PathRegexBuilder.java    From blade with Apache License 2.0 5 votes vote down vote up
public String parsePath(String path) {
    if (StringKit.isBlank(path)) return path;
    String[] pathModule = path.split("/");

    Arrays.stream(pathModule)
            .filter(row -> !row.isEmpty())
            .map(this::rowToPath)
            .forEach(this::join);

    pathBuilder.deleteCharAt(pathBuilder.length() - 1);
    return build(true);
}
 
Example #18
Source File: HttpRequest.java    From blade with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Cookie> cookies() {
    if (!initCookie) {
        initCookie = true;
        String cookie = header(HttpConst.COOKIE_STRING);
        if (StringKit.isNotEmpty(cookie)) {
            ServerCookieDecoder.LAX.decode(cookie).forEach(this::parseCookie);
        }
    }
    return this.cookies;
}
 
Example #19
Source File: SessionHandler.java    From blade with Apache License 2.0 5 votes vote down vote up
private Session getSession(Request request) {
    String cookieHeader = request.cookie(WebContext.sessionKey());
    if (StringKit.isEmpty(cookieHeader)) {
        return null;
    }
    return sessionManager.getSession(cookieHeader);
}
 
Example #20
Source File: RouteActionArguments.java    From blade with Apache License 2.0 5 votes vote down vote up
public static <T> T parseModel(Class<T> argType, Request request, String name) {

        T obj = ReflectKit.newInstance(argType);

        List<Field> fields = ReflectKit.loopFields(argType);

        for (Field field : fields) {
            if ("serialVersionUID".equals(field.getName())) {
                continue;
            }
            Object value = null;

            Optional<String> fieldValue = request.query(field.getName());

            if (StringKit.isNotBlank(name)) {
                String fieldName = name + "[" + field.getName() + "]";
                fieldValue = request.query(fieldName);
            }

            if (fieldValue.isPresent() && StringKit.isNotBlank(fieldValue.get())) {
                value = ReflectKit.convert(field.getType(), fieldValue.get());
            }
            if (null != value) {
                ReflectKit.setFieldValue(field, obj, value);
            }
        }
        return obj;
    }
 
Example #21
Source File: HttpResponse.java    From blade with Apache License 2.0 5 votes vote down vote up
@Override
public void download(@NonNull String fileName, @NonNull File file) throws Exception {
    if (!file.exists() || !file.isFile()) {
        throw new NotFoundException("Not found file: " + file.getPath());
    }
    String contentType = StringKit.mimeType(file.getName());
    headers.put("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859_1"));
    headers.put(HttpConst.CONTENT_LENGTH.toString(), String.valueOf(file.length()));
    headers.put(HttpConst.CONTENT_TYPE_STRING, contentType);
    this.body = new StreamBody(new FileInputStream(file));
}
 
Example #22
Source File: Ason.java    From blade with Apache License 2.0 5 votes vote down vote up
public Boolean getBoolean(String key) {
    String val = getString(key);
    if (StringKit.isNotBlank(val)) {
        return Boolean.parseBoolean(val);
    }
    return Boolean.FALSE;
}
 
Example #23
Source File: CsrfMiddleware.java    From blade with Apache License 2.0 5 votes vote down vote up
public String genToken(RouteContext context) {
    String tokenUUID = context.session().attribute(sessionToken);
    if (StringKit.isEmpty(tokenUUID)) {
        tokenUUID = UUID.UU64();
        context.session().attribute(sessionToken, tokenUUID);
    }
    String token = Base64.getEncoder().encodeToString(PasswordKit.hashPassword(tokenUUID).getBytes());
    context.attribute("_csrf_token", token);
    context.attribute("_csrf_token_input", "<input type='hidden' name='_token' value='" + token + "'/>");
    return token;
}
 
Example #24
Source File: Ason.java    From blade with Apache License 2.0 5 votes vote down vote up
public Long getLong(String key) {
    String val = getString(key);
    if (StringKit.isNotBlank(val)) {
        return Long.parseLong(val);
    }
    return null;
}
 
Example #25
Source File: BasicAuthMiddleware.java    From blade with Apache License 2.0 5 votes vote down vote up
private String searchCredential(String authValue) {
    if (StringKit.isEmpty(authValue)) {
        return null;
    }
    return authPairs.stream()
            .filter(authPair -> authPair.getValue().equals(authValue))
            .map(AuthPair::getUser)
            .findFirst().orElse(null);
}
 
Example #26
Source File: Ason.java    From blade with Apache License 2.0 5 votes vote down vote up
public Integer getInt(String key) {
    String val = getString(key);
    if (StringKit.isNotBlank(val)) {
        return Integer.parseInt(val);
    }
    return null;
}
 
Example #27
Source File: ContentsService.java    From tale with MIT License 5 votes vote down vote up
/**
 * 根据id或slug获取文章
 *
 * @param id 唯一标识
 */
public Optional<Contents> getContents(String id) {
    if (StringKit.isNotBlank(id)) {
        if (StringKit.isNumber(id)) {
            return Optional.ofNullable(new Contents().find(id));
        } else {
            return Optional.ofNullable(new Contents().where("slug", id).find());
        }
    }
    return Optional.empty();
}
 
Example #28
Source File: SiteService.java    From tale with MIT License 5 votes vote down vote up
/**
 * 清楚缓存
 *
 * @param key 缓存key
 */
public void cleanCache(String key) {
    if (StringKit.isNotBlank(key)) {
        if ("*".equals(key)) {
            mapCache.clean();
        } else {
            mapCache.del(key);
        }
    }
}
 
Example #29
Source File: CsrfMiddleware.java    From blade with Apache License 2.0 5 votes vote down vote up
@Override
public boolean before(RouteContext context) {
    if (csrfOption.isIgnoreMethod(context.method())) {
        if (csrfOption.isStartExclusion(context.uri())) {
            return true;
        }
        this.genToken(context);
        return true;
    }

    if (csrfOption.isExclusion(context.uri())) {
        return true;
    }

    String tokenUUID = context.session().attribute(sessionToken);
    if (StringKit.isEmpty(tokenUUID)) {
        csrfOption.getErrorHandler().accept(context);
        return false;
    }

    String token = csrfOption.getTokenGetter().apply(context.request());
    if (StringKit.isEmpty(token)) {
        csrfOption.getErrorHandler().accept(context);
        return false;
    }
    String hash = new String(Base64.getDecoder().decode(token));
    if (!PasswordKit.checkPassword(tokenUUID, hash)) {
        csrfOption.getErrorHandler().accept(context);
        return false;
    }

    return true;
}
 
Example #30
Source File: OptionsService.java    From tale with MIT License 5 votes vote down vote up
/**
 * 根据key前缀查找配置项
 *
 * @param key 配置key
 */
public Map<String, String> getOptions(String key) {
    Map<String, String> options = new HashMap<>();

    Options activeRecord = new Options();
    if (StringKit.isNotBlank(key)) {
        activeRecord.like("name", key + "%");
    }
    List<Options> optionsList = activeRecord.findAll();
    if (null != optionsList) {
        optionsList.forEach(option -> options.put(option.getName(), option.getValue()));
    }
    return options;
}