下面列出了怎么用org.springframework.util.CollectionUtils的API类实例代码及写法,或者点击链接到github查看源代码。
private void printLog(HttpServletRequest request) {
CometLoggerProperties logger = this.cometLoggerProperties;
List<String> exclude = logger.getExclude();
String requestURI = request.getRequestURI();
if (!CollectionUtils.isEmpty(exclude)) {
if (exclude.contains(requestURI)) {
return;
}
}
List<CometLoggerProperties.Strategy> strategyList = this.strategyList;
if (CollectionUtils.isEmpty(strategyList)) {
return;
}
String requestParams = CometAspect.resolveThreadLocal.get();
for (CometLoggerProperties.Strategy strategy : strategyList) {
if (CollectionUtils.isEmpty(strategy.getPaths()) ||
!URLPathMatcher.match(strategy.getPaths(), requestURI)) {
continue;
}
log.info(urlPlaceholderParser.parse(strategy.getTpl(), request, requestParams, strategy.getCacheKeys()));
break;
}
}
@Test
public void preFlightRequest() throws Exception {
this.handlerMapping.registerHandler(new MethodLevelController());
this.request.setMethod("OPTIONS");
this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
this.request.setRequestURI("/default");
HandlerExecutionChain chain = this.handlerMapping.getHandler(request);
CorsConfiguration config = getCorsConfiguration(chain, true);
assertNotNull(config);
assertArrayEquals(new String[] {"GET"}, config.getAllowedMethods().toArray());
assertArrayEquals(new String[] {"*"}, config.getAllowedOrigins().toArray());
assertNull(config.getAllowCredentials());
assertArrayEquals(new String[] {"*"}, config.getAllowedHeaders().toArray());
assertTrue(CollectionUtils.isEmpty(config.getExposedHeaders()));
assertEquals(new Long(1800), config.getMaxAge());
}
private void checkQueueMessageCount(List<QueueEntity> queueEntities) {
if (!soaConfig.getMaxTableMessageSwitch()) {
return;
}
if (CollectionUtils.isEmpty(queueEntities)) {
return;
}
Long allMessageCount = 0L;
for (QueueEntity queueEntity : queueEntities) {
allMessageCount += getQueueMessage(queueEntity);
}
if (allMessageCount / queueEntities.size() > soaConfig.getMaxTableMessage()) {
throw new CheckFailException("每队列消息量未达到最大值,不允许扩容,可联系管理员强制扩容");
}
}
/**
* Return declared "params" conditions but only among those that also
* match the "methods", "consumes", and "params" conditions.
*/
public List<String[]> getParamConditions() {
List<String[]> result = new ArrayList<>();
for (PartialMatch match : this.partialMatches) {
if (match.hasProducesMatch()) {
Set<NameValueExpression<String>> set = match.getInfo().getParamsCondition().getExpressions();
if (!CollectionUtils.isEmpty(set)) {
int i = 0;
String[] array = new String[set.size()];
for (NameValueExpression<String> expression : set) {
array[i++] = expression.toString();
}
result.add(array);
}
}
}
return result;
}
private void handleSkuStockCode(List<PmsSkuStock> skuStockList, Long productId) {
if(CollectionUtils.isEmpty(skuStockList))return;
for(int i=0;i<skuStockList.size();i++){
PmsSkuStock skuStock = skuStockList.get(i);
if(StringUtils.isEmpty(skuStock.getSkuCode())){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
StringBuilder sb = new StringBuilder();
//日期
sb.append(sdf.format(new Date()));
//四位商品id
sb.append(String.format("%04d", productId));
//三位索引id
sb.append(String.format("%03d", i+1));
skuStock.setSkuCode(sb.toString());
}
}
}
/**
* Instantiates a new Open api builder.
*
* @param openAPI the open api
* @param context the context
* @param securityParser the security parser
* @param springDocConfigProperties the spring doc config properties
* @param openApiBuilderCustomisers the open api builder customisers
*/
OpenAPIBuilder(Optional<OpenAPI> openAPI, ApplicationContext context, SecurityParser securityParser,
SpringDocConfigProperties springDocConfigProperties,
Optional<List<OpenApiBuilderCustomiser>> openApiBuilderCustomisers) {
if (openAPI.isPresent()) {
this.openAPI = openAPI.get();
if (this.openAPI.getComponents() == null)
this.openAPI.setComponents(new Components());
if (this.openAPI.getPaths() == null)
this.openAPI.setPaths(new Paths());
if (!CollectionUtils.isEmpty(this.openAPI.getServers()))
this.isServersPresent = true;
}
this.context = context;
this.securityParser = securityParser;
this.springDocConfigProperties = springDocConfigProperties;
this.openApiBuilderCustomisers = openApiBuilderCustomisers;
}
@Autowired
public OneNetClient(OneNetServerSessionManager oneNetServerSessionManager, OneNetClientConfig oneNetClientConfig) throws Exception {
bootstrap = new Bootstrap();
final EventLoopGroup workerGroup = new NioEventLoopGroup();
bootstrap.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true);
oneNetServerSessionManager.setClientName(oneNetClientConfig.getServerName());
oneNetServerSessionManager.setReconnectAfterNSeconds(oneNetClientConfig.getReconnectSeconds());
if (!CollectionUtils.isEmpty(oneNetClientConfig.getServerConfigs())) {
clientName = oneNetClientConfig.getServerName();
oneNetClientConfig.getServerConfigs().stream().forEach(
(onenetClientServerConfig) ->
oneNetServerSessionManager.getOneNetServerSessions()
.putIfAbsent(oneNetClientConfig.getServerName(),
new ServerSession(onenetClientServerConfig))
);
}
}
/**
* 新增角色部门信息(数据权限)
*
* @param role 角色对象
*/
private int insertRoleDept(SysRole role) {
int rows = 1;
// 新增角色与部门(数据权限)管理
List<SysRoleDept> list = new ArrayList<>();
for (Long deptId : role.getDeptIds()) {
SysRoleDept rd = new SysRoleDept();
rd.setRoleId(role.getRoleId());
rd.setDeptId(deptId);
list.add(rd);
}
if (!CollectionUtils.isEmpty(list)) {
rows = roleDeptMapper.batchRoleDept(list);
}
return rows;
}
@Override
public List<T> distribute(String targetServiceName, List<T> list, PolicyRuleItem invokeRule) {
//初始化LatestVersion
initLatestVersion(targetServiceName, list);
invokeRule.check(
RouterRuleCache.getServiceInfoCacheMap().get(targetServiceName).getLatestVersionTag());
// 建立tag list
Map<TagItem, List<T>> versionServerMap = getDistributList(targetServiceName, list, invokeRule);
//如果没有匹配到合适的规则,直接返回最新版本的服务列表
if (CollectionUtils.isEmpty(versionServerMap)) {
LOGGER.debug("route management can not match any rule and route the latest version");
return getLatestVersionList(list, targetServiceName);
}
// 分配流量,返回结果
TagItem targetTag = getFiltedServerTagItem(invokeRule, targetServiceName);
if (versionServerMap.containsKey(targetTag)) {
return versionServerMap.get(targetTag);
}
return getLatestVersionList(list, targetServiceName);
}
protected void printSummary(Message message, long batchId, int size) {
long memsize = 0;
for (Entry entry : message.getEntries()) {
memsize += entry.getHeader().getEventLength();
}
String startPosition = null;
String endPosition = null;
if (!CollectionUtils.isEmpty(message.getEntries())) {
startPosition = buildPositionForDump(message.getEntries().get(0));
endPosition = buildPositionForDump(message.getEntries().get(message.getEntries().size() - 1));
}
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
logger.info(context_format, new Object[] { batchId, size, memsize, format.format(new Date()), startPosition,
endPosition });
}
public ReplicationRoutingDataSource(DataSource master, List<DataSource> slaves) {
Assert.notNull(master, "master datasource can not be null.");
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(MASTER_KEY, new LazyConnectionDataSourceProxy(master));
if (!CollectionUtils.isEmpty(slaves)) {
slaveSize = slaves.size();
for (int i = 0; i < slaveSize; i++) {
targetDataSources.put(SLAVE_PREFIX + i,
new LazyConnectionDataSourceProxy(slaves.get(i)));
}
}
else {
this.onlyMaster = true;
}
setTargetDataSources(targetDataSources);
setDefaultTargetDataSource(targetDataSources.get(MASTER_KEY));
}
private void update(FileChanges fileChanges) {
fileChanges.setId(null);
fileChanges.preInsert();
fileChanges.setIsLatest(1);
fileChanges.setAction("edit");
String path = writeContentIntoFile(fileChanges);
fileChanges.setContent(path);
fileChangesDao.updateIsLatest(fileChanges.getDocCode());
fileChangesDao.insertSelective(fileChanges);
// label
List<Integer> labelIds = fileChanges.getLabelIds();
if(!CollectionUtils.isEmpty(labelIds)){
List<FileLabel> fileLabels = new ArrayList<>();
for(Integer labelId : labelIds){
FileLabel fileLabel = new FileLabel();
fileLabel.preInsert();
fileLabel.setFileId(fileChanges.getId());
fileLabel.setLabelId(labelId);
fileLabels.add(fileLabel);
}
fileLabelDao.insertBatch(fileLabels);
}
}
public TradeOrder findByMerchantOrderNo(String merchantOrderNo) {
List<TradeOrder> list = jdbcTemplate.query("select id,self_user_id,opposite_user_id,merchant_order_no,amount,status from red_trade_order where merchant_order_no = ?", new RowMapper<TradeOrder>() {
@Override
public TradeOrder mapRow(ResultSet rs, int i) throws SQLException {
TradeOrder tradeOrder = new TradeOrder();
tradeOrder.setId(rs.getLong("id"));
tradeOrder.setSelfUserId(rs.getLong("self_user_id"));
tradeOrder.setOppositeUserId(rs.getLong("opposite_user_id"));
tradeOrder.setMerchantOrderNo(rs.getString("merchant_order_no"));
tradeOrder.setAmount(rs.getBigDecimal("amount"));
tradeOrder.setStatus(rs.getString("status"));
return tradeOrder;
}
}, merchantOrderNo);
if (!CollectionUtils.isEmpty(list)) {
return list.get(0);
} else {
return null;
}
}
@Override
public YamlProcessor.MatchStatus matches(Properties properties) {
List<String> profiles = extractSpringProfiles(properties);
ProfilesMatcher profilesMatcher = getProfilesMatcher();
Set<String> negative = extractProfiles(profiles, ProfileType.NEGATIVE);
Set<String> positive = extractProfiles(profiles, ProfileType.POSITIVE);
if (!CollectionUtils.isEmpty(negative)) {
if (profilesMatcher.matches(negative) == YamlProcessor.MatchStatus.FOUND) {
return YamlProcessor.MatchStatus.NOT_FOUND;
}
if (CollectionUtils.isEmpty(positive)) {
return YamlProcessor.MatchStatus.FOUND;
}
}
return profilesMatcher.matches(positive);
}
private int assignPermissions(List<XXPortalUser> xXPortalUsers){
int countUserPermissionUpdated = 0;
if(!CollectionUtils.isEmpty(xXPortalUsers)){
for (XXPortalUser xPortalUser : xXPortalUsers) {
try{
if(xPortalUser!=null){
VXPortalUser vPortalUser = xPortalUserService.populateViewBean(xPortalUser);
if(vPortalUser!=null){
vPortalUser.setUserRoleList(daoManager.getXXPortalUserRole().findXPortalUserRolebyXPortalUserId(vPortalUser.getId()));
xUserMgr.assignPermissionToUser(vPortalUser, false);
countUserPermissionUpdated += 1;
logger.info("Permissions assigned/updated on base of User's Role, UserId [" + xPortalUser.getId() + "]");
}
}
}catch(Exception ex){
}
}
}
return countUserPermissionUpdated;
}
@SuppressWarnings("unchecked")
private boolean safeExtension(HttpServletRequest request, String extension) {
if (!StringUtils.hasText(extension)) {
return true;
}
extension = extension.toLowerCase(Locale.ENGLISH);
if (this.safeExtensions.contains(extension)) {
return true;
}
String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
if (pattern != null && pattern.endsWith("." + extension)) {
return true;
}
if (extension.equals("html")) {
String name = HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE;
Set<MediaType> mediaTypes = (Set<MediaType>) request.getAttribute(name);
if (!CollectionUtils.isEmpty(mediaTypes) && mediaTypes.contains(MediaType.TEXT_HTML)) {
return true;
}
}
return safeMediaTypesForExtension(extension);
}
private void handleSkuStockCode(List<PmsSkuStock> skuStockList, Long productId) {
if(CollectionUtils.isEmpty(skuStockList))return;
for(int i=0;i<skuStockList.size();i++){
PmsSkuStock skuStock = skuStockList.get(i);
if(StringUtils.isEmpty(skuStock.getSkuCode())){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
StringBuilder sb = new StringBuilder();
//日期
sb.append(sdf.format(new Date()));
//四位商品id
sb.append(String.format("%04d", productId));
//三位索引id
sb.append(String.format("%03d", i+1));
skuStock.setSkuCode(sb.toString());
}
}
}
@SuppressWarnings("unchecked")
private Rule<JCodeModel, JDefinedClass, ApiResourceMetadata> loadRule() {
Rule<JCodeModel, JDefinedClass, ApiResourceMetadata> ruleInstance = new Spring4ControllerStubRule();
try {
ruleInstance = (Rule<JCodeModel, JDefinedClass, ApiResourceMetadata>) getClassRealm().loadClass(rule).newInstance();
this.getLog().debug(StringUtils.collectionToCommaDelimitedString(ruleConfiguration.keySet()));
this.getLog().debug(StringUtils.collectionToCommaDelimitedString(ruleConfiguration.values()));
if (ruleInstance instanceof ConfigurableRule<?, ?, ?> && !CollectionUtils.isEmpty(ruleConfiguration)) {
this.getLog().debug("SETTING CONFIG");
((ConfigurableRule<?, ?, ?>) ruleInstance).applyConfiguration(ruleConfiguration);
}
} catch (Exception e) {
getLog().error("Could not instantiate Rule " + this.rule + ". The default Rule will be used for code generation.", e);
}
return ruleInstance;
}
@SuppressWarnings("unchecked")
public static void loadDataSet() {
collectDbTableName();
File folder = FileUtil.getTestResourceFile(ActsPathConstants.OBJECT_DATA_PATH);
if (folder.isDirectory()) {
String[] files = folder.list();
for (String fileName : files) {
objectDataSet.add(fileName);
}
}
File msgFile = FileUtil.getTestResourceFile(ActsPathConstants.MSGCONFIG_PATH);
LinkedHashMap<?, ?> msgConfigData = FileUtil.readYaml(msgFile);
if (CollectionUtils.isEmpty(msgConfigData)) {
return;
}
}
@Override
protected List<AbstractValuedPropertyDocument> completeWithMustacheContent(List<AbstractPropertyDocument> abstractModelProperties) {
List<PropertyDocument> matchingProperties = AbstractPropertyDocument.getFlatProperties(abstractModelProperties)
.filter(abstractModuleProperty -> name.equals(abstractModuleProperty.getName()))
.collect(Collectors.toList());
if (CollectionUtils.isEmpty(matchingProperties)) {
// Si on ne la retrouve pas dans le module (propriété définie puis
// valorisée puis supprimée du template) on la conserve telle quelle
return Collections.singletonList(this);
}
// Il arrive qu'une propriété soit déclarée plusieurs fois avec le même nom
// et un commentaire distinct. Dans ce cas on crée autant de propriétés valorisées
// qu'il n'y a de propriétés déclarées
return matchingProperties.stream()
.map(propertyDocument -> new ValuedPropertyDocument(name, value))
.collect(Collectors.toList());
}
/**
* 获取 IoT 映射信息
*/
private Map<String, IotInfo> getIoTSnIdMapper(String key) throws Exception {
LOGGER.info("get IoT SnId Mapper... key is [{}]", key);
Map<Object, Object> mapperMap = redisService.hGetAll(key);
if (CollectionUtils.isEmpty(mapperMap)) {
LOGGER.warn("the IoTSnIdMapper is empty!");
return new HashMap<>(0);
}
Map<String, IotInfo> mapperStrMap = new HashMap<>(mapperMap.size());
Set<Object> keySet = mapperMap.keySet();
for (Object sn : keySet) {
Object data = mapperMap.get(sn);
IotInfo dataMap = JsonUtils.jsonStr2Obj(String.valueOf(data), IotInfo.class);
mapperStrMap.put(String.valueOf(sn), dataMap);
}
return mapperStrMap;
}
@Override
public Map<String, Object> buildHBaseReader() {
DataxHbasePojo dataxHbasePojo = new DataxHbasePojo();
dataxHbasePojo.setJdbcDatasource(readerDatasource);
List<Map<String, Object>> columns = Lists.newArrayList();
for (int i = 0; i < readerColumns.size(); i++) {
Map<String, Object> column = Maps.newLinkedHashMap();
column.put("name", readerColumns.get(i));
column.put("type", "string");
columns.add(column);
}
dataxHbasePojo.setColumns(columns);
dataxHbasePojo.setReaderHbaseConfig(readerDatasource.getZkAdress());
String readerTable=!CollectionUtils.isEmpty(readerTables)?readerTables.get(0):Constants.STRING_BLANK;
dataxHbasePojo.setReaderTable(readerTable);
dataxHbasePojo.setReaderMode(hbaseReaderDto.getReaderMode());
dataxHbasePojo.setReaderRange(hbaseReaderDto.getReaderRange());
return readerPlugin.buildHbase(dataxHbasePojo);
}
/**
* Filter out undesired attributes from the given model.
* The return value can be either another {@link Map} or a single value object.
* <p>The default implementation removes {@link BindingResult} instances and entries
* not included in the {@link #setModelKeys modelKeys} property.
* @param model the model, as passed on to {@link #renderMergedOutputModel}
* @return the value to be rendered
*/
@Override
protected Object filterModel(Map<String, Object> model) {
Map<String, Object> result = new HashMap<>(model.size());
Set<String> modelKeys = (!CollectionUtils.isEmpty(this.modelKeys) ? this.modelKeys : model.keySet());
model.forEach((clazz, value) -> {
if (!(value instanceof BindingResult) && modelKeys.contains(clazz) &&
!clazz.equals(JsonView.class.getName()) &&
!clazz.equals(FilterProvider.class.getName())) {
result.put(clazz, value);
}
});
return (this.extractValueFromSingleKeyModel && result.size() == 1 ? result.values().iterator().next() : result);
}
/**
* Create a WebSocketExtension with the given name and parameters.
* @param name the name of the extension
* @param parameters the parameters
*/
public WebSocketExtension(String name, Map<String, String> parameters) {
Assert.hasLength(name, "extension name must not be empty");
this.name = name;
if (!CollectionUtils.isEmpty(parameters)) {
Map<String, String> m = new LinkedCaseInsensitiveMap<String>(parameters.size(), Locale.ENGLISH);
m.putAll(parameters);
this.parameters = Collections.unmodifiableMap(m);
}
else {
this.parameters = Collections.emptyMap();
}
}
/**
* Load the specified schema mappings lazily.
*/
private Map<String, String> getSchemaMappings() {
Map<String, String> schemaMappings = this.schemaMappings;
if (schemaMappings == null) {
synchronized (this) {
schemaMappings = this.schemaMappings;
if (schemaMappings == null) {
if (logger.isTraceEnabled()) {
logger.trace("Loading schema mappings from [" + this.schemaMappingsLocation + "]");
}
try {
Properties mappings =
PropertiesLoaderUtils.loadAllProperties(this.schemaMappingsLocation, this.classLoader);
if (logger.isTraceEnabled()) {
logger.trace("Loaded schema mappings: " + mappings);
}
schemaMappings = new ConcurrentHashMap<>(mappings.size());
CollectionUtils.mergePropertiesIntoMap(mappings, schemaMappings);
this.schemaMappings = schemaMappings;
}
catch (IOException ex) {
throw new IllegalStateException(
"Unable to load schema mappings from location [" + this.schemaMappingsLocation + "]", ex);
}
}
}
}
return schemaMappings;
}
public static Map<String, String> runCommand(Retry retry, SaltConnector sc, String command) {
return retry.testWith2SecDelayMax15Times(() -> {
try {
CommandExecutionResponse resp = sc.run(Glob.ALL, "cmd.run", LOCAL, CommandExecutionResponse.class, command);
List<Map<String, String>> result = resp.getResult();
return CollectionUtils.isEmpty(result) ? new HashMap<>() : result.get(0);
} catch (RuntimeException e) {
LOGGER.error("Salt run command failed", e);
throw new Retry.ActionFailedException("Salt run command failed");
}
});
}
private static void ensureDlqMessageCanBeProperlySerialized(
Map<String, String> configuration,
Predicate<Map<String, String>> configPredicate, String dataType) {
if (CollectionUtils.isEmpty(configuration)
|| configPredicate.test(configuration)) {
throw new IllegalArgumentException("Native decoding is used on the consumer. "
+ dataType
+ " is not byte[] and no serializer is set on the DLQ producer.");
}
}
private void getAlreadyBuildModules(Pipeline pipeline, Set<Integer> alreadBuild) {
if (!StringUtils.equals(pipeline.getNode(), node)) {
return;
}
List<Integer> modules = new ArrayList<>();
if (CollectionUtils.isEmpty(pipeline.getModulesPorjects())) {
return;
}
pipeline.getModulesPorjects().forEach((modulesPorject) -> {
modules.add(modulesPorject.getProjectId());
});
if (CollectionUtils.isEmpty(modules)) {
return;
}
//TODO FAILED --> throw
if (StringUtils.equalsAnyIgnoreCase(pipeline.getStatus(), RUNNING_DEPLOY.toString(), FAILED.toString(),
SUCCESS.toString())) {
alreadBuild.addAll(modules);
return;
}
Integer current = pipeline.getCurrent();
if (isNull(current)) {// if null ,it mean : not begin build
return;
}
for (Integer module : modules) {
if (current.equals(module)) {
break;
} else {
alreadBuild.add(module);
}
}
}
protected boolean hasBillableAccounts(ContractsAndGrantsBillingAward award) {
String billingFrequencyCode = award.getBillingFrequencyCode();
if (StringUtils.equalsIgnoreCase(billingFrequencyCode, ArConstants.MILESTONE_BILLING_SCHEDULE_CODE) ||
StringUtils.equalsIgnoreCase(billingFrequencyCode, ArConstants.PREDETERMINED_BILLING_SCHEDULE_CODE)) {
return !getContractsGrantsBillingAwardVerificationService().isInvoiceInProgress(award);
} else {
return CollectionUtils.isEmpty(award.getActiveAwardAccounts()) || !CollectionUtils.isEmpty(getValidAwardAccounts(award.getActiveAwardAccounts(), award));
}
}
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
NativeWebRequest request, @Nullable WebDataBinderFactory binderFactory) throws Exception {
@SuppressWarnings("unchecked")
Map<String, MultiValueMap<String, String>> matrixVariables =
(Map<String, MultiValueMap<String, String>>) request.getAttribute(
HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
if (CollectionUtils.isEmpty(matrixVariables)) {
return Collections.emptyMap();
}
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
MatrixVariable ann = parameter.getParameterAnnotation(MatrixVariable.class);
Assert.state(ann != null, "No MatrixVariable annotation");
String pathVariable = ann.pathVar();
if (!pathVariable.equals(ValueConstants.DEFAULT_NONE)) {
MultiValueMap<String, String> mapForPathVariable = matrixVariables.get(pathVariable);
if (mapForPathVariable == null) {
return Collections.emptyMap();
}
map.putAll(mapForPathVariable);
}
else {
for (MultiValueMap<String, String> vars : matrixVariables.values()) {
vars.forEach((name, values) -> {
for (String value : values) {
map.add(name, value);
}
});
}
}
return (isSingleValueMap(parameter) ? map.toSingleValueMap() : map);
}