Java Code Examples for org.apache.commons.lang3.StringUtils#splitByWholeSeparatorPreserveAllTokens()

The following examples show how to use org.apache.commons.lang3.StringUtils#splitByWholeSeparatorPreserveAllTokens() . 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: mithqtt   File: Topics.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validate the topic filter, add EMPTY and END, return as a List of levels
 *
 * @param topicFilter Topic Filter
 * @return List of levels
 */
public static List<String> sanitizeTopicFilter(String topicFilter) {
    if (StringUtils.isEmpty(topicFilter)) throw new IllegalArgumentException("Empty topic filer");
    if (!topicFilter.contains("+") && !topicFilter.contains("#"))
        throw new IllegalArgumentException("Topic filter does not contain wildcard");

    List<String> levels = new ArrayList<>();

    if (topicFilter.startsWith("/")) topicFilter = EMPTY + topicFilter;
    if (topicFilter.endsWith("/")) topicFilter = topicFilter + EMPTY;

    String[] tokens = StringUtils.splitByWholeSeparatorPreserveAllTokens(topicFilter, "/");
    for (int i = 0; i < tokens.length; i++) {
        if (tokens[i].contains("+") && !tokens[i].equals("+"))
            throw new IllegalArgumentException("Illegal topic filter: " + topicFilter);
        if (tokens[i].contains("#") && !tokens[i].equals("#"))
            throw new IllegalArgumentException("Illegal topic filter: " + topicFilter);
        if (tokens[i].equals("#") && !(i == tokens.length - 1 || (i == tokens.length - 2 && END.equals(tokens[i + 1]))))
            throw new IllegalArgumentException("Illegal topic filter: " + topicFilter);
        levels.add(StringUtils.isNotEmpty(tokens[i]) ? tokens[i] : EMPTY);
    }

    if (!topicFilter.endsWith(END)) levels.add(END);

    return levels;
}
 
Example 2
Source Project: FEBS-Cloud   File: MenuController.java    License: Apache License 2.0 5 votes vote down vote up
@GetMapping("/{username}")
public FebsResponse getUserRouters(@NotBlank(message = "{required}") @PathVariable String username) {
    Map<String, Object> result = new HashMap<>(2);
    List<VueRouter<Menu>> userRouters = this.menuService.getUserRouters(username);
    String userPermissions = this.menuService.findUserPermissions(username);
    String[] permissionArray = new String[0];
    if (StringUtils.isNoneBlank(userPermissions)) {
        permissionArray = StringUtils.splitByWholeSeparatorPreserveAllTokens(userPermissions, StringConstant.COMMA);
    }
    result.put("routes", userRouters);
    result.put("permissions", permissionArray);
    return new FebsResponse().data(result);
}
 
Example 3
Source Project: FEBS-Cloud   File: UserServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public void createUser(SystemUser user) {
    // 创建用户
    user.setCreateTime(new Date());
    user.setAvatar(SystemUser.DEFAULT_AVATAR);
    user.setPassword(passwordEncoder.encode(SystemUser.DEFAULT_PASSWORD));
    save(user);
    // 保存用户角色
    String[] roles = StringUtils.splitByWholeSeparatorPreserveAllTokens(user.getRoleId(), StringConstant.COMMA);
    setUserRoles(user, roles);
    // 保存用户数据权限关联关系
    String[] deptIds = StringUtils.splitByWholeSeparatorPreserveAllTokens(user.getDeptIds(), StringConstant.COMMA);
    setUserDataPermissions(user, deptIds);
}
 
Example 4
Source Project: FEBS-Cloud   File: RoleServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public void createRole(Role role) {
    role.setCreateTime(new Date());
    this.save(role);

    if (StringUtils.isNotBlank(role.getMenuIds())) {
        String[] menuIds = StringUtils.splitByWholeSeparatorPreserveAllTokens(role.getMenuIds(), StringConstant.COMMA);
        setRoleMenus(role, menuIds);
    }
}
 
