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

The following examples show how to use org.apache.commons.lang3.StringUtils#isNoneBlank() . 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: myth   File: JdbcLogServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CommonPager<LogVO> listByPage(final ConditionQuery query) {
    final String tableName = RepositoryPathUtils.buildDbTableName(query.getApplicationName());
    final PageParameter pageParameter = query.getPageParameter();
    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("select trans_id,target_class,target_method,"
            + " retried_count,create_time,last_time,version,error_msg from ")
            .append(tableName).append(" where 1= 1 ");

    if (StringUtils.isNoneBlank(query.getTransId())) {
        sqlBuilder.append(" and trans_id = ").append(query.getTransId());
    }
    final String sql = buildPageSql(sqlBuilder.toString(), pageParameter);
    CommonPager<LogVO> pager = new CommonPager<>();
    final List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
    if (CollectionUtils.isNotEmpty(mapList)) {
        pager.setDataList(mapList.stream().map(this::buildByMap).collect(Collectors.toList()));
    }
    final Integer totalCount =
            jdbcTemplate.queryForObject(String.format("select count(1) from %s", tableName), Integer.class);
    pager.setPage(PageHelper.buildPage(pageParameter, totalCount));
    return pager;
}
 
Example 2
Source Project: mblog   File: Base64Test.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws UnsupportedEncodingException {
    byte[] keys = "mtons".getBytes("UTF-8");
    System.out.println(Base64Utils.encodeToString(Arrays.copyOf(keys, 16)));

    String src = "/static/";
    if (StringUtils.isNoneBlank(src) && src.length() > 1) {
        if (src.startsWith("/")) {
            src = src.substring(1);
        }

        if (!src.endsWith("/")) {
            src = src + "/";
        }
    }
    System.out.println(src);

    System.out.println("sg[hide]test[/hide]<asf>fsd</sdf>".replaceAll("\\[hide\\]([\\s\\S]*)\\[\\/hide\\]", "$1"));
}
 
Example 3
Source Project: frpMgr   File: DateUtils.java    License: MIT License 6 votes vote down vote up
/**
 * 解析日期范围字符串为日期对象
 * @param dateString 2018-01-01 ~ 2018-01-31
 * @return new Date[]{2018-01-01, 2018-01-31}
 * @author ThinkGem
 */
public static Date[] parseDateBetweenString(String dateString){
	Date beginDate = null; Date endDate = null;
	if (StringUtils.isNotBlank(dateString)){
		String[] ss = StringUtils.split(dateString, "~");
		if (ss != null && ss.length == 2){
			String begin = StringUtils.trim(ss[0]);
			String end = StringUtils.trim(ss[1]);
			if (StringUtils.isNoneBlank(begin, end)){
				beginDate = DateUtils.parseDate(begin);
				endDate = DateUtils.parseDate(end);
			}
		}
	}
	return new Date[]{beginDate, endDate};
}
 
Example 4
Source Project: soul   File: HttpServiceDiscovery.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
    Boolean register = env.getProperty("soul.http.register", Boolean.class, false);
    if (!register) {
        return;
    }
    String zookeeperUrl = env.getProperty("soul.http.zookeeperUrl", "");
    if (StringUtils.isNoneBlank(zookeeperUrl)) {
        zkClient = new ZkClient(zookeeperUrl, 5000, 2000);
        boolean exists = zkClient.exists(ROOT);
        if (!exists) {
            zkClient.createPersistent(ROOT, true);
        }
        contextPathList = zkClient.getChildren(ROOT);
        updateServerNode(contextPathList);
        zkClient.subscribeChildChanges(ROOT, (parentPath, childs) -> {
            final List<String> addSubscribePath = addSubscribePath(contextPathList, childs);
            updateServerNode(addSubscribePath);
            contextPathList = childs;
        });
    }
}
 
