jodd.util.StringUtil Java Examples

The following examples show how to use jodd.util.StringUtil. 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: Variable.java    From maven-framework-project with MIT License 6 votes vote down vote up
public Map<String, Object> getVariableMap() {
	Map<String, Object> vars = new HashMap<String, Object>();

	ConvertUtils.register(new DateConverter(), java.util.Date.class);

	if (StringUtil.isBlank(keys)) {
		return vars;
	}

	String[] arrayKey = keys.split(",");
	String[] arrayValue = values.split(",");
	String[] arrayType = types.split(",");
	for (int i = 0; i < arrayKey.length; i++) {
		String key = arrayKey[i];
		String value = arrayValue[i];
		String type = arrayType[i];

		Class<?> targetType = Enum.valueOf(PropertyType.class, type).getValue();
		Object objectValue = ConvertUtils.convert(value, targetType);
		vars.put(key, objectValue);
	}
	return vars;
}
 
Example #2
Source File: AreaDao.java    From DAFramework with MIT License 6 votes vote down vote up
public EArea allArea(WMap query) {
	//处理查询条件
	Criteria cnd = Cnd.cri();
	cnd.where().andEquals("del_flag", Constans.POS_NEG.NEG);
	if (query.get("extId") != null && StringUtil.isNotBlank(query.get("extId").toString())) {
		cnd.where().andNotIn("id", query.get("extId").toString());
		cnd.where().andNotLike("parent_ids", "%," + query.get("extId").toString() + ",%");
	}
	cnd.getOrderBy().asc("sort");
	List<EArea> allAreas = query(cnd);
	List<ITreeNode<EArea>> allNodes = new ArrayList<>();
	EArea root = new EArea();
	root.setId(0L);
	allNodes.add(root);
	if (allAreas != null && !allAreas.isEmpty()) {
		allNodes.addAll(allAreas);
	}
	return (EArea) root.buildTree(allNodes);
}
 
Example #3
Source File: SysUserDetailsServiceTest.java    From DAFramework with MIT License 6 votes vote down vote up
@Test
public void testFetchUserAuthoritiesPrincipal() {
	//principal==null时获取到guest权限信息
	Set<String> authorities = userDetailsService.principalAuthorities(null);
	notNull(authorities, "");
	isTrue(authorities.size() == 1, "");
	isTrue("guest".equals(StringUtil.join(authorities, ",")), "");
	//admin user时获取全部权限
	UserPrincipal up = new UserPrincipal("watano");
	authorities = userDetailsService.principalAuthorities(up);
	notNull(authorities, "");
	isTrue(authorities.size() > 0, "");
	isTrue(authorities.contains("pro_list"), "");
	List<EAuthority> allAuthorities = authorityDao.query();
	assertEquals(authorities.size(), allAuthorities.size());
}
 
Example #4
Source File: UserController.java    From DAFramework with MIT License 6 votes vote down vote up
@RequestMapping(value = "/currInfo", method = RequestMethod.GET)
public ActionResultObj getUser() {
	ActionResultObj result = new ActionResultObj();
	// 获取当前用户
	UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	if (StringUtil.isNotBlank(userDetails.getUsername())) {
		EUser currentUser = userDao.fetchByName(userDetails.getUsername());
		EAccount account = accountDao.fetch(currentUser);
		EOrg org = orgDao.fetch(currentUser.getOrgId());
		WMap map = new WMap();
		map.put("userName", account != null ? account.getFullName() : currentUser.getUsername());
		map.put("accountId", account != null ? account.getId() : "");
		map.put("orgName", org.getName());
		result.ok(map);
	} else {
		result.errorMsg("获取失败");
	}
	return result;
}
 
Example #5
Source File: UserController.java    From DAFramework with MIT License 6 votes vote down vote up
/**
 * 新增一个用户,同时增加account和user
 *
 * @param account
 * @return
 */