Example 5
/** Create a FuncotationMap where all Funcotations will be TableFuncotations.  This is useful for parsing existing
 *   VCFs.
 * Only renders for a single allele.
 * See {@link FuncotatorUtils#extractFuncotatorKeysFromHeaderDescription(String)} for getting the funcotation keys.
 *
 * @param transcriptFieldName The field name to use for transcript IDs.  Use {@see NO_TRANSCRIPT_AVAILABLE_KEY} if unknown.
 *                            If not in the funcotation keys, then the Funcotation map will be created with one transcript ID, {@see NO_TRANSCRIPT_AVAILABLE_KEY}
 *                            Never {@code null}
 * @param funcotationKeys The ordered keys of the funcotation field.  Never {@code null}
 * @param funcotationAttributeForSingleAllele  The funcotation attribute from a VCF, split for a single Allele.  Never {@code null}
 * @param altAllele The alternate allele for the created funcotations.  Never {@code null}
 * @param datasourceName The datasource name to use for all of the created funcotatinos.  Never {@code null}
 * @return a funcotation map.  Note that no funcotations will be GencodeFuncotations.  Never {@code null}
 */
public static FuncotationMap createAsAllTableFuncotationsFromVcf(final String transcriptFieldName, final String[] funcotationKeys,
                                                                 final String funcotationAttributeForSingleAllele, final Allele altAllele,
                                                                 final String datasourceName) {
    Utils.nonNull(transcriptFieldName);
    Utils.nonNull(funcotationKeys);
    Utils.nonNull(funcotationAttributeForSingleAllele);
    Utils.nonNull(altAllele);
    Utils.nonNull(datasourceName);

    final FuncotationMap result = createEmpty();
    final String[] funcotationAttributeForSingleAlleleByTranscript = StringUtils.splitByWholeSeparator(funcotationAttributeForSingleAllele, VcfOutputRenderer.END_TRANSCRIPT_DELIMITER +
            VcfOutputRenderer.ALL_TRANSCRIPT_DELIMITER + VcfOutputRenderer.START_TRANSCRIPT_DELIMITER);

    for (final String funcotationAttribute : funcotationAttributeForSingleAlleleByTranscript) {
        final String[] values = StringUtils.splitByWholeSeparatorPreserveAllTokens(funcotationAttribute, VcfOutputRenderer.FIELD_DELIMITER);
        if (values[0].startsWith(VcfOutputRenderer.START_TRANSCRIPT_DELIMITER)) {
            values[0] = values[0].replace(VcfOutputRenderer.START_TRANSCRIPT_DELIMITER, "");
        }
        if (values[values.length - 1].endsWith(VcfOutputRenderer.END_TRANSCRIPT_DELIMITER)) {
            values[values.length - 1] = values[values.length - 1].replace(VcfOutputRenderer.END_TRANSCRIPT_DELIMITER, "");
        }
        if (values.length != funcotationKeys.length) {
            logger.error("Keys:  " + StringUtils.join(funcotationKeys, ", "));
            logger.error("Values:  " + StringUtils.join(values, ", "));
            throw new GATKException.ShouldNeverReachHereException("Cannot parse the funcotation attribute.  Num values: " + values.length + "   Num keys: " + funcotationKeys.length);
        }
        final Map<String, String> simpleNameValuePairs = IntStream.range(0, values.length).boxed().collect(Collectors
                .toMap(i -> funcotationKeys[i], i-> values[i]));

        final List<String> valuesAsList = Arrays.stream(funcotationKeys).map(simpleNameValuePairs::get).collect(Collectors.toList());
        result.add(simpleNameValuePairs.getOrDefault(transcriptFieldName, NO_TRANSCRIPT_AVAILABLE_KEY), TableFuncotation.create(Arrays.asList(funcotationKeys), valuesAsList, altAllele, datasourceName, null));
    }
    return result;
}
 
Example 6
Source Project: async-gamequery-lib   File: AbstractRestClient.java    License: MIT License 5 votes vote down vote up
/**
 * <p>A Simply utility method for parsing Content-Type which contains parameters</p>
 *
 * @param contentType A {@link String} containing the Content-Type
 *
 * @return The parsed content-type {@link String} excluding the parameters
 */