Example 5
Source Project: SeimiCrawler   File: CrawlerModel.java    License: Apache License 2.0 6 votes vote down vote up
private void init() {
    Crawler c = clazz.getAnnotation(Crawler.class);
    Assert.notNull(c, StrFormatUtil.info("crawler {} lost annotation @cn.wanghaomiao.seimi.annotation.Crawler!", clazz.getName()));
    this.queueClass = c.queue();
    this.queueInstance = context.getBean(queueClass);
    Assert.notNull(queueInstance, StrFormatUtil.info("can not get {} instance,please check scan path", queueClass));
    memberMethods = new HashMap<>();
    ReflectionUtils.doWithMethods(clazz, method -> memberMethods.put(method.getName(), method));
    this.crawlerName = StringUtils.isNoneBlank(c.name()) ? c.name() : clazz.getSimpleName();
    instance.setCrawlerName(this.crawlerName);
    resolveProxy(c.proxy());
    this.useCookie = c.useCookie();
    this.currentUA = instance.getUserAgent();
    this.delay = c.delay();
    this.useUnrepeated = c.useUnrepeated();
    this.seimiHttpType = c.httpType();
    this.httpTimeOut = c.httpTimeOut();
    logger.info("Crawler[{}] init complete.", crawlerName);
}
 
Example 6
Source Project: cuba   File: RuntimePropertiesFrame.java    License: Apache License 2.0 5 votes vote down vote up
protected List<FieldGroup.FieldConfig> createFieldsForAttributes(FieldGroup newRuntimeFieldGroup) {
    @SuppressWarnings("unchecked")
    Collection<DynamicAttributesMetaProperty> metaProperties = rds.getPropertiesFilteredByCategory();
    List<FieldGroup.FieldConfig> fields = new ArrayList<>(metaProperties.size());

    for (DynamicAttributesMetaProperty property : metaProperties) {
        FieldGroup.FieldConfig field = newRuntimeFieldGroup.createField(property.getName());
        field.setProperty(property.getName());
        CategoryAttribute attribute = property.getAttribute();
        if (attribute != null) {
            field.setCaption(attribute.getLocaleName());
            if (StringUtils.isNoneBlank(attribute.getLocaleDescription())) {
                field.setDescription(attribute.getLocaleDescription());
            }
            if (StringUtils.isNotBlank(attribute.getWidth())) {
                field.setWidth(attribute.getWidth());
            } else {
                field.setWidth(fieldWidth);
            }
        } else {
            field.setCaption(property.getName());
            field.setWidth(fieldWidth);
        }
        fields.add(field);
    }
    return fields;
}
 
Example 7
Source Project: cloudbreak   File: ClusterProxyService.java    License: Apache License 2.0 5 votes vote down vote up
private ClientCertificate clientCertificates(Stack stack) {
    SecurityConfig securityConfig = securityConfigService.findOneByStack(stack);
    ClientCertificate clientCertificate = null;
    if (securityConfig != null
            && StringUtils.isNoneBlank(securityConfig.getClientCertVaultSecret(), securityConfig.getClientKeyVaultSecret())) {
        String clientCertRef = vaultPath(securityConfig.getClientCertVaultSecret());
        String clientKeyRef =  vaultPath(securityConfig.getClientKeyVaultSecret());
        clientCertificate = new ClientCertificate(clientKeyRef, clientCertRef);
    }
    return clientCertificate;
}
 
Example 8
@Override
public ProxyConfig convert(ProxyRequest source) {
    ProxyConfig proxyConfig = new ProxyConfig();
    proxyConfig.setName(source.getName());
    proxyConfig.setDescription(source.getDescription());
    proxyConfig.setProtocol(source.getProtocol());
    proxyConfig.setServerHost(source.getHost());
    proxyConfig.setServerPort(source.getPort());
    if (StringUtils.isNoneBlank(source.getUserName(), source.getPassword())) {
        proxyConfig.setUserName(source.getUserName());
        proxyConfig.setPassword(source.getPassword());
    }
    return proxyConfig;
}
 
Example 9
Source Project: soul   File: PluginController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * update plugin.
 *
 * @param id        primary key.
 * @param pluginDTO plugin.
 * @return {@linkplain SoulAdminResult}
 */
