org.springframework.lang.NonNull Java Examples
The following examples show how to use
org.springframework.lang.NonNull.
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: ActuatorMappingsDimension.java From sofa-dashboard-client with Apache License 2.0 | 6 votes |
/** * 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()); }
Example #2
Source File: ValueResolver.java From rqueue with Apache License 2.0 | 6 votes |
@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; }
Example #3
Source File: CometInterceptor.java From Milkomeda with MIT License | 6 votes |
@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<>(); }
Example #4
Source File: AbstractFallbackSQLExceptionTranslator.java From spring-analysis-note with MIT License | 6 votes |
/** * 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); }
Example #5
Source File: ActuatorMappingsDimension.java From sofa-dashboard-client with Apache License 2.0 | 6 votes |
/** * 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()); }
Example #6
Source File: AbstractFallbackSQLExceptionTranslator.java From java-technology-stack with MIT License | 6 votes |
/** * 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); }
Example #7
Source File: ExcelDrivenReadHandler.java From tools with MIT License | 6 votes |
@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()); }
Example #8
Source File: BeanUtils.java From White-Jotter with MIT License | 6 votes |
/** * 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; }
Example #9
Source File: Crust.java From Milkomeda with MIT License | 6 votes |
@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; }
Example #10
Source File: Crust.java From Milkomeda with MIT License | 6 votes |
/** * 登录成功后生成令牌 * * @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; }
Example #11
Source File: BeanUtils.java From White-Jotter with MIT License | 6 votes |
/** * 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); } }
Example #12
Source File: ToolsCacheAdapter.java From tools with MIT License | 6 votes |
/** * 获取缓存 * * @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; }
Example #13
Source File: AnnotationAuthorizingMethodInterceptor.java From tools with MIT License | 6 votes |
@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; }
Example #14
Source File: CompanyModelAssembler.java From springdoc-openapi with Apache License 2.0 | 5 votes |
@Override @NonNull public CompanyDto toModel(@NonNull final Company company) { final CompanyDto dto = CompanyDto.builder() .id(company.getId()) .name(company.getName()) .build(); return dto; }
Example #15
Source File: DashboardConfig.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 5 votes |
@NonNull private static String getConfig(String name) { // env String val = System.getenv(name); if (StringUtils.isNotEmpty(val)) { return val; } // properties val = System.getProperty(name); if (StringUtils.isNotEmpty(val)) { return val; } return ""; }
Example #16
Source File: BeanUtils.java From White-Jotter with MIT License | 5 votes |
/** * Update properties (non null). * * @param source source data must not be null * @param target target data must not be null * @throws BeanUtilsException if copying failed */ public static void updateProperties(@NonNull Object source, @NonNull Object target) { Assert.notNull(source, "source object must not be null"); Assert.notNull(target, "target object must not be null"); // Set non null properties from source properties to target properties try { org.springframework.beans.BeanUtils.copyProperties(source, target, getNullPropertyNames(source)); } catch (BeansException e) { throw new BeanUtilsException("Failed to copy properties", e); } }
Example #17
Source File: BeanUtils.java From White-Jotter with MIT License | 5 votes |
/** * 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()); }
Example #18
Source File: ToolsCacheAdapter.java From tools with MIT License | 5 votes |
/** * 判断是否存在,存在则插入 * * @param key key * @param val value * @return ValueWrapper */ @Override public ValueWrapper putIfAbsent(@NonNull Object key, Object val) { key = getKey(key); List<Object> keys = Collections.singletonList(key); Boolean execute = this.redisTemplate.execute(this.setNxScript, keys, val, this.getExpire()); assert execute != null; if (execute) { caffeineCache.put(key, toStoreValue(val)); } return toValueWrapper(val); }
Example #19
Source File: ActuatorMappingsDimension.java From sofa-dashboard-client with Apache License 2.0 | 5 votes |
/** * Parse dispatch servlet from data list * * @param data data list * @return Handler Mapping Info list */ private List<MappingsDescriptor.HandlerMappingInfo> parseDispatchServlet( @NonNull List<Map<String, Object>> data ) { return data.stream().map(map -> { // Read meta info from map String handler = readDict(map, "handler"); String predicate = readDict(map, "predicate"); List<String> methods = readDict(map, "details", "requestMappingConditions", "methods"); List<Map<String, Object>> paramsType = readDict(map, "details", "requestMappingConditions", "consumes"); List<Map<String, Object>> returnType = readDict(map, "details", "requestMappingConditions", "produces"); // Map to description text String methodsDesc = mapToDesc(methods); String paramTypeDesc = Optional.ofNullable(paramsType).orElse(new ArrayList<>()) .stream() .map(it -> (String) it.getOrDefault("mediaType", "")) .reduce((a, b) -> a + SPIT + b) .orElse(""); String returnTypeDesc = Optional.ofNullable(returnType).orElse(new ArrayList<>()) .stream() .map(it -> (String) it.getOrDefault("mediaType", "")) .reduce((a, b) -> a + SPIT + b) .orElse(""); // Generate mapping info MappingsDescriptor.HandlerMappingInfo info = new MappingsDescriptor.HandlerMappingInfo(); info.setHandler(Optional.ofNullable(handler).orElse("")); info.setPredicate(Optional.ofNullable(predicate).orElse("")); info.setMethods(methodsDesc); info.setParamsType(paramTypeDesc); info.setResponseType(returnTypeDesc); return info; }).collect(Collectors.toList()); }
Example #20
Source File: ToolsCacheAdapter.java From tools with MIT License | 5 votes |
/** * 插入值 * * @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); }
Example #21
Source File: AbstractHydrogenLoader.java From Milkomeda with MIT License | 5 votes |
@Override public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; // 获取ApplicationContext后,刷新处理器列表 refresh(); }
Example #22
Source File: OutputConverter.java From White-Jotter with MIT License | 5 votes |
/** * 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; }
Example #23
Source File: ToolsSecondCacheSelector.java From tools with MIT License | 5 votes |
@Override @NonNull public String[] selectImports(@NonNull AnnotationMetadata annotationMetadata) { return new String[]{ ToolsCacheConfiguration.class.getName() }; }
Example #24
Source File: FebsServerProtectInterceptor.java From FEBS-Cloud with Apache License 2.0 | 5 votes |
@Override public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws IOException { if (!properties.getOnlyFetchByGateway()) { return true; } String token = request.getHeader(FebsConstant.GATEWAY_TOKEN_HEADER); String gatewayToken = new String(Base64Utils.encode(FebsConstant.GATEWAY_TOKEN_VALUE.getBytes())); if (StringUtils.equals(gatewayToken, token)) { return true; } else { FebsResponse febsResponse = new FebsResponse(); FebsUtil.makeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, febsResponse.message("请通过网关获取资源")); return false; } }
Example #25
Source File: ToolsCacheManager.java From tools with MIT License | 5 votes |
@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; }
Example #26
Source File: SingleDocConfiguration.java From tools with MIT License | 5 votes |
@NonNull @Override public String[] selectImports(@NonNull AnnotationMetadata annotationMetadata) { return new String[]{ Doc.class.getName(), DocContact.class.getName(), DefaultSingleDocHandler.class.getName(), }; }
Example #27
Source File: JavaConcurrentLockFactory.java From summerframework with Apache License 2.0 | 5 votes |
@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; }
Example #28
Source File: HydrogenMappedInterceptor.java From Milkomeda with MIT License | 5 votes |
@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; }
Example #29
Source File: Crust.java From Milkomeda with MIT License | 5 votes |
/** * 获取登录时用户信息 * <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()); }
Example #30
Source File: ToolsCacheAdapter.java From tools with MIT License | 5 votes |
/** * @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; }