@RequestMapping(value = "/save")
public ActionResultObj save(@RequestBody EAccount account) {
	ActionResultObj result = new ActionResultObj();
	try {
		account = userDetailsService.saveUser(account);
		if (account.getId() != null && account.getId() != 0) {
			result.okMsg("保存成功!");
		} else {
			result.errorMsg("保存失败!");
		}
	} catch (Exception e) {
		LOG.error("保存失败,原因:" + e.getMessage());
		result.error(e);
		EUser user = account.getUser();
		if (user.getUsername() != null && StringUtil.isNotBlank(user.getUsername())) {
			if (userDetailsService.isUserExisted(user.getUsername())) {
				result.errorMsg("用户  " + user.getUsername() + " 已存在!");
			}
		}
	}
	return result;
}
 
Example #6
Source File: DictController.java    From DAFramework with MIT License 6 votes vote down vote up
@RequestMapping(value="type/{type}")
public ActionResultObj findByType(@PathVariable String type){
	ActionResultObj result = new ActionResultObj();
	try{
		if(StringUtil.isNotBlank(type)){
				List<EDict> dictList = dictDao.query(Cnd.where("type", "=", type).and("del_flag", "=", Constans.POS_NEG.NEG).orderBy("sort", "asc"));
				//处理返回值
				WMap map = new WMap();
				map.put("type", type);
				map.put("data", dictList);
				result.ok(map);
				result.okMsg("查询成功!");
		}else{
			result.errorMsg("查询失败,字典类型不存在!");
		}
	}catch(Exception e){
		e.printStackTrace();
		LOG.error("查询失败,原因:"+e.getMessage());
		result.error(e);
	}
	return result;
}
 
Example #7
Source File: MenuController.java    From DAFramework with MIT License 6 votes vote down vote up
@RequestMapping(value = "/allMenu", method = RequestMethod.POST)
public ActionResultObj findAllmenu(@RequestBody SearchQueryJS queryJs) {
	ActionResultObj result = new ActionResultObj();
	try {
		WMap query = queryJs.getQuery();
		//处理查询条件
		Criteria cnd = Cnd.cri();
		cnd.where().andEquals("del_flag", Constans.POS_NEG.NEG);
		if (query.get("extId") != null && StringUtil.isNotBlank(query.get("extId").toString())) {
			cnd.where().andNotIn("id", query.get("extId").toString());
			cnd.where().andNotLike("parent_ids", "%," + query.get("extId").toString() + ",%");
		}
		cnd.getOrderBy().asc("sort");
		List<EMenu> allMenus = menuDao.query(cnd);
		EMenu menu = menuDao.buildMenuTree(allMenus);
		WMap map = new WMap();
		map.put("data", menu.getItems());
		result.setData(map);
		result.okMsg("查询成功!");
	} catch (Exception e) {
		e.printStackTrace();
		LOG.error("查询失败,原因:" + e.getMessage());
		result.error(e);
	}
	return result;
}
 
Example #8
Source File: Jerry.java    From web-data-extractor with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the value of a style property for the first element
 * in the set of matched elements. Returns <code>null</code>
 * if set is empty.
 */
public String css(String propertyName) {
    if (nodes.length == 0) {
        return null;
    }

    propertyName = StringUtil.fromCamelCase(propertyName, '-');

    String styleAttrValue = nodes[0].getAttribute("style");
    if (styleAttrValue == null) {
        return null;
    }

    Map<String, String> styles = createPropertiesMap(styleAttrValue, ';', ':');
    return styles.get(propertyName);
}
 
Example #9
Source File: Jerry.java    From web-data-extractor with Apache License 2.0 6 votes vote down vote up
/**
 * Sets one or more CSS properties for the set of matched elements.
 * By passing an empty value, that property will be removed.
 * Note that this is different from jQuery, where this means
 * that property will be reset to previous value if existed.
 */
