下面列出了org.springframework.boot.autoconfigure.mail.MailProperties#org.springframework.lang.NonNull 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Parse servlet from data list
*
* @param data data list
* @return Servlet info list
*/
private List<MappingsDescriptor.ServletInfo> parseServletInfo(
@NonNull List<Map<String, Object>> data
) {
return data.stream().map(map -> {
// Read meta info from map
List<String> mappings = readDict(map, "mappings");
String name = readDict(map, "name");
String className = readDict(map, "className");
// Generate mapping info
MappingsDescriptor.ServletInfo info = new MappingsDescriptor.ServletInfo();
info.setMappings(mapToDesc(mappings));
info.setName(Optional.ofNullable(name).orElse(""));
info.setClassName(Optional.ofNullable(className).orElse(""));
return info;
}).collect(Collectors.toList());
}
@NonNull
private static Object resolveExpression(ApplicationContext applicationContext, String name) {
if (applicationContext instanceof ConfigurableApplicationContext) {
ConfigurableBeanFactory configurableBeanFactory =
((ConfigurableApplicationContext) applicationContext).getBeanFactory();
String placeholdersResolved = configurableBeanFactory.resolveEmbeddedValue(name);
BeanExpressionResolver exprResolver = configurableBeanFactory.getBeanExpressionResolver();
if (exprResolver == null) {
return name;
}
Object result =
exprResolver.evaluate(
placeholdersResolved, new BeanExpressionContext(configurableBeanFactory, null));
if (result != null) {
return result;
}
}
return name;
}
/**
* Pre-checks the arguments, calls {@link #doTranslate}, and invokes the
* {@link #getFallbackTranslator() fallback translator} if necessary.
*/
@Override
@NonNull
public DataAccessException translate(String task, @Nullable String sql, SQLException ex) {
Assert.notNull(ex, "Cannot translate a null SQLException");
DataAccessException dae = doTranslate(task, sql, ex);
if (dae != null) {
// Specific exception match found.
return dae;
}
// Looking for a fallback...
SQLExceptionTranslator fallback = getFallbackTranslator();
if (fallback != null) {
dae = fallback.translate(task, sql, ex);
if (dae != null) {
// Fallback exception match found.
return dae;
}
}
// We couldn't identify it more precisely.
return new UncategorizedSQLException(task, sql, ex);
}
/**
* Gets null names set of property.
*
* @param source object data must not be null
* @return null name set of property
*/
@NonNull
private static Set<String> getNullPropertyNameSet(@NonNull Object source) {
Assert.notNull(source, "source object must not be null");
BeanWrapperImpl beanWrapper = new BeanWrapperImpl(source);
PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<>();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String propertyName = propertyDescriptor.getName();
Object propertyValue = beanWrapper.getPropertyValue(propertyName);
// if property value is equal to null, add it to empty name set
if (propertyValue == null) {
emptyNames.add(propertyName);
}
}
return emptyNames;
}
/**
* Pre-checks the arguments, calls {@link #doTranslate}, and invokes the
* {@link #getFallbackTranslator() fallback translator} if necessary.
*/
@Override
@NonNull
public DataAccessException translate(String task, @Nullable String sql, SQLException ex) {
Assert.notNull(ex, "Cannot translate a null SQLException");
DataAccessException dae = doTranslate(task, sql, ex);
if (dae != null) {
// Specific exception match found.
return dae;
}
// Looking for a fallback...
SQLExceptionTranslator fallback = getFallbackTranslator();
if (fallback != null) {
dae = fallback.translate(task, sql, ex);
if (dae != null) {
// Fallback exception match found.
return dae;
}
}
// We couldn't identify it more precisely.
return new UncategorizedSQLException(task, sql, ex);
}
/**
* Transforms from the source object. (copy same properties only)
*
* @param source source data
* @param targetClass target class must not be null
* @param <T> target class type
* @return instance with specified type copying from source data; or null if source data is null
* @throws BeanUtilsException if newing target instance failed or copying failed
*/
@Nullable
public static <T> T transformFrom(@Nullable Object source, @NonNull Class<T> targetClass) {
Assert.notNull(targetClass, "Target class must not be null");
if (source == null) {
return null;
}
// Init the instance
try {
// New instance for the target class
T targetInstance = targetClass.newInstance();
// Copy properties
org.springframework.beans.BeanUtils.copyProperties(source, targetInstance, getNullPropertyNames(source));
// Return the target instance
return targetInstance;
} catch (Exception e) {
throw new BeanUtilsException("Failed to new " + targetClass.getName() + " instance or copy properties", e);
}
}
/**
* 登录成功后生成令牌
*
* @param authentication 认证对象
* @param entityClazz 实体类型
* @return CrustUserInfo
*/
@NonNull
private <T> CrustUserInfo<T> generateToken(@NonNull Authentication authentication, @NonNull Class<T> entityClazz) {
Map<String, Object> claims = new HashMap<>(6);
CrustUserInfo<T> userInfo = getLoginUserInfo(authentication, entityClazz);
claims.put(UID, userInfo.getUid());
claims.put(USERNAME, userInfo.getUsername());
claims.put(CREATED, new Date());
Object principal = authentication.getPrincipal();
if (principal instanceof CrustUserDetails) {
List<Long> roleIds = ((CrustUserDetails) principal).getRoleIds();
if (!CollectionUtils.isEmpty(roleIds)) {
claims.put(ROLE_IDS, StringUtils.arrayToCommaDelimitedString(roleIds.toArray()));
}
}
String token = JwtUtil.generateToken(claims, getSignKey(), Math.toIntExact(props.getExpire().toMinutes()), props.isUseRsa());
userInfo.setToken(token);
return userInfo;
}
@SuppressWarnings("unchecked")
@LightCacheable(value = CATCH_NAME, keyPrefix = CATCH_KEY_PREFIX, key = "T(org.springframework.util.DigestUtils).md5DigestAsHex(#authentication?.token.bytes)", // #authentication 与 args[0] 等价
condition = "#authentication!=null&&#target.props.enableCache") // #target 与 @crust、#this.object、#root.object等价(#this在表达式不同部分解析过程中可能会改变,但是#root总是指向根,object为自定义root对象属性)
public <T> CrustUserInfo<T> getTokenUserInfo(Authentication authentication, @NonNull Class<T> clazz) {
CrustUserInfo<T> userInfo = null;
if (authentication != null) {
// 解析Token方式获取用户信息
if (authentication instanceof CrustAuthenticationToken) {
CrustAuthenticationToken authenticationToken = (CrustAuthenticationToken) authentication;
String token = authenticationToken.getToken();
Object principal = authentication.getPrincipal();
if (principal instanceof CrustUserDetails) {
CrustUserDetails userDetails = (CrustUserDetails) principal;
String uid = userDetails.getUid();
List<Long> roleIds = userDetails.getRoleIds();
T entity = (T) getCrustUserDetailsService().findEntityById(uid);
return new CrustUserInfo<>(uid, authenticationToken.getName(), token, roleIds, entity);
}
}
}
return userInfo;
}
@Override
public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
if (this.cometCollectorProperties == null || !this.cometCollectorProperties.isEnableTag()) {
return;
}
Map<String, CometCollectorProperties.Tag> tagMap = cometCollectorProperties.getTags();
this.tagCollectorMap = tagMap.keySet().stream()
.collect(Collectors.toMap(Object::toString, tagName -> applicationContext.getBean(tagName, TagCollector.class)));
aliasNodesMap = new HashMap<>();
for (Map.Entry<String, CometCollectorProperties.Tag> tagCollectorEntry : cometCollectorProperties.getTags().entrySet()) {
Map<String, Object> exceptionMonitor = tagCollectorEntry.getValue().getExceptionMonitor();
if(CollectionUtils.isEmpty(exceptionMonitor)) {
continue;
}
String tag = tagCollectorEntry.getKey();
aliasNodesMap.put(tag, YmlParser.parseAliasMap(exceptionMonitor));
}
threadLocal = new ThreadLocal<>();
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public void handleReturnValue(Object o, @NonNull MethodParameter methodParameter, @NonNull ModelAndViewContainer modelAndViewContainer,
@NonNull NativeWebRequest nativeWebRequest) throws Exception {
if (o instanceof ExcelReadWrapper) {
modelAndViewContainer.setRequestHandled(true);
ExcelRead readAnno = methodParameter.getMethodAnnotation(ExcelRead.class);
assert readAnno != null;
ExcelReadWrapper wrapper = (ExcelReadWrapper) o;
if (wrapper.getInputStream() == null) {
throw new ExcelResolverException("The data cannot be empty");
}
ExcelReader<?> reader = ExcelFactory.createReader(wrapper.getInputStream(), wrapper.getMapping(), wrapper.getIgnores() == null ? readAnno.ignores() : wrapper.getIgnores());
reader.addListener(wrapper.getReadListeners())
.subscribe(wrapper.getResultReadListener())
.metaInfo(readAnno.metaInfo())
.check(readAnno.check())
.read(readAnno.headerIndex(), readAnno.value())
.finish();
return;
}
throw new ExcelResolverException("Method return value type must be ExcelReadWrapper: " + methodParameter.getExecutable().getName());
}
/**
* Parse servlet filter from data list
*
* @param data data list
* @return Handler Filter info list
*/
private List<MappingsDescriptor.HandlerFilterInfo> parseServletFilter(
@NonNull List<Map<String, Object>> data
) {
return data.stream().map(map -> {
// Read meta info from map
String name = readDict(map, "name");
String className = readDict(map, "className");
List<String> servletNameMappings = readDict(map, "servletNameMappings");
List<String> urlPatternMappings = readDict(map, "urlPatternMappings");
// Generate mapping info
MappingsDescriptor.HandlerFilterInfo info = new MappingsDescriptor.HandlerFilterInfo();
info.setName(Optional.ofNullable(name).orElse(""));
info.setClassName(Optional.ofNullable(className).orElse(""));
info.setServletNameMappings(mapToDesc(servletNameMappings));
info.setUrlPatternMappings(mapToDesc(urlPatternMappings));
return info;
}).collect(Collectors.toList());
}
/**
* 获取缓存
*
* @param key keu
* @param callable callable
* @param <T> t
* @return t
*/
@Override
@SuppressWarnings("unchecked")
public <T> T get(@NonNull Object key, @NonNull Callable<T> callable) {
key = getKey(key);
Object value = this.lookup(key);
if (value != null) {
return (T) value;
}
try {
value = callable.call();
} catch (Exception e) {
e.printStackTrace();
}
Object storeValue = toStoreValue(value);
this.put(key, storeValue);
return (T) value;
}
@Override
public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
String token = request.getHeader(this.authorizationInfo.getHeader());
AuthorizationMetaData authorizationMetaData = this.authorizationListener.supplyAccess(token);
if (authorizationMetaData == null) {
throw new NoAccountException("Account not found");
}
if (this.methodInterceptors != null) {
for (AnnotationHandler annotationHandler : methodInterceptors) {
Annotation annotation = method.getAnnotation(annotationHandler.getAnnotationClass());
if (annotation != null) {
annotationHandler.assertAuthorization(annotation, authorizationMetaData);
}
}
}
this.authorizationListener.authentication(token);
}
return true;
}
@Override
@NonNull
public String[] selectImports(@NonNull AnnotationMetadata annotationMetadata) {
return new String[]{
CommonCorsConfiguration.class.getName(),
CommonCors.class.getName()
};
}
/**
* pid 和 uid 必须要有一个不为null
*
* @param type 积分类型
* @param pid 积分ID
* @param uid 用户uid
* @return 用户积分数据
*/
public PointVo getPointVo(@NonNull String type,
Long pid,
String uid, String subUid) {
if (pid == null && uid == null) {
throw new HyenaParameterException("invalid parameter");
}
String pointTableName = TableNameHelper.getPointTableName(type);
return this.pointMapper.getPointVo(pointTableName, pid, uid, subUid);
}
/**
* Returns the list of labels for the entity to be created from the "main" node returned.
*
* @param queryResult The complete query result
* @return The list of labels defined by the query variable {@link org.neo4j.springframework.data.core.schema.Constants#NAME_OF_LABELS}.
*/
@NonNull
private List<String> getLabels(MapAccessor queryResult) {
Value labelsValue = queryResult.get(NAME_OF_LABELS);
List<String> labels = new ArrayList<>();
if (!labelsValue.isNull()) {
labels = labelsValue.asList(Value::asString);
} else if (queryResult instanceof Node) {
Node nodeRepresentation = (Node) queryResult;
nodeRepresentation.labels().forEach(labels::add);
}
return labels;
}
/**
* The additional labels will get computed and returned by following rules:<br>
* 1. If there is no {@link Node} annotation, empty {@code String} array.<br>
* 2. If there is an annotation but it has no properties set, empty {@code String} array.<br>
* 3. If only {@link Node#labels()} property is set, use the all but the first one as the additional labels.<br>
* 3. If the {@link Node#primaryLabel()} property is set, use the all but the first one as the additional labels.<br>
*
* @return computed additional labels of the concrete class
*/
@NonNull
private List<String> computeOwnAdditionalLabels() {
Node nodeAnnotation = this.findAnnotation(Node.class);
if (nodeAnnotation == null || hasEmptyLabelInformation(nodeAnnotation)) {
return emptyList();
} else if (hasText(nodeAnnotation.primaryLabel())) {
return Arrays.asList(nodeAnnotation.labels());
} else {
return Arrays.asList(Arrays.copyOfRange(nodeAnnotation.labels(), 1, nodeAnnotation.labels().length));
}
}
@NonNull
private List<String> computeParentLabels() {
List<String> parentLabels = new ArrayList<>();
while (parentNodeDescription != null) {
parentLabels.add(parentNodeDescription.getPrimaryLabel());
parentLabels.addAll(parentNodeDescription.getAdditionalLabels());
parentNodeDescription = ((DefaultNeo4jPersistentEntity<?>) parentNodeDescription).getParentNodeDescription();
}
return parentLabels;
}
@Override
public void onApplicationEvent(@NonNull ContextRefreshedEvent event) {
if (event.getApplicationContext().getParent() == null) {
return;
}
log.info("正加载配置源...");
// 模拟配置源
Map<String, String> source = new HashMap<>();
source.put("env", "dev");
source.put("version", "1.0");
source.put("platform", "mk");
source.put("fee_rate_config", "{\"service\":0.53, \"inst\": 0.3}");
MetalHolder.init(source);
}
@Override
@NonNull
public Lock getLock(LockInstance lockInstance) {
WeakReferenceWithKey<Lock> lockRef = lockCache.computeIfAbsent(lockInstance.getName(), (key) -> new WeakReferenceWithKey<>(new ReentrantLock(lockInstance.isFair()),queue,key));
Lock lock=lockRef.get();
if(lock==null){
ReentrantLock newLock = new ReentrantLock(lockInstance.isFair());
lockCache.computeIfAbsent(lockInstance.getName(), (key) -> new WeakReferenceWithKey<>(newLock,queue,key));
lock=newLock;
}
return lock;
}
/**
* 获取当前用户信息
*
* @param entityClazz 实体类型
* @param <T> 实体类型
* @return CrustUserInfo
*/
@NonNull
public <T> CrustUserInfo<T> getUserInfo(@NonNull Class<T> entityClazz) {
Authentication authentication = getAuthentication();
if (authentication == null) {
throw new RuntimeException("authentication is null");
}
// Session方式开启超级缓存
if (getProps().isEnableCache() && !props.isStateless()) {
// 先检测超级缓存(提高性能)
Spot<Serializable, CrustUserInfo<T>> spot = CacheHelper.get(lightCacheCrust);
if (spot != null && spot.getData() != null) {
return spot.getData();
}
CrustUserInfo<T> userInfo = getLoginUserInfo(authentication, entityClazz);
// 设置用户数据到超级缓存(在内存中已经有一份用户登录数据了)
Spot<Serializable, CrustUserInfo<T>> sessionSpot = new Spot<>();
sessionSpot.setView(userInfo.getUid());
sessionSpot.setData(userInfo);
CacheHelper.set(lightCacheCrust, sessionSpot);
return userInfo;
}
// Token方式
Crust crustProxy = AopContextHolder.self(this.getClass());
return crustProxy.getTokenUserInfo(authentication, entityClazz);
}
/**
* @param key key
* @return o
*/
@Override
protected Object lookup(@NonNull Object key) {
key = getKey(key);
Object value = caffeineCache.getIfPresent(key);
if (value != null) {
return value;
}
value = redisTemplate.opsForValue().get(key);
if (value != null) {
caffeineCache.put(key, value);
}
return value;
}
/**
* 获取登录时用户信息
* <br>
* Session方式和Token方式登录时都会调用(Session方式获取用户信息也走这里)
*
* @param authentication 认证信息
* @param clazz 实体类型
* @param <T> 实体类型
* @return CrustUserInfo
*/
@SuppressWarnings("unchecked")
private <T> CrustUserInfo<T> getLoginUserInfo(Authentication authentication, @NonNull Class<T> clazz) {
if (authentication == null) {
throw new AuthenticationServiceException("Authentication is must be not null");
}
// 此时 authentication 就是内部封装的 UsernamePasswordAuthenticationToken
Object principal = authentication.getPrincipal();
if (!(principal instanceof CrustUserDetails)) {
throw new AuthenticationServiceException("Authentication principal must be subtype of CrustUserDetails");
}
CrustUserDetails userDetails = (CrustUserDetails) principal;
return new CrustUserInfo<>(userDetails.getUid(), userDetails.getUsername(), getToken(), userDetails.getRoleIds(), (T) userDetails.getEntity());
}
@Override
public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
// 由于Spring MVC源码在创建interceptorChain时只识别MappedInterceptor类型才能匹配URL,这里补充进来
String lookupPath = WebContext.getUrlPathHelper().getLookupPathForRequest(request, LOOKUP_PATH);
if (mappedInterceptor.matches(lookupPath, WebContext.getMvcPathMatcher())) {
return mappedInterceptor.preHandle(request, response, handler);
}
return true;
}
@Override
@NonNull
public ReadWriteLock getReadWriteLock(LockInstance lockInstance) {
WeakReferenceWithKey<ReadWriteLock> lockRef = readWriteLockCache.computeIfAbsent(lockInstance.getName(), (key) -> new WeakReferenceWithKey<>(new ReentrantReadWriteLock(lockInstance.isFair()),queue,key));
ReadWriteLock lock=lockRef.get();
if(lock==null){
ReentrantReadWriteLock newLock = new ReentrantReadWriteLock(lockInstance.isFair());
readWriteLockCache.computeIfAbsent(lockInstance.getName(), (key) -> new WeakReferenceWithKey<>(newLock,queue,key));
lock=newLock;
}
return lock;
}
@Override
public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
// 获取ApplicationContext后,刷新处理器列表
refresh();
}
/**
* Transforms from source data collection in batch.
*
* @param sources source data collection
* @param targetClass target class must not be null
* @param <T> target class type
* @return target collection transforming from source data collection.
* @throws BeanUtilsException if newing target instance failed or copying failed
*/
@NonNull
public static <T> List<T> transformFromInBatch(Collection<?> sources, @NonNull Class<T> targetClass) {
if (CollectionUtils.isEmpty(sources)) {
return Collections.emptyList();
}
// Transform in batch
return sources.stream()
.map(source -> transformFrom(source, targetClass))
.collect(Collectors.toList());
}
@Override
public Cache getCache(@NonNull String s) {
Cache cache = cacheMap.get(s);
if (cache != null) {
return cache;
}
if (!dynamic && cacheNames.contains(s)) {
return null;
}
cache = new ToolsCacheAdapter(s, redisTemplate, caffeineCache(), toolsCache, setScript, setNxScript,redisCache);
Cache newCache = cacheMap.putIfAbsent(s, cache);
return newCache == null ? cache : newCache;
}
/**
* Convert from domain.(shallow)
*
* @param domain domain data
* @return converted dto data
*/
@SuppressWarnings("unchecked")
@NonNull
default <T extends DTO> T convertFrom(@NonNull DOMAIN domain) {
updateProperties(domain, this);
return (T) this;
}
/**
* 插入值
*
* @param key key
* @param val val
*/
@Override
public void put(@NonNull Object key, Object val) {
key = getKey(key);
if (!super.isAllowNullValues() && val == null) {
this.evict(key);
return;
}
List<Object> keys = Collections.singletonList(key);
this.redisTemplate.execute(this.setScript, keys, val, this.getExpire());
this.caffeineCache.put(key, val);
}