proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/config/AsyncConfig.java
|
AsyncConfig
|
getAsyncUncaughtExceptionHandler
|
class AsyncConfig implements AsyncConfigurer {
/**
* 自定义 @Async 注解使用系统线程池
*/
@Override
public Executor getAsyncExecutor() {
return SpringUtil.getBean("scheduledExecutorService");
}
/**
* 异步执行异常处理
*/
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {<FILL_FUNCTION_BODY>}
}
|
return (throwable, method, objects) -> {
throwable.printStackTrace();
StringBuilder sb = new StringBuilder();
sb.append("Exception message - ").append(throwable.getMessage())
.append(", Method name - ").append(method.getName());
if (ArrayUtil.isNotEmpty(objects)) {
sb.append(", Parameter value - ").append(Arrays.toString(objects));
}
throw new ServiceException(sb.toString());
};
| 121
| 124
| 245
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/config/JacksonConfig.java
|
JacksonConfig
|
customizer
|
class JacksonConfig {
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer() {<FILL_FUNCTION_BODY>}
}
|
return builder -> {
// 全局配置序列化返回 JSON 处理
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(Long.class, BigNumberSerializer.INSTANCE);
javaTimeModule.addSerializer(Long.TYPE, BigNumberSerializer.INSTANCE);
javaTimeModule.addSerializer(BigInteger.class, BigNumberSerializer.INSTANCE);
javaTimeModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
builder.modules(javaTimeModule);
//时区配置
builder.timeZone(TimeZone.getDefault());
log.info("初始化 jackson 配置");
};
| 39
| 243
| 282
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/config/KaptchaTextCreator.java
|
KaptchaTextCreator
|
getText
|
class KaptchaTextCreator extends DefaultTextCreator {
private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(",");
@Override
public String getText() {<FILL_FUNCTION_BODY>}
}
|
Integer result = 0;
Random random = new Random();
int x = random.nextInt(10);
int y = random.nextInt(10);
StringBuilder suChinese = new StringBuilder();
int randomoperands = random.nextInt(3);
if (randomoperands == 0) {
result = x * y;
suChinese.append(CNUMBERS[x]);
suChinese.append("*");
suChinese.append(CNUMBERS[y]);
} else if (randomoperands == 1) {
if ((x != 0) && y % x == 0) {
result = y / x;
suChinese.append(CNUMBERS[y]);
suChinese.append("/");
suChinese.append(CNUMBERS[x]);
} else {
result = x + y;
suChinese.append(CNUMBERS[x]);
suChinese.append("+");
suChinese.append(CNUMBERS[y]);
}
} else {
if (x >= y) {
result = x - y;
suChinese.append(CNUMBERS[x]);
suChinese.append("-");
suChinese.append(CNUMBERS[y]);
} else {
result = y - x;
suChinese.append(CNUMBERS[y]);
suChinese.append("-");
suChinese.append(CNUMBERS[x]);
}
}
suChinese.append("=?@" + result);
return suChinese.toString();
| 81
| 407
| 488
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/config/MyWebMvcConfig.java
|
MyWebMvcConfig
|
corsFilter
|
class MyWebMvcConfig implements WebMvcConfigurer {
@Autowired
private RepeatSubmitInterceptor repeatSubmitInterceptor;
/**
* 映射到访问本地的资源文件
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/** 本地文件上传路径 */
registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**")
.addResourceLocations("file:" + ConfigExpander.getFileProfile() + "/");
/** swagger配置 */
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
}
/**
* 自定义拦截规则
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
}
/**
* 跨域配置
*/
@Bean
public CorsFilter corsFilter() {<FILL_FUNCTION_BODY>}
/**
* RequestContextListener监听器
* bug:https://blog.csdn.net/qq_39575279/article/details/86562195
*
* @return
*/
@Bean
public RequestContextListener requestContextListenerBean() {
return new RequestContextListener();
}
}
|
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// 设置访问源地址
config.addAllowedOriginPattern("*");
// 设置访问源请求头
config.addAllowedHeader("*");
// 设置访问源请求方法
config.addAllowedMethod("*");
// 有效期 1800秒
config.setMaxAge(1800L);
// 添加映射路径,拦截一切请求
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
// 返回新的CorsFilter
return new CorsFilter(source);
| 397
| 184
| 581
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/config/MybatisPlusConfig.java
|
MybatisPlusConfig
|
mybatisPlusInterceptor
|
class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {<FILL_FUNCTION_BODY>}
/**
* 自动填充参数类
*
* @return
*/
@Bean
public MetaObjectHandler defaultMetaObjectHandler() {
return new MyDBFieldHandler();
}
}
|
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
| 166
| 59
| 225
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/config/SecurityConfig.java
|
SecurityConfig
|
configure
|
class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 自定义用户认证逻辑
*/
@Autowired
private UserDetailsService userDetailsService;
/**
* 认证失败处理类
*/
@Autowired
private AuthenticationEntryPointImpl unauthorizedHandler;
/**
* 退出处理类
*/
@Autowired
private LogoutSuccessHandlerImpl logoutSuccessHandler;
/**
* token认证过滤器
*/
@Autowired
private JwtAuthenticationTokenFilter authenticationTokenFilter;
/**
* 跨域过滤器
*/
@Autowired
private CorsFilter corsFilter;
/**
* 允许匿名访问的地址
*/
@Autowired
private PermitAllUrlProperties permitAllUrl;
/**
* 解决 无法直接注入 AuthenticationManager
*
* @return
* @throws Exception
*/
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
/**
* anyRequest | 匹配所有请求路径
* access | SpringEl表达式结果为true时可以访问
* anonymous | 匿名可以访问
* denyAll | 用户不能访问
* fullyAuthenticated | 用户完全认证可以访问(非remember-me下自动登录)
* hasAnyAuthority | 如果有参数,参数表示权限,则其中任何一个权限可以访问
* hasAnyRole | 如果有参数,参数表示角色,则其中任何一个角色可以访问
* hasAuthority | 如果有参数,参数表示权限,则其权限可以访问
* hasIpAddress | 如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
* hasRole | 如果有参数,参数表示角色,则其角色可以访问
* permitAll | 用户可以任意访问
* rememberMe | 允许通过remember-me登录的用户访问
* authenticated | 用户登录后可访问
*/
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {<FILL_FUNCTION_BODY>}
/**
* 强散列哈希加密实现
*/
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* 身份认证接口
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
}
|
// 注解标记允许匿名访问的url
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();
permitAllUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll());
httpSecurity
// CSRF禁用,因为不使用session
.csrf().disable()
// 认证失败处理类
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
// 基于token,所以不需要session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 过滤请求
.authorizeRequests()
// 对于登录login 注册register 验证码captchaImage 允许匿名访问
.antMatchers("/login", "/register", "/captchaImage").anonymous()
// 静态资源,可匿名访问
.antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
.antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated()
.and()
.headers().frameOptions().disable();
// 添加Logout filter
httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
// 添加JWT filter
httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
// 添加CORS filter
httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
| 700
| 475
| 1,175
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/config/ThreadPoolConfig.java
|
ThreadPoolConfig
|
scheduledExecutorService
|
class ThreadPoolConfig {
// 核心线程池大小
private int corePoolSize = 50;
// 最大可创建的线程数
private int maxPoolSize = 200;
// 队列最大长度
private int queueCapacity = 1000;
// 线程池维护线程所允许的空闲时间
private int keepAliveSeconds = 300;
@Bean(name = "threadPoolTaskExecutor")
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setMaxPoolSize(maxPoolSize);
executor.setCorePoolSize(corePoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveSeconds);
// 线程池对拒绝任务(无线程可用)的处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
/**
* 执行周期性或定时任务
*/
@Bean(name = "scheduledExecutorService")
protected ScheduledExecutorService scheduledExecutorService() {<FILL_FUNCTION_BODY>}
}
|
return new ScheduledThreadPoolExecutor(corePoolSize,
new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(),
new ThreadPoolExecutor.CallerRunsPolicy()) {
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
Threads.printException(r, t);
}
};
| 315
| 110
| 425
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/expander/SysConfigExpander.java
|
SysConfigExpander
|
getFileProfile
|
class SysConfigExpander {
private static SysConfigService configService;
@Autowired
private SysConfigService sysConfigService;
@PostConstruct
public void init() {
configService = sysConfigService;
}
/**
* 用户默认头像url
*/
public static String getUserDefaultAvatar() {
return configService.selectConfigByKey("sys.user.default.avatar");
}
/**
* 验证码类型
*
* @return
*/
public static String getLoginCaptchaType() {
return configService.selectConfigByKey("sys.login.captchaType", String.class, "math");
}
/**
* 获取文件保存目录
*
* @return
*/
public static String getFileProfile() {<FILL_FUNCTION_BODY>}
}
|
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win")) {
return configService.selectConfigByKey("sys.local.profile.win", String.class, "D:\\uploadPath");
}
if (osName.contains("mac")) {
return configService.selectConfigByKey("sys.local.profile.mac", String.class, "~/uploadPath");
}
if (osName.contains("linux")) {
return configService.selectConfigByKey("sys.local.profile.linux", String.class, "/data/uploadPath");
}
return null;
| 232
| 161
| 393
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/expander/SysFileConfigExpander.java
|
SysFileConfigExpander
|
getProfile
|
class SysFileConfigExpander {
/**
* 获取文件保存目录
*/
public static String getProfile() {<FILL_FUNCTION_BODY>}
/**
* 获取导入上传路径
*/
public static String getImportPath()
{
return getProfile() + "/import";
}
/**
* 获取头像上传路径
*/
public static String getAvatarPath()
{
return getProfile() + "/avatar";
}
/**
* 获取下载路径
*/
public static String getDownloadPath()
{
return getProfile() + "/download/";
}
/**
* 获取上传路径
*/
public static String getUploadPath()
{
return getProfile() + "/upload";
}
}
|
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win")) {
return ConfigContext.me().selectConfigByKey("sys.local.profile.win", String.class, "D:\\uploadPath");
}
if (osName.contains("mac")) {
return ConfigContext.me().selectConfigByKey("sys.local.profile.mac", String.class, "~/uploadPath");
}
if (osName.contains("linux")) {
return ConfigContext.me().selectConfigByKey("sys.local.profile.linux", String.class, "/data/uploadPath");
}
return null;
| 219
| 167
| 386
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/handler/BigNumberSerializer.java
|
BigNumberSerializer
|
serialize
|
class BigNumberSerializer extends NumberSerializer {
/**
* 根据 JS Number.MAX_SAFE_INTEGER 与 Number.MIN_SAFE_INTEGER 得来
*/
private static final long MAX_SAFE_INTEGER = 9007199254740991L;
private static final long MIN_SAFE_INTEGER = -9007199254740991L;
/**
* 提供实例
*/
public static final BigNumberSerializer INSTANCE = new BigNumberSerializer(Number.class);
public BigNumberSerializer(Class<? extends Number> rawType) {
super(rawType);
}
@Override
public void serialize(Number value, JsonGenerator gen, SerializerProvider provider) throws IOException {<FILL_FUNCTION_BODY>}
}
|
// 超出范围 序列化位字符串
if (value.longValue() > MIN_SAFE_INTEGER && value.longValue() < MAX_SAFE_INTEGER) {
super.serialize(value, gen, provider);
} else {
gen.writeString(value.toString());
}
| 218
| 85
| 303
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/handler/MyDBFieldHandler.java
|
MyDBFieldHandler
|
updateFill
|
class MyDBFieldHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
// this.strictInsertFill(metaObject, "createTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
Date current = new Date();
// 创建时间为空,则以当前时间为插入时间
if (Objects.isNull(baseEntity.getCreateTime())) {
baseEntity.setCreateTime(current);
}
// 更新时间为空,则以当前时间为更新时间
if (Objects.isNull(baseEntity.getUpdateTime())) {
baseEntity.setUpdateTime(current);
}
//TODO getRequest2
Long userId = WebFrameworkUtils.getLoginUserId(ServletUtils.getRequest());
// 当前登录用户不为空,创建人为空,则当前登录用户为创建人
if (Objects.nonNull(userId) && Objects.isNull(baseEntity.getCreateUser())) {
baseEntity.setCreateUser(userId);
}
// 当前登录用户不为空,更新人为空,则当前登录用户为更新人
if (Objects.nonNull(userId) && Objects.isNull(baseEntity.getUpdateUser())) {
baseEntity.setUpdateUser(userId);
}
if (Objects.isNull(baseEntity.getDelFlag())) {
baseEntity.setDelFlag(0);
}
}
}
@Override
public void updateFill(MetaObject metaObject) {<FILL_FUNCTION_BODY>}
}
|
// this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
// 更新时间为空,则以当前时间为更新时间
Object modifyTime = getFieldValByName("updateTime", metaObject);
if (Objects.isNull(modifyTime)) {
setFieldValByName("updateTime", new Date(), metaObject);
}
// 当前登录用户不为空,更新人为空,则当前登录用户为更新人
Object modifier = getFieldValByName("updateUser", metaObject);
Long userId = WebFrameworkUtils.getLoginUserId(ServletUtils.getRequest());
if (Objects.nonNull(userId) && Objects.isNull(modifier)) {
setFieldValByName("updateUser", userId, metaObject);
}
| 454
| 223
| 677
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/interceptor/RepeatSubmitInterceptor.java
|
RepeatSubmitInterceptor
|
preHandle
|
class RepeatSubmitInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {<FILL_FUNCTION_BODY>}
/**
* 验证是否重复提交由子类实现具体的防重复提交的规则
*
* @param request
* @return
* @throws Exception
*/
public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation);
}
|
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
if (annotation != null) {
if (this.isRepeatSubmit(request, annotation)) {
R r = R.error(annotation.message());
ServletUtils.renderString(response, JSON.toJSONString(r));
return false;
}
}
return true;
} else {
return true;
}
| 130
| 147
| 277
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/interceptor/impl/SameUrlDataInterceptor.java
|
SameUrlDataInterceptor
|
isRepeatSubmit
|
class SameUrlDataInterceptor extends RepeatSubmitInterceptor
{
public final String REPEAT_PARAMS = "repeatParams";
public final String REPEAT_TIME = "repeatTime";
// 令牌自定义标识
@Value("${token.header}")
private String header;
@Autowired
private RedisCache redisCache;
@SuppressWarnings("unchecked")
@Override
public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation)
{<FILL_FUNCTION_BODY>}
/**
* 判断参数是否相同
*/
private boolean compareParams(Map<String, Object> nowMap, Map<String, Object> preMap)
{
String nowParams = (String) nowMap.get(REPEAT_PARAMS);
String preParams = (String) preMap.get(REPEAT_PARAMS);
return nowParams.equals(preParams);
}
/**
* 判断两次间隔时间
*/
private boolean compareTime(Map<String, Object> nowMap, Map<String, Object> preMap, int interval)
{
long time1 = (Long) nowMap.get(REPEAT_TIME);
long time2 = (Long) preMap.get(REPEAT_TIME);
if ((time1 - time2) < interval)
{
return true;
}
return false;
}
}
|
String nowParams = "";
if (request instanceof RepeatedlyRequestWrapper)
{
RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request;
nowParams = HttpHelper.getBodyString(repeatedlyRequest);
}
// body参数为空,获取Parameter的数据
if (StringUtils.isEmpty(nowParams))
{
nowParams = JSON.toJSONString(request.getParameterMap());
}
Map<String, Object> nowDataMap = new HashMap<String, Object>();
nowDataMap.put(REPEAT_PARAMS, nowParams);
nowDataMap.put(REPEAT_TIME, System.currentTimeMillis());
// 请求地址(作为存放cache的key值)
String url = request.getRequestURI();
// 唯一值(没有消息头则使用请求地址)
String submitKey = StringUtils.trimToEmpty(request.getHeader(header));
// 唯一标识(指定key + url + 消息头)
String cacheRepeatKey = CacheConstants.REPEAT_SUBMIT_KEY + url + submitKey;
Object sessionObj = redisCache.getCacheObject(cacheRepeatKey);
if (sessionObj != null)
{
Map<String, Object> sessionMap = (Map<String, Object>) sessionObj;
if (sessionMap.containsKey(url))
{
Map<String, Object> preDataMap = (Map<String, Object>) sessionMap.get(url);
if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap, annotation.interval()))
{
return true;
}
}
}
Map<String, Object> cacheMap = new HashMap<String, Object>();
cacheMap.put(url, nowDataMap);
redisCache.setCacheObject(cacheRepeatKey, cacheMap, annotation.interval(), TimeUnit.MILLISECONDS);
return false;
| 370
| 504
| 874
|
<methods>public non-sealed void <init>() ,public abstract boolean isRepeatSubmit(HttpServletRequest, com.oddfar.campus.common.annotation.RepeatSubmit) ,public boolean preHandle(HttpServletRequest, HttpServletResponse, java.lang.Object) throws java.lang.Exception<variables>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/listener/ApiResourceScanner.java
|
ApiResourceScanner
|
createDefinition
|
class ApiResourceScanner implements BeanPostProcessor {
@Value("${spring.application.name:}")
private String springApplicationName;
/**
* 权限资源收集接口
*/
private final ResourceCollectorApi resourceCollectorApi;
public ApiResourceScanner(ResourceCollectorApi resourceCollectorApi) {
this.resourceCollectorApi = resourceCollectorApi;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Object aopTarget = AopTargetUtils.getTarget(bean);
if (aopTarget == null) {
aopTarget = bean;
}
Class<?> clazz = aopTarget.getClass();
// 判断是不是控制器,不是控制器就略过
boolean controllerFlag = getControllerFlag(clazz);
if (!controllerFlag) {
return bean;
}
ApiResource classApiAnnotation = clazz.getAnnotation(ApiResource.class);
if (classApiAnnotation != null) {
// 扫描控制器的所有带ApiResource注解的方法
List<SysResourceEntity> apiResources = doScan(clazz);
// 将扫描到的注解转化为资源实体存储到缓存
resourceCollectorApi.collectResources(apiResources);
}
return bean;
}
/**
* 判断一个类是否是控制器
*/
private boolean getControllerFlag(Class<?> clazz) {
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
if (RestController.class.equals(annotation.annotationType())) {
return true;
}
}
return false;
}
/**
* 扫描整个类中包含的所有@ApiResource资源
*/
private List<SysResourceEntity> doScan(Class<?> clazz) {
ArrayList<SysResourceEntity> apiResources = new ArrayList<>();
Method[] declaredMethods = clazz.getDeclaredMethods();
if (declaredMethods.length > 0) {
for (Method declaredMethod : declaredMethods) {
Annotation annotation = null;
Annotation[] annotations = declaredMethod.getAnnotations();
for (Annotation a : annotations) {
//若是 spring 的请求注解
if (a.toString().contains("Mapping(")) {
annotation = a;
}
}
if (annotation != null) {
SysResourceEntity definition = createDefinition(clazz, declaredMethod, annotation);
apiResources.add(definition);
}
}
}
return apiResources;
}
/**
* 根据类信息,方法信息,注解信息创建 SysResourceEntity 对象
*/
private SysResourceEntity createDefinition(Class<?> controllerClass, Method method, Annotation annotation) {<FILL_FUNCTION_BODY>}
/**
* 根据控制器类上的RequestMapping注解的映射路径,以及方法上的路径,拼出整个接口的路径
*/
private String createControllerPath(Class<?> clazz, String[] paths) {
String path = "";
if (paths.length > 0) {
path = "/" + paths[0];
}
String controllerPath;
RequestMapping controllerRequestMapping = clazz.getDeclaredAnnotation(RequestMapping.class);
if (controllerRequestMapping == null) {
controllerPath = "";
} else {
String[] values = controllerRequestMapping.value();
if (values.length > 0) {
controllerPath = values[0];
} else {
controllerPath = "";
}
}
// 控制器上的path要以/开头
if (!controllerPath.startsWith("/")) {
controllerPath = "/" + controllerPath;
}
// 前缀多个左斜杠替换为一个
return (controllerPath + path).replaceAll("/+", "/");
}
/**
* 调用注解上的某个方法,并获取结果
*
* @author fengshuonan
* @date 2020/12/8 17:13
*/
private <T> T invokeAnnotationMethod(Annotation apiResource, String methodName, Class<T> resultType) {
try {
Class<? extends Annotation> annotationType = apiResource.annotationType();
Method method = annotationType.getMethod(methodName);
return (T) method.invoke(apiResource);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
}
throw new RuntimeException("扫描api资源时出错!");
}
}
|
SysResourceEntity resource = new SysResourceEntity();
//设置类和方法名称
resource.setClassName(controllerClass.getSimpleName());
resource.setMethodName(method.getName());
// 填充模块编码,模块编码就是控制器名称截取Controller关键字前边的字符串
String className = resource.getClassName();
int controllerIndex = className.indexOf("Controller");
if (controllerIndex == -1) {
throw new IllegalArgumentException("controller class name is not illegal, it should end with Controller!");
}
//去掉Controller
String modular = className.substring(0, controllerIndex);
resource.setModular_code(modular);
// 填充模块的中文名称
ApiResource apiResource = controllerClass.getAnnotation(ApiResource.class);
// 接口资源的类别
resource.setResourceBizType(apiResource.resBizType().getCode());
resource.setModularName(apiResource.name());
// 设置appCode
if (StrUtil.isNotBlank(apiResource.appCode())) {
resource.setAppCode(apiResource.appCode());
}else {
resource.setAppCode(springApplicationName);
}
//资源唯一编码
String resourceCode = StrUtil.toUnderlineCase(resource.getAppCode()) + "." + StrUtil.toUnderlineCase(modular) + "." + StrUtil.toUnderlineCase(resource.getMethodName());
resource.setResourceCode(resourceCode);
//是否需要鉴权
PreAuthorize preAuthorize = method.getAnnotation(PreAuthorize.class);
resource.setRequiredPermissionFlag(Constants.NO);
if (preAuthorize != null) {
if (preAuthorize.value().contains("@ss.resourceAuth")) {
resource.setRequiredPermissionFlag(Constants.YES);
}
}
// 填充其他属性
String name = invokeAnnotationMethod(annotation, "name", String.class);
//不存在则资源名称为方法名
if (StringUtils.isNotEmpty(name)) {
resource.setResourceName(name);
} else {
resource.setResourceName(resource.getMethodName());
}
String[] value = invokeAnnotationMethod(annotation, "value", String[].class);
String controllerMethodPath = createControllerPath(controllerClass, value);
resource.setUrl(controllerMethodPath);
//填充请求方法
resource.setHttpMethod(StringUtils.substringBetween(annotation.toString(), "annotation.", "Mapping").toLowerCase());
return resource;
| 1,222
| 654
| 1,876
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/listener/ReadyEventListener.java
|
ReadyEventListener
|
onApplicationEvent
|
class ReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {
@Autowired
private SysResourceService resourceService;
@Autowired
private SysRoleService roleService;
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {<FILL_FUNCTION_BODY>}
}
|
//导入资源数据
ConfigurableApplicationContext applicationContext = event.getApplicationContext();
//清空数据
resourceService.truncateResource();
// 获取当前系统的所有资源
ResourceCollectorApi resourceCollectorApi = applicationContext.getBean(ResourceCollectorApi.class);
List<SysResourceEntity> allResources = resourceCollectorApi.getAllResources();
//添加api接口资源到数据库
resourceService.saveBatch(allResources);
//把用户资源和权限缓存
roleService.resetRoleAuthCache();
| 82
| 142
| 224
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/listener/ResourceReportListener.java
|
ResourceReportListener
|
onApplicationEvent
|
class ResourceReportListener {
@Autowired
WebApplicationContext applicationContext;
@Autowired
SysResourceService resourceService;
// @Override
public void onApplicationEvent(ApplicationReadyEvent event) {<FILL_FUNCTION_BODY>}
/**
* 根据 Method 设置其内容
*
* @param m
*/
private void setSource(Method m) {
Class<?> aClass = m.getDeclaringClass();
Annotation[] annotations = m.getDeclaredAnnotations();
for (Annotation a : annotations) {
//若是 spring 的请求注解
if (a.toString().contains("Mapping(")) {
SysResourceEntity resource = new SysResourceEntity();
resource.setClassName(aClass.getSimpleName());
//获取注解@Api,并设置模块名称
// Api api = AnnotationUtils.getAnnotation(aClass, Api.class);
// resource.setModularName(api.value());
resource.setMethodName(m.getName());
//设置注解其他内容
setSource(resource, a);
//保存到数据库
resourceService.insertResource(resource);
}
}
}
/**
* 设置 SysResourceEntity 的其他内容
*
* @param resource
* @param a 例如 @GetMapping,设置其参数的内容
*/
private void setSource(SysResourceEntity resource, Annotation a) {
String s = a.toString();
resource.setResourceName(StringUtils.substringBetween(s, ", name=", ", "));
resource.setUrl(StringUtils.substringBetween(s, ", value=", ", "));
resource.setHttpMethod(StringUtils.substringBetween(s, "annotation.", "Mapping"));
resource.setAppCode("zhiyuan");
//ClassName+MethodName(替换)
resource.setResourceCode(resource.getClassName().toLowerCase().replace("controller", "") + ":" + resource.getMethodName());
}
}
|
//清空表
resourceService.truncateResource();
RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
// 获取所有controller方法
Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
map.keySet().forEach(info -> {
HandlerMethod handlerMethod = map.get(info);
PreAuthorize preAuthorize = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), PreAuthorize.class);
//如果方法上含有 @PreAuthorize 注解
Optional.ofNullable(preAuthorize).ifPresent(anonymous -> {
if (preAuthorize.value().contains("@ss.test")) {
Method m = handlerMethod.getMethod();
setSource(m);
}
});
});
| 530
| 205
| 735
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/manager/AsyncFactory.java
|
AsyncFactory
|
run
|
class AsyncFactory {
private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");
/**
* 记录登录信息
*
* @param userName 用户名
* @param status 状态
* @param message 消息
* @param args 列表
* @return 任务task
*/
public static TimerTask recordLogininfor(final String userName, final Long userId, final String status,
final String message, final Object... args) {
final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
final String ip = IpUtils.getIpAddr(ServletUtils.getRequest2());
return new TimerTask() {
@Override
public void run() {<FILL_FUNCTION_BODY>}
};
}
/**
* 操作日志记录
*
* @param operLog 操作日志信息
* @return 任务task
*/
public static TimerTask recordOper(final SysOperLogEntity operLog) {
return new TimerTask() {
@Override
public void run() {
SpringUtils.getBean(SysOperLogService.class).insertOperlog(operLog);
}
};
}
}
|
String address = AddressUtils.getRealAddressByIP(ip);
StringBuilder s = new StringBuilder();
s.append(LogUtils.getBlock(ip));
s.append(address);
s.append(LogUtils.getBlock(userName));
s.append(LogUtils.getBlock(userId));
s.append(LogUtils.getBlock(status));
s.append(LogUtils.getBlock(message));
// 打印信息到日志
sys_user_logger.info(s.toString(), args);
// 获取客户端操作系统
String os = userAgent.getOperatingSystem().getName();
// 获取客户端浏览器
String browser = userAgent.getBrowser().getName();
// 封装对象
SysLoginLogEntity logininfor = new SysLoginLogEntity();
logininfor.setLoginTime(new Date());
logininfor.setUserName(userName);
logininfor.setUserId(userId);
logininfor.setIpaddr(ip);
logininfor.setLoginLocation(address);
logininfor.setBrowser(browser);
logininfor.setOs(os);
logininfor.setMsg(message);
// 日志状态
if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
logininfor.setStatus(Constants.SUCCESS);
} else if (Constants.LOGIN_FAIL.equals(status)) {
logininfor.setStatus(Constants.FAIL);
}
// 插入数据
SpringUtils.getBean(SysLoginLogService.class).insertLogininfor(logininfor);
| 333
| 432
| 765
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/security/filter/JwtAuthenticationTokenFilter.java
|
JwtAuthenticationTokenFilter
|
doFilterInternal
|
class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
@Autowired
private TokenService tokenService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {<FILL_FUNCTION_BODY>}
/**
* 设置当前用户
*
* @param loginUser 登录用户
* @param request 请求
*/
public static void setLoginUser(LoginUser loginUser, HttpServletRequest request) {
// 额外设置到 request 中,有的过滤器在 Spring Security 之前
WebFrameworkUtils.setLoginUserId(request, loginUser.getUserId());
}
}
|
LoginUser loginUser = tokenService.getLoginUser(request);
if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
// 设置当前用户
setLoginUser(loginUser, request);
tokenService.verifyToken(loginUser);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
chain.doFilter(request, response);
| 181
| 156
| 337
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/security/handle/AuthenticationEntryPointImpl.java
|
AuthenticationEntryPointImpl
|
commence
|
class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {
private static final long serialVersionUID = -8970718410437077606L;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
throws IOException {<FILL_FUNCTION_BODY>}
}
|
int code = HttpStatus.UNAUTHORIZED;
String msg = StringUtils.format("请求访问:{},认证失败,无法访问系统资源", request.getRequestURI());
ServletUtils.renderString(response, JSON.toJSONString(R.error(code, msg)));
| 93
| 75
| 168
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/security/handle/LogoutSuccessHandlerImpl.java
|
LogoutSuccessHandlerImpl
|
onLogoutSuccess
|
class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
@Autowired
private TokenService tokenService;
/**
* 退出处理
*
*/
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {<FILL_FUNCTION_BODY>}
}
|
LoginUser loginUser = tokenService.getLoginUser(request);
if (StringUtils.isNotNull(loginUser)) {
// 删除用户缓存记录
tokenService.delLoginUser(loginUser.getToken());
// 记录用户退出日志
AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginUser.getUsername(), loginUser.getUserId(), Constants.LOGOUT, MessageUtils.message("user.logout.success")));
}
ServletUtils.renderString(response, JSON.toJSONString(R.error(HttpStatus.SUCCESS, MessageUtils.message("user.logout.success"))));
| 95
| 164
| 259
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/security/properties/PermitAllUrlProperties.java
|
PermitAllUrlProperties
|
afterPropertiesSet
|
class PermitAllUrlProperties implements InitializingBean, ApplicationContextAware
{
private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");
private ApplicationContext applicationContext;
private List<String> urls = new ArrayList<>();
public String ASTERISK = "*";
@Override
public void afterPropertiesSet()
{<FILL_FUNCTION_BODY>}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException
{
this.applicationContext = context;
}
public List<String> getUrls()
{
return urls;
}
public void setUrls(List<String> urls)
{
this.urls = urls;
}
}
|
RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
map.keySet().forEach(info -> {
HandlerMethod handlerMethod = map.get(info);
// 获取方法上边的注解 替代path variable 为 *
Anonymous method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Anonymous.class);
Optional.ofNullable(method).ifPresent(anonymous -> info.getPatternsCondition().getPatterns()
.forEach(url -> urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK))));
// 获取类上边的注解, 替代path variable 为 *
Anonymous controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Anonymous.class);
Optional.ofNullable(controller).ifPresent(anonymous -> info.getPatternsCondition().getPatterns()
.forEach(url -> urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK))));
});
| 200
| 281
| 481
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/service/impl/SysConfigServiceImpl.java
|
SysConfigServiceImpl
|
insertConfig
|
class SysConfigServiceImpl implements SysConfigService {
@Resource
private SysConfigMapper configMapper;
@Autowired
private RedisCache redisCache;
/**
* 项目启动时,初始化参数到缓存
*/
@PostConstruct
public void init() {
loadingConfigCache();
}
@Override
public PageResult<SysConfigEntity> page(SysConfigEntity sysConfigEntity) {
return configMapper.selectPage(sysConfigEntity);
}
@Override
public SysConfigEntity selectConfigById(Long configId) {
SysConfigEntity config = new SysConfigEntity();
config.setConfigId(configId);
return configMapper.selectById(config);
}
/**
* 根据键名查询参数配置信息
*
* @param configKey 参数key
* @return 参数键值
*/
@Override
public String selectConfigByKey(String configKey) {
String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey)));
if (StringUtils.isNotEmpty(configValue)) {
return configValue;
}
SysConfigEntity config = new SysConfigEntity();
config.setConfigKey(configKey);
SysConfigEntity retConfig = configMapper.selectConfig(config);
if (StringUtils.isNotNull(retConfig)) {
redisCache.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
return retConfig.getConfigValue();
}
return StringUtils.EMPTY;
}
@Override
public <T> T selectConfigByKey(String configKey, Class<T> clazz) {
T configValue = redisCache.getCacheObject(getCacheKey(configKey));
if (ObjectUtil.isNotEmpty(configValue)) {
return configValue;
}
SysConfigEntity config = new SysConfigEntity();
config.setConfigKey(configKey);
SysConfigEntity retConfig = configMapper.selectConfig(config);
if (ObjectUtil.isNotNull(retConfig)) {
redisCache.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
return Convert.convert(clazz, retConfig.getConfigValue());
}
return null;
}
@Override
public <T> T selectConfigByKey(String configKey, Class<T> clazz, T defaultValue) {
T value = this.selectConfigByKey(configKey, clazz);
return value == null ? defaultValue : value;
}
/**
* 获取验证码开关
*
* @return true开启,false关闭
*/
@Override
public boolean selectCaptchaEnabled() {
String captchaEnabled = selectConfigByKey("sys.account.captchaEnabled");
if (StringUtils.isEmpty(captchaEnabled)) {
return true;
}
return Convert.toBool(captchaEnabled);
}
@Override
public int insertConfig(SysConfigEntity config) {<FILL_FUNCTION_BODY>}
@Override
public int updateConfig(SysConfigEntity config) {
int row = configMapper.updateById(config);
if (row > 0) {
redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
}
return row;
}
@Override
public void deleteConfigByIds(Long[] configIds) {
for (Long configId : configIds) {
SysConfigEntity config = selectConfigById(configId);
if (StringUtils.equals(UserConstants.YES, config.getConfigType())) {
throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
}
configMapper.deleteById(configId);
redisCache.deleteObject(getCacheKey(config.getConfigKey()));
}
}
/**
* 加载参数缓存数据
*/
@Override
public void loadingConfigCache() {
List<SysConfigEntity> configsList = configMapper.selectList();
for (SysConfigEntity config : configsList) {
redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
}
}
@Override
public boolean checkConfigKeyUnique(SysConfigEntity config) {
Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId();
SysConfigEntity info = configMapper.checkConfigKeyUnique(config);
if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) {
return false;
}
return true;
}
@Override
public void clearConfigCache() {
Collection<String> keys = redisCache.keys(CacheConstants.SYS_CONFIG_KEY + "*");
redisCache.deleteObject(keys);
}
@Override
public void resetConfigCache() {
clearConfigCache();
loadingConfigCache();
}
/**
* 设置cache key
*
* @param configKey 参数键
* @return 缓存键key
*/
private String getCacheKey(String configKey) {
return CacheConstants.SYS_CONFIG_KEY + configKey;
}
}
|
int row = configMapper.insert(config);
if (row > 0) {
redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
}
return row;
| 1,373
| 58
| 1,431
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/service/impl/SysDictDataServiceImpl.java
|
SysDictDataServiceImpl
|
updateDictData
|
class SysDictDataServiceImpl implements SysDictDataService {
@Resource
private SysDictDataMapper dictDataMapper;
@Override
public PageResult<SysDictDataEntity> page(SysDictDataEntity dictDataEntity) {
return dictDataMapper.selectPage(dictDataEntity);
}
@Override
public int insertDictData(SysDictDataEntity dictData) {
int row = dictDataMapper.insert(dictData);
if (row > 0) {
List<SysDictDataEntity> dictDatas = dictDataMapper.selectDictDataByType(dictData.getDictType());
DictUtils.setDictCache(dictData.getDictType(), dictDatas);
}
return row;
}
@Override
public SysDictDataEntity selectDictDataById(Long dictCode) {
return dictDataMapper.selectById(dictCode);
}
@Override
public int updateDictData(SysDictDataEntity data) {<FILL_FUNCTION_BODY>}
@Override
public void deleteDictDataByIds(Long[] dictCodes) {
for (Long dictCode : dictCodes) {
SysDictDataEntity data = dictDataMapper.selectById(dictCode);
dictDataMapper.deleteById(dictCode);
List<SysDictDataEntity> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType());
DictUtils.setDictCache(data.getDictType(), dictDatas);
}
}
}
|
int row = dictDataMapper.updateById(data);
if (row > 0) {
List<SysDictDataEntity> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType());
DictUtils.setDictCache(data.getDictType(), dictDatas);
}
return row;
| 407
| 89
| 496
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/service/impl/SysDictTypeServiceImpl.java
|
SysDictTypeServiceImpl
|
selectDictDataByType
|
class SysDictTypeServiceImpl implements SysDictTypeService {
@Resource
private SysDictTypeMapper dictTypeMapper;
@Resource
private SysDictDataMapper dictDataMapper;
@Override
public PageResult<SysDictTypeEntity> page(SysDictTypeEntity sysDictTypeEntity) {
return dictTypeMapper.selectPage(sysDictTypeEntity);
}
/**
* 根据字典类型查询字典数据
*
* @param dictType 字典类型
* @return 字典数据集合信息
*/
@Override
public List<SysDictDataEntity> selectDictDataByType(String dictType) {<FILL_FUNCTION_BODY>}
@Override
public SysDictTypeEntity selectDictTypeById(Long dictId) {
return dictTypeMapper.selectById(dictId);
}
@Override
public List<SysDictTypeEntity> selectDictTypeAll() {
return dictTypeMapper.selectList();
}
@Override
@Transactional
public int updateDictType(SysDictTypeEntity dictType) {
SysDictTypeEntity oldDict = dictTypeMapper.selectById(dictType.getDictId());
dictDataMapper.updateDictDataType(oldDict.getDictType(), dictType.getDictType());
//把要更新的dictType的内容赋值到oldDict
// BeanUtil.copyProperties(dictType, oldDict);
int row = dictTypeMapper.updateById(dictType);
if (row > 0) {
List<SysDictDataEntity> dictDatas = dictDataMapper.selectDictDataByType(dictType.getDictType());
DictUtils.setDictCache(dictType.getDictType(), dictDatas);
}
return row;
}
@Override
public int insertDictType(SysDictTypeEntity dictType) {
int row = dictTypeMapper.insert(dictType);
if (row > 0) {
DictUtils.setDictCache(dictType.getDictType(), null);
}
return row;
}
@Override
public void deleteDictTypeByIds(Long[] dictIds) {
for (Long dictId : dictIds) {
SysDictTypeEntity dictType = selectDictTypeById(dictId);
if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) {
throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
}
// this.removeById(dictId);
dictTypeMapper.deleteById(dictId);
DictUtils.removeDictCache(dictType.getDictType());
}
}
@Override
public void resetDictCache() {
clearDictCache();
loadingDictCache();
}
/**
* 加载字典缓存数据
*/
@Override
public void loadingDictCache() {
Map<String, List<SysDictDataEntity>> dictDataMap = dictDataMapper.selectList("status", "0").stream().collect(Collectors.groupingBy(SysDictDataEntity::getDictType));
for (Map.Entry<String, List<SysDictDataEntity>> entry : dictDataMap.entrySet()) {
DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictDataEntity::getDictSort)).collect(Collectors.toList()));
}
}
@Override
public boolean checkDictTypeUnique(SysDictTypeEntity dictType) {
Long dictId = StringUtils.isNull(dictType.getDictId()) ? -1L : dictType.getDictId();
SysDictTypeEntity info = dictTypeMapper.selectOne(new LambdaQueryWrapperX<SysDictTypeEntity>()
.eq(SysDictTypeEntity::getDictType, dictType.getDictType()));
if (StringUtils.isNotNull(info) && info.getDictId().longValue() != dictId.longValue()) {
return false;
}
return true;
}
}
|
List<SysDictDataEntity> dictDatas = DictUtils.getDictCache(dictType);
if (StringUtils.isNotEmpty(dictDatas)) {
return dictDatas;
}
dictDatas = dictDataMapper.selectDictDataByType(dictType);
if (StringUtils.isNotEmpty(dictDatas)) {
DictUtils.setDictCache(dictType, dictDatas);
return dictDatas;
}
return null;
| 1,090
| 129
| 1,219
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/service/impl/SysResourceServiceImpl.java
|
SysResourceServiceImpl
|
buildResourceTreeSelect
|
class SysResourceServiceImpl extends ServiceImpl<SysResourceMapper, SysResourceEntity> implements SysResourceService {
@Resource
private SysResourceMapper resourceMapper;
@Resource
private SysRoleResourceMapper roleResourceMapper;
@Override
public PageResult<SysResourceEntity> page(SysResourceEntity sysResourceEntity) {
return resourceMapper.selectPage(sysResourceEntity);
}
/**
* 新增接口资源信息
*
* @param resource
* @return
*/
@Override
public int insertResource(SysResourceEntity resource) {
int row = resourceMapper.insert(resource);
return row;
}
/**
* 清空 sys_resource 数据库
*/
@Override
public void truncateResource() {
resourceMapper.truncateResource();
}
/**
* 根据角色ID查询资源编码列表
*
* @param roleId 角色ID
* @return 权限列表
*/
@Override
public Set<String> selectResourceCodeByRoleId(Long roleId) {
return resourceMapper.selectResourceCodeByRoleId(roleId);
}
@Override
public List<SysResourceEntity> selectApiResourceList(Long userId) {
SysResourceEntity resourceEntity = new SysResourceEntity();
resourceEntity.setRequiredPermissionFlag(Constants.YES);
return selectApiResourceList(resourceEntity, userId);
}
@Override
public List<SysRoleAuth> selectSysRoleAuthAll() {
return roleResourceMapper.selectList().stream()
.map(SysRoleAuth::new).collect(Collectors.toList());
}
@Override
public List<SysResourceEntity> selectApiResourceList(SysResourceEntity resource, Long userId) {
List<SysResourceEntity> resourceList = null;
// 管理员显示所有资源信息
if (SysUserEntity.isAdmin(userId)) {
resourceList = resourceMapper.selectResourceList(resource);
} else {
resource.getParams().put("userId", userId);
resourceList = resourceMapper.selectResourceListByUserId(resource);
}
return resourceList;
}
@Override
public List<Long> selectResourceListByRoleId(Long roleId) {
return resourceMapper.selectResourceListByRoleId(roleId);
}
@Override
public List<TreeSelect> buildResourceTreeSelect(List<SysResourceEntity> resources) {<FILL_FUNCTION_BODY>}
@Override
public void editRoleResource(Long roleId, Long[] resourceIds) {
// 删除角色与api资源关联
roleResourceMapper.deleteRoleResourceByRoleId(roleId);
//添加角色与api资源管理
if (resourceIds.length > 0) {
List<SysResourceEntity> resourceEntities = resourceMapper.selectBatchIds(Arrays.asList(resourceIds));
insertRoleMenu(roleId, resourceEntities);
}
}
public int insertRoleMenu(Long roleId, List<SysResourceEntity> resourceEntities) {
List<SysRoleResourceEntity> rrList = new ArrayList<>();
for (SysResourceEntity resourceEntity : resourceEntities) {
SysRoleResourceEntity rr = new SysRoleResourceEntity();
rr.setRoleId(roleId);
rr.setResourceCode(resourceEntity.getResourceCode());
rrList.add(rr);
}
return roleResourceMapper.saveBatch(rrList);
}
}
|
List<TreeSelect> treeSelects = new ArrayList<>();
Map<String, List<SysResourceEntity>> map = resources.stream().collect(
Collectors.groupingBy(SysResourceEntity::getClassName));
long size = 0L;
for (String key : map.keySet()) {
String modularName = map.get(key).get(0).getModularName();
TreeSelect treeSelect = new TreeSelect(++size, modularName, map.get(key));
treeSelects.add(treeSelect);
}
return treeSelects;
| 908
| 145
| 1,053
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/service/impl/SysRoleServiceImpl.java
|
SysRoleServiceImpl
|
deleteRoleByIds
|
class SysRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRoleEntity> implements SysRoleService {
@Resource
private SysRoleMapper roleMapper;
@Resource
private SysUserRoleMapper userRoleMapper;
@Resource
private SysRoleMenuMapper roleMenuMapper;
@Resource
private SysMenuService menuService;
@Resource
private SysResourceService resourceService;
@Resource
ApplicationContext applicationContext;
@Override
public PageResult<SysRoleEntity> page(SysRoleEntity sysRoleEntity) {
return roleMapper.selectPage(sysRoleEntity);
}
@Override
public List<SysRoleEntity> selectRoleList(SysRoleEntity role) {
return roleMapper.selectRoleList(role);
}
/**
* 根据用户ID查询权限
*
* @param userId 用户ID
* @return 权限列表
*/
@Override
public Set<String> selectRolePermissionByUserId(Long userId) {
List<SysRoleEntity> perms = roleMapper.selectRolePermissionByUserId(userId);
Set<String> permsSet = new HashSet<>();
for (SysRoleEntity perm : perms) {
if (StringUtils.isNotNull(perm)) {
permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
}
}
return permsSet;
}
/**
* 通过角色ID查询角色
*
* @param roleId 角色ID
* @return 角色对象信息
*/
@Override
public SysRoleEntity selectRoleById(Long roleId) {
return roleMapper.selectRoleById(roleId);
}
@Override
public List<SysRoleEntity> selectRoleAll() {
return this.selectRoleList(new SysRoleEntity());
// return SpringUtils.getAopProxy(this).selectRoleList(new SysRoleEntity());
}
@Override
public List<SysRoleEntity> selectRolesByUserId(Long userId) {
List<SysRoleEntity> userRoles = roleMapper.selectRolePermissionByUserId(userId);
List<SysRoleEntity> roles = selectRoleAll();
for (SysRoleEntity role : roles) {
for (SysRoleEntity userRole : userRoles) {
if (role.getRoleId().longValue() == userRole.getRoleId().longValue()) {
role.setFlag(true);
break;
}
}
}
return roles;
}
@Override
@Transactional
public int insertRole(SysRoleEntity role) {
// 新增角色信息
roleMapper.insert(role);
return insertRoleMenu(role);
}
@Override
public int updateRole(SysRoleEntity role) {
// 修改角色信息
roleMapper.updateById(role);
// 删除角色与菜单关联
roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
return insertRoleMenu(role);
}
@Override
public int updateRoleStatus(SysRoleEntity role) {
return roleMapper.updateById(role);
}
@Override
@Transactional
public int deleteRoleByIds(Long[] roleIds) {<FILL_FUNCTION_BODY>}
@Override
public int deleteAuthUser(SysUserRoleEntity userRole) {
return userRoleMapper.deleteUserRoleInfo(userRole);
}
@Override
public int deleteAuthUsers(Long roleId, Long[] userIds) {
return userRoleMapper.deleteUserRoleInfos(roleId, userIds);
}
@Override
public boolean insertAuthUsers(Long roleId, Long[] userIds) {
// 新增用户与角色管理
List<SysUserRoleEntity> list = new ArrayList<SysUserRoleEntity>();
for (Long userId : userIds) {
SysUserRoleEntity ur = new SysUserRoleEntity();
ur.setUserId(userId);
ur.setRoleId(roleId);
list.add(ur);
}
return this.saveBatch(list);
}
@Override
public int countUserRoleByRoleId(Long roleId) {
return userRoleMapper.countUserRoleByRoleId(roleId);
}
@Override
public boolean checkRoleNameUnique(SysRoleEntity role) {
Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
SysRoleEntity info = roleMapper.checkRoleNameUnique(role.getRoleName());
if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
return false;
}
return true;
}
@Override
public boolean checkRoleKeyUnique(SysRoleEntity role) {
Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
SysRoleEntity info = roleMapper.checkRoleKeyUnique(role.getRoleKey());
if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
return false;
}
return true;
}
@Override
public void checkRoleAllowed(SysRoleEntity role) {
if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin()) {
throw new ServiceException("不允许操作超级管理员角色");
}
}
@Override
public void resetRoleAuthCache() {
//把用户资源和权限缓存
Map<Long, List<SysRoleAuth>> rolePermsMap = menuService.selectMenuPermsAll();
Map<Long, List<SysRoleAuth>> roleResourceMap = resourceService.selectSysRoleAuthAll().stream().collect(Collectors.groupingBy(SysRoleAuth::getRoleID));
ResourceCollectorApi resourceCollectorApi = applicationContext.getBean(ResourceCollectorApi.class);
resourceCollectorApi.setRoleAuthCache(rolePermsMap, roleResourceMap);
}
/**
* 新增角色菜单信息
*
* @param role 角色对象
*/
public int insertRoleMenu(SysRoleEntity role) {
int rows = 1;
// 新增用户与角色管理
List<SysRoleMenuEntity> list = new ArrayList<SysRoleMenuEntity>();
for (Long menuId : role.getMenuIds()) {
SysRoleMenuEntity rm = new SysRoleMenuEntity();
rm.setRoleId(role.getRoleId());
rm.setMenuId(menuId);
list.add(rm);
}
if (list.size() > 0) {
rows = roleMenuMapper.batchRoleMenu(list);
}
return rows;
}
}
|
for (Long roleId : roleIds) {
checkRoleAllowed(new SysRoleEntity(roleId));
SysRoleEntity role = selectRoleById(roleId);
if (countUserRoleByRoleId(roleId) > 0) {
throw new ServiceException(String.format("%1$s已分配,不能删除", role.getRoleName()));
}
}
// 删除角色与菜单关联
roleMenuMapper.deleteRoleMenu(roleIds);
// 删除角色
return roleMapper.deleteBatchIds(Arrays.asList(roleIds));
| 1,771
| 148
| 1,919
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/web/exception/GlobalExceptionHandler.java
|
GlobalExceptionHandler
|
handleRuntimeException
|
class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 权限校验异常
*/
@ExceptionHandler(AccessDeniedException.class)
public R handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
return R.error(HttpStatus.FORBIDDEN, "没有权限,请联系管理员授权");
}
/**
* 请求方式不支持
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public R handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
return R.error(e.getMessage());
}
/**
* 业务异常
*/
@ExceptionHandler(ServiceException.class)
public R handleServiceException(ServiceException e, HttpServletRequest request) {
log.error(e.getMessage(), e);
Integer code = e.getCode();
return StringUtils.isNotNull(code) ? R.error(code, e.getMessage()) : R.error(e.getMessage());
}
/**
* 拦截未知的运行时异常
*/
@ExceptionHandler(RuntimeException.class)
public R handleRuntimeException(RuntimeException e, HttpServletRequest request) {<FILL_FUNCTION_BODY>}
/**
* 系统异常
*/
@ExceptionHandler(Exception.class)
public R handleException(Exception e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',发生系统异常.", requestURI, e);
return R.error(e.getMessage());
}
/**
* 自定义验证异常
*/
@ExceptionHandler(BindException.class)
public R handleBindException(BindException e) {
log.error(e.getMessage(), e);
String message = e.getAllErrors().get(0).getDefaultMessage();
return R.error(message);
}
/**
* 自定义验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
log.error(e.getMessage(), e);
String message = e.getBindingResult().getFieldError().getDefaultMessage();
return R.error(message);
}
}
|
String requestURI = request.getRequestURI();
log.error("请求地址'{}',发生未知异常.", requestURI, e);
return R.error(e.getMessage());
| 687
| 47
| 734
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/web/service/PermissionService.java
|
PermissionService
|
hasRole
|
class PermissionService {
private static final Logger log = LoggerFactory.getLogger(PermissionService.class);
@Value("${spring.application.name:}")
private String springApplicationName;
@Autowired
WebApplicationContext applicationContext;
/**
* 所有权限标识
*/
private static final String ALL_PERMISSION = "*:*:*";
/**
* 管理员角色权限标识
*/
private static final String SUPER_ADMIN = "admin";
private static final String ROLE_DELIMETER = ",";
private static final String PERMISSION_DELIMETER = ",";
/**
* 验证用户是否具备某权限
*
* @param permission 权限字符串
* @return 用户是否具备某权限
*/
public boolean hasPermi(String permission) {
if (StringUtils.isEmpty(permission)) {
return false;
}
LoginUser loginUser = SecurityUtils.getLoginUser();
if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) {
return false;
}
PermissionContextHolder.setContext(permission);
return hasPermissions(loginUser.getPermissions(), permission);
}
/**
* 验证用户是否具备某接口
* @return 用户是否具备某接口
*/
public boolean resourceAuth() {
LoginUser loginUser = SecurityUtils.getLoginUser();
if (StringUtils.isNull(loginUser)) {
return false;
}
HttpServletRequest request = ServletUtils.getRequest();
RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
HandlerExecutionChain handlerChain = null;
try {
handlerChain = mapping.getHandler(request);
} catch (Exception e) {
e.printStackTrace();
}
//通过处理链找到对应的HandlerMethod类
HandlerMethod handler = (HandlerMethod) handlerChain.getHandler();
String resourceCode = getResourceCode(handler);
return hasResources(loginUser.getResources(), resourceCode);
}
/**
* 获取controller方法的编码
*
* @param handler
* @return
*/
private String getResourceCode(HandlerMethod handler) {
Object bean = handler.getBean();//处理请求的类
Class<?> aClass = bean.getClass();
Method method = handler.getMethod();//处理请求的方法
//获取@ApiResource接口
ApiResource apiResource = method.getDeclaringClass().getAnnotation(ApiResource.class);
//资源唯一编码
StringBuffer resourceCode = new StringBuffer();
//应用编码
String appCode = springApplicationName;
if (apiResource != null) {
if (StringUtils.isNotEmpty(apiResource.appCode())) {
appCode = apiResource.appCode();
}
}
String className = StrUtil.toUnderlineCase(StringUtils.substringBefore(aClass.getSimpleName(), "$$")
.replace("Controller", ""));
String methodName = StrUtil.toUnderlineCase(method.getName());
return resourceCode.append(appCode).append(".").append(className).append(".").append(methodName).toString();
}
/**
* 判断是否包含接口
*
* @param resources 资源列表
* @param resource 资源接口字符串
* @return 用户是否具备某权限
*/
private boolean hasResources(Set<String> resources, String resource) {
return resources.contains(ALL_PERMISSION) || resources.contains(StringUtils.trim(resource));
}
/**
* 验证用户是否不具备某权限,与 hasPermi逻辑相反
*
* @param permission 权限字符串
* @return 用户是否不具备某权限
*/
public boolean lacksPermi(String permission) {
return hasPermi(permission) != true;
}
/**
* 验证用户是否具有以下任意一个权限
*
* @param permissions 以 PERMISSION_NAMES_DELIMETER 为分隔符的权限列表
* @return 用户是否具有以下任意一个权限
*/
public boolean hasAnyPermi(String permissions) {
if (StringUtils.isEmpty(permissions)) {
return false;
}
LoginUser loginUser = SecurityUtils.getLoginUser();
if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) {
return false;
}
PermissionContextHolder.setContext(permissions);
Set<String> authorities = loginUser.getPermissions();
for (String permission : permissions.split(PERMISSION_DELIMETER)) {
if (permission != null && hasPermissions(authorities, permission)) {
return true;
}
}
return false;
}
/**
* 判断用户是否拥有某个角色
*
* @param role 角色字符串
* @return 用户是否具备某角色
*/
public boolean hasRole(String role) {<FILL_FUNCTION_BODY>}
/**
* 验证用户是否不具备某角色,与 isRole逻辑相反。
*
* @param role 角色名称
* @return 用户是否不具备某角色
*/
public boolean lacksRole(String role) {
return hasRole(role) != true;
}
/**
* 验证用户是否具有以下任意一个角色
*
* @param roles 以 ROLE_NAMES_DELIMETER 为分隔符的角色列表
* @return 用户是否具有以下任意一个角色
*/
public boolean hasAnyRoles(String roles) {
if (StringUtils.isEmpty(roles)) {
return false;
}
LoginUser loginUser = SecurityUtils.getLoginUser();
if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles())) {
return false;
}
for (String role : roles.split(ROLE_DELIMETER)) {
if (hasRole(role)) {
return true;
}
}
return false;
}
/**
* 判断是否包含权限
*
* @param permissions 权限列表
* @param permission 权限字符串
* @return 用户是否具备某权限
*/
private boolean hasPermissions(Set<String> permissions, String permission) {
return permissions.contains(ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission));
}
}
|
if (StringUtils.isEmpty(role)) {
return false;
}
LoginUser loginUser = SecurityUtils.getLoginUser();
if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles())) {
return false;
}
for (SysRoleEntity sysRole : loginUser.getUser().getRoles()) {
String roleKey = sysRole.getRoleKey();
if (SUPER_ADMIN.equals(roleKey) || roleKey.equals(StringUtils.trim(role))) {
return true;
}
}
return false;
| 1,719
| 156
| 1,875
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/web/service/SysLoginService.java
|
SysLoginService
|
login
|
class SysLoginService {
@Autowired
private TokenService tokenService;
@Resource
private AuthenticationManager authenticationManager;
@Autowired
private RedisCache redisCache;
@Autowired
private SysUserService userService;
@Autowired
private SysConfigService configService;
/**
* 登录验证
*
* @param username 用户名
* @param password 密码
* @param code 验证码
* @param uuid 唯一标识
* @return 结果
*/
public String login(String username, String password, String code, String uuid) {<FILL_FUNCTION_BODY>}
/**
* 校验验证码
*
* @param username 用户名
* @param code 验证码
* @param uuid 唯一标识
* @return 结果
*/
public void validateCaptcha(String username, String code, String uuid) {
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
String captcha = redisCache.getCacheObject(verifyKey);
redisCache.deleteObject(verifyKey);
if (captcha == null) {
// AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
throw new ServiceException("验证码失效");
}
if (!code.equalsIgnoreCase(captcha)) {
// AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
throw new ServiceException("验证码错误");
}
}
/**
* 记录登录信息
*
* @param userId 用户ID
*/
public void recordLoginInfo(Long userId) {
SysUserEntity sysUser = new SysUserEntity();
sysUser.setUserId(userId);
sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
sysUser.setLoginDate(DateUtil.date());
userService.updateUserProfile(sysUser);
}
}
|
boolean captchaEnabled = configService.selectCaptchaEnabled();
// 验证码开关
if (captchaEnabled) {
validateCaptcha(username, code, uuid);
}
// 用户验证
Authentication authentication = null;
try {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
AuthenticationContextHolder.setContext(authenticationToken);
// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
authentication = authenticationManager.authenticate(authenticationToken);
} catch (Exception e) {
if (e instanceof BadCredentialsException) {
//异步执行->保存登录信息
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, null, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new ServiceException("账号或密码错误");
} else {
//异步执行->登录信息
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, null, Constants.LOGIN_FAIL, e.getMessage()));
e.printStackTrace();
throw new ServiceException(e.getMessage());
}
} finally {
AuthenticationContextHolder.clearContext();
}
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//异步记录登录成功日志
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, loginUser.getUserId(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
// 额外设置到 request 中,有的过滤器在 Spring Security 之前
WebFrameworkUtils.setLoginUserId(ServletUtils.getRequest(), loginUser.getUserId());
//记录登录信息
recordLoginInfo(loginUser.getUserId());
// 生成token
return tokenService.createToken(loginUser);
| 593
| 488
| 1,081
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/web/service/SysPasswordService.java
|
SysPasswordService
|
validate
|
class SysPasswordService {
@Autowired
private RedisCache redisCache;
@Value(value = "${user.password.maxRetryCount}")
private int maxRetryCount;
@Value(value = "${user.password.lockTime}")
private int lockTime;
/**
* 登录账户密码错误次数缓存键名
*
* @param username 用户名
* @return 缓存键key
*/
private String getCacheKey(String username) {
return CacheConstants.PWD_ERR_CNT_KEY + username;
}
public void validate(SysUserEntity user) {<FILL_FUNCTION_BODY>}
public boolean matches(SysUserEntity user, String rawPassword) {
return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
}
public void clearLoginRecordCache(String loginName) {
if (redisCache.hasKey(getCacheKey(loginName))) {
redisCache.deleteObject(getCacheKey(loginName));
}
}
}
|
Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
String username = usernamePasswordAuthenticationToken.getName();
String password = usernamePasswordAuthenticationToken.getCredentials().toString();
Integer retryCount = redisCache.getCacheObject(getCacheKey(username));
if (retryCount == null) {
retryCount = 0;
}
if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, null, Constants.LOGIN_FAIL,
MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime)));
throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
}
if (!matches(user, password)) {
retryCount = retryCount + 1;
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, null, Constants.LOGIN_FAIL,
MessageUtils.message("user.password.retry.limit.count", retryCount)));
redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
throw new UserPasswordNotMatchException();
} else {
clearLoginRecordCache(username);
}
| 280
| 333
| 613
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/web/service/SysPermissionService.java
|
SysPermissionService
|
getRolePermission
|
class SysPermissionService {
@Autowired
private SysRoleService roleService;
@Autowired
private SysMenuService menuService;
@Autowired
private SysResourceService resourceService;
@Autowired
private SysUserService userService;
@Autowired
private TokenService tokenService;
@Autowired
private RedisCache redisCache;
/**
* 获取角色数据权限
*
* @param user 用户信息
* @return 角色权限信息
*/
public Set<String> getRolePermission(SysUserEntity user) {<FILL_FUNCTION_BODY>}
/**
* 获取菜单数据权限
*
* @param user 用户信息
* @return 菜单权限信息
*/
public Set<String> getMenuPermission(SysUserEntity user) {
Set<String> perms = new HashSet<String>();
// 管理员拥有所有权限
if (user.isAdmin()) {
perms.add("*:*:*");
} else {
List<SysRoleEntity> roles = user.getRoles();
if (!roles.isEmpty() && roles.size() > 1) {
// 多角色设置permissions属性,以便数据权限匹配权限
for (SysRoleEntity role : roles) {
Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
role.setPermissions(rolePerms);
perms.addAll(rolePerms);
}
} else {
perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
}
}
return perms;
}
/**
* 获取菜单数据权限
*
* @param roleID 角色id
* @return 菜单权限信息
*/
public Set<String> getMenuPermissionByRoleId(Long roleID) {
Set<String> perms = new HashSet<String>();
// 管理员拥有所有权限
if (roleID == 1) {
perms.add("*:*:*");
} else {
perms = menuService.selectMenuPermsByRoleId(roleID);
}
return perms;
}
/**
* 获取接口资源数据权限
*
* @param user 用户信息
* @return 资源信息
*/
public Set<String> getResources(SysUserEntity user) {
Set<String> res = new HashSet<String>();
// 超级管理员拥有所有权限
if (user.isAdmin()) {
res.add("*:*:*");
} else {
List<SysRoleEntity> roles = user.getRoles();
if (roles != null && !roles.isEmpty()) {
for (SysRoleEntity role : roles) {
Set<String> code = resourceService.selectResourceCodeByRoleId(role.getRoleId());
res.addAll(code);
}
}
}
return res;
}
/**
* 重置登录用户的权限缓存
*
* @param roleId 角色id
*/
public void resetLoginUserRoleCache(long roleId) {
// Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_USER_KEY + "*");
SysUserEntity user = new SysUserEntity();
user.setRoleId(roleId);
List<SysUserEntity> sysUserEntities = userService.selectAllocatedList(user).getRecords();
sysUserEntities.forEach(u -> resetUserRoleAuthCache(u.getUserId()));
}
/**
* 重置redis里用户权限的缓存
*
* @param userId 用户id
*/
public void resetUserRoleAuthCache(long userId) {
LoginUser loginUser = tokenService.getLoginUserByUserId(userId);
if (loginUser != null) {
loginUser.setPermissions(getMenuPermission(loginUser.getUser()));
loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
loginUser.setResources(getResources(loginUser.getUser()));
tokenService.setLoginUser(loginUser);
}
}
}
|
Set<String> roles = new HashSet<String>();
// 管理员拥有所有权限
if (user.isAdmin()) {
roles.add("admin");
} else {
roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
}
return roles;
| 1,127
| 82
| 1,209
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/web/service/SysRegisterService.java
|
SysRegisterService
|
validateCaptcha
|
class SysRegisterService {
@Autowired
private SysUserService userService;
@Autowired
private SysConfigService configService;
@Autowired
private RedisCache redisCache;
/**
* 注册
*/
public String register(RegisterBody registerBody) {
String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
SysUserEntity sysUser = new SysUserEntity();
sysUser.setUserName(username);
// 验证码开关
boolean captchaEnabled = configService.selectCaptchaEnabled();
if (captchaEnabled) {
validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
}
if (StringUtils.isEmpty(username)) {
msg = "用户名不能为空";
} else if (StringUtils.isEmpty(password)) {
msg = "用户密码不能为空";
} else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
|| username.length() > UserConstants.USERNAME_MAX_LENGTH) {
msg = "账户长度必须在2到20个字符之间";
} else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
|| password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
msg = "密码长度必须在5到20个字符之间";
} else if (!(userService.checkUserNameUnique(sysUser))) {
msg = "保存用户'" + username + "'失败,注册账号已存在";
} else {
sysUser.setNickName(username);
sysUser.setPassword(SecurityUtils.encryptPassword(password));
boolean regFlag = userService.registerUser(sysUser);
if (!regFlag) {
msg = "注册失败,请联系系统管理人员";
} else {
//注册失败异步记录信息
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, null, Constants.REGISTER, MessageUtils.message("user.register.success")));
}
}
return msg;
}
/**
* 校验验证码
*
* @param username 用户名
* @param code 验证码
* @param uuid 唯一标识
* @return 结果
*/
public void validateCaptcha(String username, String code, String uuid) {<FILL_FUNCTION_BODY>}
}
|
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
String captcha = redisCache.getCacheObject(verifyKey);
redisCache.deleteObject(verifyKey);
if (captcha == null) {
throw new CaptchaExpireException();
}
if (!code.equalsIgnoreCase(captcha)) {
throw new CaptchaException();
}
| 634
| 112
| 746
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/web/service/TokenService.java
|
TokenService
|
refreshToken
|
class TokenService {
// 令牌自定义标识
@Value("${token.header}")
private String header;
// 令牌秘钥
@Value("${token.secret}")
private String secret;
// 令牌有效期(默认30分钟)
@Value("${token.expireTime}")
private int expireTime;
protected static final long MILLIS_SECOND = 1000;
protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;
@Autowired
private RedisCache redisCache;
/**
* 获取用户身份信息
*
* @return 用户信息
*/
public LoginUser getLoginUser(HttpServletRequest request) {
LoginUserToken loginUserToken = getLoginUserToken(request);
if (StringUtils.isNotNull(loginUserToken)) {
LoginUser user = redisCache.getCacheObject(getLoginKey(loginUserToken.getUserId()));
return user;
}
return null;
}
/**
* 获取用户身份信息
*
* @return 用户信息
*/
public LoginUserToken getLoginUserToken(HttpServletRequest request) {
// 获取请求携带的令牌
String token = getToken(request);
if (StringUtils.isNotEmpty(token)) {
try {
Claims claims = parseToken(token);
// 解析对应的权限以及用户信息
String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
String userKey = getTokenKey(uuid);
//获取用户id
LoginUserToken loginUserToken = redisCache.getCacheObject(userKey);
return loginUserToken;
} catch (Exception e) {
}
}
return null;
}
/**
* 获取用户身份信息
*
* @return 用户信息
*/
public LoginUser getLoginUserByUserId(long userId) {
String loginKey = getLoginKey(userId);
if (redisCache.hasKey(loginKey)) {
try {
LoginUser user = redisCache.getCacheObject(getLoginKey(userId));
return user;
} catch (Exception e) {
}
}
return null;
}
/**
* 设置用户身份信息
*/
public void setLoginUser(LoginUser loginUser) {
if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
refreshToken(loginUser);
}
}
/**
* 删除用户身份信息
*/
public void delLoginUser(String token) {
if (StringUtils.isNotEmpty(token)) {
String userKey = getTokenKey(token);
redisCache.deleteObject(userKey);
}
}
/**
* 创建令牌
*
* @param loginUser 用户信息
* @return 令牌
*/
public String createToken(LoginUser loginUser) {
String token = IdUtils.fastUUID();
loginUser.setToken(token);
//设置登录信息
LoginUserToken loginUserToken = new LoginUserToken(loginUser);
setUserAgent(loginUserToken);
refreshToken(loginUser, loginUserToken);
Map<String, Object> claims = new HashMap<>();
claims.put(Constants.LOGIN_USER_KEY, token);
return createToken(claims);
}
/**
* 验证令牌有效期,相差不足20分钟,自动刷新缓存
*
* @param loginUser
* @return 令牌
*/
public void verifyToken(LoginUser loginUser) {
long expireTime = loginUser.getExpireTime();
long currentTime = System.currentTimeMillis();
if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
refreshToken(loginUser);
}
}
/**
* 刷新令牌有效期
*
* @param loginUser 登录信息
*/
public void refreshToken(LoginUser loginUser) {<FILL_FUNCTION_BODY>}
/**
* 刷新令牌有效期
*
* @param loginUser 登录信息
*/
public void refreshToken(LoginUser loginUser, LoginUserToken loginUserToken) {
loginUserToken.setLoginTime(System.currentTimeMillis());
loginUser.setExpireTime(loginUserToken.getLoginTime() + expireTime * MILLIS_MINUTE);
loginUserToken.setExpireTime(loginUserToken.getLoginTime() + expireTime * MILLIS_MINUTE);
// 根据uuid将loginUser登录的缓存
String userKey = getTokenKey(loginUser.getToken());
redisCache.setCacheObject(userKey, loginUserToken, expireTime, TimeUnit.MINUTES);
//设置loginUser缓存
redisCache.setCacheObject(getLoginKey(loginUser.getUserId()), loginUser, expireTime, TimeUnit.MINUTES);
}
/**
* 设置用户代理信息
*
* @param loginUserToken 登录信息
*/
public void setUserAgent(LoginUserToken loginUserToken) {
UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
loginUserToken.setIpaddr(ip);
loginUserToken.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
loginUserToken.setBrowser(userAgent.getBrowser().getName());
loginUserToken.setOs(userAgent.getOperatingSystem().getName());
}
/**
* 从数据声明生成令牌
*
* @param claims 数据声明
* @return 令牌
*/
private String createToken(Map<String, Object> claims) {
String token = Jwts.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.HS512, secret).compact();
return token;
}
/**
* 从令牌中获取数据声明
*
* @param token 令牌
* @return 数据声明
*/
private Claims parseToken(String token) {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}
/**
* 从令牌中获取用户名
*
* @param token 令牌
* @return 用户名
*/
public String getUsernameFromToken(String token) {
Claims claims = parseToken(token);
return claims.getSubject();
}
/**
* 获取请求token
*
* @param request
* @return token
*/
private String getToken(HttpServletRequest request) {
String token = request.getHeader(header);
if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
token = token.replace(Constants.TOKEN_PREFIX, "");
}
return token;
}
private String getTokenKey(String uuid) {
return CacheConstants.LOGIN_TOKEN_KEY + uuid;
}
private String getLoginKey(Long userId) {
return CacheConstants.LOGIN_USER_KEY + userId;
}
}
|
String userKey = getTokenKey(loginUser.getToken());
LoginUserToken loginUserToken = redisCache.getCacheObject(userKey);
refreshToken(loginUser, loginUserToken);
| 1,969
| 51
| 2,020
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-framework/src/main/java/com/oddfar/campus/framework/web/service/UserDetailsServiceImpl.java
|
UserDetailsServiceImpl
|
loadUserByUsername
|
class UserDetailsServiceImpl implements UserDetailsService {
private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
@Autowired
private SysUserService userService;
@Autowired
private SysPasswordService passwordService;
@Autowired
private SysPermissionService permissionService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<FILL_FUNCTION_BODY>}
public UserDetails createLoginUser(SysUserEntity user) {
return new LoginUser(user.getUserId(), user,
permissionService.getMenuPermission(user), permissionService.getResources(user));
}
}
|
SysUserEntity user = userService.selectUserByUserName(username);
if (StringUtils.isNull(user)) {
log.info("登录用户:{} 不存在.", username);
throw new UserPasswordNotMatchException();
} else if (UserStatusEnum.DELETED.getCode().equals(user.getStatus())) {
log.info("登录用户:{} 已被删除.", username);
throw new ServiceException("对不起,您的账号:" + username + " 已被删除");
} else if (UserStatusEnum.DISABLE.getCode().equals(user.getStatus())) {
log.info("登录用户:{} 已被停用.", username);
throw new ServiceException("对不起,您的账号:" + username + " 已停用");
}
passwordService.validate(user);
return createLoginUser(user);
| 178
| 226
| 404
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-modular/src/main/java/com/oddfar/campus/business/api/PushPlusApi.java
|
PushPlusApi
|
run
|
class PushPlusApi {
public static void sendNotice(IUser iUser, ILog operLog) {
String token = iUser.getPushPlusToken();
if (StringUtils.isEmpty(token)) {
return;
}
String title, content;
if (operLog.getStatus() == 0) {
//预约成功
title = iUser.getRemark() + "-i茅台执行成功";
content = iUser.getMobile() + System.lineSeparator() + operLog.getLogContent();
AsyncManager.me().execute(sendNotice(token, title, content, "txt"));
} else {
//预约失败
title = iUser.getRemark() + "-i茅台执行失败";
content = iUser.getMobile() + System.lineSeparator() + operLog.getLogContent();
AsyncManager.me().execute(sendNotice(token, title, content, "txt"));
}
}
/**
* push推送
*
* @param token token
* @param title 消息标题
* @param content 具体消息内容
* @param template 发送消息模板
*/
public static TimerTask sendNotice(String token, String title, String content, String template) {
return new TimerTask() {
@Override
public void run() {<FILL_FUNCTION_BODY>}
};
}
}
|
String url = "http://www.pushplus.plus/send";
Map<String, Object> map = new HashMap<>();
map.put("token", token);
map.put("title", title);
map.put("content", content);
if (StringUtils.isEmpty(template)) {
map.put("template", "html");
}
HttpUtil.post(url, map);
| 363
| 102
| 465
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-modular/src/main/java/com/oddfar/campus/business/controller/IUserController.java
|
IUserController
|
edit
|
class IUserController {
private final IUserService iUserService;
private final IUserMapper iUserMapper;
private final IMTService imtService;
private final IShopService iShopService;
/**
* 查询I茅台用户列表
*/
@GetMapping(value = "/list", name = "查询I茅台用户列表")
@PreAuthorize("@ss.resourceAuth()")
public R list(IUser iUser) {
PageResult<IUser> page = iUserService.page(iUser);
return R.ok().put(page);
}
/**
* 发送验证码
*/
@GetMapping(value = "/sendCode", name = "发送验证码")
@PreAuthorize("@ss.resourceAuth()")
public R sendCode(String mobile, String deviceId) {
imtService.sendCode(mobile, deviceId);
return R.ok();
}
/**
* 预约
*/
@GetMapping(value = "/reservation", name = "预约")
@PreAuthorize("@ss.resourceAuth()")
public R reservation(String mobile) {
IUser user = iUserMapper.selectById(mobile);
if (user == null) {
return R.error("用户不存在");
}
if (StringUtils.isEmpty(user.getItemCode())) {
return R.error("商品预约code为空");
}
imtService.reservation(user);
return R.ok();
}
/**
* 小茅运旅行活动
*/
@GetMapping(value = "/travelReward", name = "旅行")
@PreAuthorize("@ss.resourceAuth()")
public R travelReward(String mobile) {
IUser user = iUserMapper.selectById(mobile);
if (user == null) {
return R.error("用户不存在");
} else {
imtService.getTravelReward(user);
return R.ok();
}
}
/**
* 登录
*/
@GetMapping(value = "/login", name = "登录")
@PreAuthorize("@ss.resourceAuth()")
public R login(String mobile, String code, String deviceId) {
imtService.login(mobile, code, deviceId);
return R.ok();
}
/**
* 获取I茅台用户详细信息
*/
@PreAuthorize("@ss.resourceAuth()")
@GetMapping(value = "/{mobile}", name = "获取I茅台用户详细信息")
public R getInfo(@PathVariable("mobile") Long mobile) {
return R.ok(iUserMapper.selectById(mobile));
}
/**
* 新增I茅台用户
*/
@PreAuthorize("@ss.resourceAuth()")
@PostMapping(name = "新增I茅台用户")
public R add(@RequestBody IUser iUser) {
IShop iShop = iShopService.selectByIShopId(iUser.getIshopId());
if (iShop == null) {
throw new ServiceException("门店商品id不存在");
}
iUser.setLng(iShop.getLng());
iUser.setLat(iShop.getLat());
iUser.setProvinceName(iShop.getProvinceName());
iUser.setCityName(iShop.getCityName());
return R.ok(iUserService.insertIUser(iUser));
}
/**
* 修改I茅台用户
*/
@PreAuthorize("@ss.resourceAuth()")
@PutMapping(name = "修改I茅台用户")
public R edit(@RequestBody IUser iUser) {<FILL_FUNCTION_BODY>}
/**
* 删除I茅台用户
*/
@PreAuthorize("@ss.resourceAuth()")
@DeleteMapping(value = "/{mobiles}", name = "删除I茅台用户")
public R remove(@PathVariable Long[] mobiles) {
return R.ok(iUserMapper.deleteIUser(mobiles));
}
}
|
IShop iShop = iShopService.selectByIShopId(iUser.getIshopId());
if (iShop == null) {
throw new ServiceException("门店商品id不存在");
}
iUser.setLng(iShop.getLng());
iUser.setLat(iShop.getLat());
iUser.setProvinceName(iShop.getProvinceName());
iUser.setCityName(iShop.getCityName());
return R.ok(iUserService.updateIUser(iUser));
| 1,076
| 137
| 1,213
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-modular/src/main/java/com/oddfar/campus/business/domain/IUserRequest.java
|
IUserRequest
|
getParams
|
class IUserRequest {
private static final long serialVersionUID = 1L;
/**
* 手机号
*/
private Long mobile;
/**
* 用户ID
*/
private Long userId;
/**
* token
*/
private String token;
/**
* cookie
*/
private String cookie;
/**
* 设备id
*/
private String deviceId;
/**
* 商品预约code,用@间隔
*/
private String itemCode;
/**
* 完整地址
*/
private String address;
/**
* 预约的分钟(1-59)
*/
private int minute;
/**
* 随机分钟预约,9点取一个时间(0:随机,1:不随机)
*/
private String randomMinute;
/**
* 类型
*/
private int shopType;
/**
* 门店商品ID
*/
private String ishopId;
/**
* push_plus_token
*/
private String pushPlusToken;
/**
* 备注
*/
private String remark;
/**
* token过期时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date expireTime;
@TableField(exist = false)
private Map<String, Object> params;
public Map<String, Object> getParams() {<FILL_FUNCTION_BODY>}
public int getMinute() {
if (minute > 59 || minute < 1) {
this.minute = 5;
}
return minute;
}
}
|
if (params == null) {
params = new HashMap<>();
}
return params;
| 461
| 29
| 490
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-modular/src/main/java/com/oddfar/campus/business/entity/ILog.java
|
ILog
|
getParams
|
class ILog {
private static final long serialVersionUID = 1L;
private static final Integer PAGE_NUM = 1;
private static final Integer PAGE_SIZE = 10;
/**
* 日志主键
*/
@TableId("log_id")
private Long logId;
/**
* 日志记录内容
*/
private String logContent;
/**
* 操作人员手机号
*/
private Long mobile;
/**
* 操作状态(0正常 1异常)
*/
private Integer status;
/**
* 操作时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date operTime;
/**
* 上级人
*/
private Long createUser;
@TableField(exist = false)
private Map<String, Object> params;
public Map<String, Object> getParams() {<FILL_FUNCTION_BODY>}
@NotNull(message = "页码不能为空")
@Min(value = 1, message = "页码最小值为 1")
@TableField(exist = false)
@JsonIgnore
private Integer pageNum = PAGE_NUM;
@NotNull(message = "每页条数不能为空")
@Min(value = 1, message = "每页条数最小值为 1")
@Max(value = 100, message = "每页条数最大值为 100")
@TableField(exist = false)
@JsonIgnore
private Integer pageSize = PAGE_SIZE;
}
|
if (params == null) {
params = new HashMap<>();
}
return params;
| 428
| 29
| 457
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-modular/src/main/java/com/oddfar/campus/business/entity/IShop.java
|
IShop
|
getParams
|
class IShop {
private static final long serialVersionUID = 1L;
/**
* ID
*/
@TableId
private Long shopId;
/**
* 商品ID
*/
private String iShopId;
/**
* 省份
*/
private String provinceName;
/**
* 城市
*/
private String cityName;
/**
* 地区
*/
private String districtName;
/**
* 完整地址
*/
private String fullAddress;
/**
* 纬度
*/
private String lat;
/**
* 经度
*/
private String lng;
/**
* 名称
*/
private String name;
/**
* 公司名称
*/
private String tenantName;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@TableField(exist = false)
private Map<String, Object> params;
/**
* 距离
*/
@TableField(exist = false)
private Double distance;
public IShop() {
}
public IShop(String iShopId, JSONObject jsonObject) {
this.iShopId = iShopId;
this.provinceName = jsonObject.getString("provinceName");
this.cityName = jsonObject.getString("cityName");
this.districtName = jsonObject.getString("districtName");
this.fullAddress = jsonObject.getString("fullAddress");
this.lat = jsonObject.getString("lat");
this.lng = jsonObject.getString("lng");
this.name = jsonObject.getString("name");
this.tenantName = jsonObject.getString("tenantName");
this.createTime = new Date();
}
public Map<String, Object> getParams() {<FILL_FUNCTION_BODY>}
}
|
if (params == null) {
params = new HashMap<>();
}
return params;
| 516
| 29
| 545
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-modular/src/main/java/com/oddfar/campus/business/entity/IUser.java
|
IUser
|
getParams
|
class IUser extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 手机号
*/
@TableId
private Long mobile;
/**
* 用户ID
*/
private Long userId;
/**
* token
*/
private String token;
/**
* cookie
*/
private String cookie;
/**
* 设备id
*/
private String deviceId;
/**
* 商品预约code,用@间隔
*/
private String itemCode;
/**
* 门店商品ID
*/
private String ishopId;
/**
* 省份
*/
private String provinceName;
/**
* 城市
*/
private String cityName;
/**
* 完整地址
*/
private String address;
/**
* 纬度
*/
private String lat;
/**
* 经度
*/
private String lng;
/**
* 预约的分钟(1-59)
*/
private int minute;
/**
* 随机分钟预约,9点取一个时间(0:随机,1:不随机)
*/
private String randomMinute;
/**
* 类型(1:预约本市出货量最大的门店,2:预约你的位置附近门店)
*/
private int shopType;
/**
* push_plus_token
*/
private String pushPlusToken;
/**
* 返回参数
*/
@JsonIgnore
private String jsonResult;
/**
* 备注
*/
private String remark;
/**
* token过期时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date expireTime;
@TableField(exist = false)
private Map<String, Object> params;
public IUser() {
}
public IUser(Long mobile, JSONObject jsonObject) {
JSONObject data = jsonObject.getJSONObject("data");
this.userId = data.getLong("userId");
this.mobile = mobile;
this.token = data.getString("token");
this.cookie = data.getString("cookie");
this.jsonResult = StringUtils.substring(jsonObject.toJSONString(), 0, 2000);
// if (StringUtils.isEmpty(this.remark)) {
// this.remark = data.getString("userName");
// }
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 30);
Date thirtyDaysLater = calendar.getTime();
this.expireTime = thirtyDaysLater;
}
public IUser(Long mobile, String deviceId, JSONObject jsonObject) {
JSONObject data = jsonObject.getJSONObject("data");
this.userId = data.getLong("userId");
this.mobile = mobile;
this.token = data.getString("token");
this.cookie = data.getString("cookie");
this.deviceId = deviceId.toLowerCase();
this.jsonResult = StringUtils.substring(jsonObject.toJSONString(), 0, 2000);
if (StringUtils.isEmpty(this.remark)) {
this.remark = data.getString("userName");
}
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 30);
Date thirtyDaysLater = calendar.getTime();
this.expireTime = thirtyDaysLater;
}
public Map<String, Object> getParams() {<FILL_FUNCTION_BODY>}
public int getMinute() {
if (minute > 59 || minute < 1) {
this.minute = 5;
}
return minute;
}
}
|
if (params == null) {
params = new HashMap<>();
}
return params;
| 1,035
| 29
| 1,064
|
<methods>public non-sealed void <init>() <variables>private java.util.Date createTime,private java.lang.Long createUser,private java.lang.Integer delFlag,private Map<java.lang.String,java.lang.Object> params,private static final long serialVersionUID,private java.util.Date updateTime,private java.lang.Long updateUser
|
oddfar_campus-imaotai
|
campus-imaotai/campus-modular/src/main/java/com/oddfar/campus/business/service/IMTLogFactory.java
|
IMTLogFactory
|
reservation
|
class IMTLogFactory {
public static void reservation(IUser iUser, String logContent) {<FILL_FUNCTION_BODY>}
/**
* 操作日志记录
*
* @param operLog 操作日志信息
* @return 任务task
*/
public static TimerTask recordOper(final ILog operLog) {
return new TimerTask() {
@Override
public void run() {
SpringUtils.getBean(IMTLogService.class).insertLog(operLog);
}
};
}
}
|
//{"code":2000,"data":{"successDesc":"申购完成,请于7月6日18:00查看预约申购结果","reservationList":[{"reservationId":17053404357,"sessionId":678,"shopId":"233331084001","reservationTime":1688608601720,"itemId":"10214","count":1}],"reservationDetail":{"desc":"申购成功后将以短信形式通知您,请您在申购成功次日18:00前确认支付方式,并在7天内完成提货。","lotteryTime":1688637600000,"cacheValidTime":1688637600000}}}
ILog operLog = new ILog();
operLog.setOperTime(new Date());
if (logContent.contains("报错")) {
//失败
operLog.setStatus(1);
} else {
operLog.setStatus(0);
}
operLog.setMobile(iUser.getMobile());
operLog.setCreateUser(iUser.getCreateUser());
operLog.setLogContent(logContent);
AsyncManager.me().execute(recordOper(operLog));
//推送
PushPlusApi.sendNotice(iUser, operLog);
| 148
| 351
| 499
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-modular/src/main/java/com/oddfar/campus/business/service/impl/IMTLogServiceImpl.java
|
IMTLogServiceImpl
|
page
|
class IMTLogServiceImpl implements IMTLogService {
@Autowired
private ILogMapper logMapper;
@Override
public PageResult<ILog> page(ILog iLog) {<FILL_FUNCTION_BODY>}
@Override
public int deleteLogByIds(Long[] operIds) {
return logMapper.deleteBatchIds(Arrays.asList(operIds));
}
@Override
public void cleanLog() {
logMapper.cleanLog();
}
@Override
public int insertLog(ILog iLog) {
return logMapper.insert(iLog);
}
}
|
Long userId = SecurityUtils.getUserId();
if (userId != 1) {
return logMapper.selectPage(iLog, userId);
}
return logMapper.selectPage(iLog);
| 164
| 57
| 221
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-modular/src/main/java/com/oddfar/campus/business/service/impl/IUserServiceImpl.java
|
IUserServiceImpl
|
insertIUser
|
class IUserServiceImpl implements IUserService {
@Autowired
private IUserMapper iUserMapper;
@Override
public PageResult<IUser> page(IUser iUser) {
Long userId = SecurityUtils.getUserId();
if (userId != 1) {
return iUserMapper.selectPage(iUser, userId);
}
return iUserMapper.selectPage(iUser);
}
@Override
public int insertIUser(Long mobile, String deviceId, JSONObject jsonObject) {
JSONObject data = jsonObject.getJSONObject("data");
IUser user = iUserMapper.selectById(mobile);
if (user != null) {
//存在则更新
IUser iUser = new IUser(mobile, jsonObject);
iUser.setCreateUser(SecurityUtils.getUserId());
BeanUtil.copyProperties(iUser, user, "shopType", "minute");
return iUserMapper.updateById(user);
} else {
if (StringUtils.isEmpty(deviceId)) {
deviceId = UUID.randomUUID().toString().toLowerCase();
}
IUser iUser = new IUser(mobile, deviceId, jsonObject);
iUser.setCreateUser(SecurityUtils.getUserId());
return iUserMapper.insert(iUser);
}
}
@Override
public List<IUser> selectReservationUser() {
return iUserMapper.selectReservationUser();
}
@Override
public List<IUser> selectReservationUserByMinute(int minute) {
return iUserMapper.selectReservationUserByMinute(minute);
}
@Override
public int insertIUser(IUser iUser) {<FILL_FUNCTION_BODY>}
@Override
public int updateIUser(IUser iUser) {
if (SecurityUtils.getUserId() != 1 && !iUser.getCreateUser().equals(SecurityUtils.getUserId())) {
throw new ServiceException("只能修改自己创建的用户");
}
return iUserMapper.updateById(iUser);
}
@Override
@Async
public void updateUserMinuteBatch() {
Long userCount = iUserMapper.selectCount();
if (userCount > 60) {
iUserMapper.updateUserMinuteEven();
}else {
iUserMapper.updateUserMinuteBatch();
}
}
@Override
public int deleteIUser(Long[] iUserId) {
return iUserMapper.deleteIUser(iUserId);
}
}
|
IUser user = iUserMapper.selectById(iUser.getMobile());
if (user != null) {
throw new ServiceException("禁止重复添加");
}
if (StringUtils.isEmpty(iUser.getDeviceId())) {
iUser.setDeviceId(UUID.randomUUID().toString().toLowerCase());
}
iUser.setCreateUser(SecurityUtils.getUserId());
return iUserMapper.insert(iUser);
| 655
| 117
| 772
|
<no_super_class>
|
oddfar_campus-imaotai
|
campus-imaotai/campus-modular/src/main/java/com/oddfar/campus/business/task/CampusIMTTask.java
|
CampusIMTTask
|
refresh
|
class CampusIMTTask {
private static final Logger logger = LoggerFactory.getLogger(CampusIMTTask.class);
private final IMTService imtService;
private final IUserService iUserService;
/**
* 1:10 批量修改用户随机预约的时间
*/
@Async
@Scheduled(cron = "0 10 1 ? * * ")
public void updateUserMinuteBatch() {
iUserService.updateUserMinuteBatch();
}
/**
* 11点期间,每分钟执行一次批量获得旅行奖励
*/
@Async
@Scheduled(cron = "0 0/1 11 ? * *")
public void getTravelRewardBatch() {
imtService.getTravelRewardBatch();
}
/**
* 9点期间,每分钟执行一次
*/
@Async
@Scheduled(cron = "0 0/1 9 ? * *")
public void reservationBatchTask() {
imtService.reservationBatch();
}
@Async
@Scheduled(cron = "0 10,55 7,8 ? * * ")
public void refresh() {<FILL_FUNCTION_BODY>}
/**
* 18.05分获取申购结果
*/
@Async
@Scheduled(cron = "0 5 18 ? * * ")
public void appointmentResults() {
imtService.appointmentResults();
}
}
|
logger.info("「刷新数据」开始刷新版本号,预约item,门店shop列表 ");
try {
imtService.refreshAll();
} catch (Exception e) {
logger.info("「刷新数据执行报错」%s", e.getMessage());
}
| 404
| 79
| 483
|
<no_super_class>
|
Grt1228_chatgpt-java
|
chatgpt-java/src/main/java/com/unfbx/chatgpt/entity/chat/ChatCompletion.java
|
ChatCompletion
|
tokens
|
class ChatCompletion extends BaseChatCompletion implements Serializable {
/**
* 问题描述
*/
@NonNull
private List<Message> messages;
/**
* 获取当前参数的tokens数
*/
public long tokens() {<FILL_FUNCTION_BODY>}
}
|
if (CollectionUtil.isEmpty(this.messages) || StrUtil.isBlank(this.getModel())) {
log.warn("参数异常model:{},prompt:{}", this.getModel(), this.messages);
return 0;
}
return TikTokensUtil.tokens(this.getModel(), this.messages);
| 81
| 88
| 169
|
<methods>public non-sealed void <init>() <variables>private double frequencyPenalty,private java.lang.Object functionCall,private List<com.unfbx.chatgpt.entity.chat.Functions> functions,private Map#RAW logitBias,private java.lang.Integer maxTokens,private java.lang.String model,private java.lang.Integer n,private double presencePenalty,private com.unfbx.chatgpt.entity.chat.ResponseFormat responseFormat,private java.lang.Integer seed,private List<java.lang.String> stop,private boolean stream,private double temperature,private java.lang.Object toolChoice,private List<com.unfbx.chatgpt.entity.chat.tool.Tools> tools,private java.lang.Double topP,private java.lang.String user
|
Grt1228_chatgpt-java
|
chatgpt-java/src/main/java/com/unfbx/chatgpt/entity/completions/Completion.java
|
Completion
|
tokens
|
class Completion implements Serializable {
@NonNull
@Builder.Default
private String model = Model.DAVINCI_003.getName();
/**
* 问题描述
*/
@NonNull
private String prompt;
/**
* 完成输出后的后缀,用于格式化输出结果
*/
private String suffix;
/**
* 最大支持4096
*/
@JsonProperty("max_tokens")
@Builder.Default
private Integer maxTokens = 2048;
/**
* 使用什么取样温度,0到2之间。较高的值(如0.8)将使输出更加随机,而较低的值(如0.2)将使输出更加集中和确定。
* <p>
* We generally recommend altering this or but not both.top_p
*/
@Builder.Default
private double temperature = 0;
/**
* 使用温度采样的替代方法称为核心采样,其中模型考虑具有top_p概率质量的令牌的结果。因此,0.1 意味着只考虑包含前 10% 概率质量的代币。
* <p>
* 我们通常建议更改此设置,但不要同时更改两者。temperature
*/
@JsonProperty("top_p")
@Builder.Default
private Double topP = 1d;
/**
* 为每个提示生成的完成次数。
*/
@Builder.Default
private Integer n = 1;
@Builder.Default
private boolean stream = false;
/**
* 最大值:5
*/
private Integer logprobs;
@Builder.Default
private boolean echo = false;
private List<String> stop;
@JsonProperty("presence_penalty")
@Builder.Default
private double presencePenalty = 0;
/**
* -2.0 ~~ 2.0
*/
@JsonProperty("frequency_penalty")
@Builder.Default
private double frequencyPenalty = 0;
@JsonProperty("best_of")
@Builder.Default
private Integer bestOf = 1;
@JsonProperty("logit_bias")
private Map logitBias;
/**
* @since 1.1.2
*/
private Integer seed;
/**
* 用户唯一值,确保接口不被重复调用
*/
private String user;
/**
* 获取当前参数的tokens数
*
* @return token数量
*/
public long tokens() {<FILL_FUNCTION_BODY>}
@Getter
@AllArgsConstructor
public enum Model {
DAVINCI_003("text-davinci-003"),
DAVINCI_002("text-davinci-002"),
DAVINCI("davinci"),
;
private final String name;
}
}
|
if (StrUtil.isBlank(this.prompt) || StrUtil.isBlank(this.model)) {
log.warn("参数异常model:{},prompt:{}", this.model, this.prompt);
return 0;
}
return TikTokensUtil.tokens(this.model, this.prompt);
| 762
| 90
| 852
|
<no_super_class>
|
Grt1228_chatgpt-java
|
chatgpt-java/src/main/java/com/unfbx/chatgpt/entity/edits/Edit.java
|
Edit
|
setTemperature
|
class Edit implements Serializable {
/**
* 编辑模型,目前支持两种
*/
@NonNull
private String model;
@NonNull
private String input;
/**
* 提示说明。告知模型如何修改。
*/
@NonNull
private String instruction;
/**
* 使用什么取样温度,0到2之间。较高的值(如0.8)将使输出更加随机,而较低的值(如0.2)将使输出更加集中和确定。
*
* We generally recommend altering this or but not both.top_p
*/
@Builder.Default
private double temperature = 0;
/**
* 使用温度采样的替代方法称为核心采样,其中模型考虑具有top_p概率质量的令牌的结果。因此,0.1 意味着只考虑包含前 10% 概率质量的代币。
*
* 我们通常建议更改此设置,但不要同时更改两者。temperature
*/
@JsonProperty("top_p")
@Builder.Default
private Double topP = 1d;
/**
* 为每个提示生成的完成次数。
*/
@Builder.Default
private Integer n = 1;
public void setModel(Model model) {
this.model = model.getName();
}
public void setTemperature(double temperature) {<FILL_FUNCTION_BODY>}
public void setTopP(Double topP) {
this.topP = topP;
}
public void setN(Integer n) {
this.n = n;
}
public void setInput(String input) {
this.input = input;
}
public void setInstruction(String instruction) {
this.instruction = instruction;
}
@Getter
@AllArgsConstructor
public enum Model {
TEXT_DAVINCI_EDIT_001("text-davinci-edit-001"),
CODE_DAVINCI_EDIT_001("code-davinci-edit-001"),
;
private final String name;
}
}
|
if (temperature > 2 || temperature < 0) {
log.error("temperature参数异常,temperature属于[0,2]");
this.temperature = 2;
return;
}
this.temperature = temperature;
| 557
| 57
| 614
|
<no_super_class>
|
Grt1228_chatgpt-java
|
chatgpt-java/src/main/java/com/unfbx/chatgpt/entity/embeddings/Embedding.java
|
Embedding
|
setModel
|
class Embedding implements Serializable {
@NonNull
@Builder.Default
private String model = Model.TEXT_EMBEDDING_ADA_002.getName();
/**
* 必选项:长度不能超过:8192
*/
@NonNull
private List<String> input;
private String user;
/**
* Can be either float or base64.
* @see EncodingFormat
*/
@JsonProperty("encoding_format")
private String encodingFormat;
public void setModel(Model model) {<FILL_FUNCTION_BODY>}
public void setUser(String user) {
this.user = user;
}
@Getter
@AllArgsConstructor
public enum Model {
TEXT_EMBEDDING_ADA_002("text-embedding-ada-002"),
;
private final String name;
}
@Getter
@AllArgsConstructor
public enum EncodingFormat {
FLOAT("float"),
BASE64("base64"),
;
private final String name;
}
}
|
if (Objects.isNull(model)) {
model = Model.TEXT_EMBEDDING_ADA_002;
}
this.model = model.getName();
| 296
| 49
| 345
|
<no_super_class>
|
Grt1228_chatgpt-java
|
chatgpt-java/src/main/java/com/unfbx/chatgpt/entity/fineTune/FineTune.java
|
FineTune
|
setSuffix
|
class FineTune implements Serializable {
/**
* 上传的文件ID
*/
@NonNull
@JsonProperty("training_file")
private String trainingFile;
@JsonProperty("validation_file")
private String validationFile;
/**
* 参考
* @see FineTune.Model
*/
private String model;
@JsonProperty("n_epochs")
@Builder.Default
private Integer n_epochs = 4;
@JsonProperty("batch_size")
private Integer batchSize;
@JsonProperty("learning_rate_multiplier")
private Double learningRateMultiplier;
@JsonProperty("prompt_loss_weight")
@Builder.Default
private Double promptLossWeight = 0.01;
@JsonProperty("compute_classification_metrics")
@Builder.Default
private boolean computeClassificationMetrics = false;
@JsonProperty("classification_n_classes")
private Integer classificationNClasses;
@JsonProperty("classification_betas")
private List classificationBetas;
private String suffix;
public void setTrainingFile(String trainingFile) {
this.trainingFile = trainingFile;
}
public void setValidationFile(String validationFile) {
this.validationFile = validationFile;
}
public void setModel(String model) {
this.model = model;
}
public void setN_epochs(Integer n_epochs) {
this.n_epochs = n_epochs;
}
public void setBatchSize(Integer batchSize) {
this.batchSize = batchSize;
}
public void setLearningRateMultiplier(Double learningRateMultiplier) {
this.learningRateMultiplier = learningRateMultiplier;
}
public void setPromptLossWeight(Double promptLossWeight) {
this.promptLossWeight = promptLossWeight;
}
public void setComputeClassificationMetrics(boolean computeClassificationMetrics) {
this.computeClassificationMetrics = computeClassificationMetrics;
}
public void setClassificationNClasses(Integer classificationNClasses) {
this.classificationNClasses = classificationNClasses;
}
public void setClassificationBetas(List classificationBetas) {
this.classificationBetas = classificationBetas;
}
public void setSuffix(String suffix) {<FILL_FUNCTION_BODY>}
@Getter
@AllArgsConstructor
public enum Model {
// or a fine-tuned model created after 2022-04-21.
ADA("ada"),
BABBAGE("babbage"),
CURIE("curie"),
DAVINCI("davinci"),
;
private final String name;
}
}
|
if(Objects.nonNull(suffix) && !"".equals(suffix) && suffix.length() > 40){
log.error("后缀长度不能大于40");
throw new BaseException(CommonError.PARAM_ERROR);
}
this.suffix = suffix;
| 728
| 76
| 804
|
<no_super_class>
|
Grt1228_chatgpt-java
|
chatgpt-java/src/main/java/com/unfbx/chatgpt/entity/images/ImageEdit.java
|
ImageEdit
|
setResponseFormat
|
class ImageEdit implements Serializable {
/**
* 必选项:描述文字,最多1000字符
*/
@NonNull
private String prompt;
/**
* 为每个提示生成的完成次数。
*/
@Builder.Default
private Integer n = 1;
/**
* 256x256
* 512x512
* 1024x1024
*/
@Builder.Default
private String size = SizeEnum.size_512.getName();
@JsonProperty("response_format")
@Builder.Default
private String responseFormat = ResponseFormat.URL.getName();
private String user;
public ImageEdit setN(Integer n) {
if(n < 1){
log.warn("n最小值1");
n = 1;
}
if(n > 10){
log.warn("n最大值10");
n = 10;
}
this.n = n;
return this;
}
public ImageEdit setPrompt(String prompt) {
if(StrUtil.isEmpty(prompt)){
log.error("参数异常");
throw new BaseException(CommonError.PARAM_ERROR);
}
if(prompt.length() > 1000){
log.error("长度超过1000");
throw new BaseException(CommonError.PARAM_ERROR);
}
this.prompt = prompt;
return this;
}
public ImageEdit setSize(SizeEnum size) {
if(Objects.isNull(size)){
size = SizeEnum.size_512;
}
this.size = size.getName();
return this;
}
public ImageEdit setResponseFormat(ResponseFormat responseFormat) {<FILL_FUNCTION_BODY>}
public ImageEdit setUser(String user) {
this.user = user;
return this;
}
}
|
if(Objects.isNull(responseFormat)){
responseFormat = ResponseFormat.URL;
}
this.responseFormat = responseFormat.getName();
return this;
| 504
| 45
| 549
|
<no_super_class>
|
Grt1228_chatgpt-java
|
chatgpt-java/src/main/java/com/unfbx/chatgpt/entity/images/ImageVariations.java
|
ImageVariations
|
setSize
|
class ImageVariations implements Serializable {
/**
* 为每个提示生成的完成次数。
*/
@Builder.Default
private Integer n = 1;
/**
* 256x256
* 512x512
* 1024x1024
*/
@Builder.Default
private String size = SizeEnum.size_512.getName();
@JsonProperty("response_format")
@Builder.Default
private String responseFormat = ResponseFormat.URL.getName();
private String user;
public void setN(Integer n) {
if (n < 1) {
log.warn("n最小值1");
this.n = 1;
return;
}
if (n > 10) {
log.warn("n最大值10");
this.n = 10;
return;
}
this.n = n;
}
public void setSize(SizeEnum size) {<FILL_FUNCTION_BODY>}
public void setResponseFormat(ResponseFormat responseFormat) {
if (Objects.isNull(responseFormat)) {
responseFormat = ResponseFormat.URL;
}
this.responseFormat = responseFormat.getName();
}
public void setUser(String user) {
this.user = user;
}
}
|
if (Objects.isNull(size)) {
size = SizeEnum.size_512;
}
this.size = size.getName();
| 351
| 41
| 392
|
<no_super_class>
|
Grt1228_chatgpt-java
|
chatgpt-java/src/main/java/com/unfbx/chatgpt/entity/moderations/Moderation.java
|
Moderation
|
setInput
|
class Moderation implements Serializable {
@NonNull
private List<String> input;
@Builder.Default
private String model = Model.TEXT_MODERATION_LATEST.getName();
public void setInput(List<String> input) {<FILL_FUNCTION_BODY>}
public void setModel(Model model) {
if (Objects.isNull(model)) {
model = Model.TEXT_MODERATION_LATEST;
}
this.model = model.getName();
}
@Getter
@AllArgsConstructor
public enum Model {
TEXT_MODERATION_STABLE("text-moderation-stable"),
TEXT_MODERATION_LATEST("text-moderation-latest"),
;
private final String name;
}
}
|
if (Objects.isNull(input) || input.size() == 0) {
log.error("input不能为空");
throw new BaseException(CommonError.PARAM_ERROR);
}
this.input = input;
| 208
| 59
| 267
|
<no_super_class>
|
Grt1228_chatgpt-java
|
chatgpt-java/src/main/java/com/unfbx/chatgpt/interceptor/DynamicKeyOpenAiAuthInterceptor.java
|
DynamicKeyOpenAiAuthInterceptor
|
intercept
|
class DynamicKeyOpenAiAuthInterceptor extends OpenAiAuthInterceptor {
/**
* 账号被封了
*/
private static final String ACCOUNT_DEACTIVATED = "account_deactivated";
/**
* key不正确
*/
private static final String INVALID_API_KEY = "invalid_api_key";
/**
* 请求头处理
*
*/
public DynamicKeyOpenAiAuthInterceptor() {
this.setWarringConfig(null);
}
/**
* 构造方法
*
* @param warringConfig 所有的key都失效后的告警参数配置
*/
public DynamicKeyOpenAiAuthInterceptor(Map warringConfig) {
this.setWarringConfig(warringConfig);
}
@Override
public Response intercept(Chain chain) throws IOException {<FILL_FUNCTION_BODY>}
@Override
protected List<String> onErrorDealApiKeys(String errorKey) {
List<String> apiKey = super.getApiKey().stream().filter(e -> !errorKey.equals(e)).collect(Collectors.toList());
log.error("--------> 当前ApiKey:[{}] 失效了,移除!", errorKey);
return apiKey;
}
/**
* 所有的key都失效后,自定义预警配置
* 不配置直接return
*/
@Override
protected void noHaveActiveKeyWarring() {
log.error("--------> [告警] 没有可用的key!!!");
return;
}
@Override
public Request auth(String key, Request original) {
return super.auth(key, original);
}
}
|
String key = getKey();
Request original = chain.request();
Request request = this.auth(key, original);
Response response = chain.proceed(request);
if (!response.isSuccessful() && response.body() != null) {
String errorMsg = response.body().string();
if (response.code() == CommonError.OPENAI_AUTHENTICATION_ERROR.code()
|| response.code() == CommonError.OPENAI_LIMIT_ERROR.code()
|| response.code() == CommonError.OPENAI_SERVER_ERROR.code()) {
OpenAiResponse openAiResponse = JSONUtil.toBean(errorMsg, OpenAiResponse.class);
String errorCode = openAiResponse.getError().getCode();
log.error("--------> 请求openai异常,错误code:{}", errorCode);
log.error("--------> 请求异常:{}", errorMsg);
//账号被封或者key不正确就移除掉
if (ACCOUNT_DEACTIVATED.equals(errorCode) || INVALID_API_KEY.equals(errorCode)) {
super.setApiKey(this.onErrorDealApiKeys(key));
}
throw new BaseException(openAiResponse.getError().getMessage());
}
//非官方定义的错误code
log.error("--------> 请求异常:{}", errorMsg);
OpenAiResponse openAiResponse = JSONUtil.toBean(errorMsg, OpenAiResponse.class);
if (Objects.nonNull(openAiResponse.getError())) {
log.error(openAiResponse.getError().getMessage());
throw new BaseException(openAiResponse.getError().getMessage());
}
throw new BaseException(CommonError.RETRY_ERROR);
}
return response;
| 448
| 451
| 899
|
<methods>public non-sealed void <init>() ,public Request auth(java.lang.String, Request) ,public final java.lang.String getKey() <variables>private List<java.lang.String> apiKey,private KeyStrategyFunction<List<java.lang.String>,java.lang.String> keyStrategy,private Map#RAW warringConfig
|
Grt1228_chatgpt-java
|
chatgpt-java/src/main/java/com/unfbx/chatgpt/interceptor/OpenAiAuthInterceptor.java
|
OpenAiAuthInterceptor
|
auth
|
class OpenAiAuthInterceptor implements Interceptor {
/**
* key 集合
*/
@Getter
@Setter
private List<String> apiKey;
/**
* 自定义的key的使用策略
*/
@Getter
@Setter
private KeyStrategyFunction<List<String>, String> keyStrategy;
/**
* 预警触发参数配置,配置参数实现飞书、钉钉、企业微信、邮箱预警等功能
*/
@Getter
@Setter
private Map warringConfig;
/**
* 自定义apiKeys的处理逻辑
*
* @param errorKey 错误的key
* @return 返回值是新的apiKeys
*/
protected abstract List<String> onErrorDealApiKeys(String errorKey);
/**
* 所有的key都失效后,自定义预警配置
* 可以通过warringConfig配置参数实现飞书、钉钉、企业微信、邮箱预警等
*/
protected abstract void noHaveActiveKeyWarring();
/**
* 获取请求key
*
* @return key
*/
public final String getKey() {
if (CollectionUtil.isEmpty(apiKey)) {
this.noHaveActiveKeyWarring();
throw new BaseException(CommonError.NO_ACTIVE_API_KEYS);
}
return keyStrategy.apply(apiKey);
}
/**
* 默认的鉴权处理方法
*
* @param key api key
* @param original 源请求体
* @return 请求体
*/
public Request auth(String key, Request original) {<FILL_FUNCTION_BODY>}
}
|
return original.newBuilder()
.header(Header.AUTHORIZATION.getValue(), "Bearer " + key)
.header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue())
.method(original.method(), original.body())
.build();
| 448
| 72
| 520
|
<no_super_class>
|
Grt1228_chatgpt-java
|
chatgpt-java/src/main/java/com/unfbx/chatgpt/interceptor/OpenAiResponseInterceptor.java
|
OpenAiResponseInterceptor
|
intercept
|
class OpenAiResponseInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {<FILL_FUNCTION_BODY>}
}
|
Request original = chain.request();
Response response = chain.proceed(original);
if (!response.isSuccessful() && response.body() != null) {
if (response.code() == CommonError.OPENAI_AUTHENTICATION_ERROR.code()
|| response.code() == CommonError.OPENAI_LIMIT_ERROR.code()
|| response.code() == CommonError.OPENAI_SERVER_ERROR.code()) {
OpenAiResponse openAiResponse = JSONUtil.toBean(response.body().string(), OpenAiResponse.class);
log.error(openAiResponse.getError().getMessage());
throw new BaseException(openAiResponse.getError().getMessage());
}
String errorMsg = response.body().string();
log.error("--------> 请求异常:{}", errorMsg);
OpenAiResponse openAiResponse = JSONUtil.toBean(errorMsg, OpenAiResponse.class);
if (Objects.nonNull(openAiResponse.getError())) {
log.error(openAiResponse.getError().getMessage());
throw new BaseException(openAiResponse.getError().getMessage());
}
throw new BaseException(CommonError.RETRY_ERROR);
}
return response;
| 45
| 314
| 359
|
<no_super_class>
|
Grt1228_chatgpt-java
|
chatgpt-java/src/main/java/com/unfbx/chatgpt/plugin/PluginAbstract.java
|
PluginAbstract
|
setParameters
|
class PluginAbstract<R extends PluginParam, T> {
private Class<?> R;
private String name;
private String function;
private String description;
private List<Arg> args;
private List<String> required;
private Parameters parameters;
public PluginAbstract(Class<?> r) {
R = r;
}
public void setRequired(List<String> required) {
if (CollectionUtil.isEmpty(required)) {
this.required = this.getArgs().stream().filter(e -> e.isRequired()).map(Arg::getName).collect(Collectors.toList());
return;
}
this.required = required;
}
private void setRequired() {
if (CollectionUtil.isEmpty(required)) {
this.required = this.getArgs().stream().filter(e -> e.isRequired()).map(Arg::getName).collect(Collectors.toList());
}
}
private void setParameters() {<FILL_FUNCTION_BODY>}
public void setArgs(List<Arg> args) {
this.args = args;
setRequired();
setParameters();
}
@Data
public static class Arg {
private String name;
private String type;
private String description;
@JsonIgnore
private boolean enumDict;
@JsonProperty("enum")
private List<String> enumDictValue;
@JsonIgnore
private boolean required;
}
public abstract T func(R args);
public abstract String content(T t);
}
|
JSONObject properties = new JSONObject();
args.forEach(e -> {
JSONObject param = new JSONObject();
param.putOpt("type", e.getType());
param.putOpt("enum", e.getEnumDictValue());
param.putOpt("description", e.getDescription());
properties.putOpt(e.getName(), param);
});
this.parameters = Parameters.builder()
.type("object")
.properties(properties)
.required(this.getRequired())
.build();
| 402
| 134
| 536
|
<no_super_class>
|
Grt1228_chatgpt-java
|
chatgpt-java/src/main/java/com/unfbx/chatgpt/sse/ConsoleEventSourceListener.java
|
ConsoleEventSourceListener
|
onFailure
|
class ConsoleEventSourceListener extends EventSourceListener {
@Override
public void onOpen(EventSource eventSource, Response response) {
log.info("OpenAI建立sse连接...");
}
@Override
public void onEvent(EventSource eventSource, String id, String type, String data) {
log.info("OpenAI返回数据:{}", data);
if ("[DONE]".equals(data)) {
log.info("OpenAI返回数据结束了");
return;
}
}
@Override
public void onClosed(EventSource eventSource) {
log.info("OpenAI关闭sse连接...");
}
@SneakyThrows
@Override
public void onFailure(EventSource eventSource, Throwable t, Response response) {<FILL_FUNCTION_BODY>}
}
|
if(Objects.isNull(response)){
log.error("OpenAI sse连接异常:{}", t);
eventSource.cancel();
return;
}
ResponseBody body = response.body();
if (Objects.nonNull(body)) {
log.error("OpenAI sse连接异常data:{},异常:{}", body.string(), t);
} else {
log.error("OpenAI sse连接异常data:{},异常:{}", response, t);
}
eventSource.cancel();
| 216
| 139
| 355
|
<no_super_class>
|
Grt1228_chatgpt-java
|
chatgpt-java/src/main/java/com/unfbx/chatgpt/sse/PluginListener.java
|
PluginListener
|
onFailure
|
class PluginListener<R extends PluginParam, T> extends EventSourceListener {
/**
* openAi插件构建的参数
*/
private String arguments = "";
/**
* 获取openAi插件构建的参数
*
* @return arguments
*/
private String getArguments() {
return this.arguments;
}
private OpenAiStreamClient client;
private EventSourceListener eventSourceListener;
private PluginAbstract<R, T> plugin;
private ChatCompletion chatCompletion;
/**
* 构造方法必备四个元素
*
* @param client OpenAiStreamClient
* @param eventSourceListener 处理真实第二次sse请求的自定义监听
* @param plugin 插件信息
* @param chatCompletion 请求参数
*/
public PluginListener(OpenAiStreamClient client, EventSourceListener eventSourceListener, PluginAbstract<R, T> plugin, ChatCompletion chatCompletion) {
this.client = client;
this.eventSourceListener = eventSourceListener;
this.plugin = plugin;
this.chatCompletion = chatCompletion;
}
/**
* sse关闭后处理,第二次请求方法
*/
public void onClosedAfter() {
log.debug("构造的方法值:{}", getArguments());
R realFunctionParam = (R) JSONUtil.toBean(getArguments(), plugin.getR());
T tq = plugin.func(realFunctionParam);
FunctionCall functionCall = FunctionCall.builder()
.arguments(getArguments())
.name(plugin.getFunction())
.build();
chatCompletion.getMessages().add(Message.builder().role(Message.Role.ASSISTANT).content("function_call").functionCall(functionCall).build());
chatCompletion.getMessages().add(Message.builder().role(Message.Role.FUNCTION).name(plugin.getFunction()).content(plugin.content(tq)).build());
//设置第二次,请求的参数
chatCompletion.setFunctionCall(null);
chatCompletion.setFunctions(null);
client.streamChatCompletion(chatCompletion, eventSourceListener);
}
@Override
public final void onEvent(EventSource eventSource, String id, String type, String data) {
log.debug("插件开发返回信息收集sse监听器返回数据:{}", data);
if ("[DONE]".equals(data)) {
log.debug("插件开发返回信息收集sse监听器返回数据结束了");
return;
}
ChatCompletionResponse chatCompletionResponse = JSONUtil.toBean(data, ChatCompletionResponse.class);
if (Objects.nonNull(chatCompletionResponse.getChoices().get(0).getDelta().getFunctionCall())) {
this.arguments += chatCompletionResponse.getChoices().get(0).getDelta().getFunctionCall().getArguments();
}
}
@Override
public final void onClosed(EventSource eventSource) {
log.debug("插件开发返回信息收集sse监听器关闭连接...");
this.onClosedAfter();
}
@Override
public void onOpen(EventSource eventSource, Response response) {
log.debug("插件开发返回信息收集sse监听器建立连接...");
}
@SneakyThrows
@Override
public void onFailure(EventSource eventSource, Throwable t, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (Objects.isNull(response)) {
log.error("插件开发返回信息收集sse监听器,连接异常:{}", t);
eventSource.cancel();
return;
}
ResponseBody body = response.body();
if (Objects.nonNull(body)) {
log.error("插件开发返回信息收集sse监听器,连接异常data:{},异常:{}", body.string(), t);
} else {
log.error("插件开发返回信息收集sse监听器,连接异常data:{},异常:{}", response, t);
}
eventSource.cancel();
| 897
| 167
| 1,064
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/AnnotationClassRef.java
|
AnnotationClassRef
|
toString
|
class AnnotationClassRef extends ScanResultObject {
/** The type descriptor str. */
private String typeDescriptorStr;
/** The type signature. */
private transient TypeSignature typeSignature;
/** The class name. */
private transient String className;
/**
* Constructor.
*/
AnnotationClassRef() {
super();
}
/**
* Constructor.
*
* @param typeDescriptorStr
* the type descriptor str
*/
AnnotationClassRef(final String typeDescriptorStr) {
super();
this.typeDescriptorStr = typeDescriptorStr;
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get the name of the referenced class.
*
* @return The name of the referenced class.
*/
public String getName() {
return getClassName();
}
/**
* Get the type signature.
*
* @return The type signature of the {@code Class<?>} reference. This will be a {@link ClassRefTypeSignature}, a
* {@link BaseTypeSignature}, or an {@link ArrayTypeSignature}.
*/
private TypeSignature getTypeSignature() {
if (typeSignature == null) {
try {
// There can't be any type variables to resolve in ClassRefTypeSignature,
// BaseTypeSignature or ArrayTypeSignature, so just set definingClassName to null
typeSignature = TypeSignature.parse(typeDescriptorStr, /* definingClassName = */ null);
typeSignature.setScanResult(scanResult);
} catch (final ParseException e) {
throw new IllegalArgumentException(e);
}
}
return typeSignature;
}
/**
* Loads the referenced class, returning a {@code Class<?>} reference for the referenced class.
*
* @param ignoreExceptions
* if true, ignore exceptions and instead return null if the class could not be loaded.
* @return The {@code Class<?>} reference for the referenced class.
* @throws IllegalArgumentException
* if the class could not be loaded and ignoreExceptions was false.
*/
@Override
public Class<?> loadClass(final boolean ignoreExceptions) {
getTypeSignature();
if (typeSignature instanceof BaseTypeSignature) {
return ((BaseTypeSignature) typeSignature).getType();
} else if (typeSignature instanceof ClassRefTypeSignature) {
return typeSignature.loadClass(ignoreExceptions);
} else if (typeSignature instanceof ArrayTypeSignature) {
return typeSignature.loadClass(ignoreExceptions);
} else {
throw new IllegalArgumentException("Got unexpected type " + typeSignature.getClass().getName()
+ " for ref type signature: " + typeDescriptorStr);
}
}
/**
* Loads the referenced class, returning a {@code Class<?>} reference for the referenced class.
*
* @return The {@code Class<?>} reference for the referenced class.
* @throws IllegalArgumentException
* if the class could not be loaded.
*/
@Override
public Class<?> loadClass() {
return loadClass(/* ignoreExceptions = */ false);
}
// -------------------------------------------------------------------------------------------------------------
/* (non-Javadoc)
* @see io.github.classgraph.ScanResultObject#getClassName()
*/
@Override
protected String getClassName() {
if (className == null) {
getTypeSignature();
if (typeSignature instanceof BaseTypeSignature) {
className = ((BaseTypeSignature) typeSignature).getTypeStr();
} else if (typeSignature instanceof ClassRefTypeSignature) {
className = ((ClassRefTypeSignature) typeSignature).getFullyQualifiedClassName();
} else if (typeSignature instanceof ArrayTypeSignature) {
className = typeSignature.getClassName();
} else {
throw new IllegalArgumentException("Got unexpected type " + typeSignature.getClass().getName()
+ " for ref type signature: " + typeDescriptorStr);
}
}
return className;
}
/**
* Get the class info.
*
* @return The {@link ClassInfo} object for the referenced class, or null if the referenced class was not
* encountered during scanning (i.e. if no ClassInfo object was created for the class during scanning).
* N.B. even if this method returns null, {@link #loadClass()} may be able to load the referenced class
* by name.
*/
@Override
public ClassInfo getClassInfo() {
getTypeSignature();
return typeSignature.getClassInfo();
}
/* (non-Javadoc)
* @see io.github.classgraph.ScanResultObject#setScanResult(io.github.classgraph.ScanResult)
*/
@Override
void setScanResult(final ScanResult scanResult) {
super.setScanResult(scanResult);
if (typeSignature != null) {
typeSignature.setScanResult(scanResult);
}
}
// -------------------------------------------------------------------------------------------------------------
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return getTypeSignature().hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof AnnotationClassRef)) {
return false;
}
return getTypeSignature().equals(((AnnotationClassRef) obj).getTypeSignature());
}
@Override
protected void toString(final boolean useSimpleNames, final StringBuilder buf) {<FILL_FUNCTION_BODY>}
}
|
// More recent versions of Annotation::toString() have dropped the "class"/"interface" prefix,
// and added ".class" to the end of the class reference (which does not actually match the
// annotation source syntax...)
// String prefix = "class ";
// if (scanResult != null) {
// final ClassInfo ci = getClassInfo();
// // The JDK uses "interface" for both interfaces and annotations in Annotation::toString
// if (ci != null && ci.isInterfaceOrAnnotation()) {
// prefix = "interface ";
// }
// }
/* prefix + */
buf.append(getTypeSignature().toString(useSimpleNames)).append(".class");
| 1,440
| 180
| 1,620
|
<methods>public java.lang.String toString() ,public java.lang.String toStringWithSimpleNames() <variables>private transient io.github.classgraph.ClassInfo classInfo,protected transient Class<?> classRef,protected transient io.github.classgraph.ScanResult scanResult
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/AnnotationEnumValue.java
|
AnnotationEnumValue
|
loadClassAndReturnEnumValue
|
class AnnotationEnumValue extends ScanResultObject implements Comparable<AnnotationEnumValue> {
/** The class name. */
private String className;
/** The value name. */
private String valueName;
/** Default constructor for deserialization. */
AnnotationEnumValue() {
super();
}
/**
* Constructor.
*
* @param className
* The enum class name.
* @param constValueName
* The enum const value name.
*/
AnnotationEnumValue(final String className, final String constValueName) {
super();
this.className = className;
this.valueName = constValueName;
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get the class name.
*
* @return The name of the enum class.
*/
@Override
public String getClassName() {
return className;
}
/**
* Get the value name.
*
* @return The name of the enum const value.
*/
public String getValueName() {
return valueName;
}
/**
* Get the name.
*
* @return The fully-qualified name of the enum constant value, i.e. ({@link #getClassName()} +
* {#getValueName()}).
*/
public String getName() {
return className + "." + valueName;
}
/**
* Loads the enum class, instantiates the enum constants for the class, and returns the enum constant value
* represented by this {@link AnnotationEnumValue}.
*
* @param ignoreExceptions
* If true, ignore classloading exceptions and return null on failure.
* @return The enum constant value represented by this {@link AnnotationEnumValue}
* @throws IllegalArgumentException
* if the class could not be loaded and ignoreExceptions was false, or if the enum constant is
* invalid.
*/
public Object loadClassAndReturnEnumValue(final boolean ignoreExceptions) throws IllegalArgumentException {<FILL_FUNCTION_BODY>}
/**
* Loads the enum class, instantiates the enum constants for the class, and returns the enum constant value
* represented by this {@link AnnotationEnumValue}.
*
* @return The enum constant value represented by this {@link AnnotationEnumValue}
* @throws IllegalArgumentException
* if the class could not be loaded, or the enum constant is invalid.
*/
public Object loadClassAndReturnEnumValue() throws IllegalArgumentException {
return loadClassAndReturnEnumValue(/* ignoreExceptions = */ false);
}
// -------------------------------------------------------------------------------------------------------------
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(final AnnotationEnumValue o) {
final int diff = className.compareTo(o.className);
return diff == 0 ? valueName.compareTo(o.valueName) : diff;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof AnnotationEnumValue)) {
return false;
}
return compareTo((AnnotationEnumValue) obj) == 0;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return className.hashCode() * 11 + valueName.hashCode();
}
@Override
protected void toString(final boolean useSimpleNames, final StringBuilder buf) {
buf.append(useSimpleNames ? ClassInfo.getSimpleName(className) : className);
buf.append('.');
buf.append(valueName);
}
}
|
final Class<?> classRef = super.loadClass(ignoreExceptions);
if (classRef == null) {
if (ignoreExceptions) {
return null;
} else {
throw new IllegalArgumentException("Enum class " + className + " could not be loaded");
}
}
if (!classRef.isEnum()) {
throw new IllegalArgumentException("Class " + className + " is not an enum");
}
Field field;
try {
field = classRef.getDeclaredField(valueName);
} catch (final ReflectiveOperationException | SecurityException e) {
throw new IllegalArgumentException("Could not find enum constant " + this, e);
}
if (!field.isEnumConstant()) {
throw new IllegalArgumentException("Field " + this + " is not an enum constant");
}
try {
return field.get(null);
} catch (final ReflectiveOperationException | SecurityException e) {
throw new IllegalArgumentException("Field " + this + " is not accessible", e);
}
| 984
| 255
| 1,239
|
<methods>public java.lang.String toString() ,public java.lang.String toStringWithSimpleNames() <variables>private transient io.github.classgraph.ClassInfo classInfo,protected transient Class<?> classRef,protected transient io.github.classgraph.ScanResult scanResult
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/AnnotationInfo.java
|
AnnotationInvocationHandler
|
invoke
|
class AnnotationInvocationHandler implements InvocationHandler {
/** The annotation class. */
private final Class<? extends Annotation> annotationClass;
/** The {@link AnnotationInfo} object for this annotation. */
private final AnnotationInfo annotationInfo;
/** The annotation parameter values instantiated. */
private final Map<String, Object> annotationParameterValuesInstantiated = new HashMap<>();
/**
* Constructor.
*
* @param annotationClass
* the annotation class
* @param annotationInfo
* the annotation info
*/
AnnotationInvocationHandler(final Class<? extends Annotation> annotationClass,
final AnnotationInfo annotationInfo) {
this.annotationClass = annotationClass;
this.annotationInfo = annotationInfo;
// Instantiate the annotation parameter values (this loads and gets references for class literals,
// enum constants, etc.)
for (final AnnotationParameterValue apv : annotationInfo.getParameterValues()) {
final Object instantiatedValue = apv.instantiate(annotationInfo.getClassInfo());
if (instantiatedValue == null) {
// Annotations cannot contain null values
throw new IllegalArgumentException("Got null value for annotation parameter " + apv.getName()
+ " of annotation " + annotationInfo.name);
}
this.annotationParameterValuesInstantiated.put(apv.getName(), instantiatedValue);
}
}
/* (non-Javadoc)
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method,
* java.lang.Object[])
*/
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) {<FILL_FUNCTION_BODY>}
}
|
final String methodName = method.getName();
final Class<?>[] paramTypes = method.getParameterTypes();
if ((args == null ? 0 : args.length) != paramTypes.length) {
throw new IllegalArgumentException(
"Wrong number of arguments for " + annotationClass.getName() + "." + methodName + ": got "
+ (args == null ? 0 : args.length) + ", expected " + paramTypes.length);
}
if (args != null && paramTypes.length == 1) {
if ("equals".equals(methodName) && paramTypes[0] == Object.class) {
// equals() needs to function the same as the JDK implementation
// (see src/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java in the JDK)
if (this == args[0]) {
return true;
} else if (!annotationClass.isInstance(args[0])) {
return false;
}
final ReflectionUtils reflectionUtils = annotationInfo.scanResult == null
? new ReflectionUtils()
: annotationInfo.scanResult.reflectionUtils;
for (final Entry<String, Object> ent : annotationParameterValuesInstantiated.entrySet()) {
final String paramName = ent.getKey();
final Object paramVal = ent.getValue();
final Object otherParamVal = reflectionUtils.invokeMethod(/* throwException = */ false,
args[0], paramName);
if ((paramVal == null) != (otherParamVal == null)) {
// Annotation values should never be null, but just to be safe
return false;
} else if (paramVal == null && otherParamVal == null) {
return true;
} else if (paramVal == null || !paramVal.equals(otherParamVal)) {
return false;
}
}
return true;
} else {
// .equals(Object) is the only method of an enum that can take one parameter
throw new IllegalArgumentException();
}
} else if (paramTypes.length == 0) {
// Handle .toString(), .hashCode(), .annotationType()
switch (methodName) {
case "toString":
return annotationInfo.toString();
case "hashCode": {
// hashCode() needs to function the same as the JDK implementation
// (see src/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java in the JDK)
int result = 0;
for (final Entry<String, Object> ent : annotationParameterValuesInstantiated.entrySet()) {
final String paramName = ent.getKey();
final Object paramVal = ent.getValue();
int paramValHashCode;
if (paramVal == null) {
// Annotation values should never be null, but just to be safe
paramValHashCode = 0;
} else {
final Class<?> type = paramVal.getClass();
if (!type.isArray()) {
paramValHashCode = paramVal.hashCode();
} else if (type == byte[].class) {
paramValHashCode = Arrays.hashCode((byte[]) paramVal);
} else if (type == char[].class) {
paramValHashCode = Arrays.hashCode((char[]) paramVal);
} else if (type == double[].class) {
paramValHashCode = Arrays.hashCode((double[]) paramVal);
} else if (type == float[].class) {
paramValHashCode = Arrays.hashCode((float[]) paramVal);
} else if (type == int[].class) {
paramValHashCode = Arrays.hashCode((int[]) paramVal);
} else if (type == long[].class) {
paramValHashCode = Arrays.hashCode((long[]) paramVal);
} else if (type == short[].class) {
paramValHashCode = Arrays.hashCode((short[]) paramVal);
} else if (type == boolean[].class) {
paramValHashCode = Arrays.hashCode((boolean[]) paramVal);
} else {
paramValHashCode = Arrays.hashCode((Object[]) paramVal);
}
}
result += (127 * paramName.hashCode()) ^ paramValHashCode;
}
return result;
}
case "annotationType":
return annotationClass;
default:
// Fall through (other method names are used for returning annotation parameter values)
break;
}
} else {
// Throw exception for 2 or more params
throw new IllegalArgumentException();
}
// Instantiate the annotation parameter value (this loads and gets references for class literals,
// enum constants, etc.)
final Object annotationParameterValue = annotationParameterValuesInstantiated.get(methodName);
if (annotationParameterValue == null) {
// Undefined enum constant (enum values cannot be null)
throw new IncompleteAnnotationException(annotationClass, methodName);
}
// Clone any array-typed annotation parameter values, in keeping with the Java Annotation API
final Class<?> annotationParameterValueClass = annotationParameterValue.getClass();
if (annotationParameterValueClass.isArray()) {
// Handle array types
if (annotationParameterValueClass == String[].class) {
return ((String[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == byte[].class) {
return ((byte[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == char[].class) {
return ((char[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == double[].class) {
return ((double[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == float[].class) {
return ((float[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == int[].class) {
return ((int[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == long[].class) {
return ((long[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == short[].class) {
return ((short[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == boolean[].class) {
return ((boolean[]) annotationParameterValue).clone();
} else {
// Handle arrays of nested annotation types
final Object[] arr = (Object[]) annotationParameterValue;
return arr.clone();
}
}
return annotationParameterValue;
| 441
| 1,599
| 2,040
|
<methods>public java.lang.String toString() ,public java.lang.String toStringWithSimpleNames() <variables>private transient io.github.classgraph.ClassInfo classInfo,protected transient Class<?> classRef,protected transient io.github.classgraph.ScanResult scanResult
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/AnnotationParameterValueList.java
|
AnnotationParameterValueList
|
convertWrapperArraysToPrimitiveArrays
|
class AnnotationParameterValueList extends MappableInfoList<AnnotationParameterValue> {
/** serialVersionUID */
private static final long serialVersionUID = 1L;
/** An unmodifiable empty {@link AnnotationParameterValueList}. */
static final AnnotationParameterValueList EMPTY_LIST = new AnnotationParameterValueList();
static {
EMPTY_LIST.makeUnmodifiable();
}
/**
* Return an unmodifiable empty {@link AnnotationParameterValueList}.
*
* @return the unmodifiable empty {@link AnnotationParameterValueList}.
*/
public static AnnotationParameterValueList emptyList() {
return EMPTY_LIST;
}
/**
* Construct a new modifiable empty list of {@link AnnotationParameterValue} objects.
*/
public AnnotationParameterValueList() {
super();
}
/**
* Construct a new modifiable empty list of {@link AnnotationParameterValue} objects, given a size hint.
*
* @param sizeHint
* the size hint
*/
public AnnotationParameterValueList(final int sizeHint) {
super(sizeHint);
}
/**
* Construct a new modifiable empty {@link AnnotationParameterValueList}, given an initial list of
* {@link AnnotationParameterValue} objects.
*
* @param annotationParameterValueCollection
* the collection of {@link AnnotationParameterValue} objects.
*/
public AnnotationParameterValueList(
final Collection<AnnotationParameterValue> annotationParameterValueCollection) {
super(annotationParameterValueCollection);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get {@link ClassInfo} objects for any classes referenced in the methods in this list.
*
* @param classNameToClassInfo
* the map from class name to {@link ClassInfo}.
* @param refdClassInfo
* the referenced class info
* @param log
* the log
*/
protected void findReferencedClassInfo(final Map<String, ClassInfo> classNameToClassInfo,
final Set<ClassInfo> refdClassInfo, final LogNode log) {
for (final AnnotationParameterValue apv : this) {
apv.findReferencedClassInfo(classNameToClassInfo, refdClassInfo, log);
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* For primitive array type params, replace Object[] arrays containing boxed types with primitive arrays (need
* to check the type of each method of the annotation class to determine if it is a primitive array type).
*
* @param annotationClassInfo
* the annotation class info
*/
void convertWrapperArraysToPrimitiveArrays(final ClassInfo annotationClassInfo) {<FILL_FUNCTION_BODY>}
// -------------------------------------------------------------------------------------------------------------
/**
* Get the annotation parameter value, by calling {@link AnnotationParameterValue#getValue()} on the result of
* {@link #get(String)}, if non-null.
*
* @param parameterName
* The name of an annotation parameter.
* @return The value of the {@link AnnotationParameterValue} object in the list with the given name, by calling
* {@link AnnotationParameterValue#getValue()} on that object, or null if not found.
*
* <p>
* The annotation parameter value may be one of the following types:
* <ul>
* <li>String for string constants
* <li>String[] for arrays of strings
* <li>A boxed type, e.g. Integer or Character, for primitive-typed constants
* <li>A 1-dimensional primitive-typed array (i.e. int[], long[], short[], char[], byte[], boolean[],
* float[], or double[]), for arrays of primitives
* <li>A 1-dimensional {@link Object}[] array for array types (and then the array element type may be
* one of the types in this list)
* <li>{@link AnnotationEnumValue}, for enum constants (this wraps the enum class and the string name of
* the constant)
* <li>{@link AnnotationClassRef}, for Class references within annotations (this wraps the name of the
* referenced class)
* <li>{@link AnnotationInfo}, for nested annotations
* </ul>
*/
public Object getValue(final String parameterName) {
final AnnotationParameterValue apv = get(parameterName);
return apv == null ? null : apv.getValue();
}
}
|
for (final AnnotationParameterValue apv : this) {
apv.convertWrapperArraysToPrimitiveArrays(annotationClassInfo);
}
| 1,128
| 40
| 1,168
|
<methods>public Map<java.lang.String,io.github.classgraph.AnnotationParameterValue> asMap() ,public boolean containsName(java.lang.String) ,public io.github.classgraph.AnnotationParameterValue get(java.lang.String) <variables>private static final long serialVersionUID
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/ArrayClassInfo.java
|
ArrayClassInfo
|
getElementClassInfo
|
class ArrayClassInfo extends ClassInfo {
/** The array type signature. */
private ArrayTypeSignature arrayTypeSignature;
/** The element class info. */
private ClassInfo elementClassInfo;
/** Default constructor for deserialization. */
ArrayClassInfo() {
super();
}
/**
* Constructor.
*
* @param arrayTypeSignature
* the array type signature
*/
ArrayClassInfo(final ArrayTypeSignature arrayTypeSignature) {
super(arrayTypeSignature.getClassName(), /* modifiers = */ 0, /* resource = */ null);
this.arrayTypeSignature = arrayTypeSignature;
// Pre-load fields from element type
getElementClassInfo();
}
/* (non-Javadoc)
* @see io.github.classgraph.ClassInfo#setScanResult(io.github.classgraph.ScanResult)
*/
@Override
void setScanResult(final ScanResult scanResult) {
super.setScanResult(scanResult);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get the raw type signature string of the array class, e.g. "[[I" for "int[][]".
*
* @return The raw type signature string of the array class.
*/
@Override
public String getTypeSignatureStr() {
return arrayTypeSignature.getTypeSignatureStr();
}
/**
* Returns null, because array classes do not have a ClassTypeSignature. Call {@link #getArrayTypeSignature()}
* instead.
*
* @return null (always).
*/
@Override
public ClassTypeSignature getTypeSignature() {
return null;
}
/**
* Get the type signature of the class.
*
* @return The class type signature, if available, otherwise returns null.
*/
public ArrayTypeSignature getArrayTypeSignature() {
return arrayTypeSignature;
}
/**
* Get the type signature of the array elements.
*
* @return The type signature of the array elements.
*/
public TypeSignature getElementTypeSignature() {
return arrayTypeSignature.getElementTypeSignature();
}
/**
* Get the number of dimensions of the array.
*
* @return The number of dimensions of the array.
*/
public int getNumDimensions() {
return arrayTypeSignature.getNumDimensions();
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get the {@link ClassInfo} instance for the array element type.
*
* @return the {@link ClassInfo} instance for the array element type. Returns null if the element type was not
* found during the scan. In particular, will return null for arrays that have a primitive element type.
*/
public ClassInfo getElementClassInfo() {<FILL_FUNCTION_BODY>}
// -------------------------------------------------------------------------------------------------------------
/**
* Get a {@code Class<?>} reference for the array element type. Causes the ClassLoader to load the element
* class, if it is not already loaded.
*
* @param ignoreExceptions
* Whether or not to ignore exceptions.
* @return a {@code Class<?>} reference for the array element type. Also works for arrays of primitive element
* type.
*/
public Class<?> loadElementClass(final boolean ignoreExceptions) {
return arrayTypeSignature.loadElementClass(ignoreExceptions);
}
/**
* Get a {@code Class<?>} reference for the array element type. Causes the ClassLoader to load the element
* class, if it is not already loaded.
*
* @return a {@code Class<?>} reference for the array element type. Also works for arrays of primitive element
* type.
*/
public Class<?> loadElementClass() {
return arrayTypeSignature.loadElementClass();
}
/**
* Obtain a {@code Class<?>} reference for the array class named by this {@link ArrayClassInfo} object. Causes
* the ClassLoader to load the element class, if it is not already loaded.
*
* @param ignoreExceptions
* Whether or not to ignore exceptions
* @return The class reference, or null, if ignoreExceptions is true and there was an exception or error loading
* the class.
* @throws IllegalArgumentException
* if ignoreExceptions is false and there were problems loading the class.
*/
@Override
public Class<?> loadClass(final boolean ignoreExceptions) {
if (classRef == null) {
classRef = arrayTypeSignature.loadClass(ignoreExceptions);
}
return classRef;
}
/**
* Obtain a {@code Class<?>} reference for the array class named by this {@link ArrayClassInfo} object. Causes
* the ClassLoader to load the element class, if it is not already loaded.
*
* @return The class reference.
* @throws IllegalArgumentException
* if there were problems loading the class.
*/
@Override
public Class<?> loadClass() {
if (classRef == null) {
classRef = arrayTypeSignature.loadClass();
}
return classRef;
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get {@link ClassInfo} objects for any classes referenced in the type descriptor or type signature.
*
* @param classNameToClassInfo
* the map from class name to {@link ClassInfo}.
* @param refdClassInfo
* the referenced class info
*/
@Override
protected void findReferencedClassInfo(final Map<String, ClassInfo> classNameToClassInfo,
final Set<ClassInfo> refdClassInfo, final LogNode log) {
super.findReferencedClassInfo(classNameToClassInfo, refdClassInfo, log);
}
// -------------------------------------------------------------------------------------------------------------
/* (non-Javadoc)
* @see io.github.classgraph.ClassInfo#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
return super.equals(obj);
}
/* (non-Javadoc)
* @see io.github.classgraph.ClassInfo#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode();
}
}
|
if (elementClassInfo == null) {
final TypeSignature elementTypeSignature = arrayTypeSignature.getElementTypeSignature();
if (!(elementTypeSignature instanceof BaseTypeSignature)) {
elementClassInfo = arrayTypeSignature.getElementTypeSignature().getClassInfo();
if (elementClassInfo != null) {
// Copy over relevant fields from array element ClassInfo
this.classpathElement = elementClassInfo.classpathElement;
this.classfileResource = elementClassInfo.classfileResource;
this.classLoader = elementClassInfo.classLoader;
this.isScannedClass = elementClassInfo.isScannedClass;
this.isExternalClass = elementClassInfo.isExternalClass;
this.moduleInfo = elementClassInfo.moduleInfo;
this.packageInfo = elementClassInfo.packageInfo;
}
}
}
return elementClassInfo;
| 1,571
| 211
| 1,782
|
<methods>public int compareTo(io.github.classgraph.ClassInfo) ,public boolean equals(java.lang.Object) ,public boolean extendsSuperclass(Class<?>) ,public boolean extendsSuperclass(java.lang.String) ,public io.github.classgraph.AnnotationParameterValueList getAnnotationDefaultParameterValues() ,public io.github.classgraph.AnnotationInfoList getAnnotationInfo() ,public io.github.classgraph.AnnotationInfo getAnnotationInfo(Class<? extends java.lang.annotation.Annotation>) ,public io.github.classgraph.AnnotationInfo getAnnotationInfo(java.lang.String) ,public io.github.classgraph.AnnotationInfoList getAnnotationInfoRepeatable(Class<? extends java.lang.annotation.Annotation>) ,public io.github.classgraph.AnnotationInfoList getAnnotationInfoRepeatable(java.lang.String) ,public io.github.classgraph.ClassInfoList getAnnotations() ,public io.github.classgraph.ClassInfoList getClassDependencies() ,public io.github.classgraph.ClassInfoList getClassesImplementing() ,public io.github.classgraph.ClassInfoList getClassesWithAnnotation() ,public io.github.classgraph.ClassInfoList getClassesWithFieldAnnotation() ,public io.github.classgraph.ClassInfoList getClassesWithMethodAnnotation() ,public io.github.classgraph.ClassInfoList getClassesWithMethodParameterAnnotation() ,public int getClassfileMajorVersion() ,public int getClassfileMinorVersion() ,public java.io.File getClasspathElementFile() ,public java.net.URI getClasspathElementURI() ,public java.net.URL getClasspathElementURL() ,public io.github.classgraph.MethodInfoList getConstructorInfo() ,public io.github.classgraph.MethodInfoList getDeclaredConstructorInfo() ,public io.github.classgraph.FieldInfoList getDeclaredFieldInfo() ,public io.github.classgraph.FieldInfo getDeclaredFieldInfo(java.lang.String) ,public io.github.classgraph.MethodInfoList getDeclaredMethodAndConstructorInfo() ,public io.github.classgraph.MethodInfoList getDeclaredMethodInfo() ,public io.github.classgraph.MethodInfoList getDeclaredMethodInfo(java.lang.String) ,public List<java.lang.Object> getEnumConstantObjects() ,public io.github.classgraph.FieldInfoList getEnumConstants() ,public io.github.classgraph.ClassInfoList getFieldAnnotations() ,public io.github.classgraph.FieldInfoList getFieldInfo() ,public io.github.classgraph.FieldInfo getFieldInfo(java.lang.String) ,public java.lang.String getFullyQualifiedDefiningMethodName() ,public io.github.classgraph.ClassInfoList getInnerClasses() ,public io.github.classgraph.ClassInfoList getInterfaces() ,public io.github.classgraph.MethodInfoList getMethodAndConstructorInfo() ,public io.github.classgraph.ClassInfoList getMethodAnnotations() ,public io.github.classgraph.MethodInfoList getMethodInfo() ,public io.github.classgraph.MethodInfoList getMethodInfo(java.lang.String) ,public io.github.classgraph.ClassInfoList getMethodParameterAnnotations() ,public int getModifiers() ,public java.lang.String getModifiersStr() ,public io.github.classgraph.ModuleInfo getModuleInfo() ,public io.github.classgraph.ModuleRef getModuleRef() ,public java.lang.String getName() ,public io.github.classgraph.ClassInfoList getOuterClasses() ,public io.github.classgraph.PackageInfo getPackageInfo() ,public java.lang.String getPackageName() ,public io.github.classgraph.Resource getResource() ,public java.lang.String getSimpleName() ,public java.lang.String getSourceFile() ,public io.github.classgraph.ClassInfoList getSubclasses() ,public io.github.classgraph.ClassInfo getSuperclass() ,public io.github.classgraph.ClassInfoList getSuperclasses() ,public io.github.classgraph.ClassTypeSignature getTypeDescriptor() ,public io.github.classgraph.ClassTypeSignature getTypeSignature() ,public io.github.classgraph.ClassTypeSignature getTypeSignatureOrTypeDescriptor() ,public java.lang.String getTypeSignatureStr() ,public boolean hasAnnotation(Class<? extends java.lang.annotation.Annotation>) ,public boolean hasAnnotation(java.lang.String) ,public boolean hasDeclaredField(java.lang.String) ,public boolean hasDeclaredFieldAnnotation(Class<? extends java.lang.annotation.Annotation>) ,public boolean hasDeclaredFieldAnnotation(java.lang.String) ,public boolean hasDeclaredMethod(java.lang.String) ,public boolean hasDeclaredMethodAnnotation(Class<? extends java.lang.annotation.Annotation>) ,public boolean hasDeclaredMethodAnnotation(java.lang.String) ,public boolean hasDeclaredMethodParameterAnnotation(Class<? extends java.lang.annotation.Annotation>) ,public boolean hasDeclaredMethodParameterAnnotation(java.lang.String) ,public boolean hasField(java.lang.String) ,public boolean hasFieldAnnotation(Class<? extends java.lang.annotation.Annotation>) ,public boolean hasFieldAnnotation(java.lang.String) ,public boolean hasMethod(java.lang.String) ,public boolean hasMethodAnnotation(Class<? extends java.lang.annotation.Annotation>) ,public boolean hasMethodAnnotation(java.lang.String) ,public boolean hasMethodParameterAnnotation(Class<? extends java.lang.annotation.Annotation>) ,public boolean hasMethodParameterAnnotation(java.lang.String) ,public int hashCode() ,public boolean implementsInterface(Class<?>) ,public boolean implementsInterface(java.lang.String) ,public boolean isAbstract() ,public boolean isAnnotation() ,public boolean isAnonymousInnerClass() ,public boolean isArrayClass() ,public boolean isEnum() ,public boolean isExternalClass() ,public boolean isFinal() ,public boolean isImplementedInterface() ,public boolean isInnerClass() ,public boolean isInterface() ,public boolean isInterfaceOrAnnotation() ,public boolean isOuterClass() ,public boolean isPackageVisible() ,public boolean isPrivate() ,public boolean isProtected() ,public boolean isPublic() ,public boolean isRecord() ,public boolean isStandardClass() ,public boolean isStatic() ,public boolean isSynthetic() ,public Class<T> loadClass(Class<T>, boolean) ,public Class<T> loadClass(Class<T>) ,public Class<?> loadClass(boolean) ,public Class<?> loadClass() <variables>private static final int ANNOTATION_CLASS_MODIFIER,private static final io.github.classgraph.ClassInfo.ReachableAndDirectlyRelatedClasses NO_REACHABLE_CLASSES,io.github.classgraph.AnnotationParameterValueList annotationDefaultParamValues,transient boolean annotationDefaultParamValuesHasBeenConvertedToPrimitive,io.github.classgraph.AnnotationInfoList annotationInfo,transient java.lang.ClassLoader classLoader,private int classfileMajorVersion,private int classfileMinorVersion,protected transient io.github.classgraph.Resource classfileResource,transient io.github.classgraph.ClasspathElement classpathElement,io.github.classgraph.FieldInfoList fieldInfo,private java.lang.String fullyQualifiedDefiningMethodName,protected boolean isExternalClass,boolean isInherited,private boolean isRecord,protected boolean isScannedClass,io.github.classgraph.MethodInfoList methodInfo,private transient List<io.github.classgraph.ClassInfo> methodOverrideOrder,private int modifiers,io.github.classgraph.ModuleInfo moduleInfo,protected java.lang.String name,private transient List<io.github.classgraph.ClassInfo> overrideOrder,io.github.classgraph.PackageInfo packageInfo,private Set<java.lang.String> referencedClassNames,private io.github.classgraph.ClassInfoList referencedClasses,private Map<io.github.classgraph.ClassInfo.RelType,Set<io.github.classgraph.ClassInfo>> relatedClasses,private java.lang.String sourceFile,transient List<io.github.classgraph.Classfile.ClassTypeAnnotationDecorator> typeAnnotationDecorators,private transient io.github.classgraph.ClassTypeSignature typeDescriptor,private transient io.github.classgraph.ClassTypeSignature typeSignature,protected java.lang.String typeSignatureStr
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/Classfile.java
|
SkipClassException
|
scheduleScanningIfExternalClass
|
class SkipClassException extends IOException {
/** serialVersionUID. */
static final long serialVersionUID = 1L;
/**
* Constructor.
*
* @param message
* the message
*/
public SkipClassException(final String message) {
super(message);
}
/**
* Speed up exception (stack trace is not needed for this exception).
*
* @return this
*/
@Override
public synchronized Throwable fillInStackTrace() {
return this;
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Extend scanning to a superclass, interface or annotation.
*
* @param className
* the class name
* @param relationship
* the relationship type
* @param log
* the log
*/
private void scheduleScanningIfExternalClass(final String className, final String relationship,
final LogNode log) {<FILL_FUNCTION_BODY>
|
// Don't scan Object
if (className != null && !className.equals("java.lang.Object")
// Don't schedule a class for scanning that was already found to be accepted
&& !acceptedClassNamesFound.contains(className)
// Only schedule each external class once for scanning, across all threads
&& classNamesScheduledForExtendedScanning.add(className)) {
if (scanSpec.classAcceptReject.isRejected(className)) {
if (log != null) {
log.log("Cannot extend scanning upwards to external " + relationship + " " + className
+ ", since it is rejected");
}
} else {
// Search for the named class' classfile among classpath elements, in classpath order (this is O(N)
// for each class, but there shouldn't be too many cases of extending scanning upwards)
final String classfilePath = JarUtils.classNameToClassfilePath(className);
// First check current classpath element, to avoid iterating through other classpath elements
Resource classResource = classpathElement.getResource(classfilePath);
ClasspathElement foundInClasspathElt = null;
if (classResource != null) {
// Found the classfile in the current classpath element
foundInClasspathElt = classpathElement;
} else {
// Didn't find the classfile in the current classpath element -- iterate through other elements
for (final ClasspathElement classpathOrderElt : classpathOrder) {
if (classpathOrderElt != classpathElement) {
classResource = classpathOrderElt.getResource(classfilePath);
if (classResource != null) {
foundInClasspathElt = classpathOrderElt;
break;
}
}
}
}
if (classResource != null) {
// Found class resource
if (log != null) {
// Log the extended scan as a child LogNode of the current class' scan log, since the
// external class is not scanned at the regular place in the classpath element hierarchy
// traversal
classResource.scanLog = log
.log("Extending scanning to external " + relationship
+ (foundInClasspathElt == classpathElement ? " in same classpath element"
: " in classpath element " + foundInClasspathElt)
+ ": " + className);
}
if (additionalWorkUnits == null) {
additionalWorkUnits = new ArrayList<>();
}
// Schedule class resource for scanning
additionalWorkUnits.add(new ClassfileScanWorkUnit(foundInClasspathElt, classResource,
/* isExternalClass = */ true));
} else {
if (log != null) {
log.log("External " + relationship + " " + className + " was not found in "
+ "non-rejected packages -- cannot extend scanning to this class");
}
}
}
}
| 248
| 727
| 975
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/CloseableByteBuffer.java
|
CloseableByteBuffer
|
close
|
class CloseableByteBuffer implements Closeable {
private ByteBuffer byteBuffer;
private Runnable onClose;
/**
* A wrapper for {@link ByteBuffer} that implements the {@link Closeable} interface, releasing the
* {@link ByteBuffer} when it is no longer needed.
*
* @param byteBuffer
* The {@link ByteBuffer} to wrap
* @param onClose
* The method to run when {@link #close()} is called.
*/
CloseableByteBuffer(final ByteBuffer byteBuffer, final Runnable onClose) {
this.byteBuffer = byteBuffer;
this.onClose = onClose;
}
/**
* @return The wrapped {@link ByteBuffer}.
*/
public ByteBuffer getByteBuffer() {
return byteBuffer;
}
/** Release the wrapped {@link ByteBuffer}. */
@Override
public void close() throws IOException {<FILL_FUNCTION_BODY>}
}
|
if (onClose != null) {
try {
onClose.run();
} catch (final Exception e) {
// Ignore
}
onClose = null;
}
byteBuffer = null;
| 243
| 60
| 303
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/FieldInfoList.java
|
FieldInfoList
|
filter
|
class FieldInfoList extends MappableInfoList<FieldInfo> {
/** serialVersionUID */
private static final long serialVersionUID = 1L;
/** An unmodifiable empty {@link FieldInfoList}. */
static final FieldInfoList EMPTY_LIST = new FieldInfoList();
static {
EMPTY_LIST.makeUnmodifiable();
}
/**
* Return an unmodifiable empty {@link FieldInfoList}.
*
* @return the unmodifiable empty {@link FieldInfoList}.
*/
public static FieldInfoList emptyList() {
return EMPTY_LIST;
}
/**
* Construct a new modifiable empty list of {@link FieldInfo} objects.
*/
public FieldInfoList() {
super();
}
/**
* Construct a new modifiable empty list of {@link FieldInfo} objects, given a size hint.
*
* @param sizeHint
* the size hint
*/
public FieldInfoList(final int sizeHint) {
super(sizeHint);
}
/**
* Construct a new modifiable empty {@link FieldInfoList}, given an initial list of {@link FieldInfo} objects.
*
* @param fieldInfoCollection
* the collection of {@link FieldInfo} objects.
*/
public FieldInfoList(final Collection<FieldInfo> fieldInfoCollection) {
super(fieldInfoCollection);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get {@link ClassInfo} objects for any classes referenced in the list.
*
* @param classNameToClassInfo
* the map from class name to {@link ClassInfo}.
* @param refdClassInfo
* the referenced class info
* @param log
* the log
*/
protected void findReferencedClassInfo(final Map<String, ClassInfo> classNameToClassInfo,
final Set<ClassInfo> refdClassInfo, final LogNode log) {
for (final FieldInfo fi : this) {
fi.findReferencedClassInfo(classNameToClassInfo, refdClassInfo, log);
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Filter an {@link FieldInfoList} using a predicate mapping an {@link FieldInfo} object to a boolean, producing
* another {@link FieldInfoList} for all items in the list for which the predicate is true.
*/
@FunctionalInterface
public interface FieldInfoFilter {
/**
* Whether or not to allow an {@link FieldInfo} list item through the filter.
*
* @param fieldInfo
* The {@link FieldInfo} item to filter.
* @return Whether or not to allow the item through the filter. If true, the item is copied to the output
* list; if false, it is excluded.
*/
boolean accept(FieldInfo fieldInfo);
}
/**
* Find the subset of the {@link FieldInfo} objects in this list for which the given filter predicate is true.
*
* @param filter
* The {@link FieldInfoFilter} to apply.
* @return The subset of the {@link FieldInfo} objects in this list for which the given filter predicate is
* true.
*/
public FieldInfoList filter(final FieldInfoFilter filter) {<FILL_FUNCTION_BODY>}
}
|
final FieldInfoList fieldInfoFiltered = new FieldInfoList();
for (final FieldInfo resource : this) {
if (filter.accept(resource)) {
fieldInfoFiltered.add(resource);
}
}
return fieldInfoFiltered;
| 823
| 67
| 890
|
<methods>public Map<java.lang.String,io.github.classgraph.FieldInfo> asMap() ,public boolean containsName(java.lang.String) ,public io.github.classgraph.FieldInfo get(java.lang.String) <variables>private static final long serialVersionUID
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/HierarchicalTypeSignature.java
|
HierarchicalTypeSignature
|
setScanResult
|
class HierarchicalTypeSignature extends ScanResultObject {
protected AnnotationInfoList typeAnnotationInfo;
/**
* Add a type annotation.
*
* @param annotationInfo
* the annotation
*/
protected void addTypeAnnotation(final AnnotationInfo annotationInfo) {
if (typeAnnotationInfo == null) {
typeAnnotationInfo = new AnnotationInfoList(1);
}
typeAnnotationInfo.add(annotationInfo);
}
@Override
void setScanResult(final ScanResult scanResult) {<FILL_FUNCTION_BODY>}
/**
* Get a list of {@link AnnotationInfo} objects for any type annotations on this type, or null if none.
*
* @return a list of {@link AnnotationInfo} objects for any type annotations on this type, or null if none.
*/
public AnnotationInfoList getTypeAnnotationInfo() {
return typeAnnotationInfo;
}
/**
* Add a type annotation.
*
* @param typePath
* the type path
* @param annotationInfo
* the annotation
*/
protected abstract void addTypeAnnotation(List<TypePathNode> typePath, AnnotationInfo annotationInfo);
/**
* Render type signature to string.
*
* @param useSimpleNames
* whether to use simple names for classes.
* @param annotationsToExclude
* toplevel annotations to exclude, to eliminate duplication (toplevel annotations are both
* class/field/method annotations and type annotations).
* @param buf
* the {@link StringBuilder} to write to.
*/
protected abstract void toStringInternal(final boolean useSimpleNames, AnnotationInfoList annotationsToExclude,
StringBuilder buf);
/**
* Render type signature to string.
*
* @param useSimpleNames
* whether to use simple names for classes.
* @param buf
* the {@link StringBuilder} to write to.
*/
@Override
protected void toString(final boolean useSimpleNames, final StringBuilder buf) {
toStringInternal(useSimpleNames, /* annotationsToExclude = */ null, buf);
}
}
|
super.setScanResult(scanResult);
if (typeAnnotationInfo != null) {
for (final AnnotationInfo annotationInfo : typeAnnotationInfo) {
annotationInfo.setScanResult(scanResult);
}
}
| 554
| 60
| 614
|
<methods>public java.lang.String toString() ,public java.lang.String toStringWithSimpleNames() <variables>private transient io.github.classgraph.ClassInfo classInfo,protected transient Class<?> classRef,protected transient io.github.classgraph.ScanResult scanResult
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/InfoList.java
|
InfoList
|
getAsStrings
|
class InfoList<T extends HasName> extends PotentiallyUnmodifiableList<T> {
/** serialVersionUID. */
static final long serialVersionUID = 1L;
/**
* Constructor.
*/
InfoList() {
super();
}
/**
* Constructor.
*
* @param sizeHint
* the size hint
*/
InfoList(final int sizeHint) {
super(sizeHint);
}
/**
* Constructor.
*
* @param infoCollection
* the initial elements.
*/
InfoList(final Collection<T> infoCollection) {
super(infoCollection);
}
// Keep Scrutinizer happy
@Override
public boolean equals(final Object o) {
return super.equals(o);
}
// Keep Scrutinizer happy
@Override
public int hashCode() {
return super.hashCode();
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get the names of all items in this list, by calling {@code getName()} on each item in the list.
*
* @return The names of all items in this list, by calling {@code getName()} on each item in the list.
*/
public List<String> getNames() {
if (this.isEmpty()) {
return Collections.emptyList();
} else {
final List<String> names = new ArrayList<>(this.size());
for (final T i : this) {
if (i != null) {
names.add(i.getName());
}
}
return names;
}
}
/**
* Get the String representations of all items in this list, by calling {@code toString()} on each item in the
* list.
*
* @return The String representations of all items in this list, by calling {@code toString()} on each item in
* the list.
*/
public List<String> getAsStrings() {<FILL_FUNCTION_BODY>}
/**
* Get the String representations of all items in this list, using only <a href=
* "https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/Class.html#getSimpleName()">simple
* names</a> of any named classes, by calling {@code ScanResultObject#toStringWithSimpleNames()} if the object
* is a subclass of {@code ScanResultObject} (e.g. {@link ClassInfo}, {@link MethodInfo} or {@link FieldInfo}
* object), otherwise calling {@code toString()}, for each item in the list.
*
* @return The String representations of all items in this list, using only the <a href=
* "https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/Class.html#getSimpleName()">
* simple names</a> of any named classes.
*/
public List<String> getAsStringsWithSimpleNames() {
if (this.isEmpty()) {
return Collections.emptyList();
} else {
final List<String> toStringVals = new ArrayList<>(this.size());
for (final T i : this) {
toStringVals.add(i == null ? "null"
: i instanceof ScanResultObject ? ((ScanResultObject) i).toStringWithSimpleNames()
: i.toString());
}
return toStringVals;
}
}
}
|
if (this.isEmpty()) {
return Collections.emptyList();
} else {
final List<String> toStringVals = new ArrayList<>(this.size());
for (final T i : this) {
toStringVals.add(i == null ? "null" : i.toString());
}
return toStringVals;
}
| 895
| 92
| 987
|
<methods>public boolean add(T) ,public void add(int, T) ,public boolean addAll(Collection<? extends T>) ,public boolean addAll(int, Collection<? extends T>) ,public void clear() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public Iterator<T> iterator() ,public ListIterator<T> listIterator() ,public boolean remove(java.lang.Object) ,public T remove(int) ,public boolean removeAll(Collection<?>) ,public boolean retainAll(Collection<?>) ,public T set(int, T) <variables>boolean modifiable,static final long serialVersionUID
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/MappableInfoList.java
|
MappableInfoList
|
get
|
class MappableInfoList<T extends HasName> extends InfoList<T> {
/** serialVersionUID */
private static final long serialVersionUID = 1L;
/**
* Constructor.
*/
MappableInfoList() {
super();
}
/**
* Constructor.
*
* @param sizeHint
* the size hint
*/
MappableInfoList(final int sizeHint) {
super(sizeHint);
}
/**
* Constructor.
*
* @param infoCollection
* the initial elements
*/
MappableInfoList(final Collection<T> infoCollection) {
super(infoCollection);
}
/**
* Get an index for this list, as a map from the name of each list item (obtained by calling {@code getName()}
* on each list item) to the list item.
*
* @return An index for this list, as a map from the name of each list item (obtained by calling
* {@code getName()} on each list item) to the list item.
*/
public Map<String, T> asMap() {
final Map<String, T> nameToInfoObject = new HashMap<>();
for (final T i : this) {
if (i != null) {
nameToInfoObject.put(i.getName(), i);
}
}
return nameToInfoObject;
}
/**
* Check if this list contains an item with the given name.
*
* @param name
* The name to search for.
* @return true if this list contains an item with the given name.
*/
public boolean containsName(final String name) {
for (final T i : this) {
if (i != null && i.getName().equals(name)) {
return true;
}
}
return false;
}
/**
* Get the list item with the given name, or null if not found.
*
* @param name
* The name to search for.
* @return The list item with the given name, or null if not found.
*/
@SuppressWarnings("null")
public T get(final String name) {<FILL_FUNCTION_BODY>}
}
|
for (final T i : this) {
if (i != null && i.getName().equals(name)) {
return i;
}
}
return null;
| 585
| 48
| 633
|
<methods>public boolean equals(java.lang.Object) ,public List<java.lang.String> getAsStrings() ,public List<java.lang.String> getAsStringsWithSimpleNames() ,public List<java.lang.String> getNames() ,public int hashCode() <variables>static final long serialVersionUID
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/MethodInfoList.java
|
MethodInfoList
|
asMap
|
class MethodInfoList extends InfoList<MethodInfo> {
/** serialVersionUID */
private static final long serialVersionUID = 1L;
/** An unmodifiable empty {@link MethodInfoList}. */
static final MethodInfoList EMPTY_LIST = new MethodInfoList();
static {
EMPTY_LIST.makeUnmodifiable();
}
/**
* Return an unmodifiable empty {@link MethodInfoList}.
*
* @return the unmodifiable empty {@link MethodInfoList}.
*/
public static MethodInfoList emptyList() {
return EMPTY_LIST;
}
/** Construct a new modifiable empty list of {@link MethodInfo} objects. */
public MethodInfoList() {
super();
}
/**
* Construct a new modifiable empty list of {@link MethodInfo} objects, given a size hint.
*
* @param sizeHint
* the size hint
*/
public MethodInfoList(final int sizeHint) {
super(sizeHint);
}
/**
* Construct a new modifiable empty {@link MethodInfoList}, given an initial collection of {@link MethodInfo}
* objects.
*
* @param methodInfoCollection
* the collection of {@link MethodInfo} objects.
*/
public MethodInfoList(final Collection<MethodInfo> methodInfoCollection) {
super(methodInfoCollection);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get {@link ClassInfo} objects for any classes referenced in the type descriptor or type signature.
*
* @param classNameToClassInfo
* the map from class name to {@link ClassInfo}.
* @param refdClassInfo
* the referenced class info
* @param log
* the log
*/
protected void findReferencedClassInfo(final Map<String, ClassInfo> classNameToClassInfo,
final Set<ClassInfo> refdClassInfo, final LogNode log) {
for (final MethodInfo mi : this) {
mi.findReferencedClassInfo(classNameToClassInfo, refdClassInfo, log);
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get this {@link MethodInfoList} as a map from method name to a {@link MethodInfoList} of methods with that
* name.
*
* @return This {@link MethodInfoList} as a map from method name to a {@link MethodInfoList} of methods with
* that name.
*/
public Map<String, MethodInfoList> asMap() {<FILL_FUNCTION_BODY>}
// -------------------------------------------------------------------------------------------------------------
/**
* Check whether the list contains a method with the given name.
*
* @param methodName
* The name of a class.
* @return true if the list contains a method with the given name.
*/
public boolean containsName(final String methodName) {
for (final MethodInfo mi : this) {
if (mi.getName().equals(methodName)) {
return true;
}
}
return false;
}
/**
* Returns a list of all methods matching a given name. (There may be more than one method with a given name,
* due to overloading, so this returns a {@link MethodInfoList} rather than a single {@link MethodInfo}.)
*
* @param methodName
* The name of a method.
* @return A {@link MethodInfoList} of {@link MethodInfo} objects from this list that have the given name (there
* may be more than one method with a given name, due to overloading, so this returns a
* {@link MethodInfoList} rather than a single {@link MethodInfo}). Returns the empty list if no method
* had a matching name.
*/
public MethodInfoList get(final String methodName) {
boolean hasMethodWithName = false;
for (final MethodInfo mi : this) {
if (mi.getName().equals(methodName)) {
hasMethodWithName = true;
break;
}
}
if (!hasMethodWithName) {
return EMPTY_LIST;
} else {
final MethodInfoList matchingMethods = new MethodInfoList(2);
for (final MethodInfo mi : this) {
if (mi.getName().equals(methodName)) {
matchingMethods.add(mi);
}
}
return matchingMethods;
}
}
/**
* Returns a single method with the given name, or null if not found. Throws {@link IllegalArgumentException} if
* there are two methods with the given name.
*
* @param methodName
* The name of a method.
* @return The {@link MethodInfo} object from the list with the given name, if there is exactly one method with
* the given name. Returns null if there were no methods with the given name.
* @throws IllegalArgumentException
* if there are two or more methods with the given name.
*/
public MethodInfo getSingleMethod(final String methodName) {
int numMethodsWithName = 0;
MethodInfo lastFoundMethod = null;
for (final MethodInfo mi : this) {
if (mi.getName().equals(methodName)) {
numMethodsWithName++;
lastFoundMethod = mi;
}
}
if (numMethodsWithName == 0) {
return null;
} else if (numMethodsWithName == 1) {
return lastFoundMethod;
} else {
throw new IllegalArgumentException("There are multiple methods named \"" + methodName + "\" in class "
+ iterator().next().getClassInfo().getName());
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Filter an {@link MethodInfoList} using a predicate mapping an {@link MethodInfo} object to a boolean,
* producing another {@link MethodInfoList} for all items in the list for which the predicate is true.
*/
@FunctionalInterface
public interface MethodInfoFilter {
/**
* Whether or not to allow an {@link MethodInfo} list item through the filter.
*
* @param methodInfo
* The {@link MethodInfo} item to filter.
* @return Whether or not to allow the item through the filter. If true, the item is copied to the output
* list; if false, it is excluded.
*/
boolean accept(MethodInfo methodInfo);
}
/**
* Find the subset of the {@link MethodInfo} objects in this list for which the given filter predicate is true.
*
* @param filter
* The {@link MethodInfoFilter} to apply.
* @return The subset of the {@link MethodInfo} objects in this list for which the given filter predicate is
* true.
*/
public MethodInfoList filter(final MethodInfoFilter filter) {
final MethodInfoList methodInfoFiltered = new MethodInfoList();
for (final MethodInfo resource : this) {
if (filter.accept(resource)) {
methodInfoFiltered.add(resource);
}
}
return methodInfoFiltered;
}
}
|
// Note that MethodInfoList extends InfoList rather than MappableInfoList, because one
// name can be shared by multiple MethodInfo objects (so asMap() needs to be of type
// Map<String, MethodInfoList> rather than Map<String, MethodInfo>)
final Map<String, MethodInfoList> methodNameToMethodInfoList = new HashMap<>();
for (final MethodInfo methodInfo : this) {
final String name = methodInfo.getName();
MethodInfoList methodInfoList = methodNameToMethodInfoList.get(name);
if (methodInfoList == null) {
methodInfoList = new MethodInfoList(1);
methodNameToMethodInfoList.put(name, methodInfoList);
}
methodInfoList.add(methodInfo);
}
return methodNameToMethodInfoList;
| 1,753
| 202
| 1,955
|
<methods>public boolean equals(java.lang.Object) ,public List<java.lang.String> getAsStrings() ,public List<java.lang.String> getAsStringsWithSimpleNames() ,public List<java.lang.String> getNames() ,public int hashCode() <variables>static final long serialVersionUID
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/ModuleInfoList.java
|
ModuleInfoList
|
filter
|
class ModuleInfoList extends MappableInfoList<ModuleInfo> {
/** serialVersionUID */
private static final long serialVersionUID = 1L;
/**
* Constructor.
*/
ModuleInfoList() {
super();
}
/**
* Constructor.
*
* @param sizeHint
* the size hint
*/
ModuleInfoList(final int sizeHint) {
super(sizeHint);
}
/**
* Constructor.
*
* @param moduleInfoCollection
* the module info collection
*/
ModuleInfoList(final Collection<ModuleInfo> moduleInfoCollection) {
super(moduleInfoCollection);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Filter an {@link ModuleInfoList} using a predicate mapping an {@link ModuleInfo} object to a boolean,
* producing another {@link ModuleInfoList} for all items in the list for which the predicate is true.
*/
@FunctionalInterface
public interface ModuleInfoFilter {
/**
* Whether or not to allow an {@link ModuleInfo} list item through the filter.
*
* @param moduleInfo
* The {@link ModuleInfo} item to filter.
* @return Whether or not to allow the item through the filter. If true, the item is copied to the output
* list; if false, it is excluded.
*/
boolean accept(ModuleInfo moduleInfo);
}
/**
* Find the subset of the {@link ModuleInfo} objects in this list for which the given filter predicate is true.
*
* @param filter
* The {@link ModuleInfoFilter} to apply.
* @return The subset of the {@link ModuleInfo} objects in this list for which the given filter predicate is
* true.
*/
public ModuleInfoList filter(final ModuleInfoFilter filter) {<FILL_FUNCTION_BODY>}
}
|
final ModuleInfoList moduleInfoFiltered = new ModuleInfoList();
for (final ModuleInfo resource : this) {
if (filter.accept(resource)) {
moduleInfoFiltered.add(resource);
}
}
return moduleInfoFiltered;
| 474
| 67
| 541
|
<methods>public Map<java.lang.String,io.github.classgraph.ModuleInfo> asMap() ,public boolean containsName(java.lang.String) ,public io.github.classgraph.ModuleInfo get(java.lang.String) <variables>private static final long serialVersionUID
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/ModuleReaderProxy.java
|
ModuleReaderProxy
|
read
|
class ModuleReaderProxy implements Closeable {
/** The module reader. */
private final AutoCloseable moduleReader;
/** Class<Collector> collectorClass = Class.forName("java.util.stream.Collector"); */
private static Class<?> collectorClass;
/** Collector<Object, ?, List<Object>> collectorsToList = Collectors.toList(); */
private static Object collectorsToList;
private ReflectionUtils reflectionUtils;
/**
* Constructor.
*
* @param moduleRef
* the module ref
* @throws IOException
* If an I/O exception occurs.
*/
ModuleReaderProxy(final ModuleRef moduleRef) throws IOException {
try {
reflectionUtils = moduleRef.reflectionUtils;
if (collectorClass == null || collectorsToList == null) {
collectorClass = reflectionUtils.classForNameOrNull("java.util.stream.Collector");
final Class<?> collectorsClass = reflectionUtils.classForNameOrNull("java.util.stream.Collectors");
if (collectorsClass != null) {
collectorsToList = reflectionUtils.invokeStaticMethod(/* throwException = */ true,
collectorsClass, "toList");
}
}
moduleReader = (AutoCloseable) reflectionUtils.invokeMethod(/* throwException = */ true,
moduleRef.getReference(), "open");
if (moduleReader == null) {
throw new IllegalArgumentException("moduleReference.open() should not return null");
}
} catch (final SecurityException e) {
throw new IOException("Could not open module " + moduleRef.getName(), e);
}
}
/** Calls ModuleReader#close(). */
@Override
public void close() {
try {
moduleReader.close();
} catch (final Exception e) {
// Ignore
}
}
/**
* Get the list of resources accessible to a ModuleReader.
*
* From the documentation for ModuleReader#list(): "Whether the stream of elements includes names corresponding
* to directories in the module is module reader specific. In lazy implementations then an IOException may be
* thrown when using the stream to list the module contents. If this occurs then the IOException will be wrapped
* in an java.io.UncheckedIOException and thrown from the method that caused the access to be attempted.
* SecurityException may also be thrown when using the stream to list the module contents and access is denied
* by the security manager."
*
* @return A list of the paths of resources in the module.
* @throws SecurityException
* If the module cannot be accessed.
*/
public List<String> list() throws SecurityException {
if (collectorsToList == null) {
throw new IllegalArgumentException("Could not call Collectors.toList()");
}
final Object /* Stream<String> */ resourcesStream = reflectionUtils
.invokeMethod(/* throwException = */ true, moduleReader, "list");
if (resourcesStream == null) {
throw new IllegalArgumentException("Could not call moduleReader.list()");
}
final Object resourcesList = reflectionUtils.invokeMethod(/* throwException = */ true, resourcesStream,
"collect", collectorClass, collectorsToList);
if (resourcesList == null) {
throw new IllegalArgumentException("Could not call moduleReader.list().collect(Collectors.toList())");
}
@SuppressWarnings("unchecked")
final List<String> resourcesListTyped = (List<String>) resourcesList;
return resourcesListTyped;
}
/**
* Use the proxied ModuleReader to open the named resource as an InputStream.
*
* @param path
* The path to the resource to open.
*
* @return An {@link InputStream} for the content of the resource.
* @throws SecurityException
* If the module cannot be accessed.
* @throws IllegalArgumentException
* If the module cannot be accessed.
*/
public InputStream open(final String path) throws SecurityException {
final Object /* Optional<InputStream> */ optionalInputStream = reflectionUtils
.invokeMethod(/* throwException = */ true, moduleReader, "open", String.class, path);
if (optionalInputStream == null) {
throw new IllegalArgumentException("Got null result from ModuleReader#open for path " + path);
}
final InputStream inputStream = (InputStream) reflectionUtils.invokeMethod(/* throwException = */ true,
optionalInputStream, "get");
if (inputStream == null) {
throw new IllegalArgumentException("Got null result from ModuleReader#open(String)#get()");
}
return inputStream;
}
/**
* Use the proxied ModuleReader to open the named resource as a ByteBuffer. Call {@link #release(ByteBuffer)}
* when you have finished with the ByteBuffer.
*
* @param path
* The path to the resource to open.
* @return A {@link ByteBuffer} for the content of the resource.
* @throws SecurityException
* If the module cannot be accessed.
* @throws OutOfMemoryError
* if the resource is larger than 2GB, the maximum capacity of a byte buffer.
*/
public ByteBuffer read(final String path) throws SecurityException, OutOfMemoryError {<FILL_FUNCTION_BODY>}
/**
* Release a {@link ByteBuffer} allocated by calling {@link #read(String)}.
*
* @param byteBuffer
* The {@link ByteBuffer} to release.
*/
public void release(final ByteBuffer byteBuffer) {
reflectionUtils.invokeMethod(/* throwException = */ true, moduleReader, "release", ByteBuffer.class,
byteBuffer);
}
/**
* Use the proxied ModuleReader to find the named resource as a URI.
*
* @param path
* The path to the resource to open.
* @return A {@link URI} for the resource.
* @throws SecurityException
* If the module cannot be accessed.
*/
public URI find(final String path) {
final Object /* Optional<URI> */ optionalURI = reflectionUtils.invokeMethod(/* throwException = */ true,
moduleReader, "find", String.class, path);
if (optionalURI == null) {
throw new IllegalArgumentException("Got null result from ModuleReader#find(String)");
}
final URI uri = (URI) reflectionUtils.invokeMethod(/* throwException = */ true, optionalURI, "get");
if (uri == null) {
throw new IllegalArgumentException("Got null result from ModuleReader#find(String).get()");
}
return uri;
}
}
|
final Object /* Optional<ByteBuffer> */ optionalByteBuffer = reflectionUtils
.invokeMethod(/* throwException = */ true, moduleReader, "read", String.class, path);
if (optionalByteBuffer == null) {
throw new IllegalArgumentException("Got null result from ModuleReader#read(String)");
}
final ByteBuffer byteBuffer = (ByteBuffer) reflectionUtils.invokeMethod(/* throwException = */ true,
optionalByteBuffer, "get");
if (byteBuffer == null) {
throw new IllegalArgumentException("Got null result from ModuleReader#read(String).get()");
}
return byteBuffer;
| 1,651
| 154
| 1,805
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/PackageInfoList.java
|
PackageInfoList
|
filter
|
class PackageInfoList extends MappableInfoList<PackageInfo> {
/** serialVersionUID */
private static final long serialVersionUID = 1L;
/**
* Constructor.
*/
PackageInfoList() {
super();
}
/**
* Constructor.
*
* @param sizeHint
* the size hint
*/
PackageInfoList(final int sizeHint) {
super(sizeHint);
}
/**
* Constructor.
*
* @param packageInfoCollection
* the package info collection
*/
PackageInfoList(final Collection<PackageInfo> packageInfoCollection) {
super(packageInfoCollection);
}
/** An unmodifiable {@link PackageInfoList}. */
static final PackageInfoList EMPTY_LIST = new PackageInfoList() {
/** serialVersionUID */
private static final long serialVersionUID = 1L;
@Override
public boolean add(final PackageInfo e) {
throw new IllegalArgumentException("List is immutable");
}
@Override
public void add(final int index, final PackageInfo element) {
throw new IllegalArgumentException("List is immutable");
}
@Override
public boolean remove(final Object o) {
throw new IllegalArgumentException("List is immutable");
}
@Override
public PackageInfo remove(final int index) {
throw new IllegalArgumentException("List is immutable");
}
@Override
public boolean addAll(final Collection<? extends PackageInfo> c) {
throw new IllegalArgumentException("List is immutable");
}
@Override
public boolean addAll(final int index, final Collection<? extends PackageInfo> c) {
throw new IllegalArgumentException("List is immutable");
}
@Override
public boolean removeAll(final Collection<?> c) {
throw new IllegalArgumentException("List is immutable");
}
@Override
public boolean retainAll(final Collection<?> c) {
throw new IllegalArgumentException("List is immutable");
}
@Override
public void clear() {
throw new IllegalArgumentException("List is immutable");
}
@Override
public PackageInfo set(final int index, final PackageInfo element) {
throw new IllegalArgumentException("List is immutable");
}
};
// -------------------------------------------------------------------------------------------------------------
/**
* Filter an {@link PackageInfoList} using a predicate mapping an {@link PackageInfo} object to a boolean,
* producing another {@link PackageInfoList} for all items in the list for which the predicate is true.
*/
@FunctionalInterface
public interface PackageInfoFilter {
/**
* Whether or not to allow an {@link PackageInfo} list item through the filter.
*
* @param packageInfo
* The {@link PackageInfo} item to filter.
* @return Whether or not to allow the item through the filter. If true, the item is copied to the output
* list; if false, it is excluded.
*/
boolean accept(PackageInfo packageInfo);
}
/**
* Find the subset of the {@link PackageInfo} objects in this list for which the given filter predicate is true.
*
* @param filter
* The {@link PackageInfoFilter} to apply.
* @return The subset of the {@link PackageInfo} objects in this list for which the given filter predicate is
* true.
*/
public PackageInfoList filter(final PackageInfoFilter filter) {<FILL_FUNCTION_BODY>}
}
|
final PackageInfoList packageInfoFiltered = new PackageInfoList();
for (final PackageInfo resource : this) {
if (filter.accept(resource)) {
packageInfoFiltered.add(resource);
}
}
return packageInfoFiltered;
| 876
| 67
| 943
|
<methods>public Map<java.lang.String,io.github.classgraph.PackageInfo> asMap() ,public boolean containsName(java.lang.String) ,public io.github.classgraph.PackageInfo get(java.lang.String) <variables>private static final long serialVersionUID
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/PotentiallyUnmodifiableList.java
|
PotentiallyUnmodifiableList
|
hasPrevious
|
class PotentiallyUnmodifiableList<T> extends ArrayList<T> {
/** serialVersionUID. */
static final long serialVersionUID = 1L;
/** Whether or not the list is modifiable. */
boolean modifiable = true;
/**
* Constructor.
*/
PotentiallyUnmodifiableList() {
super();
}
/**
* Constructor.
*
* @param sizeHint
* the size hint
*/
PotentiallyUnmodifiableList(final int sizeHint) {
super(sizeHint);
}
/**
* Constructor.
*
* @param collection
* the initial elements.
*/
PotentiallyUnmodifiableList(final Collection<T> collection) {
super(collection);
}
// Keep Scrutinizer happy
@Override
public boolean equals(final Object o) {
return super.equals(o);
}
// Keep Scrutinizer happy
@Override
public int hashCode() {
return super.hashCode();
}
/** Make this list unmodifiable. */
void makeUnmodifiable() {
modifiable = false;
}
@Override
public boolean add(final T element) {
if (!modifiable) {
throw new IllegalArgumentException("List is immutable");
} else {
return super.add(element);
}
}
@Override
public void add(final int index, final T element) {
if (!modifiable) {
throw new IllegalArgumentException("List is immutable");
} else {
super.add(index, element);
}
}
@Override
public boolean remove(final Object o) {
if (!modifiable) {
throw new IllegalArgumentException("List is immutable");
} else {
return super.remove(o);
}
}
@Override
public T remove(final int index) {
if (!modifiable) {
throw new IllegalArgumentException("List is immutable");
} else {
return super.remove(index);
}
}
@Override
public boolean addAll(final Collection<? extends T> c) {
if (!modifiable && !c.isEmpty()) {
throw new IllegalArgumentException("List is immutable");
} else {
return super.addAll(c);
}
}
@Override
public boolean addAll(final int index, final Collection<? extends T> c) {
if (!modifiable && !c.isEmpty()) {
throw new IllegalArgumentException("List is immutable");
} else {
return super.addAll(index, c);
}
}
@Override
public boolean removeAll(final Collection<?> c) {
if (!modifiable && !c.isEmpty()) {
throw new IllegalArgumentException("List is immutable");
} else {
return super.removeAll(c);
}
}
@Override
public boolean retainAll(final Collection<?> c) {
if (!modifiable && !isEmpty()) {
throw new IllegalArgumentException("List is immutable");
} else {
return super.retainAll(c);
}
}
@Override
public void clear() {
if (!modifiable && !isEmpty()) {
throw new IllegalArgumentException("List is immutable");
} else {
super.clear();
}
}
@Override
public T set(final int index, final T element) {
if (!modifiable) {
throw new IllegalArgumentException("List is immutable");
} else {
return super.set(index, element);
}
}
// Provide replacement iterators so that there is no chance of a thread that
// is trying to sort the empty list causing a ConcurrentModificationException
// in another thread that is iterating over the empty list (#334)
@Override
public Iterator<T> iterator() {
final Iterator<T> iterator = super.iterator();
return new Iterator<T>() {
@Override
public boolean hasNext() {
if (isEmpty()) {
return false;
} else {
return iterator.hasNext();
}
}
@Override
public T next() {
return iterator.next();
}
@Override
public void remove() {
if (!modifiable) {
throw new IllegalArgumentException("List is immutable");
} else {
iterator.remove();
}
}
};
}
@Override
public ListIterator<T> listIterator() {
final ListIterator<T> iterator = super.listIterator();
return new ListIterator<T>() {
@Override
public boolean hasNext() {
if (isEmpty()) {
return false;
} else {
return iterator.hasNext();
}
}
@Override
public T next() {
return iterator.next();
}
@Override
public boolean hasPrevious() {<FILL_FUNCTION_BODY>}
@Override
public T previous() {
return iterator.previous();
}
@Override
public int nextIndex() {
if (isEmpty()) {
return 0;
} else {
return iterator.nextIndex();
}
}
@Override
public int previousIndex() {
if (isEmpty()) {
return -1;
} else {
return iterator.previousIndex();
}
}
@Override
public void remove() {
if (!modifiable) {
throw new IllegalArgumentException("List is immutable");
} else {
iterator.remove();
}
}
@Override
public void set(final T e) {
if (!modifiable) {
throw new IllegalArgumentException("List is immutable");
} else {
iterator.set(e);
}
}
@Override
public void add(final T e) {
if (!modifiable) {
throw new IllegalArgumentException("List is immutable");
} else {
iterator.add(e);
}
}
};
}
}
|
if (isEmpty()) {
return false;
} else {
return iterator.hasPrevious();
}
| 1,564
| 32
| 1,596
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Collection<? extends T>) ,public boolean add(T) ,public void add(int, T) ,public boolean addAll(Collection<? extends T>) ,public boolean addAll(int, Collection<? extends T>) ,public void clear() ,public java.lang.Object clone() ,public boolean contains(java.lang.Object) ,public void ensureCapacity(int) ,public boolean equals(java.lang.Object) ,public void forEach(Consumer<? super T>) ,public T get(int) ,public int hashCode() ,public int indexOf(java.lang.Object) ,public boolean isEmpty() ,public Iterator<T> iterator() ,public int lastIndexOf(java.lang.Object) ,public ListIterator<T> listIterator() ,public ListIterator<T> listIterator(int) ,public T remove(int) ,public boolean remove(java.lang.Object) ,public boolean removeAll(Collection<?>) ,public boolean removeIf(Predicate<? super T>) ,public void replaceAll(UnaryOperator<T>) ,public boolean retainAll(Collection<?>) ,public T set(int, T) ,public int size() ,public void sort(Comparator<? super T>) ,public Spliterator<T> spliterator() ,public List<T> subList(int, int) ,public java.lang.Object[] toArray() ,public T[] toArray(T[]) ,public void trimToSize() <variables>private static final java.lang.Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA,private static final int DEFAULT_CAPACITY,private static final java.lang.Object[] EMPTY_ELEMENTDATA,transient java.lang.Object[] elementData,private static final long serialVersionUID,private int size
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/ReferenceTypeSignature.java
|
ReferenceTypeSignature
|
parseReferenceTypeSignature
|
class ReferenceTypeSignature extends TypeSignature {
/** Constructor. */
protected ReferenceTypeSignature() {
super();
}
/**
* Parse a reference type signature.
*
* @param parser
* The parser
* @param definingClassName
* The class containing the type descriptor.
* @return The parsed type reference type signature.
* @throws ParseException
* If the type signature could not be parsed.
*/
static ReferenceTypeSignature parseReferenceTypeSignature(final Parser parser, final String definingClassName)
throws ParseException {<FILL_FUNCTION_BODY>}
/**
* Parse a class bound.
*
* @param parser
* The parser.
* @param definingClassName
* The class containing the type descriptor.
* @return The parsed class bound.
* @throws ParseException
* If the type signature could not be parsed.
*/
static ReferenceTypeSignature parseClassBound(final Parser parser, final String definingClassName)
throws ParseException {
parser.expect(':');
// May return null if there is no signature after ':' (class bound signature may be empty)
return parseReferenceTypeSignature(parser, definingClassName);
}
}
|
final ClassRefTypeSignature classTypeSignature = ClassRefTypeSignature.parse(parser, definingClassName);
if (classTypeSignature != null) {
return classTypeSignature;
}
final TypeVariableSignature typeVariableSignature = TypeVariableSignature.parse(parser, definingClassName);
if (typeVariableSignature != null) {
return typeVariableSignature;
}
final ArrayTypeSignature arrayTypeSignature = ArrayTypeSignature.parse(parser, definingClassName);
if (arrayTypeSignature != null) {
return arrayTypeSignature;
}
return null;
| 317
| 142
| 459
|
<methods>public abstract boolean equalsIgnoringTypeParams(io.github.classgraph.TypeSignature) ,public io.github.classgraph.AnnotationInfoList getTypeAnnotationInfo() <variables>
|
classgraph_classgraph
|
classgraph/src/main/java/io/github/classgraph/TypeSignature.java
|
TypeSignature
|
parse
|
class TypeSignature extends HierarchicalTypeSignature {
/** Constructor. */
protected TypeSignature() {
// Empty
}
/**
* Get the names of any classes referenced in the type signature.
*
* @param refdClassNames
* the referenced class names.
*/
protected void findReferencedClassNames(final Set<String> refdClassNames) {
final String className = getClassName();
if (className != null && !className.isEmpty()) {
refdClassNames.add(getClassName());
}
}
/**
* Get {@link ClassInfo} objects for any classes referenced in the type signature.
*
* @param classNameToClassInfo
* the map from class name to {@link ClassInfo}.
* @param refdClassInfo
* the referenced class info.
*/
@Override
final protected void findReferencedClassInfo(final Map<String, ClassInfo> classNameToClassInfo,
final Set<ClassInfo> refdClassInfo, final LogNode log) {
final Set<String> refdClassNames = new HashSet<>();
findReferencedClassNames(refdClassNames);
for (final String refdClassName : refdClassNames) {
final ClassInfo classInfo = ClassInfo.getOrCreateClassInfo(refdClassName, classNameToClassInfo);
classInfo.scanResult = scanResult;
refdClassInfo.add(classInfo);
}
}
/**
* Get a list of {@link AnnotationInfo} objects for any type annotations on this type, or null if none.
*
* @return a list of {@link AnnotationInfo} objects for any type annotations on this type, or null if none.
*/
public AnnotationInfoList getTypeAnnotationInfo() {
return typeAnnotationInfo;
}
/**
* Compare base types, ignoring generic type parameters.
*
* @param other
* the other {@link TypeSignature} to compare to.
* @return True if the two {@link TypeSignature} objects are equal, ignoring type parameters.
*/
public abstract boolean equalsIgnoringTypeParams(final TypeSignature other);
/**
* Parse a type signature.
*
* @param parser
* The parser
* @param definingClass
* The class containing the type descriptor.
* @return The parsed type descriptor or type signature.
* @throws ParseException
* If the type signature could not be parsed.
*/
static TypeSignature parse(final Parser parser, final String definingClass) throws ParseException {
final ReferenceTypeSignature referenceTypeSignature = ReferenceTypeSignature
.parseReferenceTypeSignature(parser, definingClass);
if (referenceTypeSignature != null) {
return referenceTypeSignature;
}
final BaseTypeSignature baseTypeSignature = BaseTypeSignature.parse(parser);
if (baseTypeSignature != null) {
return baseTypeSignature;
}
return null;
}
/**
* Parse a type signature.
*
* @param typeDescriptor
* The type descriptor or type signature to parse.
* @param definingClass
* The class containing the type descriptor.
* @return The parsed type descriptor or type signature.
* @throws ParseException
* If the type signature could not be parsed.
*/
static TypeSignature parse(final String typeDescriptor, final String definingClass) throws ParseException {<FILL_FUNCTION_BODY>}
/**
* Add a type annotation to this type.
*
* @param typePath
* The type path.
* @param annotationInfo
* The annotation to add.
*/
@Override
protected abstract void addTypeAnnotation(List<TypePathNode> typePath, AnnotationInfo annotationInfo);
}
|
final Parser parser = new Parser(typeDescriptor);
TypeSignature typeSignature;
typeSignature = parse(parser, definingClass);
if (typeSignature == null) {
throw new ParseException(parser, "Could not parse type signature");
}
if (parser.hasMore()) {
throw new ParseException(parser, "Extra characters at end of type descriptor");
}
return typeSignature;
| 951
| 104
| 1,055
|
<methods>public non-sealed void <init>() ,public io.github.classgraph.AnnotationInfoList getTypeAnnotationInfo() <variables>protected io.github.classgraph.AnnotationInfoList typeAnnotationInfo
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/AntClassLoaderHandler.java
|
AntClassLoaderHandler
|
findClassLoaderOrder
|
class AntClassLoaderHandler implements ClassLoaderHandler {
/** Class cannot be constructed. */
private AntClassLoaderHandler() {
}
/**
* Check whether this {@link ClassLoaderHandler} can handle a given {@link ClassLoader}.
*
* @param classLoaderClass
* the {@link ClassLoader} class or one of its superclasses.
* @param log
* the log
* @return true if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {
return "org.apache.tools.ant.AntClassLoader".equals(classLoaderClass.getName());
}
/**
* Find the {@link ClassLoader} delegation order for a {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the order for.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object to update.
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {<FILL_FUNCTION_BODY>}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {
classpathOrder.addClasspathPathStr(
(String) classpathOrder.reflectionUtils.invokeMethod(false, classLoader, "getClasspath"),
classLoader, scanSpec, log);
}
}
|
classLoaderOrder.delegateTo(classLoader.getParent(), /* isParent = */ true, log);
classLoaderOrder.add(classLoader, log);
| 500
| 42
| 542
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/ClassGraphClassLoaderHandler.java
|
ClassGraphClassLoaderHandler
|
findClasspathOrder
|
class ClassGraphClassLoaderHandler implements ClassLoaderHandler {
/** Class cannot be constructed. */
private ClassGraphClassLoaderHandler() {
}
/**
* Check whether this {@link ClassLoaderHandler} can handle a given {@link ClassLoader}.
*
* @param classLoaderClass
* the {@link ClassLoader} class or one of its superclasses.
* @param log
* the log
* @return true if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {
final boolean matches = "io.github.classgraph.ClassGraphClassLoader".equals(classLoaderClass.getName());
if (matches && log != null) {
log.log("Sharing a `ClassGraphClassLoader` between multiple nested scans is not advisable, "
+ "because scan criteria may differ between scans. "
+ "See: https://github.com/classgraph/classgraph/issues/485");
}
return matches;
}
/**
* Find the {@link ClassLoader} delegation order for a {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the order for.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object to update.
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {
classLoaderOrder.delegateTo(classLoader.getParent(), /* isParent = */ true, log);
classLoaderOrder.add(classLoader, log);
}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {<FILL_FUNCTION_BODY>}
}
|
// ClassGraphClassLoader overrides URLClassLoader, so we can get the basic classpath URLs the same
// way as for URLClassLoader. However, classloading will try to preferentially reuse the older
// ClassGraphClassLoader before loading with the new ClassGraphClassLoader from the current scan,
// so the following URLs will be scanned by the current scan, but classes will only be loaded from
// these URLs if the older classloader fails.
for (final URL url : ((ClassGraphClassLoader) classLoader).getURLs()) {
if (url != null) {
classpathOrder.addClasspathEntry(url, classLoader, scanSpec, log);
}
}
| 582
| 168
| 750
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/ClassLoaderHandlerRegistry.java
|
ClassLoaderHandlerRegistryEntry
|
findClassLoaderOrder
|
class ClassLoaderHandlerRegistryEntry {
/** canHandle method. */
private final Method canHandleMethod;
/** findClassLoaderOrder method. */
private final Method findClassLoaderOrderMethod;
/** findClasspathOrder method. */
private final Method findClasspathOrderMethod;
/** The ClassLoaderHandler class. */
public final Class<? extends ClassLoaderHandler> classLoaderHandlerClass;
/**
* Constructor.
*
* @param classLoaderHandlerClass
* The ClassLoaderHandler class.
*/
private ClassLoaderHandlerRegistryEntry(final Class<? extends ClassLoaderHandler> classLoaderHandlerClass) {
// TODO: replace these with MethodHandles for speed
// TODO: (although MethodHandles are disabled for now, due to Animal Sniffer bug):
// https://github.com/mojohaus/animal-sniffer/issues/67
this.classLoaderHandlerClass = classLoaderHandlerClass;
try {
canHandleMethod = classLoaderHandlerClass.getDeclaredMethod("canHandle", Class.class,
LogNode.class);
} catch (final Exception e) {
throw new RuntimeException(
"Could not find canHandle method for " + classLoaderHandlerClass.getName(), e);
}
try {
findClassLoaderOrderMethod = classLoaderHandlerClass.getDeclaredMethod("findClassLoaderOrder",
ClassLoader.class, ClassLoaderOrder.class, LogNode.class);
} catch (final Exception e) {
throw new RuntimeException(
"Could not find findClassLoaderOrder method for " + classLoaderHandlerClass.getName(), e);
}
try {
findClasspathOrderMethod = classLoaderHandlerClass.getDeclaredMethod("findClasspathOrder",
ClassLoader.class, ClasspathOrder.class, ScanSpec.class, LogNode.class);
} catch (final Exception e) {
throw new RuntimeException(
"Could not find findClasspathOrder method for " + classLoaderHandlerClass.getName(), e);
}
}
/**
* Call the static method canHandle(ClassLoader) for the associated {@link ClassLoaderHandler}.
*
* @param classLoader
* the {@link ClassLoader}.
* @param log
* the log.
* @return true, if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public boolean canHandle(final Class<?> classLoader, final LogNode log) {
try {
return (boolean) canHandleMethod.invoke(null, classLoader, log);
} catch (final Throwable e) {
throw new RuntimeException(
"Exception while calling canHandle for " + classLoaderHandlerClass.getName(), e);
}
}
/**
* Call the static method findClassLoaderOrder(ClassLoader, ClassLoaderOrder) for the associated
* {@link ClassLoaderHandler}.
*
* @param classLoader
* the {@link ClassLoader}.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object.
* @param log
* the log
*/
public void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {<FILL_FUNCTION_BODY>}
/**
* Call the static method findClasspathOrder(ClassLoader, ClasspathOrder) for the associated
* {@link ClassLoaderHandler}.
*
* @param classLoader
* the {@link ClassLoader}.
* @param classpathOrder
* a {@link ClasspathOrder} object.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {
try {
findClasspathOrderMethod.invoke(null, classLoader, classpathOrder, scanSpec, log);
} catch (final Throwable e) {
throw new RuntimeException(
"Exception while calling findClassLoaderOrder for " + classLoaderHandlerClass.getName(), e);
}
}
}
|
try {
findClassLoaderOrderMethod.invoke(null, classLoader, classLoaderOrder, log);
} catch (final Throwable e) {
throw new RuntimeException(
"Exception while calling findClassLoaderOrder for " + classLoaderHandlerClass.getName(), e);
}
| 1,022
| 72
| 1,094
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/CxfContainerClassLoaderHandler.java
|
CxfContainerClassLoaderHandler
|
findClassLoaderOrder
|
class CxfContainerClassLoaderHandler implements ClassLoaderHandler {
/** Class cannot be constructed. */
private CxfContainerClassLoaderHandler() {
}
/**
* Check whether this {@link ClassLoaderHandler} can handle a given {@link ClassLoader}.
*
* @param classLoaderClass
* the {@link ClassLoader} class or one of its superclasses.
* @param log
* the log
* @return true if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {
return "org.apache.openejb.server.cxf.transport.util.CxfContainerClassLoader"
.equals(classLoaderClass.getName());
}
/**
* Find the {@link ClassLoader} delegation order for a {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the order for.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object to update.
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {<FILL_FUNCTION_BODY>}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {
// Classloader doesn't do any classloading of its own, it only delegates to other classloaders
}
}
|
try {
classLoaderOrder.delegateTo(
Class.forName("org.apache.openejb.server.cxf.transport.util.CxfUtil").getClassLoader(),
/* isParent = */ true, log);
} catch (LinkageError | ClassNotFoundException e) {
// Ignore
}
// tccl = TomcatClassLoader
classLoaderOrder.delegateTo(
(ClassLoader) classLoaderOrder.reflectionUtils.invokeMethod(false, classLoader, "tccl"),
/* isParent = */ false, log);
// This classloader doesn't actually load any classes, but add it to the order to improve logging
classLoaderOrder.add(classLoader, log);
| 497
| 180
| 677
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/EquinoxContextFinderClassLoaderHandler.java
|
EquinoxContextFinderClassLoaderHandler
|
findClassLoaderOrder
|
class EquinoxContextFinderClassLoaderHandler implements ClassLoaderHandler {
/** Class cannot be constructed. */
private EquinoxContextFinderClassLoaderHandler() {
}
/**
* Check whether this {@link ClassLoaderHandler} can handle a given {@link ClassLoader}.
*
* @param classLoaderClass
* the {@link ClassLoader} class or one of its superclasses.
* @param log
* the log
* @return true if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {
return "org.eclipse.osgi.internal.framework.ContextFinder".equals(classLoaderClass.getName());
}
/**
* Find the {@link ClassLoader} delegation order for a {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the order for.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object to update.
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {<FILL_FUNCTION_BODY>}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {
// Nothing to handle -- embedded parentContextClassLoader will be used instead.
}
}
|
classLoaderOrder.delegateTo((ClassLoader) classLoaderOrder.reflectionUtils.getFieldVal(false, classLoader,
"parentContextClassLoader"), /* isParent = */ true, log);
classLoaderOrder.delegateTo(classLoader.getParent(), /* isParent = */ true, log);
classLoaderOrder.add(classLoader, log);
| 483
| 90
| 573
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/FelixClassLoaderHandler.java
|
FelixClassLoaderHandler
|
addBundle
|
class FelixClassLoaderHandler implements ClassLoaderHandler {
/** Class cannot be constructed. */
private FelixClassLoaderHandler() {
}
/**
* Check whether this {@link ClassLoaderHandler} can handle a given {@link ClassLoader}.
*
* @param classLoaderClass
* the {@link ClassLoader} class or one of its superclasses.
* @param log
* the log
* @return true if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {
return "org.apache.felix.framework.BundleWiringImpl$BundleClassLoaderJava5"
.equals(classLoaderClass.getName())
|| "org.apache.felix.framework.BundleWiringImpl$BundleClassLoader"
.equals(classLoaderClass.getName());
}
/**
* Find the {@link ClassLoader} delegation order for a {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the order for.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object to update.
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {
classLoaderOrder.delegateTo(classLoader.getParent(), /* isParent = */ true, log);
classLoaderOrder.add(classLoader, log);
}
/**
* Get the content location.
*
* @param content
* the content object
* @return the content location
*/
private static File getContentLocation(final Object content, final ReflectionUtils reflectionUtils) {
return (File) reflectionUtils.invokeMethod(false, content, "getFile");
}
/**
* Adds the bundle.
*
* @param bundleWiring
* the bundle wiring
* @param classLoader
* the classloader
* @param classpathOrderOut
* the classpath order out
* @param bundles
* the bundles
* @param scanSpec
* the scan spec
* @param log
* the log
*/
private static void addBundle(final Object bundleWiring, final ClassLoader classLoader,
final ClasspathOrder classpathOrderOut, final Set<Object> bundles, final ScanSpec scanSpec,
final LogNode log) {<FILL_FUNCTION_BODY>}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {
// Get the wiring for the ClassLoader's bundle
final Set<Object> bundles = new HashSet<>();
final Object bundleWiring = classpathOrder.reflectionUtils.getFieldVal(false, classLoader, "m_wiring");
addBundle(bundleWiring, classLoader, classpathOrder, bundles, scanSpec, log);
// Deal with any other bundles we might be wired to. TODO: Use the ScanSpec to narrow down the list of wires
// that we follow.
final List<?> requiredWires = (List<?>) classpathOrder.reflectionUtils.invokeMethod(false, bundleWiring,
"getRequiredWires", String.class, null);
if (requiredWires != null) {
for (final Object wire : requiredWires) {
final Object provider = classpathOrder.reflectionUtils.invokeMethod(false, wire,
"getProviderWiring");
if (!bundles.contains(provider)) {
addBundle(provider, classLoader, classpathOrder, bundles, scanSpec, log);
}
}
}
}
}
|
// Track the bundles we've processed to prevent loops
bundles.add(bundleWiring);
// Get the revision for this wiring
final Object revision = classpathOrderOut.reflectionUtils.invokeMethod(false, bundleWiring, "getRevision");
// Get the contents
final Object content = classpathOrderOut.reflectionUtils.invokeMethod(false, revision, "getContent");
final File location = content != null ? getContentLocation(content, classpathOrderOut.reflectionUtils)
: null;
if (location != null) {
// Add the bundle object
classpathOrderOut.addClasspathEntry(location, classLoader, scanSpec, log);
// And any embedded content
final List<?> embeddedContent = (List<?>) classpathOrderOut.reflectionUtils.invokeMethod(false,
revision, "getContentPath");
if (embeddedContent != null) {
for (final Object embedded : embeddedContent) {
if (embedded != content) {
final File embeddedLocation = embedded != null
? getContentLocation(embedded, classpathOrderOut.reflectionUtils)
: null;
if (embeddedLocation != null) {
classpathOrderOut.addClasspathEntry(embeddedLocation, classLoader, scanSpec, log);
}
}
}
}
}
| 1,050
| 335
| 1,385
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/JPMSClassLoaderHandler.java
|
JPMSClassLoaderHandler
|
findClasspathOrder
|
class JPMSClassLoaderHandler implements ClassLoaderHandler {
/** Class cannot be constructed. */
private JPMSClassLoaderHandler() {
}
/**
* Check whether this {@link ClassLoaderHandler} can handle a given {@link ClassLoader}.
*
* @param classLoaderClass
* the {@link ClassLoader} class or one of its superclasses.
* @param log
* the log
* @return true if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {
return "jdk.internal.loader.ClassLoaders$AppClassLoader".equals(classLoaderClass.getName())
|| "jdk.internal.loader.BuiltinClassLoader".equals(classLoaderClass.getName());
}
/**
* Find the {@link ClassLoader} delegation order for a {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the order for.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object to update.
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {
classLoaderOrder.delegateTo(classLoader.getParent(), /* isParent = */ true, log);
classLoaderOrder.add(classLoader, log);
}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {<FILL_FUNCTION_BODY>}
}
|
// The JDK9 classloaders have a field, `URLClassPath ucp`, containing URLs for unnamed modules,
// but it is not visible. Modules therefore have to be scanned using the JPMS API.
// However, it is possible for a Java agent to extend UCP by adding directly to the `ucp` field
// (#537), and there is no way to read this field. Therefore, we need to use Narcissus to break
// Java's encapsulation to read this, for this small corner case.
final Object ucpVal = classpathOrder.reflectionUtils.getFieldVal(false, classLoader, "ucp");
if (ucpVal != null) {
final URL[] urls = (URL[]) classpathOrder.reflectionUtils.invokeMethod(false, ucpVal, "getURLs");
classpathOrder.addClasspathEntryObject(urls, classLoader, scanSpec, log);
}
| 522
| 235
| 757
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/OSGiDefaultClassLoaderHandler.java
|
OSGiDefaultClassLoaderHandler
|
findClasspathOrder
|
class OSGiDefaultClassLoaderHandler implements ClassLoaderHandler {
/** Class cannot be constructed. */
private OSGiDefaultClassLoaderHandler() {
}
/**
* Check whether this {@link ClassLoaderHandler} can handle a given {@link ClassLoader}.
*
* @param classLoaderClass
* the {@link ClassLoader} class or one of its superclasses.
* @param log
* the log
* @return true if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {
return "org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader".equals(classLoaderClass.getName());
}
/**
* Find the {@link ClassLoader} delegation order for a {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the order for.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object to update.
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {
classLoaderOrder.delegateTo(classLoader.getParent(), /* isParent = */ true, log);
classLoaderOrder.add(classLoader, log);
}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {<FILL_FUNCTION_BODY>}
}
|
final Object classpathManager = classpathOrder.reflectionUtils.invokeMethod(false, classLoader,
"getClasspathManager");
final Object[] entries = (Object[]) classpathOrder.reflectionUtils.getFieldVal(false, classpathManager,
"entries");
if (entries != null) {
for (final Object entry : entries) {
final Object bundleFile = classpathOrder.reflectionUtils.invokeMethod(false, entry,
"getBundleFile");
final File baseFile = (File) classpathOrder.reflectionUtils.invokeMethod(false, bundleFile,
"getBaseFile");
if (baseFile != null) {
classpathOrder.addClasspathEntry(baseFile.getPath(), classLoader, scanSpec, log);
}
}
}
| 503
| 198
| 701
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/ParentLastDelegationOrderTestClassLoaderHandler.java
|
ParentLastDelegationOrderTestClassLoaderHandler
|
findClassLoaderOrder
|
class ParentLastDelegationOrderTestClassLoaderHandler implements ClassLoaderHandler {
/** Class cannot be constructed. */
private ParentLastDelegationOrderTestClassLoaderHandler() {
}
/**
* Check whether this {@link ClassLoaderHandler} can handle a given {@link ClassLoader}.
*
* @param classLoaderClass
* the {@link ClassLoader} class or one of its superclasses.
* @param log
* the log
* @return true if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {
return "io.github.classgraph.issues.issue267.FakeRestartClassLoader".equals(classLoaderClass.getName());
}
/**
* Find the {@link ClassLoader} delegation order for a {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the order for.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object to update.
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {<FILL_FUNCTION_BODY>}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {
final String classpath = (String) classpathOrder.reflectionUtils.invokeMethod(/* throwException = */ true,
classLoader, "getClasspath");
classpathOrder.addClasspathEntry(classpath, classLoader, scanSpec, log);
}
}
|
// Add self first, then delegate to parent
classLoaderOrder.add(classLoader, log);
classLoaderOrder.delegateTo(classLoader.getParent(), /* isParent = */ true, log);
| 533
| 53
| 586
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/PlexusClassWorldsClassRealmClassLoaderHandler.java
|
PlexusClassWorldsClassRealmClassLoaderHandler
|
findClassLoaderOrder
|
class PlexusClassWorldsClassRealmClassLoaderHandler implements ClassLoaderHandler {
/** Class cannot be constructed. */
private PlexusClassWorldsClassRealmClassLoaderHandler() {
}
/**
* Check whether this {@link ClassLoaderHandler} can handle a given {@link ClassLoader}.
*
* @param classLoaderClass
* the {@link ClassLoader} class or one of its superclasses.
* @param log
* the log
* @return true if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {
return "org.codehaus.plexus.classworlds.realm.ClassRealm".equals(classLoaderClass.getName());
}
/**
* Checks if is this classloader uses a parent-first strategy.
*
* @param classRealmInstance
* the ClassRealm instance
* @return true if classloader uses a parent-first strategy
*/
private static boolean isParentFirstStrategy(final ClassLoader classRealmInstance,
final ReflectionUtils reflectionUtils) {
final Object strategy = reflectionUtils.getFieldVal(false, classRealmInstance, "strategy");
if (strategy != null) {
final String strategyClassName = strategy.getClass().getName();
if (strategyClassName.equals("org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy")
|| strategyClassName.equals("org.codehaus.plexus.classworlds.strategy.OsgiBundleStrategy")) {
// Strategy is self-first
return false;
}
}
// Strategy is org.codehaus.plexus.classworlds.strategy.ParentFirstStrategy (or failed to find strategy)
return true;
}
/**
* Find the {@link ClassLoader} delegation order for a {@link ClassLoader}.
*
* @param classRealm
* the {@link ClassLoader} to find the order for.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object to update.
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classRealm, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {<FILL_FUNCTION_BODY>}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {
// ClassRealm extends URLClassLoader
URLClassLoaderHandler.findClasspathOrder(classLoader, classpathOrder, scanSpec, log);
}
}
|
// From ClassRealm#loadClassFromImport(String) -> getImportClassLoader(String)
final Object foreignImports = classLoaderOrder.reflectionUtils.getFieldVal(false, classRealm,
"foreignImports");
if (foreignImports != null) {
@SuppressWarnings("unchecked")
final SortedSet<Object> foreignImportEntries = (SortedSet<Object>) foreignImports;
for (final Object entry : foreignImportEntries) {
final ClassLoader foreignImportClassLoader = (ClassLoader) classLoaderOrder.reflectionUtils
.invokeMethod(false, entry, "getClassLoader");
// Treat foreign import classloader as if it is a parent classloader
classLoaderOrder.delegateTo(foreignImportClassLoader, /* isParent = */ true, log);
}
}
// Get delegation order -- different strategies have different delegation orders
final boolean isParentFirst = isParentFirstStrategy(classRealm, classLoaderOrder.reflectionUtils);
// From ClassRealm#loadClassFromSelf(String) -> findLoadedClass(String) for self-first strategy
if (!isParentFirst) {
// Add self before parent
classLoaderOrder.add(classRealm, log);
}
// From ClassRealm#loadClassFromParent -- N.B. we are ignoring parentImports, which is used to filter
// a class name before deciding whether or not to call the parent classloader (so ClassGraph will be
// able to load classes by name that are not imported from the parent classloader).
final ClassLoader parentClassLoader = (ClassLoader) classLoaderOrder.reflectionUtils.invokeMethod(false,
classRealm, "getParentClassLoader");
classLoaderOrder.delegateTo(parentClassLoader, /* isParent = */ true, log);
classLoaderOrder.delegateTo(classRealm.getParent(), /* isParent = */ true, log);
// From ClassRealm#loadClassFromSelf(String) -> findLoadedClass(String) for parent-first strategy
if (isParentFirst) {
// Add self after parent
classLoaderOrder.add(classRealm, log);
}
| 770
| 539
| 1,309
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/QuarkusClassLoaderHandler.java
|
QuarkusClassLoaderHandler
|
findClasspathOrderForRuntimeClassloader
|
class QuarkusClassLoaderHandler implements ClassLoaderHandler {
// Classloader until Quarkus 1.2
private static final String RUNTIME_CLASSLOADER = "io.quarkus.runner.RuntimeClassLoader";
// Classloader since Quarkus 1.3
private static final String QUARKUS_CLASSLOADER = "io.quarkus.bootstrap.classloading.QuarkusClassLoader";
// Classloader since Quarkus 1.13
private static final String RUNNER_CLASSLOADER = "io.quarkus.bootstrap.runner.RunnerClassLoader";
/**
* Class cannot be constructed.
*/
private QuarkusClassLoaderHandler() {
}
/**
* Can handle.
*
* @param classLoaderClass
* the classloader class
* @param log
* the log
* @return true, if classLoaderClass is the Quarkus RuntimeClassloader or QuarkusClassloader
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {
return RUNTIME_CLASSLOADER.equals(classLoaderClass.getName())
|| QUARKUS_CLASSLOADER.equals(classLoaderClass.getName())
|| RUNNER_CLASSLOADER.equals(classLoaderClass.getName());
}
/**
* Find classloader order.
*
* @param classLoader
* the class loader
* @param classLoaderOrder
* the classloader order
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {
classLoaderOrder.delegateTo(classLoader.getParent(), /* isParent = */ true, log);
classLoaderOrder.add(classLoader, log);
}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {
final String classLoaderName = classLoader.getClass().getName();
if (RUNTIME_CLASSLOADER.equals(classLoaderName)) {
findClasspathOrderForRuntimeClassloader(classLoader, classpathOrder, scanSpec, log);
} else if (QUARKUS_CLASSLOADER.equals(classLoaderName)) {
findClasspathOrderForQuarkusClassloader(classLoader, classpathOrder, scanSpec, log);
} else if (RUNNER_CLASSLOADER.equals(classLoaderName)) {
findClasspathOrderForRunnerClassloader(classLoader, classpathOrder, scanSpec, log);
}
}
@SuppressWarnings("unchecked")
private static void findClasspathOrderForQuarkusClassloader(final ClassLoader classLoader,
final ClasspathOrder classpathOrder, final ScanSpec scanSpec, final LogNode log) {
for (final Object element : (Collection<Object>) classpathOrder.reflectionUtils.getFieldVal(false,
classLoader, "elements")) {
final String elementClassName = element.getClass().getName();
if ("io.quarkus.bootstrap.classloading.JarClassPathElement".equals(elementClassName)) {
classpathOrder.addClasspathEntry(classpathOrder.reflectionUtils.getFieldVal(false, element, "file"),
classLoader, scanSpec, log);
} else if ("io.quarkus.bootstrap.classloading.DirectoryClassPathElement".equals(elementClassName)) {
classpathOrder.addClasspathEntry(classpathOrder.reflectionUtils.getFieldVal(false, element, "root"),
classLoader, scanSpec, log);
} else {
final Object rootPath = classpathOrder.reflectionUtils.invokeMethod(false, element, "getRoot");
if (rootPath instanceof Path) {
classpathOrder.addClasspathEntry(rootPath, classLoader, scanSpec, log);
}
}
}
}
@SuppressWarnings("unchecked")
private static void findClasspathOrderForRuntimeClassloader(final ClassLoader classLoader,
final ClasspathOrder classpathOrder, final ScanSpec scanSpec, final LogNode log) {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
private static void findClasspathOrderForRunnerClassloader(final ClassLoader classLoader,
final ClasspathOrder classpathOrder, final ScanSpec scanSpec, final LogNode log) {
for (final Object[] elementArray : ((Map<String, Object[]>) classpathOrder.reflectionUtils
.getFieldVal(false, classLoader, "resourceDirectoryMap")).values()) {
for (final Object element : elementArray) {
final String elementClassName = element.getClass().getName();
if ("io.quarkus.bootstrap.runner.JarResource".equals(elementClassName)) {
classpathOrder.addClasspathEntry(
classpathOrder.reflectionUtils.getFieldVal(false, element, "jarPath"), classLoader,
scanSpec, log);
}
}
}
}
}
|
final Collection<Path> applicationClassDirectories = (Collection<Path>) classpathOrder.reflectionUtils
.getFieldVal(false, classLoader, "applicationClassDirectories");
if (applicationClassDirectories != null) {
for (final Path path : applicationClassDirectories) {
try {
final URI uri = path.toUri();
classpathOrder.addClasspathEntryObject(uri, classLoader, scanSpec, log);
} catch (IOError | SecurityException e) {
if (log != null) {
log.log("Could not convert path to URI: " + path);
}
}
}
}
| 1,353
| 161
| 1,514
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/SpringBootRestartClassLoaderHandler.java
|
SpringBootRestartClassLoaderHandler
|
findClassLoaderOrder
|
class SpringBootRestartClassLoaderHandler implements ClassLoaderHandler {
/** Class cannot be constructed. */
private SpringBootRestartClassLoaderHandler() {
}
/**
* Check whether this {@link ClassLoaderHandler} can handle a given {@link ClassLoader}.
*
* @param classLoaderClass
* the {@link ClassLoader} class or one of its superclasses.
* @param log
* the log
* @return true if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {
return "org.springframework.boot.devtools.restart.classloader.RestartClassLoader"
.equals(classLoaderClass.getName());
}
/**
* Find the {@link ClassLoader} delegation order for a {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the order for.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object to update.
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {<FILL_FUNCTION_BODY>}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* Spring Boot's RestartClassLoader sits in front of the parent class loader and watches a given set of
* directories for changes. While those classes are reachable from the parent class loader directly, they should
* always be loaded through direct access from the RestartClassLoader until it's completely turned of by means
* of Spring Boot Developer tools.
*
* The RestartClassLoader shades only the project classes and additional directories that are configurable, so
* itself needs access to parent, but last.
*
* See: <a href="https://github.com/classgraph/classgraph/issues/267">#267</a>,
* <a href="https://github.com/classgraph/classgraph/issues/268">#268</a>
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {
// The Restart classloader doesn't itself store any URLs
}
}
|
// The Restart classloader is a parent-last classloader, so add the Restart classloader itself to the
// classloader order first
classLoaderOrder.add(classLoader, log);
// Delegate to the parent of the RestartClassLoader
classLoaderOrder.delegateTo(classLoader.getParent(), /* isParent = */ true, log);
| 687
| 91
| 778
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/TomcatWebappClassLoaderBaseHandler.java
|
TomcatWebappClassLoaderBaseHandler
|
findClasspathOrder
|
class TomcatWebappClassLoaderBaseHandler implements ClassLoaderHandler {
/** Class cannot be constructed. */
private TomcatWebappClassLoaderBaseHandler() {
}
/**
* Check whether this {@link ClassLoaderHandler} can handle a given {@link ClassLoader}.
*
* @param classLoaderClass
* the {@link ClassLoader} class or one of its superclasses.
* @param log
* the log
* @return true if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {
return "org.apache.catalina.loader.WebappClassLoaderBase".equals(classLoaderClass.getName());
}
/**
* Return true if this classloader delegates to its parent.
*
* @param classLoader
* the {@link ClassLoader}.
* @return true if this classloader delegates to its parent.
*/
private static boolean isParentFirst(final ClassLoader classLoader, final ReflectionUtils reflectionUtils) {
final Object delegateObject = reflectionUtils.getFieldVal(false, classLoader, "delegate");
if (delegateObject != null) {
return (boolean) delegateObject;
}
// Assume parent-first delegation order
return true;
}
/**
* Find the {@link ClassLoader} delegation order for a {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the order for.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object to update.
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {
final boolean isParentFirst = isParentFirst(classLoader, classLoaderOrder.reflectionUtils);
if (isParentFirst) {
// Use parent-first delegation order
classLoaderOrder.delegateTo(classLoader.getParent(), /* isParent = */ true, log);
}
if ("org.apache.tomee.catalina.TomEEWebappClassLoader".equals(classLoader.getClass().getName())) {
// TomEEWebappClassLoader has a lot of complex delegation rules, including classname-specific
// delegation, which is not supported by the current ClassGraph model, so we just try to approximate
// the delegation order with a fixed order.
try {
classLoaderOrder.delegateTo(Class.forName("org.apache.openejb.OpenEJB").getClassLoader(),
/* isParent = */ true, log);
} catch (LinkageError | ClassNotFoundException e) {
// Ignore
}
}
classLoaderOrder.add(classLoader, log);
if (!isParentFirst) {
// Use parent-last delegation order
classLoaderOrder.delegateTo(classLoader.getParent(), /* isParent = */ true, log);
}
}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {<FILL_FUNCTION_BODY>}
}
|
// type StandardRoot (implements WebResourceRoot)
final Object resources = classpathOrder.reflectionUtils.invokeMethod(false, classLoader, "getResources");
// type List<URL>
final Object baseURLs = classpathOrder.reflectionUtils.invokeMethod(false, resources, "getBaseUrls");
classpathOrder.addClasspathEntryObject(baseURLs, classLoader, scanSpec, log);
// type List<List<WebResourceSet>>
// members: preResources, mainResources, classResources, jarResources,
// postResources
@SuppressWarnings("unchecked")
final List<List<?>> allResources = (List<List<?>>) classpathOrder.reflectionUtils.getFieldVal(false,
resources, "allResources");
if (allResources != null) {
// type List<WebResourceSet>
for (final List<?> webResourceSetList : allResources) {
// type WebResourceSet
// {DirResourceSet, FileResourceSet, JarResourceSet, JarWarResourceSet,
// EmptyResourceSet}
for (final Object webResourceSet : webResourceSetList) {
if (webResourceSet != null) {
// For DirResourceSet
final File file = (File) classpathOrder.reflectionUtils.invokeMethod(false, webResourceSet,
"getFileBase");
String base = file == null ? null : file.getPath();
if (base == null) {
// For FileResourceSet
base = (String) classpathOrder.reflectionUtils.invokeMethod(false, webResourceSet,
"getBase");
}
if (base == null) {
// For JarResourceSet and JarWarResourceSet
// The absolute path to the WAR file on the file system in which the JAR is
// located
base = (String) classpathOrder.reflectionUtils.invokeMethod(false, webResourceSet,
"getBaseUrlString");
}
if (base != null) {
// For JarWarResourceSet: the path within the WAR file where the JAR file is
// located
final String archivePath = (String) classpathOrder.reflectionUtils.getFieldVal(false,
webResourceSet, "archivePath");
if (archivePath != null && !archivePath.isEmpty()) {
// If archivePath is non-null, this is a jar within a war
base += "!" + (archivePath.startsWith("/") ? archivePath : "/" + archivePath);
}
final String className = webResourceSet.getClass().getName();
final boolean isJar = className
.equals("java.org.apache.catalina.webresources.JarResourceSet")
|| className.equals("java.org.apache.catalina.webresources.JarWarResourceSet");
// The path within this WebResourceSet where resources will be served from,
// e.g. for a resource JAR, this would be "META-INF/resources"
final String internalPath = (String) classpathOrder.reflectionUtils.invokeMethod(false,
webResourceSet, "getInternalPath");
if (internalPath != null && !internalPath.isEmpty() && !internalPath.equals("/")) {
classpathOrder.addClasspathEntryObject(base + (isJar ? "!" : "")
+ (internalPath.startsWith("/") ? internalPath : "/" + internalPath),
classLoader, scanSpec, log);
} else {
classpathOrder.addClasspathEntryObject(base, classLoader, scanSpec, log);
}
}
}
}
}
}
// This may or may not duplicate the above
final Object urls = classpathOrder.reflectionUtils.invokeMethod(false, classLoader, "getURLs");
classpathOrder.addClasspathEntryObject(urls, classLoader, scanSpec, log);
| 913
| 947
| 1,860
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/URLClassLoaderHandler.java
|
URLClassLoaderHandler
|
findClasspathOrder
|
class URLClassLoaderHandler implements ClassLoaderHandler {
/** Class cannot be constructed. */
private URLClassLoaderHandler() {
}
/**
* Check whether this {@link ClassLoaderHandler} can handle a given {@link ClassLoader}.
*
* @param classLoaderClass
* the {@link ClassLoader} class or one of its superclasses.
* @param log
* the log
* @return true if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {
return "java.net.URLClassLoader".equals(classLoaderClass.getName());
}
/**
* Find the {@link ClassLoader} delegation order for a {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the order for.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object to update.
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {
classLoaderOrder.delegateTo(classLoader.getParent(), /* isParent = */ true, log);
classLoaderOrder.add(classLoader, log);
}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {<FILL_FUNCTION_BODY>}
}
|
final URL[] urls = ((URLClassLoader) classLoader).getURLs();
if (urls != null) {
for (final URL url : urls) {
if (url != null) {
classpathOrder.addClasspathEntry(url, classLoader, scanSpec, log);
}
}
}
| 488
| 85
| 573
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/UnoOneJarClassLoaderHandler.java
|
UnoOneJarClassLoaderHandler
|
findClassLoaderOrder
|
class UnoOneJarClassLoaderHandler implements ClassLoaderHandler {
/** Class cannot be constructed. */
private UnoOneJarClassLoaderHandler() {
}
/**
* Check whether this {@link ClassLoaderHandler} can handle a given {@link ClassLoader}.
*
* @param classLoaderClass
* the {@link ClassLoader} class or one of its superclasses.
* @param log
* the log
* @return true if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {
return "com.needhamsoftware.unojar.JarClassLoader".equals(classLoaderClass.getName())
|| "com.simontuffs.onejar.JarClassLoader".equals(classLoaderClass.getName());
}
/**
* Find the {@link ClassLoader} delegation order for a {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the order for.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object to update.
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {<FILL_FUNCTION_BODY>}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {
// For Uno-Jar:
final String unoJarOneJarPath = (String) classpathOrder.reflectionUtils.invokeMethod(false, classLoader,
"getOneJarPath");
classpathOrder.addClasspathEntry(unoJarOneJarPath, classLoader, scanSpec, log);
// If this property is defined, Uno-Jar jar path was specified on commandline. Otherwise, jar path
// should be contained in java.class.path (which will be separately picked up by ClassGraph, as
// long as classloaders/classpath are not overloaded and parent classloaders are not ignored).
final String unoJarJarPath = System.getProperty("uno-jar.jar.path");
classpathOrder.addClasspathEntry(unoJarJarPath, classLoader, scanSpec, log);
// For One-Jar:
// If this property is defined, One-Jar jar path was specified on commandline. Otherwise, jar path
// should be contained in java.class.path (which will be separately picked up by ClassGraph, as
// long as classloaders/classpath are not overloaded and parent classloaders are not ignored).
final String oneJarJarPath = System.getProperty("one-jar.jar.path");
classpathOrder.addClasspathEntry(oneJarJarPath, classLoader, scanSpec, log);
// If this property is defined, additional classpath entries were specified in OneJar format
// on the commandline, with '|' as a separator
final String oneJarClassPath = System.getProperty("one-jar.class.path");
if (oneJarClassPath != null) {
classpathOrder.addClasspathEntryObject(oneJarClassPath.split("\\|"), classLoader, scanSpec, log);
}
// For both UnoJar and OneJar, "libs/" and "main/" will be automatically picked up as library roots
// for nested jars, based on ClassLoaderHandlerRegistry.AUTOMATIC_LIB_DIR_PREFIXES.
// ("main/" contains "main.jar".)
}
}
|
classLoaderOrder.delegateTo(classLoader.getParent(), /* isParent = */ true, log);
classLoaderOrder.add(classLoader, log);
| 1,009
| 42
| 1,051
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/WeblogicClassLoaderHandler.java
|
WeblogicClassLoaderHandler
|
canHandle
|
class WeblogicClassLoaderHandler implements ClassLoaderHandler {
/** Class cannot be constructed. */
private WeblogicClassLoaderHandler() {
}
/**
* Check whether this {@link ClassLoaderHandler} can handle a given {@link ClassLoader}.
*
* @param classLoaderClass
* the {@link ClassLoader} class or one of its superclasses.
* @param log
* the log
* @return true if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {<FILL_FUNCTION_BODY>}
/**
* Find the {@link ClassLoader} delegation order for a {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the order for.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object to update.
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {
classLoaderOrder.delegateTo(classLoader.getParent(), /* isParent = */ true, log);
classLoaderOrder.add(classLoader, log);
}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {
classpathOrder.addClasspathPathStr( //
(String) classpathOrder.reflectionUtils.invokeMethod(false, classLoader, "getFinderClassPath"),
classLoader, scanSpec, log);
classpathOrder.addClasspathPathStr( //
(String) classpathOrder.reflectionUtils.invokeMethod(false, classLoader, "getClassPath"),
classLoader, scanSpec, log);
}
}
|
return "weblogic.utils.classloaders.ChangeAwareClassLoader".equals(classLoaderClass.getName())
|| "weblogic.utils.classloaders.GenericClassLoader".equals(classLoaderClass.getName())
|| "weblogic.utils.classloaders.FilteringClassLoader".equals(classLoaderClass.getName())
// TODO: The following two known classloader names have not been tested, and the fields/methods
// may not match those of the above classloaders.
|| "weblogic.servlet.jsp.JspClassLoader".equals(classLoaderClass.getName())
|| "weblogic.servlet.jsp.TagFileClassLoader".equals(classLoaderClass.getName());
| 570
| 174
| 744
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classloaderhandler/WebsphereTraditionalClassLoaderHandler.java
|
WebsphereTraditionalClassLoaderHandler
|
findClasspathOrder
|
class WebsphereTraditionalClassLoaderHandler implements ClassLoaderHandler {
/** Class cannot be constructed. */
private WebsphereTraditionalClassLoaderHandler() {
}
/**
* Check whether this {@link ClassLoaderHandler} can handle a given {@link ClassLoader}.
*
* @param classLoaderClass
* the {@link ClassLoader} class or one of its superclasses.
* @param log
* the log
* @return true if this {@link ClassLoaderHandler} can handle the {@link ClassLoader}.
*/
public static boolean canHandle(final Class<?> classLoaderClass, final LogNode log) {
return "com.ibm.ws.classloader.CompoundClassLoader".equals(classLoaderClass.getName())
|| "com.ibm.ws.classloader.ProtectionClassLoader".equals(classLoaderClass.getName())
|| "com.ibm.ws.bootstrap.ExtClassLoader".equals(classLoaderClass.getName());
}
/**
* Find the {@link ClassLoader} delegation order for a {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the order for.
* @param classLoaderOrder
* a {@link ClassLoaderOrder} object to update.
* @param log
* the log
*/
public static void findClassLoaderOrder(final ClassLoader classLoader, final ClassLoaderOrder classLoaderOrder,
final LogNode log) {
classLoaderOrder.delegateTo(classLoader.getParent(), /* isParent = */ true, log);
classLoaderOrder.add(classLoader, log);
}
/**
* Find the classpath entries for the associated {@link ClassLoader}.
*
* @param classLoader
* the {@link ClassLoader} to find the classpath entries order for.
* @param classpathOrder
* a {@link ClasspathOrder} object to update.
* @param scanSpec
* the {@link ScanSpec}.
* @param log
* the log.
*/
public static void findClasspathOrder(final ClassLoader classLoader, final ClasspathOrder classpathOrder,
final ScanSpec scanSpec, final LogNode log) {<FILL_FUNCTION_BODY>}
}
|
final String classpath = (String) classpathOrder.reflectionUtils.invokeMethod(false, classLoader,
"getClassPath");
classpathOrder.addClasspathPathStr(classpath, classLoader, scanSpec, log);
| 558
| 58
| 616
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classpath/ClassLoaderOrder.java
|
ClassLoaderOrder
|
delegateTo
|
class ClassLoaderOrder {
/** The {@link ClassLoader} order. */
private final List<Entry<ClassLoader, ClassLoaderHandlerRegistryEntry>> classLoaderOrder = new ArrayList<>();
public ReflectionUtils reflectionUtils;
/**
* The set of all {@link ClassLoader} instances that have been added to the order so far, so that classloaders
* don't get added twice.
*/
// Need to use IdentityHashMap for maps and sets here, because TomEE weirdly makes instances of
// CxfContainerClassLoader equal to (via .equals()) the instance of TomEEWebappClassLoader that it
// delegates to (#515)
private final Set<ClassLoader> added = Collections.newSetFromMap(new IdentityHashMap<ClassLoader, Boolean>());
/**
* The set of all {@link ClassLoader} instances that have been delegated to so far, to prevent an infinite loop
* in delegation.
*/
private final Set<ClassLoader> delegatedTo = Collections
.newSetFromMap(new IdentityHashMap<ClassLoader, Boolean>());
/**
* The set of all parent {@link ClassLoader} instances that have been delegated to so far, to enable
* {@link ClassGraph#ignoreParentClassLoaders()}.
*/
private final Set<ClassLoader> allParentClassLoaders = Collections
.newSetFromMap(new IdentityHashMap<ClassLoader, Boolean>());
/** A map from {@link ClassLoader} to {@link ClassLoaderHandlerRegistryEntry}. */
private final Map<ClassLoader, ClassLoaderHandlerRegistryEntry> classLoaderToClassLoaderHandlerRegistryEntry = //
new IdentityHashMap<>();
// -------------------------------------------------------------------------------------------------------------
public ClassLoaderOrder(final ReflectionUtils reflectionUtils) {
this.reflectionUtils = reflectionUtils;
}
/**
* Get the {@link ClassLoader} order.
*
* @return the {@link ClassLoader} order, as a pair: {@link ClassLoader},
* {@link ClassLoaderHandlerRegistryEntry}.
*/
public List<Entry<ClassLoader, ClassLoaderHandlerRegistryEntry>> getClassLoaderOrder() {
return classLoaderOrder;
}
/**
* Get the all parent classloaders.
*
* @return all parent classloaders
*/
public Set<ClassLoader> getAllParentClassLoaders() {
return allParentClassLoaders;
}
/**
* Find the {@link ClassLoaderHandler} that can handle a given {@link ClassLoader} instance.
*
* @param classLoader
* the {@link ClassLoader}.
* @param log
* the log
* @return the {@link ClassLoaderHandlerRegistryEntry} for the {@link ClassLoader}.
*/
private ClassLoaderHandlerRegistryEntry getRegistryEntry(final ClassLoader classLoader, final LogNode log) {
ClassLoaderHandlerRegistryEntry entry = classLoaderToClassLoaderHandlerRegistryEntry.get(classLoader);
if (entry == null) {
// Try all superclasses of classloader in turn
for (Class<?> currClassLoaderClass = classLoader.getClass(); //
currClassLoaderClass != Object.class && currClassLoaderClass != null; //
currClassLoaderClass = currClassLoaderClass.getSuperclass()) {
// Find a ClassLoaderHandler that can handle the ClassLoader
for (final ClassLoaderHandlerRegistryEntry ent : ClassLoaderHandlerRegistry.CLASS_LOADER_HANDLERS) {
if (ent.canHandle(currClassLoaderClass, log)) {
// This ClassLoaderHandler can handle the ClassLoader class, or one of its superclasses
entry = ent;
break;
}
}
if (entry != null) {
// Don't iterate to next superclass if a matching ClassLoaderHandler was found
break;
}
}
if (entry == null) {
// Use fallback handler
entry = ClassLoaderHandlerRegistry.FALLBACK_HANDLER;
}
classLoaderToClassLoaderHandlerRegistryEntry.put(classLoader, entry);
}
return entry;
}
/**
* Add a {@link ClassLoader} to the ClassLoader order at the current position.
*
* @param classLoader
* the class loader
* @param log
* the log
*/
public void add(final ClassLoader classLoader, final LogNode log) {
if (classLoader == null) {
return;
}
if (added.add(classLoader)) {
final ClassLoaderHandlerRegistryEntry entry = getRegistryEntry(classLoader, log);
if (entry != null) {
classLoaderOrder.add(new SimpleEntry<>(classLoader, entry));
}
}
}
/**
* Recursively delegate to another {@link ClassLoader}.
*
* @param classLoader
* the class loader
* @param isParent
* true if this is a parent of another classloader
* @param log
* the log
*/
public void delegateTo(final ClassLoader classLoader, final boolean isParent, final LogNode log) {<FILL_FUNCTION_BODY>}
}
|
if (classLoader == null) {
return;
}
// Check if this is a parent before checking if the classloader is already in the delegatedTo set,
// so that if the classloader is a context classloader but also a parent, it still gets marked as
// a parent classloader.
if (isParent) {
allParentClassLoaders.add(classLoader);
}
// Don't delegate to a classloader twice
if (delegatedTo.add(classLoader)) {
// Find ClassLoaderHandlerRegistryEntry for this classloader
final ClassLoaderHandlerRegistryEntry entry = getRegistryEntry(classLoader, log);
// Delegate to this classloader, by recursing to that classloader to get its classloader order
entry.findClassLoaderOrder(classLoader, this, log);
}
| 1,275
| 202
| 1,477
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classpath/ClasspathOrder.java
|
ClasspathEntry
|
addClasspathEntry
|
class ClasspathEntry {
/** The classpath entry object (a {@link String} path, {@link Path}, {@link URL} or {@link URI}). */
public final Object classpathEntryObj;
/** The classloader the classpath element was obtained from. */
public final ClassLoader classLoader;
/**
* Constructor.
*
* @param classpathEntryObj
* the classpath entry object (a {@link String} or {@link URL} or {@link Path}).
* @param classLoader
* the classloader the classpath element was obtained from.
*/
public ClasspathEntry(final Object classpathEntryObj, final ClassLoader classLoader) {
this.classpathEntryObj = classpathEntryObj;
this.classLoader = classLoader;
}
@Override
public int hashCode() {
return Objects.hash(classpathEntryObj);
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof ClasspathEntry)) {
return false;
}
final ClasspathEntry other = (ClasspathEntry) obj;
return Objects.equals(this.classpathEntryObj, other.classpathEntryObj);
}
@Override
public String toString() {
return classpathEntryObj + " [" + classLoader + "]";
}
}
/**
* Constructor.
*
* @param scanSpec
* the scan spec
*/
ClasspathOrder(final ScanSpec scanSpec, final ReflectionUtils reflectionUtils) {
this.scanSpec = scanSpec;
this.reflectionUtils = reflectionUtils;
}
/**
* Get the order of classpath elements, uniquified and in order.
*
* @return the classpath order.
*/
public List<ClasspathEntry> getOrder() {
return order;
}
/**
* Get the unique classpath entry strings.
*
* @return the classpath entry strings.
*/
public Set<String> getClasspathEntryUniqueResolvedPaths() {
return classpathEntryUniqueResolvedPaths;
}
/**
* Test to see if a classpath element has been filtered out by the user.
*
* @param classpathElementURL
* the classpath element URL
* @param classpathElementPath
* the classpath element path
* @return true, if not filtered out
*/
private boolean filter(final URL classpathElementURL, final String classpathElementPath) {
if (scanSpec.classpathElementFilters != null) {
for (final Object filterObj : scanSpec.classpathElementFilters) {
if ((classpathElementURL != null && filterObj instanceof ClasspathElementURLFilter
&& !((ClasspathElementURLFilter) filterObj).includeClasspathElement(classpathElementURL))
|| (classpathElementPath != null && filterObj instanceof ClasspathElementFilter
&& !((ClasspathElementFilter) filterObj)
.includeClasspathElement(classpathElementPath))) {
return false;
}
}
}
return true;
}
/**
* Add a system classpath entry.
*
* @param pathEntry
* the system classpath entry -- the path string should already have been run through
* FastPathResolver.resolve(FileUtils.currDirPath(), path)
* @param classLoader
* the classloader
* @return true, if added and unique
*/
boolean addSystemClasspathEntry(final String pathEntry, final ClassLoader classLoader) {
if (classpathEntryUniqueResolvedPaths.add(pathEntry)) {
order.add(new ClasspathEntry(pathEntry, classLoader));
return true;
}
return false;
}
/**
* Add a classpath entry.
*
* @param pathElement
* the {@link String} path, {@link File}, {@link Path}, {@link URL} or {@link URI} of the classpath
* element.
* @param pathElementStr
* the path element in string format
* @param classLoader
* the classloader
* @param scanSpec
* the scan spec
* @return true, if added and unique
*/
private boolean addClasspathEntry(final Object pathElement, final String pathElementStr,
final ClassLoader classLoader, final ScanSpec scanSpec) {<FILL_FUNCTION_BODY>
|
// Check if classpath element path ends with an automatic package root. If so, strip it off to
// eliminate duplication, since automatic package roots are detected automatically (#435)
String pathElementStrWithoutSuffix = pathElementStr;
boolean hasSuffix = false;
for (final String suffix : AUTOMATIC_PACKAGE_ROOT_SUFFIXES) {
if (pathElementStr.endsWith(suffix)) {
// Strip off automatic package root suffix
pathElementStrWithoutSuffix = pathElementStr.substring(0,
pathElementStr.length() - suffix.length());
hasSuffix = true;
break;
}
}
if (pathElement instanceof URL || pathElement instanceof URI || pathElement instanceof Path
|| pathElement instanceof File) {
Object pathElementWithoutSuffix = pathElement;
if (hasSuffix) {
try {
pathElementWithoutSuffix = pathElement instanceof URL ? new URL(pathElementStrWithoutSuffix)
: pathElement instanceof URI ? new URI(pathElementStrWithoutSuffix)
: pathElement instanceof Path ? Paths.get(pathElementStrWithoutSuffix)
// For File, just use path string
: pathElementStrWithoutSuffix;
} catch (MalformedURLException | URISyntaxException | InvalidPathException e) {
try {
pathElementWithoutSuffix = pathElement instanceof URL
? new URL("file:" + pathElementStrWithoutSuffix)
: pathElement instanceof URI ? new URI("file:" + pathElementStrWithoutSuffix)
: pathElementStrWithoutSuffix;
} catch (MalformedURLException | URISyntaxException | InvalidPathException e2) {
return false;
}
}
}
// Deduplicate classpath elements
if (classpathEntryUniqueResolvedPaths.add(pathElementStrWithoutSuffix)) {
// Record classpath element in classpath order
order.add(new ClasspathEntry(pathElementWithoutSuffix, classLoader));
return true;
}
} else {
final String pathElementStrResolved = FastPathResolver.resolve(FileUtils.currDirPath(),
pathElementStrWithoutSuffix);
if (scanSpec.overrideClasspath == null //
&& (SystemJarFinder.getJreLibOrExtJars().contains(pathElementStrResolved)
|| pathElementStrResolved.equals(SystemJarFinder.getJreRtJarPath()))) {
// JRE lib and ext jars are handled separately, so reject them as duplicates if they are
// returned by a system classloader
return false;
}
if (classpathEntryUniqueResolvedPaths.add(pathElementStrResolved)) {
order.add(new ClasspathEntry(pathElementStrResolved, classLoader));
return true;
}
}
return false;
| 1,125
| 721
| 1,846
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/classpath/SystemJarFinder.java
|
SystemJarFinder
|
addJREPath
|
class SystemJarFinder {
/** The paths of any "rt.jar" files found in the JRE. */
private static final Set<String> RT_JARS = new LinkedHashSet<>();
/** The path of the first "rt.jar" found. */
private static final String RT_JAR;
/** The paths of any "lib/" or "ext/" jars found in the JRE. */
private static final Set<String> JRE_LIB_OR_EXT_JARS = new LinkedHashSet<>();
/**
* Constructor.
*/
private SystemJarFinder() {
// Cannot be constructed
}
/**
* Add and search a JRE path.
*
* @param dir
* the JRE directory
* @return true if the directory was readable.
*/
private static boolean addJREPath(final File dir) {<FILL_FUNCTION_BODY>}
// Find jars in JRE dirs ({java.home}, {java.home}/lib, {java.home}/lib/ext, etc.)
static {
String javaHome = VersionFinder.getProperty("java.home");
if (javaHome == null || javaHome.isEmpty()) {
javaHome = System.getenv("JAVA_HOME");
}
if (javaHome != null && !javaHome.isEmpty()) {
final File javaHomeFile = new File(javaHome);
addJREPath(javaHomeFile);
if (javaHomeFile.getName().equals("jre")) {
// Try adding "{java.home}/.." as a JDK root when java.home is a JRE path
final File jreParent = javaHomeFile.getParentFile();
addJREPath(jreParent);
addJREPath(new File(jreParent, "lib"));
addJREPath(new File(jreParent, "lib/ext"));
} else {
// Try adding "{java.home}/jre" as a JRE root when java.home is not a JRE path
addJREPath(new File(javaHomeFile, "jre"));
}
addJREPath(new File(javaHomeFile, "lib"));
addJREPath(new File(javaHomeFile, "lib/ext"));
addJREPath(new File(javaHomeFile, "jre/lib"));
addJREPath(new File(javaHomeFile, "jre/lib/ext"));
addJREPath(new File(javaHomeFile, "packages"));
addJREPath(new File(javaHomeFile, "packages/lib"));
addJREPath(new File(javaHomeFile, "packages/lib/ext"));
}
final String javaExtDirs = VersionFinder.getProperty("java.ext.dirs");
if (javaExtDirs != null && !javaExtDirs.isEmpty()) {
for (final String javaExtDir : JarUtils.smartPathSplit(javaExtDirs, /* scanSpec = */ null)) {
if (!javaExtDir.isEmpty()) {
addJREPath(new File(javaExtDir));
}
}
}
// System extension paths -- see: https://docs.oracle.com/javase/tutorial/ext/basics/install.html
switch (VersionFinder.OS) {
case Linux:
case Unix:
case BSD:
case Unknown:
addJREPath(new File("/usr/java/packages"));
addJREPath(new File("/usr/java/packages/lib"));
addJREPath(new File("/usr/java/packages/lib/ext"));
break;
case MacOSX:
addJREPath(new File("/System/Library/Java"));
addJREPath(new File("/System/Library/Java/Libraries"));
addJREPath(new File("/System/Library/Java/Extensions"));
break;
case Windows:
final String systemRoot = File.separatorChar == '\\' ? System.getenv("SystemRoot") : null;
if (systemRoot != null) {
addJREPath(new File(systemRoot, "Sun\\Java"));
addJREPath(new File(systemRoot, "Sun\\Java\\lib"));
addJREPath(new File(systemRoot, "Sun\\Java\\lib\\ext"));
addJREPath(new File(systemRoot, "Oracle\\Java"));
addJREPath(new File(systemRoot, "Oracle\\Java\\lib"));
addJREPath(new File(systemRoot, "Oracle\\Java\\lib\\ext"));
}
break;
case Solaris:
// Solaris paths:
addJREPath(new File("/usr/jdk/packages"));
addJREPath(new File("/usr/jdk/packages/lib"));
addJREPath(new File("/usr/jdk/packages/lib/ext"));
break;
default:
break;
}
RT_JAR = RT_JARS.isEmpty() ? null : FastPathResolver.resolve(RT_JARS.iterator().next());
}
/**
* Get the JRE "rt.jar" path.
*
* @return The path of rt.jar (in JDK 7 or 8), or null if it wasn't found (e.g. in JDK 9+).
*/
public static String getJreRtJarPath() {
// Only include the first rt.jar -- if there is a copy in both the JDK and JRE, no need to scan both
return RT_JAR;
}
/**
* Get the JRE "lib/" and "ext/" jar paths.
*
* @return The paths for any jarfiles found in JRE/JDK "lib/" or "ext/" directories.
*/
public static Set<String> getJreLibOrExtJars() {
return JRE_LIB_OR_EXT_JARS;
}
}
|
if (dir != null && !dir.getPath().isEmpty() && FileUtils.canReadAndIsDir(dir)) {
final File[] dirFiles = dir.listFiles();
if (dirFiles != null) {
for (final File file : dirFiles) {
final String filePath = file.getPath();
if (filePath.endsWith(".jar")) {
final String jarPathResolved = FastPathResolver.resolve(FileUtils.currDirPath(), filePath);
if (jarPathResolved.endsWith("/rt.jar")) {
RT_JARS.add(jarPathResolved);
} else {
JRE_LIB_OR_EXT_JARS.add(jarPathResolved);
}
try {
final File canonicalFile = file.getCanonicalFile();
final String canonicalFilePath = canonicalFile.getPath();
if (!canonicalFilePath.equals(filePath)) {
final String canonicalJarPathResolved = FastPathResolver
.resolve(FileUtils.currDirPath(), filePath);
JRE_LIB_OR_EXT_JARS.add(canonicalJarPathResolved);
}
} catch (IOException | SecurityException e) {
// Ignored
}
}
}
return true;
}
}
return false;
| 1,475
| 329
| 1,804
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/concurrency/AutoCloseableExecutorService.java
|
AutoCloseableExecutorService
|
close
|
class AutoCloseableExecutorService extends ThreadPoolExecutor implements AutoCloseable {
/** The {@link InterruptionChecker}. */
public final InterruptionChecker interruptionChecker = new InterruptionChecker();
/**
* A ThreadPoolExecutor that can be used in a try-with-resources block.
*
* @param numThreads
* The number of threads to allocate.
*/
public AutoCloseableExecutorService(final int numThreads) {
super(numThreads, numThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(),
new SimpleThreadFactory("ClassGraph-worker-", true));
}
/**
* Catch exceptions from both submit() and execute(), and call {@link InterruptionChecker#interrupt()} to
* interrupt all threads.
*
* @param runnable
* the Runnable
* @param throwable
* the Throwable
*/
@Override
public void afterExecute(final Runnable runnable, final Throwable throwable) {
super.afterExecute(runnable, throwable);
if (throwable != null) {
// Wrap the throwable in an ExecutionException (execute() does not do this)
interruptionChecker.setExecutionException(new ExecutionException("Uncaught exception", throwable));
// execute() was called and an uncaught exception or error was thrown
interruptionChecker.interrupt();
} else if (/* throwable == null && */ runnable instanceof Future<?>) {
// submit() was called, so throwable is not set
try {
// This call will not block, since execution has finished
((Future<?>) runnable).get();
} catch (CancellationException | InterruptedException e) {
// If this thread was cancelled or interrupted, interrupt other threads
interruptionChecker.interrupt();
} catch (final ExecutionException e) {
// Record the exception that was thrown by the thread
interruptionChecker.setExecutionException(e);
// Interrupt other threads
interruptionChecker.interrupt();
}
}
}
/** Shut down thread pool on close(). */
@Override
public void close() {<FILL_FUNCTION_BODY>}
}
|
try {
// Prevent new tasks being submitted
shutdown();
} catch (final SecurityException e) {
// Ignore for now (caught again if shutdownNow() fails)
}
boolean terminated = false;
try {
// Await termination of any running tasks
terminated = awaitTermination(2500, TimeUnit.MILLISECONDS);
} catch (final InterruptedException e) {
interruptionChecker.interrupt();
}
if (!terminated) {
try {
// Interrupt all the threads to terminate them, if awaitTermination() timed out
shutdownNow();
} catch (final SecurityException e) {
throw new RuntimeException("Could not shut down ExecutorService -- need "
+ "java.lang.RuntimePermission(\"modifyThread\"), "
+ "or the security manager's checkAccess method denies access", e);
}
}
| 582
| 230
| 812
|
<methods>public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.ThreadFactory) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.RejectedExecutionHandler) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.ThreadFactory, java.util.concurrent.RejectedExecutionHandler) ,public void allowCoreThreadTimeOut(boolean) ,public boolean allowsCoreThreadTimeOut() ,public boolean awaitTermination(long, java.util.concurrent.TimeUnit) throws java.lang.InterruptedException,public void execute(java.lang.Runnable) ,public int getActiveCount() ,public long getCompletedTaskCount() ,public int getCorePoolSize() ,public long getKeepAliveTime(java.util.concurrent.TimeUnit) ,public int getLargestPoolSize() ,public int getMaximumPoolSize() ,public int getPoolSize() ,public BlockingQueue<java.lang.Runnable> getQueue() ,public java.util.concurrent.RejectedExecutionHandler getRejectedExecutionHandler() ,public long getTaskCount() ,public java.util.concurrent.ThreadFactory getThreadFactory() ,public boolean isShutdown() ,public boolean isTerminated() ,public boolean isTerminating() ,public int prestartAllCoreThreads() ,public boolean prestartCoreThread() ,public void purge() ,public boolean remove(java.lang.Runnable) ,public void setCorePoolSize(int) ,public void setKeepAliveTime(long, java.util.concurrent.TimeUnit) ,public void setMaximumPoolSize(int) ,public void setRejectedExecutionHandler(java.util.concurrent.RejectedExecutionHandler) ,public void setThreadFactory(java.util.concurrent.ThreadFactory) ,public void shutdown() ,public List<java.lang.Runnable> shutdownNow() ,public java.lang.String toString() <variables>private static final int COUNT_BITS,private static final int COUNT_MASK,private static final boolean ONLY_ONE,private static final int RUNNING,private static final int SHUTDOWN,private static final int STOP,private static final int TERMINATED,private static final int TIDYING,private volatile boolean allowCoreThreadTimeOut,private long completedTaskCount,private volatile int corePoolSize,private final java.util.concurrent.atomic.AtomicInteger ctl,private static final java.util.concurrent.RejectedExecutionHandler defaultHandler,private volatile java.util.concurrent.RejectedExecutionHandler handler,private volatile long keepAliveTime,private int largestPoolSize,private final java.util.concurrent.locks.ReentrantLock mainLock,private volatile int maximumPoolSize,private static final java.lang.RuntimePermission shutdownPerm,private final java.util.concurrent.locks.Condition termination,private volatile java.util.concurrent.ThreadFactory threadFactory,private final BlockingQueue<java.lang.Runnable> workQueue,private final HashSet<java.util.concurrent.ThreadPoolExecutor.Worker> workers
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/concurrency/InterruptionChecker.java
|
InterruptionChecker
|
check
|
class InterruptionChecker {
/** Set to true when a thread is interrupted. */
private final AtomicBoolean interrupted = new AtomicBoolean(false);
/** The first {@link ExecutionException} that was thrown. */
private final AtomicReference<ExecutionException> thrownExecutionException = //
new AtomicReference<>();
/** Interrupt all threads that share this InterruptionChecker. */
public void interrupt() {
interrupted.set(true);
Thread.currentThread().interrupt();
}
/**
* Set the {@link ExecutionException} that was thrown by a worker.
*
* @param executionException
* the execution exception that was thrown
*/
public void setExecutionException(final ExecutionException executionException) {
// Only set the execution exception once
if (executionException != null && thrownExecutionException.get() == null) {
thrownExecutionException.compareAndSet(/* expectedValue = */ null, executionException);
}
}
/**
* Get the {@link ExecutionException} that was thrown by a worker, or null if none.
*
* @return the {@link ExecutionException} that was thrown by a worker, or null if none.
*/
public ExecutionException getExecutionException() {
return thrownExecutionException.get();
}
/**
* Get the cause of an {@link ExecutionException}.
*
* @param throwable
* the Throwable
* @return the cause
*/
public static Throwable getCause(final Throwable throwable) {
// Unwrap possibly-nested ExecutionExceptions to get to root cause
Throwable cause = throwable;
while (cause instanceof ExecutionException) {
cause = cause.getCause();
}
return cause != null ? cause : new ExecutionException("ExecutionException with unknown cause", null);
}
/**
* Check for interruption and return interruption status.
*
* @return true if this thread or any other thread that shares this InterruptionChecker instance has been
* interrupted or has thrown an exception.
*/
public boolean checkAndReturn() {
// Check if any thread has been interrupted
if (interrupted.get()) {
// If so, interrupt this thread
interrupt();
return true;
}
// Check if this thread has been interrupted
if (Thread.currentThread().isInterrupted()) {
// If so, interrupt other threads
interrupted.set(true);
return true;
}
return false;
}
/**
* Check if this thread or any other thread that shares this InterruptionChecker instance has been interrupted
* or has thrown an exception, and if so, throw InterruptedException.
*
* @throws InterruptedException
* If a thread has been interrupted.
* @throws ExecutionException
* if a thread has thrown an uncaught exception.
*/
public void check() throws InterruptedException, ExecutionException {<FILL_FUNCTION_BODY>}
}
|
// If a thread threw an uncaught exception, re-throw it.
final ExecutionException executionException = getExecutionException();
if (executionException != null) {
throw executionException;
}
// If this thread or another thread has been interrupted, throw InterruptedException
if (checkAndReturn()) {
throw new InterruptedException();
}
| 751
| 91
| 842
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/concurrency/SimpleThreadFactory.java
|
SimpleThreadFactory
|
newThread
|
class SimpleThreadFactory implements java.util.concurrent.ThreadFactory {
/** The thread name prefix. */
private final String threadNamePrefix;
/** The thread index counter, used for assigning unique thread ids. */
private static final AtomicInteger threadIdx = new AtomicInteger();
/** Whether to set daemon mode. */
private final boolean daemon;
/**
* Constructor.
*
* @param threadNamePrefix
* prefix for created threads.
* @param daemon
* create daemon threads?
*/
SimpleThreadFactory(final String threadNamePrefix, final boolean daemon) {
this.threadNamePrefix = threadNamePrefix;
this.daemon = daemon;
}
/**
* New thread.
*
* @param runnable
* the runnable
* @return the thread
*/
@Override
public Thread newThread(final Runnable runnable) {<FILL_FUNCTION_BODY>}
}
|
// Call System.getSecurityManager().getThreadGroup() via reflection, since it is deprecated in JDK 17
ThreadGroup securityManagerThreadGroup = null;
try {
final Method getSecurityManager = System.class.getDeclaredMethod("getSecurityManager");
final Object securityManager = getSecurityManager.invoke(null);
if (securityManager != null) {
final Method getThreadGroup = securityManager.getClass().getDeclaredMethod("getThreadGroup");
securityManagerThreadGroup = (ThreadGroup) getThreadGroup.invoke(securityManager);
}
} catch (final Throwable t) {
// Fall through
}
final Thread thread = new Thread(
securityManagerThreadGroup != null ? securityManagerThreadGroup
: new ThreadGroup("ClassGraph-thread-group"),
runnable, threadNamePrefix + threadIdx.getAndIncrement());
thread.setDaemon(daemon);
return thread;
| 254
| 231
| 485
|
<no_super_class>
|
classgraph_classgraph
|
classgraph/src/main/java/nonapi/io/github/classgraph/concurrency/SingletonMap.java
|
SingletonHolder
|
get
|
class SingletonHolder<V> {
/** The singleton. */
@SuppressWarnings("null")
private volatile V singleton;
/** Whether or not the singleton has been initialized (the count will have reached 0 if so). */
private final CountDownLatch initialized = new CountDownLatch(1);
/**
* Set the singleton value, and decreases the countdown latch to 0.
*
* @param singleton
* the singleton
* @throws IllegalArgumentException
* if this method is called more than once (indicating an internal inconsistency).
*/
void set(final V singleton) throws IllegalArgumentException {
if (initialized.getCount() < 1) {
// Should not happen
throw new IllegalArgumentException("Singleton already initialized");
}
this.singleton = singleton;
initialized.countDown();
if (initialized.getCount() != 0) {
// Should not happen
throw new IllegalArgumentException("Singleton initialized more than once");
}
}
/**
* Get the singleton value.
*
* @return the singleton value.
* @throws InterruptedException
* if the thread was interrupted while waiting for the value to be set.
*/
V get() throws InterruptedException {
initialized.await();
return singleton;
}
}
/**
* Construct a new singleton instance.
*
* @param key
* The key for the singleton.
* @param log
* The log.
* @return The singleton instance. This method must either return a non-null value, or throw an exception of
* type E.
* @throws E
* If something goes wrong while instantiating the new object instance.
* @throws InterruptedException
* if the thread was interrupted while instantiating the singleton.
*/
public abstract V newInstance(K key, LogNode log) throws E, InterruptedException;
/**
* Create a new instance.
*
* @param <V>
* The instance type.
*/
@FunctionalInterface
public interface NewInstanceFactory<V, E extends Exception> {
/**
* Create a new instance.
*
* @return The new instance.
*/
public V newInstance() throws E, InterruptedException;
}
/**
* Check if the given key is in the map, and if so, return the value of {@link #newInstance(Object, LogNode)}
* for that key, or block on the result of {@link #newInstance(Object, LogNode)} if another thread is currently
* creating the new instance.
*
* If the given key is not currently in the map, store a placeholder in the map for this key, then run
* {@link #newInstance(Object, LogNode)} for the key, store the result in the placeholder (which unblocks any
* other threads waiting for the value), and then return the new instance.
*
* @param key
* The key for the singleton.
* @param newInstanceFactory
* if non-null, a factory for creating new instances, otherwise if null, then
* {@link #newInstance(Object, LogNode)} is called instead (this allows new instance creation to be
* overridden on a per-instance basis).
* @param log
* The log.
* @return The non-null singleton instance, if {@link #newInstance(Object, LogNode)} returned a non-null
* instance on this call or a previous call, otherwise throws {@link NullPointerException} if this call
* or a previous call to {@link #newInstance(Object, LogNode)} returned null.
* @throws E
* If {@link #newInstance(Object, LogNode)} threw an exception.
* @throws InterruptedException
* if the thread was interrupted while waiting for the singleton to be instantiated by another
* thread.
* @throws NullSingletonException
* if {@link #newInstance(Object, LogNode)} returned null.
* @throws NewInstanceException
* if {@link #newInstance(Object, LogNode)} threw an exception.
*/
public V get(final K key, final LogNode log, final NewInstanceFactory<V, E> newInstanceFactory)
throws E, InterruptedException, NullSingletonException, NewInstanceException {<FILL_FUNCTION_BODY>
|
final SingletonHolder<V> singletonHolder = map.get(key);
@SuppressWarnings("null")
V instance = null;
if (singletonHolder != null) {
// There is already a SingletonHolder in the map for this key -- get the value
instance = singletonHolder.get();
} else {
// There is no SingletonHolder in the map for this key, need to create one
// (need to handle race condition, hence the putIfAbsent call)
final SingletonHolder<V> newSingletonHolder = new SingletonHolder<>();
final SingletonHolder<V> oldSingletonHolder = map.putIfAbsent(key, newSingletonHolder);
if (oldSingletonHolder != null) {
// There was already a singleton in the map for this key, due to a race condition --
// return the existing singleton
instance = oldSingletonHolder.get();
} else {
try {
// Create a new instance
if (newInstanceFactory != null) {
// Call NewInstanceFactory
instance = newInstanceFactory.newInstance();
} else {
// Call overridden newInstance method
instance = newInstance(key, log);
}
} catch (final Throwable t) {
// Initialize newSingletonHolder with the new instance.
// Always need to call .set() even if an exception is thrown by newInstance()
// or newInstance() returns null, since .set() calls initialized.countDown().
// Otherwise threads that call .get() may end up waiting forever.
newSingletonHolder.set(instance);
throw new NewInstanceException(key, t);
}
newSingletonHolder.set(instance);
}
}
if (instance == null) {
throw new NullSingletonException(key);
} else {
return instance;
}
| 1,099
| 461
| 1,560
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.