public Jerry css(String propertyName, String value) {
    propertyName = StringUtil.fromCamelCase(propertyName, '-');

    for (Node node : nodes) {
        String styleAttrValue = node.getAttribute("style");
        Map<String, String> styles = createPropertiesMap(styleAttrValue, ';', ':');
        if (value.length() == 0) {
            styles.remove(propertyName);
        } else {
            styles.put(propertyName, value);
        }

        styleAttrValue = generateAttributeValue(styles, ';', ':');
        node.setAttribute("style", styleAttrValue);
    }
    return this;
}
 
Example #10
Source File: Jerry.java    From web-data-extractor with Apache License 2.0 6 votes vote down vote up
protected Map<String, String> createPropertiesMap(String attrValue, char propertiesDelimiter, char valueDelimiter) {
    if (attrValue == null) {
        return new LinkedHashMap<>();
    }
    String[] properties = StringUtil.splitc(attrValue, propertiesDelimiter);
    LinkedHashMap<String, String> map = new LinkedHashMap<>(properties.length);
    for (String property : properties) {
        int valueDelimiterIndex = property.indexOf(valueDelimiter);
        if (valueDelimiterIndex != -1) {
            String propertyName = property.substring(0, valueDelimiterIndex).trim();
            String propertyValue = property.substring(valueDelimiterIndex + 1).trim();
            map.put(propertyName, propertyValue);
        }
    }
    return map;
}
 
Example #11
Source File: Attribute.java    From web-data-extractor with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if attribute is containing some value.
 */
public boolean isContaining(String include) {
    if (value == null) {
        return false;
    }
    if (splits == null) {
        splits = StringUtil.splitc(value, ' ');
    }

    for (String s : splits) {
        if (s.equals(include)) {
            return true;
        }
    }
    return false;
}
 
Example #12
Source File: HtmlImplicitClosingRules.java    From web-data-extractor with Apache License 2.0 6 votes vote down vote up
/**
 * Returns <code>true</code> if parent node tag can be closed implicitly.
 */
public boolean implicitlyCloseParentTagOnNewTag(String parentNodeName, String nodeName) {
    if (parentNodeName == null) {
        return false;
    }
    parentNodeName = parentNodeName.toLowerCase();
    nodeName = nodeName.toLowerCase();

    for (int i = 0; i < IMPLIED_ON_START.length; i += 2) {
        if (StringUtil.equalsOne(parentNodeName, IMPLIED_ON_START[i]) != -1) {
            if (StringUtil.equalsOne(nodeName, IMPLIED_ON_START[i + 1]) != -1) {
                return true;
            }
        }
    }

    return false;
}
 
Example #13
Source File: HtmlImplicitClosingRules.java    From web-data-extractor with Apache License 2.0 6 votes vote down vote up
/**
 * Returns <code>true</code> if current end tag (node name) closes the parent tag.
 */
public boolean implicitlyCloseParentTagOnTagEnd(String parentNodeName, String nodeName) {
    if (parentNodeName == null) {
        return false;
    }

    parentNodeName = parentNodeName.toLowerCase();
    nodeName = nodeName.toLowerCase();

    for (int i = 0; i < IMPLIED_ON_END.length; i += 2) {
        if (StringUtil.equalsOne(nodeName, IMPLIED_ON_END[i]) != -1) {
            if (StringUtil.equalsOne(parentNodeName, IMPLIED_ON_END[i + 1]) != -1) {
                return true;
            }
        }
    }

    return false;
}
 
Example #14
Source File: DefaultClassLoaderStrategy.java    From web-data-extractor with Apache License 2.0 6 votes vote down vote up
/**
 * Prepares classname for loading, respecting the arrays.
 * Returns <code>null</code> if class name is not an array.
 */