private String parseContentType(String contentType) {
    if (!StringUtils.isEmpty(contentType) && contentType.contains(";")) {
        String[] types = StringUtils.splitByWholeSeparatorPreserveAllTokens(contentType, ";", 2);
        if (types != null && types.length > 1)
            return types[0].trim();
    }
    return contentType;
}
 
Example 7
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteOauthClientDetails(String clientIds) {
    Object[] clientIdArray = StringUtils.splitByWholeSeparatorPreserveAllTokens(clientIds, StringConstant.COMMA);
    LambdaQueryWrapper<OauthClientDetails> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.in(OauthClientDetails::getClientId, clientIdArray);
    boolean removed = this.remove(queryWrapper);
    if (removed) {
        log.info("删除ClientId为({})的Client", clientIds);
        Arrays.stream(clientIdArray).forEach(c -> this.redisClientDetailsService.removeRedisCache(String.valueOf(c)));

    }
}
 
Example 8
Source Project: FEBS-Security   File: QQOAuth2Template.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
    // access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14
    String result = this.getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);
    log.info("responseToken: {}", result);
    String[] params = StringUtils.splitByWholeSeparatorPreserveAllTokens(result, "&");

    String accessToken = StringUtils.substringAfterLast(params[0], "=");
    Long expiresIn = Long.valueOf(StringUtils.substringAfterLast(params[1], "="));
    String refreshToken = StringUtils.substringAfterLast(params[2], "=");
    return new AccessGrant(accessToken, null, refreshToken, expiresIn);
}
 
Example 9
Source Project: flink   File: SqlFunctionUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Split target string with custom separator and pick the index-th(start with 0) result.
 *
 * @param str       target string.
 * @param separator custom separator.
 * @param index     index of the result which you want.
 * @return the string at the index of split results.
 */
public static String splitIndex(String str, String separator, int index) {
	if (index < 0) {
		return null;
	}
	String[] values = StringUtils.splitByWholeSeparatorPreserveAllTokens(str, separator);
	if (index >= values.length) {
		return null;
	} else {
		return values[index];
	}
}
 
Example 10
Source Project: FEBS-Security   File: SmsCodeFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws ServletException {
    super.afterPropertiesSet();
    String[] configUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens(securityProperties.getCode().getSms().getUrl(), ",");
    url.addAll(Arrays.asList(configUrls));
    url.add(securityProperties.getCode().getSms().getLoginProcessingUrl());
}
 
Example 11
Source Project: vscrawler   File: SplitByWholeSeparator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected String[] split(String str, String separatorChars, int max, boolean preserveAllTokens) {
    if (preserveAllTokens) {
        return StringUtils.splitByWholeSeparatorPreserveAllTokens(str, separatorChars, max);
    } else {
        return StringUtils.splitByWholeSeparator(str, separatorChars, max);
    }
}
 
Example 12
Source Project: cs-actions   File: CollectionUtilities.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Splits the stringArray by the delimiter into an array of strings without ignoring the escaped delimiters
 *
 * @param stringArray the string to be split
 * @param delimiter   the delimiter by which to split the stringArray
 * @return an array of Strings
 */
@NotNull
public static String[] toArrayWithEscaped(@Nullable final String stringArray, @NotNull final String delimiter) {
    if (StringUtils.isEmpty(stringArray)) {
        return new String[0];
    }
    return StringUtils.splitByWholeSeparatorPreserveAllTokens(stringArray, delimiter);
}
 
Example 13
Source Project: cola   File: QQOAuth2Template.java    License: MIT License 5 votes vote down vote up
@Override
protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
    String responseStr = getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);

    log.info("【QQOAuth2Template】获取accessToke的响应:responseStr={}" , responseStr);

    String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(responseStr, "&");
    //http://wiki.connect.qq.com/使用authorization_code获取access_token
    //access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14
    String accessToken = StringUtils.substringAfterLast(items[0], "=");
    Long expiresIn = new Long(StringUtils.substringAfterLast(items[1], "="));
    String refreshToken = StringUtils.substringAfterLast(items[2], "=");

    return new AccessGrant(accessToken, null, refreshToken, expiresIn);
}
 