@PutMapping("/{id}")
public SoulAdminResult updatePlugin(@PathVariable("id") final String id, @RequestBody final PluginDTO pluginDTO) {
    Objects.requireNonNull(pluginDTO);
    pluginDTO.setId(id);
    final String result = pluginService.createOrUpdate(pluginDTO);
    if (StringUtils.isNoneBlank(result)) {
        return SoulAdminResult.error(result);
    }
    return SoulAdminResult.success("update plugin success");
}
 
Example 10
Source Project: code   File: ContainerSingleton.java    License: Apache License 2.0 5 votes vote down vote up
public static void putInstance(String key, String instance){
    if(StringUtils.isNoneBlank(key) && instance != null){
        if(!singletonMap.containsKey(key)){
            singletonMap.put(key,instance);
        }
    }
}
 
Example 11
/**
 * @param msgFilter
 * @param status      -2:执行异常,-1:结束,0:等待,1:正在执行,2:正在上传
 * @param url
 * @param description
 */
private void updateMsgFilterStatus(TopicMsgFilter msgFilter, TopicMsgFilter.FilterStatus status, String url, String description) {
    TopicMsgFilter updateMsgFilter = new TopicMsgFilter();
    updateMsgFilter.setId(msgFilter.getId());
    updateMsgFilter.setStatus(status.getStatus());
    if (StringUtils.isNoneBlank(url)) {
      updateMsgFilter.setUrl(url);
    }
    if (StringUtils.isNoneBlank(description)) {
        updateMsgFilter.setDescription(description);
    }
    updateMsgFilter.setUpdateTime(new Date(SystemClock.now()));
    repository.update(updateMsgFilter);
}
 
Example 12
Source Project: soul   File: ApplicationConfigCache.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Build reference config.
 *
 * @param metaData the meta data
 * @return the reference config
 */
public ReferenceConfig<GenericService> build(final MetaData metaData) {
    ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
    reference.setGeneric(true);
    reference.setApplication(applicationConfig);
    reference.setRegistry(registryConfig);
    reference.setInterface(metaData.getServiceName());
    reference.setProtocol("dubbo");
    String rpcExt = metaData.getRpcExt();
    DubboParamExtInfo dubboParamExtInfo = GsonUtils.getInstance().fromJson(rpcExt, DubboParamExtInfo.class);
    if (Objects.nonNull(dubboParamExtInfo)) {
        if (StringUtils.isNoneBlank(dubboParamExtInfo.getVersion())) {
            reference.setVersion(dubboParamExtInfo.getVersion());
        }
        if (StringUtils.isNoneBlank(dubboParamExtInfo.getGroup())) {
            reference.setGroup(dubboParamExtInfo.getGroup());
        }
        if (StringUtils.isNoneBlank(dubboParamExtInfo.getLoadbalance())) {
            final String loadBalance = dubboParamExtInfo.getLoadbalance();
            reference.setLoadbalance(buildLoadBalanceName(loadBalance));
        }
        Optional.ofNullable(dubboParamExtInfo.getTimeout()).ifPresent(reference::setTimeout);
        Optional.ofNullable(dubboParamExtInfo.getRetries()).ifPresent(reference::setRetries);
    }
    Object obj = reference.get();
    if (obj != null) {
        log.info("init apache dubbo reference success there meteData is :{}", metaData.toString());
        cache.put(metaData.getServiceName(), reference);
    }
    return reference;
}
 
Example 13
@Override
public void config() {
    String mailHost = siteOptions.getValue("mail_smtp_host");
    String mailUsername = siteOptions.getValue("mail_smtp_username");
    String mailPassowrd = siteOptions.getValue("mail_smtp_password");

    if (StringUtils.isNoneBlank(mailHost, mailUsername, mailPassowrd)) {
        final Properties properties = OhMyEmail.defaultConfig(false);
        properties.setProperty("mail.smtp.host", mailHost);
        OhMyEmail.config(properties, mailUsername, mailPassowrd);
    } else {
        log.error("邮件服务配置信息未设置, 请在后台系统配置中进行设置");
    }
}
 