public static String prepareArrayClassnameForLoading(String className) {
    int bracketCount = StringUtil.count(className, '[');

    if (bracketCount == 0) {
        // not an array
        return null;
    }

    String brackets = StringUtil.repeat('[', bracketCount);

    int bracketIndex = className.indexOf('[');
    className = className.substring(0, bracketIndex);

    int primitiveNdx = getPrimitiveClassNameIndex(className);
    if (primitiveNdx >= 0) {
        className = String.valueOf(PRIMITIVE_BYTECODE_NAME[primitiveNdx]);

        return brackets + className;
    } else {
        return brackets + 'L' + className + ';';
    }
}
 
Example #15
Source File: DefaultClassLoaderStrategy.java    From web-data-extractor with Apache License 2.0 6 votes vote down vote up
/**
 * Loads array class using component type.
 */
protected Class loadArrayClassByComponentType(String className, ClassLoader classLoader) throws ClassNotFoundException {
    int ndx = className.indexOf('[');
    int multi = StringUtil.count(className, '[');

    String componentTypeName = className.substring(0, ndx);

    Class componentType = loadClass(componentTypeName, classLoader);

    if (multi == 1) {
        return Array.newInstance(componentType, 0).getClass();
    }

    int[] multiSizes;

    if (multi == 2) {
        multiSizes = new int[]{0, 0};
    } else if (multi == 3) {
        multiSizes = new int[]{0, 0, 0};
    } else {
        multiSizes = (int[]) Array.newInstance(int.class, multi);
    }

    return Array.newInstance(componentType, multiSizes).getClass();
}
 
Example #16
Source File: PseudoFunctionExpression.java    From web-data-extractor with Apache License 2.0 5 votes vote down vote up
public PseudoFunctionExpression(String expression) {
    expression = StringUtil.removeChars(expression, "+ \t\n\r\n");
    if (expression.equals("odd")) {
        a = 2;
        b = 1;
    } else if (expression.equals("even")) {
        a = 2;
        b = 0;
    } else {
        int nndx = expression.indexOf('n');
        if (nndx != -1) {
            String aVal = expression.substring(0, nndx).trim();
            if (aVal.length() == 0) {
                a = 1;
            } else {
                if (aVal.equals(StringPool.DASH)) {
                    a = -1;
                } else {
                    a = parseInt(aVal);
                }
            }
            String bVal = expression.substring(nndx + 1);
            if (bVal.length() == 0) {
                b = 0;
            } else {
                b = parseInt(bVal);
            }
        } else {
            a = 0;
            b = parseInt(expression);
        }
    }
}
 
Example #17
Source File: PseudoFunction.java    From web-data-extractor with Apache License 2.0 5 votes vote down vote up
@Override
public String parseExpression(String expression) {
    if (StringUtil.startsWithChar(expression, '\'') || StringUtil.startsWithChar(expression, '"')) {
        expression = expression.substring(1, expression.length() - 1);
    }
    return expression;
}
 
Example #18
Source File: CSSelly.java    From web-data-extractor with Apache License 2.0 5 votes vote down vote up
/**
 * Parses string of selectors (separated with <b>,</b>). Returns
 * list of {@link CssSelector} lists in the same order.
 */
public static List<List<CssSelector>> parse(String query) {
    String[] singleQueries = StringUtil.splitc(query, ',');
    List<List<CssSelector>> selectors = new ArrayList<>(singleQueries.length);

    for (String singleQuery : singleQueries) {
        selectors.add(new CSSelly(singleQuery).parse());
    }

    return selectors;
}
 
Example #19
Source File: OAuth2Util.java    From jeewx with Apache License 2.0 5 votes vote down vote up
/**
 * 方法描述: 获取URL值
 * 作    者: Administrator
 * 日    期: 2015年1月13日-下午10:17:01
 * @param clazz
 * @param currentMethodName
 * @param paramsMap
 * @return 
 * 返回类型: String
 */