Example 14
Source Project: SpringAll   File: GlobalExceptionHandler.java    License: MIT License 5 votes vote down vote up
/**
 * 统一处理请求参数校验(普通传参)
 *
 * @param e ConstraintViolationException
 * @return FebsResponse
 */
@ExceptionHandler(value = ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleConstraintViolationException(ConstraintViolationException e) {
    StringBuilder message = new StringBuilder();
    Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
    for (ConstraintViolation<?> violation : violations) {
        Path path = violation.getPropertyPath();
        String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), ".");
        message.append(pathArr[1]).append(violation.getMessage()).append(",");
    }
    message = new StringBuilder(message.substring(0, message.length() - 1));
    return message.toString();
}
 
Example 15
@Override
protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
    String responseStr = getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);
    log.info("获取accessToke的响应:"+responseStr);

    String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(responseStr, "&");

    String accessToken = StringUtils.substringAfterLast(items[0], "=");
    Long expiresIn = new Long(StringUtils.substringAfterLast(items[1], "="));
    String refreshToken = StringUtils.substringAfterLast(items[2], "=");

    return new AccessGrant(accessToken, null, refreshToken, expiresIn);
}
 
Example 16
@Override
protected void configure(HttpSecurity http) throws Exception {

    String[] anonResourcesUrl = StringUtils.splitByWholeSeparatorPreserveAllTokens(febsSecurityProperties.getAnonResourcesUrl(),",");

    ImageCodeFilter imageCodeFilter = new ImageCodeFilter();
    imageCodeFilter.setAuthenticationFailureHandler(febsAuthenticationFailureHandler);
    imageCodeFilter.setSecurityProperties(febsSecurityProperties);
    imageCodeFilter.afterPropertiesSet();

    SmsCodeFilter smsCodeFilter = new SmsCodeFilter();
    smsCodeFilter.setAuthenticationFailureHandler(febsAuthenticationFailureHandler);
    smsCodeFilter.setSecurityProperties(febsSecurityProperties);
    smsCodeFilter.setSessionRegistry(sessionRegistry());
    smsCodeFilter.afterPropertiesSet();

    http.exceptionHandling().accessDeniedHandler(accessDeniedHandler()) // 权限不足处理器
         .and()
            .addFilterBefore(smsCodeFilter, UsernamePasswordAuthenticationFilter.class) // 短信验证码校验
            .addFilterBefore(imageCodeFilter, UsernamePasswordAuthenticationFilter.class) // 添加图形证码校验过滤器
            .formLogin() // 表单方式
            .loginPage(febsSecurityProperties.getLoginUrl()) // 未认证跳转 URL
            .loginProcessingUrl(febsSecurityProperties.getCode().getImage().getLoginProcessingUrl()) // 处理登录认证 URL
            .successHandler(febsAuthenticationSucessHandler) // 处理登录成功
            .failureHandler(febsAuthenticationFailureHandler) // 处理登录失败
        .and()
            .rememberMe() // 添加记住我功能
            .tokenRepository(persistentTokenRepository()) // 配置 token 持久化仓库
            .tokenValiditySeconds(febsSecurityProperties.getRememberMeTimeout()) // rememberMe 过期时间,单为秒
            .userDetailsService(febsUserDetailService) // 处理自动登录逻辑
        .and()
            .sessionManagement() // 配置 session管理器
            .invalidSessionStrategy(invalidSessionStrategy()) // 处理 session失效
            .maximumSessions(febsSecurityProperties.getSession().getMaximumSessions()) // 最大并发登录数量
            .expiredSessionStrategy(new FebsExpiredSessionStrategy()) // 处理并发登录被踢出
            .sessionRegistry(sessionRegistry()) // 配置 session注册中心
        .and()
        .and()
            .logout() // 配置登出
            .addLogoutHandler(logoutHandler()) // 配置登出处理器
            .logoutUrl(febsSecurityProperties.getLogoutUrl()) // 处理登出 url
            .logoutSuccessUrl("/") // 登出后跳转到 /
            .deleteCookies("JSESSIONID") // 删除 JSESSIONID
        .and()
            .authorizeRequests() // 授权配置
            .antMatchers(anonResourcesUrl).permitAll() // 免认证静态资源路径
            .antMatchers(
                    febsSecurityProperties.getLoginUrl(), // 登录路径
                    FebsConstant.FEBS_REGIST_URL, // 用户注册 url
                    febsSecurityProperties.getCode().getImage().getCreateUrl(), // 创建图片验证码路径
                    febsSecurityProperties.getCode().getSms().getCreateUrl(), // 创建短信验证码路径
                    febsSecurityProperties.getSocial().getSocialRedirectUrl(), // 重定向到社交账号注册(绑定)页面路径
                    febsSecurityProperties.getSocial().getSocialBindUrl(), // 社交账号绑定 URL
                    febsSecurityProperties.getSocial().getSocialRegistUrl() // 注册并绑定社交账号 URL
            ).permitAll() // 配置免认证路径
            .anyRequest()  // 所有请求
            .authenticated() // 都需要认证
        .and()
            .csrf().disable()
            .apply(febsSmsCodeAuthenticationSecurityConfig) // 添加短信验证码认证流程
        .and()
            .apply(febsSocialSecurityConfig); // social 配置
}
 