Example 14
Source Project: joyqueue   File: ProducerServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<Producer> findByTopic(String namespace, String topic) {
    try {
        TopicName topicName = TopicName.parse(topic);
        if (StringUtils.isNoneBlank(topicName.getNamespace()) && StringUtils.isBlank(namespace)) {
            namespace = topicName.getNamespace();
        }
        return fillProducers(producerNameServerService.findByTopic(topicName.getCode(), namespace));
    } catch (Exception e) {
        logger.error("findByTopic producer with nameServer failed, producer is {}, {}", namespace, topic, e);
        throw new RuntimeException(e);
    }
}
 
Example 15
Source Project: soul   File: ApplicationConfigCache.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Build reference config.
 *
 * @param metaData the meta data
 * @return the reference config
 */
public ReferenceConfig<GenericService> build(final MetaData metaData) {
    ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
    reference.setGeneric(true);
    reference.setApplication(applicationConfig);
    reference.setRegistry(registryConfig);
    reference.setInterface(metaData.getServiceName());
    reference.setProtocol("dubbo");
    String rpcExt = metaData.getRpcExt();
    DubboParamExtInfo dubboParamExtInfo = GsonUtils.getInstance().fromJson(rpcExt, DubboParamExtInfo.class);
    if (Objects.nonNull(dubboParamExtInfo)) {
        if (StringUtils.isNoneBlank(dubboParamExtInfo.getVersion())) {
            reference.setVersion(dubboParamExtInfo.getVersion());
        }
        if (StringUtils.isNoneBlank(dubboParamExtInfo.getGroup())) {
            reference.setGroup(dubboParamExtInfo.getGroup());
        }
        if (StringUtils.isNoneBlank(dubboParamExtInfo.getLoadbalance())) {
            final String loadBalance = dubboParamExtInfo.getLoadbalance();
            reference.setLoadbalance(buildLoadBalanceName(loadBalance));
        }
        Optional.ofNullable(dubboParamExtInfo.getTimeout()).ifPresent(reference::setTimeout);
        Optional.ofNullable(dubboParamExtInfo.getRetries()).ifPresent(reference::setRetries);
    }
    Object obj = reference.get();
    if (obj != null) {
        log.info("init aliaba dubbo reference success there meteData is :{}", metaData.toString());
        cache.put(metaData.getServiceName(), reference);
    }
    return reference;
}
 
Example 16
protected void addRulePropositionInfo(String childIndex, String description, String category, String propTerm,
        String propComparison, String propositionValue) throws Exception {
    String propTreeRootPath = NEW_DATA_OBJ_PATH + "agendaItemLine.rule.propositionTree.rootElement.";
    String propTreeChildPath = propTreeRootPath + "children[" + childIndex + "].";
    String propositionPath = propTreeChildPath + "data.proposition.";

    if (StringUtils.isNoneBlank(description)) {
        waitAndTypeByName(propositionPath + "description", description);
    }

    if (StringUtils.isNoneBlank(category)) {
        waitAndSelectByName(propositionPath + "categoryId", category);
    }

    if (StringUtils.isNoneBlank(propTerm)) {
        waitAndSelectByName(propositionPath + "parameters[0].value", propTerm);
    }

    if (StringUtils.isNoneBlank(propComparison)) {
        waitAndSelectByName(propositionPath + "parameters[2].value", propComparison);
        unfocusElement();
        Thread.sleep(8000); // need time for next input to be reloaded
    }

    if (StringUtils.isNoneBlank(propositionValue)) {
        waitAndTypeByName(propositionPath + "parameters[1].value", propositionValue);
    }
}
 