public static String obtainTargetUrl(Class clazz ,String currentMethodName,Map<String,String> paramsMap) {
	if(StringUtil.isEmpty(currentMethodName ) || clazz == null){
		return null;
	}
	StringBuffer targetURL =  new StringBuffer();
	String suffixStr = ".do?";
	targetURL.append(ResourceBundle.getBundle("sysConfig").getString("domain"));
	RequestMapping annotation = (RequestMapping)clazz.getAnnotation(RequestMapping.class);
	if(annotation != null){
		targetURL.append(annotation.value()[0]).append(suffixStr);
	}
	Method[] methodArray = clazz.getMethods();
	for (Method tempMethod : methodArray) {
		if(currentMethodName.equals(tempMethod.getName())){
			targetURL.append(tempMethod.getAnnotation(RequestMapping.class).params()[0]);
			break;
		}
	}
	if(paramsMap != null && paramsMap.size() > 0){
		Set<String> keys = paramsMap.keySet();
		for (String key : keys) {
			targetURL.append("&").append(key).append("=").append(paramsMap.get(key));
		}
	}
	return targetURL.toString();
}
 
Example #20
Source File: EsRestSpecGen.java    From wES with MIT License 5 votes vote down vote up
public void writeEnumType(String type, List<String> options, String defaultValue, String description) {
	try {
		String pkg2 = pkg + ".types";
		StringBuilder javaCodes = new StringBuilder();
		javaCodes.append("package " + pkg2 + ";\n\n");

		javaCodes.append("//" + description + "\n");
		javaCodes.append("//default: " + defaultValue + "\n");
		javaCodes.append("public enum " + type + " {\n");
		String enumCodes = "";
		for (String option : options) {
			String enumName = option.toUpperCase();
			if (option.trim().length() <= 0) {
				enumName = "v";
			}
			enumCodes += "\t" + enumName + "(\"" + option + "\"),\n";
		}
		enumCodes = StringUtil.cutSuffix(enumCodes, ",\n");
		javaCodes.append(enumCodes + ";\n");

		javaCodes.append("\tprivate String name;\n");
		javaCodes.append("\t" + type + "(String name) {\n");
		javaCodes.append("\t\tthis.name = name;\n");
		javaCodes.append("\t}\n\n");
		javaCodes.append("\t@Override\n");
		javaCodes.append("\tpublic String toString() {\n");
		javaCodes.append("\treturn this.name;\n");
		javaCodes.append("\t}\n");
		javaCodes.append("}");
		String filePath = sourceDir + pkg2.replace('.', File.separatorChar) + File.separatorChar;
		FileUtil.mkdirs(filePath);
		FileUtil.writeString(filePath + type + ".java", javaCodes.toString(), "utf-8");
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example #21
Source File: StrMap.java    From wES with MIT License 5 votes vote down vote up
public String eval(String text) {
	String out = text;
	for (String key : keySet()) {
		out = StringUtil.replace(out, "${" + key + "}", get(key));
	}
	return out;
}
 
Example #22
Source File: SysToolkit.java    From wES with MIT License 5 votes vote down vote up
public

	static String polishFilePath(String path) {
		String path2 = StringUtil.replace(path, "\\", File.separator);
		path2 = StringUtil.replace(path2, "/", File.separator);
		return path2;
	}
 
Example #23
Source File: CmdExecuter.java    From wES with MIT License 5 votes vote down vote up
public String[] values(String key) {
	String value = mapData.get(key);
	if (value != null) {
		return StringUtil.split(value, "|");
	} else {
		return new String[]{};
	}
}
 
Example #24
Source File: TextUtils.java    From wES with MIT License 5 votes vote down vote up
public static boolean match(String text, String regex) {
	regex = StringUtil.replace(regex, "\\", "\\\\");
	regex = StringUtil.replace(regex, ".", "\\.");
	regex = StringUtil.replace(regex, "[", "\\[");
	regex = StringUtil.replace(regex, "]", "\\]");
	regex = StringUtil.replace(regex, "(", "\\(");
	regex = StringUtil.replace(regex, ")", "\\)");

	regex = StringUtil.replace(regex, "?", ".+");
	regex = StringUtil.replace(regex, "*", ".*");
	return text.matches(regex);
}
 
Example #25
Source File: TextUtils.java    From wES with MIT License 5 votes vote down vote up
public static Long parseId(Object id) {
	if (id == null) {
		return null;
	}
	if (id instanceof String && !StringUtil.isBlank((String) id)) {
		return Long.parseLong((String) id);
	} else if (id instanceof Number) {
		return ((Number) id).longValue();
	}
	return -1l;
}
 
Example #26
Source File: TextUtils.java    From wES with MIT License 5 votes vote down vote up
public static String[] rebuildArray(String[] arr) {
	if (arr != null) {
		List<String> list = new ArrayList<String>(Arrays.asList(arr));
		for (Iterator<String> iter = list.iterator(); iter.hasNext(); ) {
			String s = iter.next();
			if (StringUtil.isEmpty(s)) {
				iter.remove();
			}
		}
		String[] newArr = new String[list.size()];
		return list.toArray(newArr);
	}
	return new String[0];
}
 
Example #27
Source File: TextUtils.java    From wES with MIT License 5 votes vote down vote up
public static String repeat(String tpl, List<String> items, String rmEndStr) {
	StringBuffer sb = new StringBuffer();
	for (String item : items) {
		sb.append(StringUtil.replace(tpl, "${0}", item));
	}
	String code = sb.toString().trim();
	if (rmEndStr != null && code.endsWith(rmEndStr)) {
		code = code.substring(0, code.length() - rmEndStr.length());
	}
	return code;
}
 
Example #28
Source File: TreeNode.java    From wES with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	try {
		String text = "&#x529f;&#x80fd;&#x754c;&#x9762;&#x8bbe;&#x8ba1;";

		System.out.println(StringUtil.escapeJava(text));
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #29
Source File: WCfg.java    From wES with MIT License 5 votes vote down vote up
public static String getPath(final String key, final String... profiles) {
	String path = getValue(key, profiles);
	path = path.trim();
	path = StringUtil.replace(path, "\\", File.separator);
	path = StringUtil.replace(path, "//", File.separator);
	if (!path.endsWith(File.separator)) {
		path += File.separator;
	}
	return getCfg().getValue(key, profiles);
}
 
Example #30
Source File: UserController.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RequiresPermissions("ueboot:user:save")
@PostMapping(value = "/save")
public Response<Void> save(@RequestBody UserReq req) {
    User entity = null;
    if (req.getId() == null) {
        entity = new User();
        User user = this.userService.findByUserName(req.getUserName());
        if (user != null) {
            throw new BusinessException("当前用户名已经存在,不能重复添加!");
        }
    } else {
        entity = userService.findById(req.getId());
    }

    BeanUtils.copyProperties(req, entity, "password");
    if (StringUtil.isNotBlank(req.getPassword())) {
        entity.setPassword(PasswordUtil.sha512(entity.getUserName(), req.getPassword()));
        if (req.getCredentialExpiredDate() == null) {
            JDateTime dateTime = new JDateTime();
            //默认密码过期日期为x个月,x个月后要求更换密码
            Date expiredDate = dateTime.addMonth(this.shiroService.getPasswordExpiredMonth()).convertToDate();
            entity.setCredentialExpiredDate(expiredDate);
        }
    }
    //解锁
    if(!req.isLocked()){
        String key = MessageFormat.format(RetryLimitHashedCredentialsMatcher .PASSWORD_RETRY_CACHE,req.getUserName());
        redisTemplate.delete(key);
    }
    userService.save(entity);

    // 保存用户日志记录
    String optUserName = (String) SecurityUtils.getSubject().getPrincipal();
    this.shiroEventListener.saveUserEvent(optUserName, req.getUserName());
    return new Response<>();
}