Example 17
Source Project: FEBS-Cloud   File: BlackListServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Flux<BlackList> delete(String ids) {
    String[] idArray = StringUtils.splitByWholeSeparatorPreserveAllTokens(ids, StringConstant.COMMA);
    return blackListMapper.deleteByIdIn(Arrays.asList(idArray))
            .doOnNext(routeEnhanceCacheService::removeBlackList);
}
 
Example 18
@Override
public Flux<RateLimitRule> delete(String ids) {
    String[] idArray = StringUtils.splitByWholeSeparatorPreserveAllTokens(ids, StringConstant.COMMA);
    return rateLimitRuleMapper.deleteByIdIn(Arrays.asList(idArray))
            .doOnNext(routeEnhanceCacheService::removeRateLimitRule);
}
 
Example 19
Source Project: FEBS-Cloud   File: BlockLogServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Flux<BlockLog> delete(String ids) {
    String[] idArray = StringUtils.splitByWholeSeparatorPreserveAllTokens(ids, StringConstant.COMMA);
    return blockLogMapper.deleteByIdIn(Arrays.asList(idArray));
}
 
Example 20
Source Project: ghidra   File: GhidraProtocolConnector.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Parse item path name from URL and establish initial values for folderPath and
 * folderItemName.
 * @return original item path from URL or null if not specified
 * @throws MalformedURLException if URL is invalid
 */
protected String parseItemPath() throws MalformedURLException {

	String path = url.getPath();

	if (repositoryName == null) {
		return null; // presumed server-only URL
	}

	// strip off repository name from path
	path = path.substring(repositoryName.length() + 1);
	if (path.length() <= 1) {
		// root path specified
		folderPath = FileSystem.SEPARATOR;
		return folderPath; // repository URL, root folder
	}

	// Handles server repository URL case  ghidra://<host>:<port>/<repository-name>[/<folder-path>]/[<folderItemName>]

	boolean isFolder = path.endsWith(FileSystem.SEPARATOR);
	folderPath = "";
	String pathToSplit = isFolder ? path.substring(0, path.length() - 1) : path;
	String[] pieces =
		StringUtils.splitByWholeSeparatorPreserveAllTokens(pathToSplit, FileSystem.SEPARATOR);
	if (pieces.length == 0) {
		throw new MalformedURLException("invalid repository path specification");
	}
	for (int i = 1; i < pieces.length; i++) {
		String p = pieces[i];
		if (p.length() == 0) {
			throw new MalformedURLException("invalid repository path specification");
		}
		if (!isFolder && i == (pieces.length - 1)) {
			folderItemName = p;
		}
		else {
			folderPath = folderPath + FileSystem.SEPARATOR + p;
		}
	}
	if (folderPath.length() == 0) {
		folderPath = FileSystem.SEPARATOR;
	}

	return path;
}