Example 17
public Schema2MarkupConfigBuilder(final Class<T> selfClass,
                                  C config,
                                  Schema2MarkupProperties schema2MarkupProperties,
                                  Configuration configuration) {
    this.self = selfClass.cast(this);
    this.config = config;

    config.listDelimiterEnabled = schema2MarkupProperties.getBoolean(LIST_DELIMITER_ENABLED, false);
    config.listDelimiter = schema2MarkupProperties.getString(LIST_DELIMITER, ",").charAt(0);

    if (config.listDelimiterEnabled && configuration instanceof AbstractConfiguration) {
        ((AbstractConfiguration) configuration).setListDelimiterHandler(new DefaultListDelimiterHandler(config.listDelimiter));
    }

    config.requestExamplesFormat = schema2MarkupProperties.getRequiredString(REQUEST_EXAMPLES_FORMAT);
    config.requestExamplesSourceFormat = schema2MarkupProperties.getRequiredString(REQUEST_EXAMPLES_SOURCE_FORMAT);
    config.requestExamplesHost = schema2MarkupProperties.getRequiredString(REQUEST_EXAMPLES_HOST);
    config.requestExamplesSchema = schema2MarkupProperties.getRequiredString(REQUEST_EXAMPLES_SCHEMA);
    config.requestExamplesHideBasePath = schema2MarkupProperties.getRequiredBoolean(REQUEST_EXAMPLES_HIDE_BASE_PATH);
    config.requestExamplesQueryArrayStyle = schema2MarkupProperties.getRequiredString(REQUEST_EXAMPLES_QUERY_ARRAY_STYLE);
    config.requestExamplesIncludeAllQueryParams = schema2MarkupProperties.getRequiredBoolean(REQUEST_EXAMPLES_INCLUDE_ALL_QUERY_PARAMS);
    config.markupLanguage = schema2MarkupProperties.getRequiredMarkupLanguage(MARKUP_LANGUAGE);
    config.schemaMarkupLanguage = schema2MarkupProperties.getRequiredMarkupLanguage(SWAGGER_MARKUP_LANGUAGE);
    config.generatedExamplesEnabled = schema2MarkupProperties.getRequiredBoolean(GENERATED_EXAMPLES_ENABLED);
    config.hostnameEnabled = schema2MarkupProperties.getRequiredBoolean(HOSTNAME_ENABLED);
    config.basePathPrefixEnabled = schema2MarkupProperties.getRequiredBoolean(BASE_PATH_PREFIX_ENABLED);
    config.separatedDefinitionsEnabled = schema2MarkupProperties.getRequiredBoolean(SEPARATED_DEFINITIONS_ENABLED);
    config.separatedOperationsEnabled = schema2MarkupProperties.getRequiredBoolean(SEPARATED_OPERATIONS_ENABLED);
    config.pathsGroupedBy = schema2MarkupProperties.getGroupBy(PATHS_GROUPED_BY);
    config.language = schema2MarkupProperties.getLanguage(OUTPUT_LANGUAGE);
    config.inlineSchemaEnabled = schema2MarkupProperties.getRequiredBoolean(INLINE_SCHEMA_ENABLED);
    config.interDocumentCrossReferencesEnabled = schema2MarkupProperties.getRequiredBoolean(INTER_DOCUMENT_CROSS_REFERENCES_ENABLED);
    config.interDocumentCrossReferencesPrefix = schema2MarkupProperties.getString(INTER_DOCUMENT_CROSS_REFERENCES_PREFIX, null);
    config.flatBodyEnabled = schema2MarkupProperties.getRequiredBoolean(FLAT_BODY_ENABLED);
    config.pathSecuritySectionEnabled = schema2MarkupProperties.getRequiredBoolean(PATH_SECURITY_SECTION_ENABLED);
    config.anchorPrefix = schema2MarkupProperties.getString(ANCHOR_PREFIX, null);
    config.overviewDocument = schema2MarkupProperties.getRequiredString(OVERVIEW_DOCUMENT);
    config.pathsDocument = schema2MarkupProperties.getRequiredString(PATHS_DOCUMENT);
    config.definitionsDocument = schema2MarkupProperties.getRequiredString(DEFINITIONS_DOCUMENT);
    config.securityDocument = schema2MarkupProperties.getRequiredString(SECURITY_DOCUMENT);
    config.separatedOperationsFolder = schema2MarkupProperties.getRequiredString(SEPARATED_OPERATIONS_FOLDER);
    config.separatedDefinitionsFolder = schema2MarkupProperties.getRequiredString(SEPARATED_DEFINITIONS_FOLDER);
    config.tagOrderBy = schema2MarkupProperties.getOrderBy(TAG_ORDER_BY);
    config.operationOrderBy = schema2MarkupProperties.getOrderBy(OPERATION_ORDER_BY);
    config.definitionOrderBy = schema2MarkupProperties.getOrderBy(DEFINITION_ORDER_BY);
    config.parameterOrderBy = schema2MarkupProperties.getOrderBy(PARAMETER_ORDER_BY);
    config.propertyOrderBy = schema2MarkupProperties.getOrderBy(PROPERTY_ORDER_BY);
    config.responseOrderBy = schema2MarkupProperties.getOrderBy(RESPONSE_ORDER_BY);
    Optional<String> lineSeparator = schema2MarkupProperties.getString(LINE_SEPARATOR);
    if (lineSeparator.isPresent() && StringUtils.isNoneBlank(lineSeparator.get())) {
        config.lineSeparator = LineSeparator.valueOf(lineSeparator.get());
    }

    config.pageBreakLocations = schema2MarkupProperties.getPageBreakLocations(PAGE_BREAK_LOCATIONS);

    Optional<Pattern> headerPattern = schema2MarkupProperties.getHeaderPattern(HEADER_REGEX);

    config.headerPattern = headerPattern.orElse(null);

    Configuration swagger2markupConfiguration = schema2MarkupProperties.getConfiguration().subset(PROPERTIES_PREFIX);
    Configuration extensionsConfiguration = swagger2markupConfiguration.subset(EXTENSION_PREFIX);
    config.extensionsProperties = new Schema2MarkupProperties(extensionsConfiguration);
    config.asciidocPegdownTimeoutMillis = schema2MarkupProperties.getRequiredInt(ASCIIDOC_PEGDOWN_TIMEOUT);
}
 
Example 18
Source Project: cloudbreak   File: NodeConfig.java    License: Apache License 2.0 4 votes vote down vote up
public boolean isNodeIdSpecified() {
    return StringUtils.isNoneBlank(id);
}
 
Example 19
@Override
public CommonPager<TransactionRecoverVO> listByPage(final RecoverTransactionQuery query) {
    CommonPager<TransactionRecoverVO> commonPager = new CommonPager<>();
    final String redisKey = RepositoryPathUtils.buildRedisKey(query.getApplicationName());
    final int currentPage = query.getPageParameter().getCurrentPage();
    final int pageSize = query.getPageParameter().getPageSize();
    int start = (currentPage - 1) * pageSize;
    Set<byte[]> keys;
    List<TransactionRecoverVO> voList;
    int totalCount;
    if (StringUtils.isBlank(query.getTxGroupId()) && Objects.nonNull(query.getRetry())) {
        keys = jedisClient.keys((redisKey + "*").getBytes());
        final List<TransactionRecoverVO> all = findAll(keys);
        final List<TransactionRecoverVO> collect =
                all.stream()
                        .filter(vo -> vo.getRetriedCount() < query.getRetry())
                        .collect(Collectors.toList());
        totalCount = collect.size();
        voList = collect.stream().skip(start).limit(pageSize).collect(Collectors.toList());
    } else if (StringUtils.isNoneBlank(query.getTxGroupId()) && Objects.isNull(query.getRetry())) {
        keys = Sets.newHashSet(String.join(":", redisKey, query.getTxGroupId()).getBytes());
        totalCount = keys.size();
        voList = findAll(keys);
    } else if (StringUtils.isNoneBlank(query.getTxGroupId()) && Objects.nonNull(query.getRetry())) {
        keys = Sets.newHashSet(String.join(":", redisKey, query.getTxGroupId()).getBytes());
        totalCount = keys.size();
        voList = findAll(keys)
                .stream()
                .filter(vo -> vo.getRetriedCount() < query.getRetry())
                .collect(Collectors.toList());
    } else {
        keys = jedisClient.keys((redisKey + "*").getBytes());
        if (keys.size() <= 0 || keys.size() < start) {
            return commonPager;
        }
        totalCount = keys.size();
        voList = findByPage(keys, start, pageSize);
    }

    if (keys.size() <= 0 || keys.size() < start) {
        return commonPager;
    }
    commonPager.setPage(PageHelper.buildPage(query.getPageParameter(), totalCount));
    commonPager.setDataList(voList);
    return commonPager;
}
 
Example 20
@Transactional
public void configureRoleWithAuthorities(RoleAuthoritiesDto grantDto) {
	SysRoleEntity role = null;

	if (StringUtils.isNotBlank(grantDto.getRoleId())) {
		Optional<SysRoleEntity> roleOpt = roleRepository.findById(grantDto.getRoleId());
		if (roleOpt.isPresent()) {
			role = roleOpt.get();
		}
	}
	
	if( role == null  && StringUtils.isNotBlank(grantDto.getRoleName()) ) {
		role = roleRepository.findNotDeletedRoleByName(grantDto.getRoleName());
	}
	
	if (role == null) {
		log.debug("such role entity does not exist,role id {}, role name {} ", grantDto.getRoleId(), grantDto.getRoleName());
		throw new AuthServerException("Such role entity does not exist.");
	}

	for (SimpleAuthorityDto authorityDto : grantDto.getAuthorities()) {
		if (StringUtils.isBlank(authorityDto.getId()) && StringUtils.isBlank(authorityDto.getCode())) {
			log.debug("The ID and code of authority to configure is blank.");
			throw new AuthServerException("The ID and code of authority to configure is blank.");
		}

		log.info("configure role {} with authority {}-{}", role.getName(), authorityDto.getId(),
				authorityDto.getCode());

		SysAuthorityEntity authority = null;
		if (StringUtils.isNoneBlank(authorityDto.getId())) {
			Optional<SysAuthorityEntity> authorityOpt = authorityRepository.findById(authorityDto.getId());
			if (!authorityOpt.isPresent()) {
				log.debug("such authority entity does not exist,authority id {}", authorityDto.getId());
				throw new AuthServerException(
						String.format("Authority with {%s} does not exist.", authorityDto.getId()));

			}

			authority = authorityOpt.get();
		} else {
			authority = authorityRepository.findNotDeletedOneByCode(authorityDto.getCode());
			if (authority == null) {
				authority = new SysAuthorityEntity();
				authority.setActive(true);
				authority.setCode(authorityDto.getCode());
				authority.setCreatedBy(AuthenticationContextHolder.getCurrentUsername());
				authority.setDeleted(false);
				authority.setScope(StringUtils.isBlank(authorityDto.getScope()) ? SysAuthorityEntity.SCOPE_GLOBAL
						: authorityDto.getScope());
				authority.setDescription(authorityDto.getDescription());
				authority.setDisplayName(StringUtils.isBlank(authorityDto.getDisplayName()) ? authorityDto.getCode()
						: authorityDto.getDisplayName());

				authorityRepository.save(authority);
			}
		}

		RoleAuthorityRsEntity roleAuthority = roleAuthorityRsRepository.findOneByRoleIdAndAuthorityId(role.getId(),
				authority.getId());

		if (roleAuthority != null) {
			continue;
		}

		roleAuthority = new RoleAuthorityRsEntity();
		roleAuthority.setActive(true);
		roleAuthority.setAuthorityCode(authority.getCode());
		roleAuthority.setAuthorityId(authority.getId());
		roleAuthority.setCreatedBy(AuthenticationContextHolder.getCurrentUsername());
		roleAuthority.setDeleted(false);
		roleAuthority.setRoleId(role.getId());
		roleAuthority.setRoleName(role.getName());

		roleAuthorityRsRepository.save(roleAuthority);
	}
}