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
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysPermissionService.java
SysPermissionService
getMenuPermission
class SysPermissionService { @Autowired private ISysRoleService roleService; @Autowired private ISysMenuService menuService; /** * 获取角色数据权限 * * @param user 用户信息 * @return 角色权限信息 */ public Set<String> getRolePermission(SysUser user) { Set<String> roles = new HashSet<String>(); // 管理员拥有所有权限 if (user.isAdmin()) { roles.add("admin"); } else { roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId())); } return roles; } /** * 获取菜单数据权限 * * @param user 用户信息 * @return 菜单权限信息 */ public Set<String> getMenuPermission(SysUser user) {<FILL_FUNCTION_BODY>} }
Set<String> perms = new HashSet<String>(); // 管理员拥有所有权限 if (user.isAdmin()) { perms.add("*:*:*"); } else { List<SysRole> roles = user.getRoles(); if (!CollectionUtils.isEmpty(roles)) { // 多角色设置permissions属性,以便数据权限匹配权限 for (SysRole role : roles) { Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId()); role.setPermissions(rolePerms); perms.addAll(rolePerms); } } else { perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId())); } } return perms;
298
255
553
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysRegisterService.java
SysRegisterService
validateCaptcha
class SysRegisterService { @Autowired private ISysUserService userService; @Autowired private ISysConfigService configService; @Autowired private RedisCache redisCache; /** * 注册 */ public String register(RegisterBody registerBody) { String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword(); SysUser sysUser = new SysUser(); 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, 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(); }
730
128
858
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/TokenService.java
TokenService
getLoginUser
class TokenService { private static final Logger log = LoggerFactory.getLogger(TokenService.class); // 令牌自定义标识 @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) {<FILL_FUNCTION_BODY>} /** * 设置用户身份信息 */ 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); setUserAgent(loginUser); refreshToken(loginUser); 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) { loginUser.setLoginTime(System.currentTimeMillis()); loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE); // 根据uuid将loginUser缓存 String userKey = getTokenKey(loginUser.getToken()); redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES); } /** * 设置用户代理信息 * * @param loginUser 登录信息 */ public void setUserAgent(LoginUser loginUser) { UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent")); String ip = IpUtils.getIpAddr(); loginUser.setIpaddr(ip); loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip)); loginUser.setBrowser(userAgent.getBrowser().getName()); loginUser.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; } }
// 获取请求携带的令牌 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); LoginUser user = redisCache.getCacheObject(userKey); return user; } catch (Exception e) { log.error("获取用户信息异常'{}'", e.getMessage()); } } return null;
1,598
189
1,787
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/UserDetailsServiceImpl.java
UserDetailsServiceImpl
loadUserByUsername
class UserDetailsServiceImpl implements UserDetailsService { private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class); @Autowired private ISysUserService userService; @Autowired private SysPasswordService passwordService; @Autowired private SysPermissionService permissionService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<FILL_FUNCTION_BODY>} public UserDetails createLoginUser(SysUser user) { return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user)); } }
SysUser user = userService.selectUserByUserName(username); if (StringUtils.isNull(user)) { log.info("登录用户:{} 不存在.", username); throw new ServiceException(MessageUtils.message("user.not.exists")); } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) { log.info("登录用户:{} 已被删除.", username); throw new ServiceException(MessageUtils.message("user.password.delete")); } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) { log.info("登录用户:{} 已被停用.", username); throw new ServiceException(MessageUtils.message("user.blocked")); } passwordService.validate(user); return createLoginUser(user);
201
247
448
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityInitializer.java
VelocityInitializer
initVelocity
class VelocityInitializer { /** * 初始化vm方法 */ public static void initVelocity() {<FILL_FUNCTION_BODY>} }
Properties p = new Properties(); try { // 加载classpath目录下的vm文件 p.setProperty("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); // 定义字符集 p.setProperty(Velocity.INPUT_ENCODING, Constants.UTF8); // 初始化Velocity引擎,指定配置Properties Velocity.init(p); } catch (Exception e) { throw new RuntimeException(e); }
57
165
222
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobController.java
SysJobController
edit
class SysJobController extends BaseController { @Autowired private ISysJobService jobService; /** * 查询定时任务列表 */ @PreAuthorize("@ss.hasPermi('monitor:job:list')") @GetMapping("/list") public TableDataInfo list(SysJob sysJob) { startPage(); List<SysJob> list = jobService.selectJobList(sysJob); return getDataTable(list); } /** * 导出定时任务列表 */ @PreAuthorize("@ss.hasPermi('monitor:job:export')") @Log(title = "定时任务", businessType = BusinessType.EXPORT) @PostMapping("/export") public void export(HttpServletResponse response, SysJob sysJob) { List<SysJob> list = jobService.selectJobList(sysJob); ExcelUtil<SysJob> util = new ExcelUtil<SysJob>(SysJob.class); util.exportExcel(response, list, "定时任务"); } /** * 获取定时任务详细信息 */ @PreAuthorize("@ss.hasPermi('monitor:job:query')") @GetMapping(value = "/{jobId}") public AjaxResult getInfo(@PathVariable("jobId") Long jobId) { return success(jobService.selectJobById(jobId)); } /** * 新增定时任务 */ @PreAuthorize("@ss.hasPermi('monitor:job:add')") @Log(title = "定时任务", businessType = BusinessType.INSERT) @PostMapping public AjaxResult add(@RequestBody SysJob job) throws SchedulerException, TaskException { if (!CronUtils.isValid(job.getCronExpression())) { return error("新增任务'" + job.getJobName() + "'失败,Cron表达式不正确"); } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) { return error("新增任务'" + job.getJobName() + "'失败,目标字符串不允许'rmi'调用"); } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS })) { return error("新增任务'" + job.getJobName() + "'失败,目标字符串不允许'ldap(s)'调用"); } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.HTTP, Constants.HTTPS })) { return error("新增任务'" + job.getJobName() + "'失败,目标字符串不允许'http(s)'调用"); } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) { return error("新增任务'" + job.getJobName() + "'失败,目标字符串存在违规"); } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) { return error("新增任务'" + job.getJobName() + "'失败,目标字符串不在白名单内"); } job.setCreateBy(getUsername()); return toAjax(jobService.insertJob(job)); } /** * 修改定时任务 */ @PreAuthorize("@ss.hasPermi('monitor:job:edit')") @Log(title = "定时任务", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult edit(@RequestBody SysJob job) throws SchedulerException, TaskException {<FILL_FUNCTION_BODY>} /** * 定时任务状态修改 */ @PreAuthorize("@ss.hasPermi('monitor:job:changeStatus')") @Log(title = "定时任务", businessType = BusinessType.UPDATE) @PutMapping("/changeStatus") public AjaxResult changeStatus(@RequestBody SysJob job) throws SchedulerException { SysJob newJob = jobService.selectJobById(job.getJobId()); newJob.setStatus(job.getStatus()); return toAjax(jobService.changeStatus(newJob)); } /** * 定时任务立即执行一次 */ @PreAuthorize("@ss.hasPermi('monitor:job:changeStatus')") @Log(title = "定时任务", businessType = BusinessType.UPDATE) @PutMapping("/run") public AjaxResult run(@RequestBody SysJob job) throws SchedulerException { boolean result = jobService.run(job); return result ? success() : error("任务不存在或已过期!"); } /** * 删除定时任务 */ @PreAuthorize("@ss.hasPermi('monitor:job:remove')") @Log(title = "定时任务", businessType = BusinessType.DELETE) @DeleteMapping("/{jobIds}") public AjaxResult remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException { jobService.deleteJobByIds(jobIds); return success(); } }
if (!CronUtils.isValid(job.getCronExpression())) { return error("修改任务'" + job.getJobName() + "'失败,Cron表达式不正确"); } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) { return error("修改任务'" + job.getJobName() + "'失败,目标字符串不允许'rmi'调用"); } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS })) { return error("修改任务'" + job.getJobName() + "'失败,目标字符串不允许'ldap(s)'调用"); } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.HTTP, Constants.HTTPS })) { return error("修改任务'" + job.getJobName() + "'失败,目标字符串不允许'http(s)'调用"); } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) { return error("修改任务'" + job.getJobName() + "'失败,目标字符串存在违规"); } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) { return error("修改任务'" + job.getJobName() + "'失败,目标字符串不在白名单内"); } job.setUpdateBy(getUsername()); return toAjax(jobService.updateJob(job));
1,494
458
1,952
<methods>public non-sealed void <init>() ,public com.ruoyi.common.core.domain.AjaxResult error() ,public com.ruoyi.common.core.domain.AjaxResult error(java.lang.String) ,public java.lang.Long getDeptId() ,public com.ruoyi.common.core.domain.model.LoginUser getLoginUser() ,public java.lang.Long getUserId() ,public java.lang.String getUsername() ,public void initBinder(org.springframework.web.bind.WebDataBinder) ,public java.lang.String redirect(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success() ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.Object) ,public com.ruoyi.common.core.domain.AjaxResult warn(java.lang.String) <variables>protected final org.slf4j.Logger logger
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-quartz/src/main/java/com/ruoyi/quartz/controller/SysJobLogController.java
SysJobLogController
export
class SysJobLogController extends BaseController { @Autowired private ISysJobLogService jobLogService; /** * 查询定时任务调度日志列表 */ @PreAuthorize("@ss.hasPermi('monitor:job:list')") @GetMapping("/list") public TableDataInfo list(SysJobLog sysJobLog) { startPage(); List<SysJobLog> list = jobLogService.selectJobLogList(sysJobLog); return getDataTable(list); } /** * 导出定时任务调度日志列表 */ @PreAuthorize("@ss.hasPermi('monitor:job:export')") @Log(title = "任务调度日志", businessType = BusinessType.EXPORT) @PostMapping("/export") public void export(HttpServletResponse response, SysJobLog sysJobLog) {<FILL_FUNCTION_BODY>} /** * 根据调度编号获取详细信息 */ @PreAuthorize("@ss.hasPermi('monitor:job:query')") @GetMapping(value = "/{jobLogId}") public AjaxResult getInfo(@PathVariable Long jobLogId) { return success(jobLogService.selectJobLogById(jobLogId)); } /** * 删除定时任务调度日志 */ @PreAuthorize("@ss.hasPermi('monitor:job:remove')") @Log(title = "定时任务调度日志", businessType = BusinessType.DELETE) @DeleteMapping("/{jobLogIds}") public AjaxResult remove(@PathVariable Long[] jobLogIds) { return toAjax(jobLogService.deleteJobLogByIds(jobLogIds)); } /** * 清空定时任务调度日志 */ @PreAuthorize("@ss.hasPermi('monitor:job:remove')") @Log(title = "调度日志", businessType = BusinessType.CLEAN) @DeleteMapping("/clean") public AjaxResult clean() { jobLogService.cleanJobLog(); return success(); } }
List<SysJobLog> list = jobLogService.selectJobLogList(sysJobLog); ExcelUtil<SysJobLog> util = new ExcelUtil<SysJobLog>(SysJobLog.class); util.exportExcel(response, list, "调度日志");
629
78
707
<methods>public non-sealed void <init>() ,public com.ruoyi.common.core.domain.AjaxResult error() ,public com.ruoyi.common.core.domain.AjaxResult error(java.lang.String) ,public java.lang.Long getDeptId() ,public com.ruoyi.common.core.domain.model.LoginUser getLoginUser() ,public java.lang.Long getUserId() ,public java.lang.String getUsername() ,public void initBinder(org.springframework.web.bind.WebDataBinder) ,public java.lang.String redirect(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success() ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.Object) ,public com.ruoyi.common.core.domain.AjaxResult warn(java.lang.String) <variables>protected final org.slf4j.Logger logger
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJob.java
SysJob
toString
class SysJob extends BaseEntity { private static final long serialVersionUID = 1L; /** 任务ID */ @Excel(name = "任务序号", cellType = ColumnType.NUMERIC) private Long jobId; /** 任务名称 */ @Excel(name = "任务名称") private String jobName; /** 任务组名 */ @Excel(name = "任务组名") private String jobGroup; /** 调用目标字符串 */ @Excel(name = "调用目标字符串") private String invokeTarget; /** cron执行表达式 */ @Excel(name = "执行表达式 ") private String cronExpression; /** cron计划策略 */ @Excel(name = "计划策略 ", readConverterExp = "0=默认,1=立即触发执行,2=触发一次执行,3=不触发立即执行") private String misfirePolicy = ScheduleConstants.MISFIRE_DEFAULT; /** 是否并发执行(0允许 1禁止) */ @Excel(name = "并发执行", readConverterExp = "0=允许,1=禁止") private String concurrent; /** 任务状态(0正常 1暂停) */ @Excel(name = "任务状态", readConverterExp = "0=正常,1=暂停") private String status; public Long getJobId() { return jobId; } public void setJobId(Long jobId) { this.jobId = jobId; } @NotBlank(message = "任务名称不能为空") @Size(min = 0, max = 64, message = "任务名称不能超过64个字符") public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobGroup() { return jobGroup; } public void setJobGroup(String jobGroup) { this.jobGroup = jobGroup; } @NotBlank(message = "调用目标字符串不能为空") @Size(min = 0, max = 500, message = "调用目标字符串长度不能超过500个字符") public String getInvokeTarget() { return invokeTarget; } public void setInvokeTarget(String invokeTarget) { this.invokeTarget = invokeTarget; } @NotBlank(message = "Cron执行表达式不能为空") @Size(min = 0, max = 255, message = "Cron执行表达式不能超过255个字符") public String getCronExpression() { return cronExpression; } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getNextValidTime() { if (StringUtils.isNotEmpty(cronExpression)) { return CronUtils.getNextExecution(cronExpression); } return null; } public String getMisfirePolicy() { return misfirePolicy; } public void setMisfirePolicy(String misfirePolicy) { this.misfirePolicy = misfirePolicy; } public String getConcurrent() { return concurrent; } public void setConcurrent(String concurrent) { this.concurrent = concurrent; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("jobId", getJobId()) .append("jobName", getJobName()) .append("jobGroup", getJobGroup()) .append("cronExpression", getCronExpression()) .append("nextValidTime", getNextValidTime()) .append("misfirePolicy", getMisfirePolicy()) .append("concurrent", getConcurrent()) .append("status", getStatus()) .append("createBy", getCreateBy()) .append("createTime", getCreateTime()) .append("updateBy", getUpdateBy()) .append("updateTime", getUpdateTime()) .append("remark", getRemark()) .toString();
1,159
208
1,367
<methods>public non-sealed void <init>() ,public java.lang.String getCreateBy() ,public java.util.Date getCreateTime() ,public Map<java.lang.String,java.lang.Object> getParams() ,public java.lang.String getRemark() ,public java.lang.String getSearchValue() ,public java.lang.String getUpdateBy() ,public java.util.Date getUpdateTime() ,public void setCreateBy(java.lang.String) ,public void setCreateTime(java.util.Date) ,public void setParams(Map<java.lang.String,java.lang.Object>) ,public void setRemark(java.lang.String) ,public void setSearchValue(java.lang.String) ,public void setUpdateBy(java.lang.String) ,public void setUpdateTime(java.util.Date) <variables>private java.lang.String createBy,private java.util.Date createTime,private Map<java.lang.String,java.lang.Object> params,private java.lang.String remark,private java.lang.String searchValue,private static final long serialVersionUID,private java.lang.String updateBy,private java.util.Date updateTime
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-quartz/src/main/java/com/ruoyi/quartz/domain/SysJobLog.java
SysJobLog
toString
class SysJobLog extends BaseEntity { private static final long serialVersionUID = 1L; /** ID */ @Excel(name = "日志序号") private Long jobLogId; /** 任务名称 */ @Excel(name = "任务名称") private String jobName; /** 任务组名 */ @Excel(name = "任务组名") private String jobGroup; /** 调用目标字符串 */ @Excel(name = "调用目标字符串") private String invokeTarget; /** 日志信息 */ @Excel(name = "日志信息") private String jobMessage; /** 执行状态(0正常 1失败) */ @Excel(name = "执行状态", readConverterExp = "0=正常,1=失败") private String status; /** 异常信息 */ @Excel(name = "异常信息") private String exceptionInfo; /** 开始时间 */ private Date startTime; /** 停止时间 */ private Date stopTime; public Long getJobLogId() { return jobLogId; } public void setJobLogId(Long jobLogId) { this.jobLogId = jobLogId; } public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobGroup() { return jobGroup; } public void setJobGroup(String jobGroup) { this.jobGroup = jobGroup; } public String getInvokeTarget() { return invokeTarget; } public void setInvokeTarget(String invokeTarget) { this.invokeTarget = invokeTarget; } public String getJobMessage() { return jobMessage; } public void setJobMessage(String jobMessage) { this.jobMessage = jobMessage; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getExceptionInfo() { return exceptionInfo; } public void setExceptionInfo(String exceptionInfo) { this.exceptionInfo = exceptionInfo; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getStopTime() { return stopTime; } public void setStopTime(Date stopTime) { this.stopTime = stopTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("jobLogId", getJobLogId()) .append("jobName", getJobName()) .append("jobGroup", getJobGroup()) .append("jobMessage", getJobMessage()) .append("status", getStatus()) .append("exceptionInfo", getExceptionInfo()) .append("startTime", getStartTime()) .append("stopTime", getStopTime()) .toString();
889
138
1,027
<methods>public non-sealed void <init>() ,public java.lang.String getCreateBy() ,public java.util.Date getCreateTime() ,public Map<java.lang.String,java.lang.Object> getParams() ,public java.lang.String getRemark() ,public java.lang.String getSearchValue() ,public java.lang.String getUpdateBy() ,public java.util.Date getUpdateTime() ,public void setCreateBy(java.lang.String) ,public void setCreateTime(java.util.Date) ,public void setParams(Map<java.lang.String,java.lang.Object>) ,public void setRemark(java.lang.String) ,public void setSearchValue(java.lang.String) ,public void setUpdateBy(java.lang.String) ,public void setUpdateTime(java.util.Date) <variables>private java.lang.String createBy,private java.util.Date createTime,private Map<java.lang.String,java.lang.Object> params,private java.lang.String remark,private java.lang.String searchValue,private static final long serialVersionUID,private java.lang.String updateBy,private java.util.Date updateTime
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/AbstractQuartzJob.java
AbstractQuartzJob
after
class AbstractQuartzJob implements Job { private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class); /** * 线程本地变量 */ private static ThreadLocal<Date> threadLocal = new ThreadLocal<>(); @Override public void execute(JobExecutionContext context) throws JobExecutionException { SysJob sysJob = new SysJob(); BeanUtils.copyBeanProp(sysJob, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES)); try { before(context, sysJob); if (sysJob != null) { doExecute(context, sysJob); } after(context, sysJob, null); } catch (Exception e) { log.error("任务执行异常 - :", e); after(context, sysJob, e); } } /** * 执行前 * * @param context 工作执行上下文对象 * @param sysJob 系统计划任务 */ protected void before(JobExecutionContext context, SysJob sysJob) { threadLocal.set(new Date()); } /** * 执行后 * * @param context 工作执行上下文对象 * @param sysJob 系统计划任务 */ protected void after(JobExecutionContext context, SysJob sysJob, Exception e) {<FILL_FUNCTION_BODY>} /** * 执行方法,由子类重载 * * @param context 工作执行上下文对象 * @param sysJob 系统计划任务 * @throws Exception 执行过程中的异常 */ protected abstract void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception; }
Date startTime = threadLocal.get(); threadLocal.remove(); final SysJobLog sysJobLog = new SysJobLog(); sysJobLog.setJobName(sysJob.getJobName()); sysJobLog.setJobGroup(sysJob.getJobGroup()); sysJobLog.setInvokeTarget(sysJob.getInvokeTarget()); sysJobLog.setStartTime(startTime); sysJobLog.setStopTime(new Date()); long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime(); sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时:" + runMs + "毫秒"); if (e != null) { sysJobLog.setStatus(Constants.FAIL); String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000); sysJobLog.setExceptionInfo(errorMsg); } else { sysJobLog.setStatus(Constants.SUCCESS); } // 写入数据库当中 SpringUtils.getBean(ISysJobLogService.class).addJobLog(sysJobLog);
524
338
862
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/CronUtils.java
CronUtils
getNextExecution
class CronUtils { /** * 返回一个布尔值代表一个给定的Cron表达式的有效性 * * @param cronExpression Cron表达式 * @return boolean 表达式是否有效 */ public static boolean isValid(String cronExpression) { return CronExpression.isValidExpression(cronExpression); } /** * 返回一个字符串值,表示该消息无效Cron表达式给出有效性 * * @param cronExpression Cron表达式 * @return String 无效时返回表达式错误描述,如果有效返回null */ public static String getInvalidMessage(String cronExpression) { try { new CronExpression(cronExpression); return null; } catch (ParseException pe) { return pe.getMessage(); } } /** * 返回下一个执行时间根据给定的Cron表达式 * * @param cronExpression Cron表达式 * @return Date 下次Cron表达式执行时间 */ public static Date getNextExecution(String cronExpression) {<FILL_FUNCTION_BODY>} }
try { CronExpression cron = new CronExpression(cronExpression); return cron.getNextValidTimeAfter(new Date(System.currentTimeMillis())); } catch (ParseException e) { throw new IllegalArgumentException(e.getMessage()); }
348
84
432
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/JobInvokeUtil.java
JobInvokeUtil
getMethodParams
class JobInvokeUtil { /** * 执行方法 * * @param sysJob 系统任务 */ public static void invokeMethod(SysJob sysJob) throws Exception { String invokeTarget = sysJob.getInvokeTarget(); String beanName = getBeanName(invokeTarget); String methodName = getMethodName(invokeTarget); List<Object[]> methodParams = getMethodParams(invokeTarget); if (!isValidClassName(beanName)) { Object bean = SpringUtils.getBean(beanName); invokeMethod(bean, methodName, methodParams); } else { Object bean = Class.forName(beanName).getDeclaredConstructor().newInstance(); invokeMethod(bean, methodName, methodParams); } } /** * 调用任务方法 * * @param bean 目标对象 * @param methodName 方法名称 * @param methodParams 方法参数 */ private static void invokeMethod(Object bean, String methodName, List<Object[]> methodParams) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { if (StringUtils.isNotNull(methodParams) && methodParams.size() > 0) { Method method = bean.getClass().getMethod(methodName, getMethodParamsType(methodParams)); method.invoke(bean, getMethodParamsValue(methodParams)); } else { Method method = bean.getClass().getMethod(methodName); method.invoke(bean); } } /** * 校验是否为为class包名 * * @param invokeTarget 名称 * @return true是 false否 */ public static boolean isValidClassName(String invokeTarget) { return StringUtils.countMatches(invokeTarget, ".") > 1; } /** * 获取bean名称 * * @param invokeTarget 目标字符串 * @return bean名称 */ public static String getBeanName(String invokeTarget) { String beanName = StringUtils.substringBefore(invokeTarget, "("); return StringUtils.substringBeforeLast(beanName, "."); } /** * 获取bean方法 * * @param invokeTarget 目标字符串 * @return method方法 */ public static String getMethodName(String invokeTarget) { String methodName = StringUtils.substringBefore(invokeTarget, "("); return StringUtils.substringAfterLast(methodName, "."); } /** * 获取method方法参数相关列表 * * @param invokeTarget 目标字符串 * @return method方法相关参数列表 */ public static List<Object[]> getMethodParams(String invokeTarget) {<FILL_FUNCTION_BODY>} /** * 获取参数类型 * * @param methodParams 参数相关列表 * @return 参数类型列表 */ public static Class<?>[] getMethodParamsType(List<Object[]> methodParams) { Class<?>[] classs = new Class<?>[methodParams.size()]; int index = 0; for (Object[] os : methodParams) { classs[index] = (Class<?>) os[1]; index++; } return classs; } /** * 获取参数值 * * @param methodParams 参数相关列表 * @return 参数值列表 */ public static Object[] getMethodParamsValue(List<Object[]> methodParams) { Object[] classs = new Object[methodParams.size()]; int index = 0; for (Object[] os : methodParams) { classs[index] = (Object) os[0]; index++; } return classs; } }
String methodStr = StringUtils.substringBetween(invokeTarget, "(", ")"); if (StringUtils.isEmpty(methodStr)) { return null; } String[] methodParams = methodStr.split(",(?=([^\"']*[\"'][^\"']*[\"'])*[^\"']*$)"); List<Object[]> classs = new LinkedList<>(); for (int i = 0; i < methodParams.length; i++) { String str = StringUtils.trimToEmpty(methodParams[i]); // String字符串类型,以'或"开头 if (StringUtils.startsWithAny(str, "'", "\"")) { classs.add(new Object[] { StringUtils.substring(str, 1, str.length() - 1), String.class }); } // boolean布尔类型,等于true或者false else if ("true".equalsIgnoreCase(str) || "false".equalsIgnoreCase(str)) { classs.add(new Object[] { Boolean.valueOf(str), Boolean.class }); } // long长整形,以L结尾 else if (StringUtils.endsWith(str, "L")) { classs.add(new Object[] { Long.valueOf(StringUtils.substring(str, 0, str.length() - 1)), Long.class }); } // double浮点类型,以D结尾 else if (StringUtils.endsWith(str, "D")) { classs.add(new Object[] { Double.valueOf(StringUtils.substring(str, 0, str.length() - 1)), Double.class }); } // 其他类型归类为整形 else { classs.add(new Object[] { Integer.valueOf(str), Integer.class }); } } return classs;
1,148
516
1,664
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-quartz/src/main/java/com/ruoyi/quartz/util/ScheduleUtils.java
ScheduleUtils
createScheduleJob
class ScheduleUtils { /** * 得到quartz任务类 * * @param sysJob 执行计划 * @return 具体执行任务类 */ private static Class<? extends Job> getQuartzJobClass(SysJob sysJob) { boolean isConcurrent = "0".equals(sysJob.getConcurrent()); return isConcurrent ? QuartzJobExecution.class : QuartzDisallowConcurrentExecution.class; } /** * 构建任务触发对象 */ public static TriggerKey getTriggerKey(Long jobId, String jobGroup) { return TriggerKey.triggerKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup); } /** * 构建任务键对象 */ public static JobKey getJobKey(Long jobId, String jobGroup) { return JobKey.jobKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup); } /** * 创建定时任务 */ public static void createScheduleJob(Scheduler scheduler, SysJob job) throws SchedulerException, TaskException {<FILL_FUNCTION_BODY>} /** * 设置定时任务策略 */ public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb) throws TaskException { switch (job.getMisfirePolicy()) { case ScheduleConstants.MISFIRE_DEFAULT: return cb; case ScheduleConstants.MISFIRE_IGNORE_MISFIRES: return cb.withMisfireHandlingInstructionIgnoreMisfires(); case ScheduleConstants.MISFIRE_FIRE_AND_PROCEED: return cb.withMisfireHandlingInstructionFireAndProceed(); case ScheduleConstants.MISFIRE_DO_NOTHING: return cb.withMisfireHandlingInstructionDoNothing(); default: throw new TaskException("The task misfire policy '" + job.getMisfirePolicy() + "' cannot be used in cron schedule tasks", Code.CONFIG_ERROR); } } /** * 检查包名是否为白名单配置 * * @param invokeTarget 目标字符串 * @return 结果 */ public static boolean whiteList(String invokeTarget) { String packageName = StringUtils.substringBefore(invokeTarget, "("); int count = StringUtils.countMatches(packageName, "."); if (count > 1) { return StringUtils.containsAnyIgnoreCase(invokeTarget, Constants.JOB_WHITELIST_STR); } Object obj = SpringUtils.getBean(StringUtils.split(invokeTarget, ".")[0]); String beanPackageName = obj.getClass().getPackage().getName(); return StringUtils.containsAnyIgnoreCase(beanPackageName, Constants.JOB_WHITELIST_STR) && !StringUtils.containsAnyIgnoreCase(beanPackageName, Constants.JOB_ERROR_STR); } }
Class<? extends Job> jobClass = getQuartzJobClass(job); // 构建job信息 Long jobId = job.getJobId(); String jobGroup = job.getJobGroup(); JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(getJobKey(jobId, jobGroup)).build(); // 表达式调度构建器 CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression()); cronScheduleBuilder = handleCronScheduleMisfirePolicy(job, cronScheduleBuilder); // 按新的cronExpression表达式构建一个新的trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobId, jobGroup)) .withSchedule(cronScheduleBuilder).build(); // 放入参数,运行时的方法可以获取 jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job); // 判断是否存在 if (scheduler.checkExists(getJobKey(jobId, jobGroup))) { // 防止创建时存在数据问题 先移除,然后在执行创建操作 scheduler.deleteJob(getJobKey(jobId, jobGroup)); } // 判断任务是否过期 if (StringUtils.isNotNull(CronUtils.getNextExecution(job.getCronExpression()))) { // 执行调度任务 scheduler.scheduleJob(jobDetail, trigger); } // 暂停任务 if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue())) { scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup)); }
873
481
1,354
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysConfig.java
SysConfig
toString
class SysConfig extends BaseEntity { private static final long serialVersionUID = 1L; /** 参数主键 */ @Excel(name = "参数主键", cellType = ColumnType.NUMERIC) private Long configId; /** 参数名称 */ @Excel(name = "参数名称") private String configName; /** 参数键名 */ @Excel(name = "参数键名") private String configKey; /** 参数键值 */ @Excel(name = "参数键值") private String configValue; /** 系统内置(Y是 N否) */ @Excel(name = "系统内置", readConverterExp = "Y=是,N=否") private String configType; public Long getConfigId() { return configId; } public void setConfigId(Long configId) { this.configId = configId; } @NotBlank(message = "参数名称不能为空") @Size(min = 0, max = 100, message = "参数名称不能超过100个字符") public String getConfigName() { return configName; } public void setConfigName(String configName) { this.configName = configName; } @NotBlank(message = "参数键名长度不能为空") @Size(min = 0, max = 100, message = "参数键名长度不能超过100个字符") public String getConfigKey() { return configKey; } public void setConfigKey(String configKey) { this.configKey = configKey; } @NotBlank(message = "参数键值不能为空") @Size(min = 0, max = 500, message = "参数键值长度不能超过500个字符") public String getConfigValue() { return configValue; } public void setConfigValue(String configValue) { this.configValue = configValue; } public String getConfigType() { return configType; } public void setConfigType(String configType) { this.configType = configType; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("configId", getConfigId()) .append("configName", getConfigName()) .append("configKey", getConfigKey()) .append("configValue", getConfigValue()) .append("configType", getConfigType()) .append("createBy", getCreateBy()) .append("createTime", getCreateTime()) .append("updateBy", getUpdateBy()) .append("updateTime", getUpdateTime()) .append("remark", getRemark()) .toString();
706
163
869
<methods>public non-sealed void <init>() ,public java.lang.String getCreateBy() ,public java.util.Date getCreateTime() ,public Map<java.lang.String,java.lang.Object> getParams() ,public java.lang.String getRemark() ,public java.lang.String getSearchValue() ,public java.lang.String getUpdateBy() ,public java.util.Date getUpdateTime() ,public void setCreateBy(java.lang.String) ,public void setCreateTime(java.util.Date) ,public void setParams(Map<java.lang.String,java.lang.Object>) ,public void setRemark(java.lang.String) ,public void setSearchValue(java.lang.String) ,public void setUpdateBy(java.lang.String) ,public void setUpdateTime(java.util.Date) <variables>private java.lang.String createBy,private java.util.Date createTime,private Map<java.lang.String,java.lang.Object> params,private java.lang.String remark,private java.lang.String searchValue,private static final long serialVersionUID,private java.lang.String updateBy,private java.util.Date updateTime
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysNotice.java
SysNotice
toString
class SysNotice extends BaseEntity { private static final long serialVersionUID = 1L; /** 公告ID */ private Long noticeId; /** 公告标题 */ private String noticeTitle; /** 公告类型(1通知 2公告) */ private String noticeType; /** 公告内容 */ private String noticeContent; /** 公告状态(0正常 1关闭) */ private String status; public Long getNoticeId() { return noticeId; } public void setNoticeId(Long noticeId) { this.noticeId = noticeId; } public void setNoticeTitle(String noticeTitle) { this.noticeTitle = noticeTitle; } @Xss(message = "公告标题不能包含脚本字符") @NotBlank(message = "公告标题不能为空") @Size(min = 0, max = 50, message = "公告标题不能超过50个字符") public String getNoticeTitle() { return noticeTitle; } public void setNoticeType(String noticeType) { this.noticeType = noticeType; } public String getNoticeType() { return noticeType; } public void setNoticeContent(String noticeContent) { this.noticeContent = noticeContent; } public String getNoticeContent() { return noticeContent; } public void setStatus(String status) { this.status = status; } public String getStatus() { return status; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("noticeId", getNoticeId()) .append("noticeTitle", getNoticeTitle()) .append("noticeType", getNoticeType()) .append("noticeContent", getNoticeContent()) .append("status", getStatus()) .append("createBy", getCreateBy()) .append("createTime", getCreateTime()) .append("updateBy", getUpdateBy()) .append("updateTime", getUpdateTime()) .append("remark", getRemark()) .toString();
530
165
695
<methods>public non-sealed void <init>() ,public java.lang.String getCreateBy() ,public java.util.Date getCreateTime() ,public Map<java.lang.String,java.lang.Object> getParams() ,public java.lang.String getRemark() ,public java.lang.String getSearchValue() ,public java.lang.String getUpdateBy() ,public java.util.Date getUpdateTime() ,public void setCreateBy(java.lang.String) ,public void setCreateTime(java.util.Date) ,public void setParams(Map<java.lang.String,java.lang.Object>) ,public void setRemark(java.lang.String) ,public void setSearchValue(java.lang.String) ,public void setUpdateBy(java.lang.String) ,public void setUpdateTime(java.util.Date) <variables>private java.lang.String createBy,private java.util.Date createTime,private Map<java.lang.String,java.lang.Object> params,private java.lang.String remark,private java.lang.String searchValue,private static final long serialVersionUID,private java.lang.String updateBy,private java.util.Date updateTime
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysPost.java
SysPost
toString
class SysPost extends BaseEntity { private static final long serialVersionUID = 1L; /** 岗位序号 */ @Excel(name = "岗位序号", cellType = ColumnType.NUMERIC) private Long postId; /** 岗位编码 */ @Excel(name = "岗位编码") private String postCode; /** 岗位名称 */ @Excel(name = "岗位名称") private String postName; /** 岗位排序 */ @Excel(name = "岗位排序") private Integer postSort; /** 状态(0正常 1停用) */ @Excel(name = "状态", readConverterExp = "0=正常,1=停用") private String status; /** 用户是否存在此岗位标识 默认不存在 */ private boolean flag = false; public Long getPostId() { return postId; } public void setPostId(Long postId) { this.postId = postId; } @NotBlank(message = "岗位编码不能为空") @Size(min = 0, max = 64, message = "岗位编码长度不能超过64个字符") public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } @NotBlank(message = "岗位名称不能为空") @Size(min = 0, max = 50, message = "岗位名称长度不能超过50个字符") public String getPostName() { return postName; } public void setPostName(String postName) { this.postName = postName; } @NotNull(message = "显示顺序不能为空") public Integer getPostSort() { return postSort; } public void setPostSort(Integer postSort) { this.postSort = postSort; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("postId", getPostId()) .append("postCode", getPostCode()) .append("postName", getPostName()) .append("postSort", getPostSort()) .append("status", getStatus()) .append("createBy", getCreateBy()) .append("createTime", getCreateTime()) .append("updateBy", getUpdateBy()) .append("updateTime", getUpdateTime()) .append("remark", getRemark()) .toString();
742
161
903
<methods>public non-sealed void <init>() ,public java.lang.String getCreateBy() ,public java.util.Date getCreateTime() ,public Map<java.lang.String,java.lang.Object> getParams() ,public java.lang.String getRemark() ,public java.lang.String getSearchValue() ,public java.lang.String getUpdateBy() ,public java.util.Date getUpdateTime() ,public void setCreateBy(java.lang.String) ,public void setCreateTime(java.util.Date) ,public void setParams(Map<java.lang.String,java.lang.Object>) ,public void setRemark(java.lang.String) ,public void setSearchValue(java.lang.String) ,public void setUpdateBy(java.lang.String) ,public void setUpdateTime(java.util.Date) <variables>private java.lang.String createBy,private java.util.Date createTime,private Map<java.lang.String,java.lang.Object> params,private java.lang.String remark,private java.lang.String searchValue,private static final long serialVersionUID,private java.lang.String updateBy,private java.util.Date updateTime
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java
SysConfigServiceImpl
selectConfigByKey
class SysConfigServiceImpl implements ISysConfigService { @Autowired private SysConfigMapper configMapper; @Autowired private RedisCache redisCache; /** * 项目启动时,初始化参数到缓存 */ @PostConstruct public void init() { loadingConfigCache(); } /** * 查询参数配置信息 * * @param configId 参数配置ID * @return 参数配置信息 */ @Override @DataSource(DataSourceType.MASTER) public SysConfig selectConfigById(Long configId) { SysConfig config = new SysConfig(); config.setConfigId(configId); return configMapper.selectConfig(config); } /** * 根据键名查询参数配置信息 * * @param configKey 参数key * @return 参数键值 */ @Override public String selectConfigByKey(String configKey) {<FILL_FUNCTION_BODY>} /** * 获取验证码开关 * * @return true开启,false关闭 */ @Override public boolean selectCaptchaEnabled() { String captchaEnabled = selectConfigByKey("sys.account.captchaEnabled"); if (StringUtils.isEmpty(captchaEnabled)) { return true; } return Convert.toBool(captchaEnabled); } /** * 查询参数配置列表 * * @param config 参数配置信息 * @return 参数配置集合 */ @Override public List<SysConfig> selectConfigList(SysConfig config) { return configMapper.selectConfigList(config); } /** * 新增参数配置 * * @param config 参数配置信息 * @return 结果 */ @Override public int insertConfig(SysConfig config) { int row = configMapper.insertConfig(config); if (row > 0) { redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue()); } return row; } /** * 修改参数配置 * * @param config 参数配置信息 * @return 结果 */ @Override public int updateConfig(SysConfig config) { SysConfig temp = configMapper.selectConfigById(config.getConfigId()); if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey())) { redisCache.deleteObject(getCacheKey(temp.getConfigKey())); } int row = configMapper.updateConfig(config); if (row > 0) { redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue()); } return row; } /** * 批量删除参数信息 * * @param configIds 需要删除的参数ID */ @Override public void deleteConfigByIds(Long[] configIds) { for (Long configId : configIds) { SysConfig config = selectConfigById(configId); if (StringUtils.equals(UserConstants.YES, config.getConfigType())) { throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey())); } configMapper.deleteConfigById(configId); redisCache.deleteObject(getCacheKey(config.getConfigKey())); } } /** * 加载参数缓存数据 */ @Override public void loadingConfigCache() { List<SysConfig> configsList = configMapper.selectConfigList(new SysConfig()); for (SysConfig config : configsList) { redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue()); } } /** * 清空参数缓存数据 */ @Override public void clearConfigCache() { Collection<String> keys = redisCache.keys(CacheConstants.SYS_CONFIG_KEY + "*"); redisCache.deleteObject(keys); } /** * 重置参数缓存数据 */ @Override public void resetConfigCache() { clearConfigCache(); loadingConfigCache(); } /** * 校验参数键名是否唯一 * * @param config 参数配置信息 * @return 结果 */ @Override public boolean checkConfigKeyUnique(SysConfig config) { Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId(); SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey()); if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) { return UserConstants.NOT_UNIQUE; } return UserConstants.UNIQUE; } /** * 设置cache key * * @param configKey 参数键 * @return 缓存键key */ private String getCacheKey(String configKey) { return CacheConstants.SYS_CONFIG_KEY + configKey; } }
String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey))); if (StringUtils.isNotEmpty(configValue)) { return configValue; } SysConfig config = new SysConfig(); config.setConfigKey(configKey); SysConfig retConfig = configMapper.selectConfig(config); if (StringUtils.isNotNull(retConfig)) { redisCache.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue()); return retConfig.getConfigValue(); } return StringUtils.EMPTY;
1,604
172
1,776
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java
SysDictDataServiceImpl
deleteDictDataByIds
class SysDictDataServiceImpl implements ISysDictDataService { @Autowired private SysDictDataMapper dictDataMapper; /** * 根据条件分页查询字典数据 * * @param dictData 字典数据信息 * @return 字典数据集合信息 */ @Override public List<SysDictData> selectDictDataList(SysDictData dictData) { return dictDataMapper.selectDictDataList(dictData); } /** * 根据字典类型和字典键值查询字典数据信息 * * @param dictType 字典类型 * @param dictValue 字典键值 * @return 字典标签 */ @Override public String selectDictLabel(String dictType, String dictValue) { return dictDataMapper.selectDictLabel(dictType, dictValue); } /** * 根据字典数据ID查询信息 * * @param dictCode 字典数据ID * @return 字典数据 */ @Override public SysDictData selectDictDataById(Long dictCode) { return dictDataMapper.selectDictDataById(dictCode); } /** * 批量删除字典数据信息 * * @param dictCodes 需要删除的字典数据ID */ @Override public void deleteDictDataByIds(Long[] dictCodes) {<FILL_FUNCTION_BODY>} /** * 新增保存字典数据信息 * * @param data 字典数据信息 * @return 结果 */ @Override public int insertDictData(SysDictData data) { int row = dictDataMapper.insertDictData(data); if (row > 0) { List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType()); DictUtils.setDictCache(data.getDictType(), dictDatas); } return row; } /** * 修改保存字典数据信息 * * @param data 字典数据信息 * @return 结果 */ @Override public int updateDictData(SysDictData data) { int row = dictDataMapper.updateDictData(data); if (row > 0) { List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType()); DictUtils.setDictCache(data.getDictType(), dictDatas); } return row; } }
for (Long dictCode : dictCodes) { SysDictData data = selectDictDataById(dictCode); dictDataMapper.deleteDictDataById(dictCode); List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType()); DictUtils.setDictCache(data.getDictType(), dictDatas); }
807
116
923
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java
SysDictTypeServiceImpl
checkDictTypeUnique
class SysDictTypeServiceImpl implements ISysDictTypeService { @Autowired private SysDictTypeMapper dictTypeMapper; @Autowired private SysDictDataMapper dictDataMapper; /** * 项目启动时,初始化字典到缓存 */ @PostConstruct public void init() { loadingDictCache(); } /** * 根据条件分页查询字典类型 * * @param dictType 字典类型信息 * @return 字典类型集合信息 */ @Override public List<SysDictType> selectDictTypeList(SysDictType dictType) { return dictTypeMapper.selectDictTypeList(dictType); } /** * 根据所有字典类型 * * @return 字典类型集合信息 */ @Override public List<SysDictType> selectDictTypeAll() { return dictTypeMapper.selectDictTypeAll(); } /** * 根据字典类型查询字典数据 * * @param dictType 字典类型 * @return 字典数据集合信息 */ @Override public List<SysDictData> selectDictDataByType(String dictType) { List<SysDictData> 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; } /** * 根据字典类型ID查询信息 * * @param dictId 字典类型ID * @return 字典类型 */ @Override public SysDictType selectDictTypeById(Long dictId) { return dictTypeMapper.selectDictTypeById(dictId); } /** * 根据字典类型查询信息 * * @param dictType 字典类型 * @return 字典类型 */ @Override public SysDictType selectDictTypeByType(String dictType) { return dictTypeMapper.selectDictTypeByType(dictType); } /** * 批量删除字典类型信息 * * @param dictIds 需要删除的字典ID */ @Override public void deleteDictTypeByIds(Long[] dictIds) { for (Long dictId : dictIds) { SysDictType dictType = selectDictTypeById(dictId); if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) { throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName())); } dictTypeMapper.deleteDictTypeById(dictId); DictUtils.removeDictCache(dictType.getDictType()); } } /** * 加载字典缓存数据 */ @Override public void loadingDictCache() { SysDictData dictData = new SysDictData(); dictData.setStatus("0"); Map<String, List<SysDictData>> dictDataMap = dictDataMapper.selectDictDataList(dictData).stream().collect(Collectors.groupingBy(SysDictData::getDictType)); for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()) { DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getDictSort)).collect(Collectors.toList())); } } /** * 清空字典缓存数据 */ @Override public void clearDictCache() { DictUtils.clearDictCache(); } /** * 重置字典缓存数据 */ @Override public void resetDictCache() { clearDictCache(); loadingDictCache(); } /** * 新增保存字典类型信息 * * @param dict 字典类型信息 * @return 结果 */ @Override public int insertDictType(SysDictType dict) { int row = dictTypeMapper.insertDictType(dict); if (row > 0) { DictUtils.setDictCache(dict.getDictType(), null); } return row; } /** * 修改保存字典类型信息 * * @param dict 字典类型信息 * @return 结果 */ @Override @Transactional public int updateDictType(SysDictType dict) { SysDictType oldDict = dictTypeMapper.selectDictTypeById(dict.getDictId()); dictDataMapper.updateDictDataType(oldDict.getDictType(), dict.getDictType()); int row = dictTypeMapper.updateDictType(dict); if (row > 0) { List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(dict.getDictType()); DictUtils.setDictCache(dict.getDictType(), dictDatas); } return row; } /** * 校验字典类型称是否唯一 * * @param dict 字典类型 * @return 结果 */ @Override public boolean checkDictTypeUnique(SysDictType dict) {<FILL_FUNCTION_BODY>} }
Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId(); SysDictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType()); if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) { return UserConstants.NOT_UNIQUE; } return UserConstants.UNIQUE;
1,755
131
1,886
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysPostServiceImpl.java
SysPostServiceImpl
checkPostCodeUnique
class SysPostServiceImpl implements ISysPostService { @Autowired private SysPostMapper postMapper; @Autowired private SysUserPostMapper userPostMapper; /** * 查询岗位信息集合 * * @param post 岗位信息 * @return 岗位信息集合 */ @Override public List<SysPost> selectPostList(SysPost post) { return postMapper.selectPostList(post); } /** * 查询所有岗位 * * @return 岗位列表 */ @Override public List<SysPost> selectPostAll() { return postMapper.selectPostAll(); } /** * 通过岗位ID查询岗位信息 * * @param postId 岗位ID * @return 角色对象信息 */ @Override public SysPost selectPostById(Long postId) { return postMapper.selectPostById(postId); } /** * 根据用户ID获取岗位选择框列表 * * @param userId 用户ID * @return 选中岗位ID列表 */ @Override public List<Long> selectPostListByUserId(Long userId) { return postMapper.selectPostListByUserId(userId); } /** * 校验岗位名称是否唯一 * * @param post 岗位信息 * @return 结果 */ @Override public boolean checkPostNameUnique(SysPost post) { Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId(); SysPost info = postMapper.checkPostNameUnique(post.getPostName()); if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) { return UserConstants.NOT_UNIQUE; } return UserConstants.UNIQUE; } /** * 校验岗位编码是否唯一 * * @param post 岗位信息 * @return 结果 */ @Override public boolean checkPostCodeUnique(SysPost post) {<FILL_FUNCTION_BODY>} /** * 通过岗位ID查询岗位使用数量 * * @param postId 岗位ID * @return 结果 */ @Override public int countUserPostById(Long postId) { return userPostMapper.countUserPostById(postId); } /** * 删除岗位信息 * * @param postId 岗位ID * @return 结果 */ @Override public int deletePostById(Long postId) { return postMapper.deletePostById(postId); } /** * 批量删除岗位信息 * * @param postIds 需要删除的岗位ID * @return 结果 */ @Override public int deletePostByIds(Long[] postIds) { for (Long postId : postIds) { SysPost post = selectPostById(postId); if (countUserPostById(postId) > 0) { throw new ServiceException(String.format("%1$s已分配,不能删除", post.getPostName())); } } return postMapper.deletePostByIds(postIds); } /** * 新增保存岗位信息 * * @param post 岗位信息 * @return 结果 */ @Override public int insertPost(SysPost post) { return postMapper.insertPost(post); } /** * 修改保存岗位信息 * * @param post 岗位信息 * @return 结果 */ @Override public int updatePost(SysPost post) { return postMapper.updatePost(post); } }
Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId(); SysPost info = postMapper.checkPostCodeUnique(post.getPostCode()); if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) { return UserConstants.NOT_UNIQUE; } return UserConstants.UNIQUE;
1,201
120
1,321
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserOnlineServiceImpl.java
SysUserOnlineServiceImpl
selectOnlineByInfo
class SysUserOnlineServiceImpl implements ISysUserOnlineService { /** * 通过登录地址查询信息 * * @param ipaddr 登录地址 * @param user 用户信息 * @return 在线用户信息 */ @Override public SysUserOnline selectOnlineByIpaddr(String ipaddr, LoginUser user) { if (StringUtils.equals(ipaddr, user.getIpaddr())) { return loginUserToUserOnline(user); } return null; } /** * 通过用户名称查询信息 * * @param userName 用户名称 * @param user 用户信息 * @return 在线用户信息 */ @Override public SysUserOnline selectOnlineByUserName(String userName, LoginUser user) { if (StringUtils.equals(userName, user.getUsername())) { return loginUserToUserOnline(user); } return null; } /** * 通过登录地址/用户名称查询信息 * * @param ipaddr 登录地址 * @param userName 用户名称 * @param user 用户信息 * @return 在线用户信息 */ @Override public SysUserOnline selectOnlineByInfo(String ipaddr, String userName, LoginUser user) {<FILL_FUNCTION_BODY>} /** * 设置在线用户信息 * * @param user 用户信息 * @return 在线用户 */ @Override public SysUserOnline loginUserToUserOnline(LoginUser user) { if (StringUtils.isNull(user) || StringUtils.isNull(user.getUser())) { return null; } SysUserOnline sysUserOnline = new SysUserOnline(); sysUserOnline.setTokenId(user.getToken()); sysUserOnline.setUserName(user.getUsername()); sysUserOnline.setIpaddr(user.getIpaddr()); sysUserOnline.setLoginLocation(user.getLoginLocation()); sysUserOnline.setBrowser(user.getBrowser()); sysUserOnline.setOs(user.getOs()); sysUserOnline.setLoginTime(user.getLoginTime()); if (StringUtils.isNotNull(user.getUser().getDept())) { sysUserOnline.setDeptName(user.getUser().getDept().getDeptName()); } return sysUserOnline; } }
if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername())) { return loginUserToUserOnline(user); } return null;
727
65
792
<no_super_class>
lukas-krecan_ShedLock
ShedLock/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/internal/CdiLockConfigurationExtractor.java
CdiLockConfigurationExtractor
getValue
class CdiLockConfigurationExtractor { private final Duration defaultLockAtMostFor; private final Duration defaultLockAtLeastFor; CdiLockConfigurationExtractor(Duration defaultLockAtMostFor, Duration defaultLockAtLeastFor) { this.defaultLockAtMostFor = requireNonNull(defaultLockAtMostFor); this.defaultLockAtLeastFor = requireNonNull(defaultLockAtLeastFor); } Optional<LockConfiguration> getLockConfiguration(Method method) { Optional<SchedulerLock> annotation = findAnnotation(method); return annotation.map(this::getLockConfiguration); } private LockConfiguration getLockConfiguration(SchedulerLock annotation) { return new LockConfiguration( ClockProvider.now(), getName(annotation), getLockAtMostFor(annotation), getLockAtLeastFor(annotation)); } private String getName(SchedulerLock annotation) { return annotation.name(); } Duration getLockAtMostFor(SchedulerLock annotation) { return getValue(annotation.lockAtMostFor(), this.defaultLockAtMostFor, "lockAtMostFor"); } Duration getLockAtLeastFor(SchedulerLock annotation) { return getValue(annotation.lockAtLeastFor(), this.defaultLockAtLeastFor, "lockAtLeastFor"); } private Duration getValue(String stringValueFromAnnotation, Duration defaultValue, String paramName) {<FILL_FUNCTION_BODY>} Optional<SchedulerLock> findAnnotation(Method method) { return Optional.ofNullable(method.getAnnotation(SchedulerLock.class)); } }
if (!stringValueFromAnnotation.isEmpty()) { return parseDuration(stringValueFromAnnotation); } else { return defaultValue; }
408
40
448
<no_super_class>
lukas-krecan_ShedLock
ShedLock/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/internal/SchedulerLockInterceptor.java
SchedulerLockInterceptor
lock
class SchedulerLockInterceptor { private final LockingTaskExecutor lockingTaskExecutor; private final CdiLockConfigurationExtractor lockConfigurationExtractor; @Inject public SchedulerLockInterceptor(LockProvider lockProvider) { this.lockingTaskExecutor = new DefaultLockingTaskExecutor(lockProvider); String lockAtMostFor = getConfigValue("shedlock.defaults.lock-at-most-for"); String lockAtLeastFor = getConfigValue("shedlock.defaults.lock-at-least-for"); Objects.requireNonNull(lockAtMostFor, "shedlock.defaults.lock-at-most-for parameter is mandatory"); this.lockConfigurationExtractor = new CdiLockConfigurationExtractor( parseDuration(lockAtMostFor), lockAtLeastFor != null ? parseDuration(lockAtLeastFor) : Duration.ZERO); } private static String getConfigValue(String propertyName) { return ConfigProvider.getConfig().getConfigValue(propertyName).getValue(); } @AroundInvoke Object lock(InvocationContext context) throws Throwable {<FILL_FUNCTION_BODY>} }
Class<?> returnType = context.getMethod().getReturnType(); if (!void.class.equals(returnType) && !Void.class.equals(returnType)) { throw new LockingNotSupportedException(); } Optional<LockConfiguration> lockConfiguration = lockConfigurationExtractor.getLockConfiguration(context.getMethod()); if (lockConfiguration.isPresent()) { lockingTaskExecutor.executeWithLock((LockingTaskExecutor.Task) context::proceed, lockConfiguration.get()); return null; } else { return context.proceed(); }
294
148
442
<no_super_class>
lukas-krecan_ShedLock
ShedLock/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/internal/Utils.java
Utils
parseDuration
class Utils { static Duration parseDuration(String value) {<FILL_FUNCTION_BODY>} }
value = value.trim(); if (value.isEmpty()) { return null; } try { return Duration.parse(value); } catch (DateTimeParseException e) { throw new IllegalArgumentException(e); }
31
66
97
<no_super_class>
lukas-krecan_ShedLock
ShedLock/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/internal/CdiLockConfigurationExtractor.java
CdiLockConfigurationExtractor
getValue
class CdiLockConfigurationExtractor { private final Duration defaultLockAtMostFor; private final Duration defaultLockAtLeastFor; CdiLockConfigurationExtractor(Duration defaultLockAtMostFor, Duration defaultLockAtLeastFor) { this.defaultLockAtMostFor = requireNonNull(defaultLockAtMostFor); this.defaultLockAtLeastFor = requireNonNull(defaultLockAtLeastFor); } Optional<LockConfiguration> getLockConfiguration(Method method) { Optional<SchedulerLock> annotation = findAnnotation(method); return annotation.map(this::getLockConfiguration); } private LockConfiguration getLockConfiguration(SchedulerLock annotation) { return new LockConfiguration( ClockProvider.now(), getName(annotation), getLockAtMostFor(annotation), getLockAtLeastFor(annotation)); } private String getName(SchedulerLock annotation) { return annotation.name(); } Duration getLockAtMostFor(SchedulerLock annotation) { return getValue(annotation.lockAtMostFor(), this.defaultLockAtMostFor, "lockAtMostFor"); } Duration getLockAtLeastFor(SchedulerLock annotation) { return getValue(annotation.lockAtLeastFor(), this.defaultLockAtLeastFor, "lockAtLeastFor"); } private Duration getValue(String stringValueFromAnnotation, Duration defaultValue, String paramName) {<FILL_FUNCTION_BODY>} Optional<SchedulerLock> findAnnotation(Method method) { return Optional.ofNullable(method.getAnnotation(SchedulerLock.class)); } }
if (!stringValueFromAnnotation.isEmpty()) { return parseDuration(stringValueFromAnnotation); } else { return defaultValue; }
408
40
448
<no_super_class>
lukas-krecan_ShedLock
ShedLock/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/internal/SchedulerLockInterceptor.java
SchedulerLockInterceptor
lock
class SchedulerLockInterceptor { private final LockingTaskExecutor lockingTaskExecutor; private final CdiLockConfigurationExtractor lockConfigurationExtractor; @Inject public SchedulerLockInterceptor(LockProvider lockProvider) { this.lockingTaskExecutor = new DefaultLockingTaskExecutor(lockProvider); String lockAtMostFor = getConfigValue("shedlock.defaults.lock-at-most-for"); String lockAtLeastFor = getConfigValue("shedlock.defaults.lock-at-least-for"); Objects.requireNonNull(lockAtMostFor, "shedlock.defaults.lock-at-most-for parameter is mandatory"); this.lockConfigurationExtractor = new CdiLockConfigurationExtractor( parseDuration(lockAtMostFor), lockAtLeastFor != null ? parseDuration(lockAtLeastFor) : Duration.ZERO); } private static String getConfigValue(String propertyName) { return ConfigProvider.getConfig().getConfigValue(propertyName).getValue(); } @AroundInvoke Object lock(InvocationContext context) throws Throwable {<FILL_FUNCTION_BODY>} }
Class<?> returnType = context.getMethod().getReturnType(); if (!void.class.equals(returnType) && !Void.class.equals(returnType)) { throw new LockingNotSupportedException(); } Optional<LockConfiguration> lockConfiguration = lockConfigurationExtractor.getLockConfiguration(context.getMethod()); if (lockConfiguration.isPresent()) { lockingTaskExecutor.executeWithLock((LockingTaskExecutor.Task) context::proceed, lockConfiguration.get()); return null; } else { return context.proceed(); }
294
148
442
<no_super_class>
lukas-krecan_ShedLock
ShedLock/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/internal/Utils.java
Utils
parseDuration
class Utils { static Duration parseDuration(String value) {<FILL_FUNCTION_BODY>} }
value = value.trim(); if (value.isEmpty()) { return null; } try { return Duration.parse(value); } catch (DateTimeParseException e) { throw new IllegalArgumentException(e); }
31
66
97
<no_super_class>
lukas-krecan_ShedLock
ShedLock/micronaut/shedlock-micronaut/src/main/java/net/javacrumbs/shedlock/micronaut/internal/MicronautLockConfigurationExtractor.java
MicronautLockConfigurationExtractor
getValue
class MicronautLockConfigurationExtractor { private final Duration defaultLockAtMostFor; private final Duration defaultLockAtLeastFor; private final ConversionService<?> conversionService; MicronautLockConfigurationExtractor( Duration defaultLockAtMostFor, Duration defaultLockAtLeastFor, ConversionService<?> conversionService) { this.defaultLockAtMostFor = requireNonNull(defaultLockAtMostFor); this.defaultLockAtLeastFor = requireNonNull(defaultLockAtLeastFor); this.conversionService = conversionService; } Optional<LockConfiguration> getLockConfiguration(ExecutableMethod<Object, Object> method) { Optional<AnnotationValue<SchedulerLock>> annotation = findAnnotation(method); return annotation.map(this::getLockConfiguration); } private LockConfiguration getLockConfiguration(AnnotationValue<SchedulerLock> annotation) { return new LockConfiguration( ClockProvider.now(), getName(annotation), getLockAtMostFor(annotation), getLockAtLeastFor(annotation)); } private String getName(AnnotationValue<SchedulerLock> annotation) { return annotation.getRequiredValue("name", String.class); } Duration getLockAtMostFor(AnnotationValue<SchedulerLock> annotation) { return getValue(annotation, this.defaultLockAtMostFor, "lockAtMostFor"); } Duration getLockAtLeastFor(AnnotationValue<SchedulerLock> annotation) { return getValue(annotation, this.defaultLockAtLeastFor, "lockAtLeastFor"); } private Duration getValue(AnnotationValue<SchedulerLock> annotation, Duration defaultValue, String paramName) {<FILL_FUNCTION_BODY>} Optional<AnnotationValue<SchedulerLock>> findAnnotation(ExecutableMethod<Object, Object> method) { return method.findAnnotation(SchedulerLock.class); } }
String stringValueFromAnnotation = annotation.get(paramName, String.class).orElse(""); if (StringUtils.hasText(stringValueFromAnnotation)) { return conversionService .convert(stringValueFromAnnotation, Duration.class) .orElseThrow(() -> new IllegalArgumentException("Invalid " + paramName + " value \"" + stringValueFromAnnotation + "\" - cannot parse into duration")); } else { return defaultValue; }
477
119
596
<no_super_class>
lukas-krecan_ShedLock
ShedLock/micronaut/shedlock-micronaut/src/main/java/net/javacrumbs/shedlock/micronaut/internal/SchedulerLockInterceptor.java
SchedulerLockInterceptor
intercept
class SchedulerLockInterceptor implements MethodInterceptor<Object, Object> { private final LockingTaskExecutor lockingTaskExecutor; private final MicronautLockConfigurationExtractor micronautLockConfigurationExtractor; public SchedulerLockInterceptor( LockProvider lockProvider, Optional<ConversionService<?>> conversionService, @Value("${shedlock.defaults.lock-at-most-for}") String defaultLockAtMostFor, @Value("${shedlock.defaults.lock-at-least-for:PT0S}") String defaultLockAtLeastFor) { ConversionService<?> resolvedConversionService = conversionService.orElse(ConversionService.SHARED); lockingTaskExecutor = new DefaultLockingTaskExecutor(lockProvider); micronautLockConfigurationExtractor = new MicronautLockConfigurationExtractor( resolvedConversionService .convert(defaultLockAtMostFor, Duration.class) .orElseThrow(() -> new IllegalArgumentException("Invalid 'defaultLockAtMostFor' value")), resolvedConversionService .convert(defaultLockAtLeastFor, Duration.class) .orElseThrow(() -> new IllegalArgumentException("Invalid 'defaultLockAtLeastFor' value")), resolvedConversionService); } @Override public Object intercept(MethodInvocationContext<Object, Object> context) {<FILL_FUNCTION_BODY>} }
Class<?> returnType = context.getReturnType().getType(); if (!void.class.equals(returnType) && !Void.class.equals(returnType)) { throw new LockingNotSupportedException(); } Optional<LockConfiguration> lockConfiguration = micronautLockConfigurationExtractor.getLockConfiguration(context.getExecutableMethod()); if (lockConfiguration.isPresent()) { lockingTaskExecutor.executeWithLock((Runnable) context::proceed, lockConfiguration.get()); return null; } else { return context.proceed(); }
357
150
507
<no_super_class>
lukas-krecan_ShedLock
ShedLock/micronaut/shedlock-micronaut4/src/main/java/net/javacrumbs/shedlock/micronaut/internal/MicronautLockConfigurationExtractor.java
MicronautLockConfigurationExtractor
getValue
class MicronautLockConfigurationExtractor { private final Duration defaultLockAtMostFor; private final Duration defaultLockAtLeastFor; private final ConversionService conversionService; MicronautLockConfigurationExtractor( Duration defaultLockAtMostFor, Duration defaultLockAtLeastFor, ConversionService conversionService) { this.defaultLockAtMostFor = requireNonNull(defaultLockAtMostFor); this.defaultLockAtLeastFor = requireNonNull(defaultLockAtLeastFor); this.conversionService = conversionService; } Optional<LockConfiguration> getLockConfiguration(ExecutableMethod<Object, Object> method) { Optional<AnnotationValue<SchedulerLock>> annotation = findAnnotation(method); return annotation.map(this::getLockConfiguration); } private LockConfiguration getLockConfiguration(AnnotationValue<SchedulerLock> annotation) { return new LockConfiguration( ClockProvider.now(), getName(annotation), getLockAtMostFor(annotation), getLockAtLeastFor(annotation)); } private String getName(AnnotationValue<SchedulerLock> annotation) { return annotation.getRequiredValue("name", String.class); } Duration getLockAtMostFor(AnnotationValue<SchedulerLock> annotation) { return getValue(annotation, this.defaultLockAtMostFor, "lockAtMostFor"); } Duration getLockAtLeastFor(AnnotationValue<SchedulerLock> annotation) { return getValue(annotation, this.defaultLockAtLeastFor, "lockAtLeastFor"); } private Duration getValue(AnnotationValue<SchedulerLock> annotation, Duration defaultValue, String paramName) {<FILL_FUNCTION_BODY>} Optional<AnnotationValue<SchedulerLock>> findAnnotation(ExecutableMethod<Object, Object> method) { return method.findAnnotation(SchedulerLock.class); } }
String stringValueFromAnnotation = annotation.get(paramName, String.class).orElse(""); if (StringUtils.hasText(stringValueFromAnnotation)) { return conversionService .convert(stringValueFromAnnotation, Duration.class) .orElseThrow(() -> new IllegalArgumentException("Invalid " + paramName + " value \"" + stringValueFromAnnotation + "\" - cannot parse into duration")); } else { return defaultValue; }
471
119
590
<no_super_class>
lukas-krecan_ShedLock
ShedLock/micronaut/shedlock-micronaut4/src/main/java/net/javacrumbs/shedlock/micronaut/internal/SchedulerLockInterceptor.java
SchedulerLockInterceptor
convert
class SchedulerLockInterceptor implements MethodInterceptor<Object, Object> { private final LockingTaskExecutor lockingTaskExecutor; private final MicronautLockConfigurationExtractor micronautLockConfigurationExtractor; public SchedulerLockInterceptor( LockProvider lockProvider, Optional<ConversionService> conversionService, @Value("${shedlock.defaults.lock-at-most-for}") String defaultLockAtMostFor, @Value("${shedlock.defaults.lock-at-least-for:PT0S}") String defaultLockAtLeastFor) { /* * From Micronaut 3 to 4, ConversionService changes from a parameterized type to * a non-parameterized one, so some raw type usage and unchecked casts are done * to support both Micronaut versions. */ ConversionService resolvedConversionService = conversionService.orElse(ConversionService.SHARED); lockingTaskExecutor = new DefaultLockingTaskExecutor(lockProvider); micronautLockConfigurationExtractor = new MicronautLockConfigurationExtractor( convert(resolvedConversionService, defaultLockAtMostFor, "defaultLockAtMostFor"), convert(resolvedConversionService, defaultLockAtLeastFor, "defaultLockAtLeastFor"), resolvedConversionService); } private static Duration convert( ConversionService resolvedConversionService, String defaultLockAtMostFor, String label) {<FILL_FUNCTION_BODY>} @Override public Object intercept(MethodInvocationContext<Object, Object> context) { Class<?> returnType = context.getReturnType().getType(); if (!void.class.equals(returnType) && !Void.class.equals(returnType)) { throw new LockingNotSupportedException(); } Optional<LockConfiguration> lockConfiguration = micronautLockConfigurationExtractor.getLockConfiguration(context.getExecutableMethod()); if (lockConfiguration.isPresent()) { lockingTaskExecutor.executeWithLock((Runnable) context::proceed, lockConfiguration.get()); return null; } else { return context.proceed(); } } }
return resolvedConversionService .convert(defaultLockAtMostFor, Duration.class) .orElseThrow(() -> new IllegalArgumentException("Invalid '" + label + "' value"));
545
48
593
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/arangodb/shedlock-provider-arangodb/src/main/java/net/javacrumbs/shedlock/provider/arangodb/ArangoLockProvider.java
ArangoLockProvider
lock
class ArangoLockProvider implements LockProvider { static final String LOCK_UNTIL = "lockUntil"; static final String LOCKED_AT = "lockedAt"; static final String LOCKED_BY = "lockedBy"; static final String COLLECTION_NAME = "shedLock"; private final ArangoCollection arangoCollection; /** * Instantiates a new Arango lock provider. * * @param arangoDatabase * the arango database */ public ArangoLockProvider(@NonNull ArangoDatabase arangoDatabase) { this(arangoDatabase.collection(COLLECTION_NAME)); } /** * Instantiates a new Arango lock provider. * * @param arangoCollection * the arango collection */ public ArangoLockProvider(@NonNull ArangoCollection arangoCollection) { this.arangoCollection = arangoCollection; } @Override @NonNull public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} private BaseDocument insertNewLock(String transactionId, String documentKey, Instant lockAtMostUntil) throws ArangoDBException { BaseDocument newDocument = new BaseDocument(); newDocument.setKey(documentKey); setDocumentAttributes(newDocument, lockAtMostUntil); DocumentCreateEntity<BaseDocument> document = arangoCollection.insertDocument( newDocument, new DocumentCreateOptions().streamTransactionId(transactionId).returnNew(true)); return document.getNew(); } private void updateLockAtMostUntil(String transactionId, BaseDocument existingDocument, Instant lockAtMostUntil) { setDocumentAttributes(existingDocument, lockAtMostUntil); arangoCollection.updateDocument( existingDocument.getKey(), existingDocument, new DocumentUpdateOptions().streamTransactionId(transactionId)); } private void setDocumentAttributes(BaseDocument baseDocument, Instant lockAtMostUntil) { baseDocument.addAttribute(LOCK_UNTIL, Utils.toIsoString(lockAtMostUntil)); baseDocument.addAttribute(LOCKED_AT, Utils.toIsoString(ClockProvider.now())); baseDocument.addAttribute(LOCKED_BY, getHostname()); } private static final class ArangoLock extends AbstractSimpleLock { private final ArangoCollection arangoCollection; private final BaseDocument document; public ArangoLock( final ArangoCollection arangoCollection, final BaseDocument document, final LockConfiguration lockConfiguration) { super(lockConfiguration); this.arangoCollection = arangoCollection; this.document = document; } @Override protected void doUnlock() { try { document.addAttribute(LOCK_UNTIL, Utils.toIsoString(lockConfiguration.getUnlockTime())); arangoCollection.updateDocument(lockConfiguration.getName(), document); } catch (ArangoDBException e) { throw new LockException("Unexpected error occured", e); } } } }
String transactionId = null; try { /* * Transaction is necessary because repsert (insert with overwrite=true in * arangodb) is not possible with condition check (see case 2 description below) */ StreamTransactionEntity streamTransactionEntity = arangoCollection .db() .beginStreamTransaction( new StreamTransactionOptions().exclusiveCollections(arangoCollection.name())); transactionId = streamTransactionEntity.getId(); /* * There are three possible situations: 1. The lock document does not exist yet * - insert document 2. The lock document exists and lockUtil <= now - update * document 3. The lock document exists and lockUtil > now - nothing to do */ BaseDocument existingDocument = arangoCollection.getDocument( lockConfiguration.getName(), BaseDocument.class, new DocumentReadOptions().streamTransactionId(transactionId)); // 1. case if (existingDocument == null) { BaseDocument newDocument = insertNewLock( transactionId, lockConfiguration.getName(), lockConfiguration.getLockAtMostUntil()); return Optional.of(new ArangoLock(arangoCollection, newDocument, lockConfiguration)); } // 2. case Instant lockUntil = Instant.parse(existingDocument.getAttribute(LOCK_UNTIL).toString()); if (lockUntil.compareTo(ClockProvider.now()) <= 0) { updateLockAtMostUntil(transactionId, existingDocument, lockConfiguration.getLockAtMostUntil()); return Optional.of(new ArangoLock(arangoCollection, existingDocument, lockConfiguration)); } // 3. case return Optional.empty(); } catch (ArangoDBException e) { if (transactionId != null) { arangoCollection.db().abortStreamTransaction(transactionId); } throw new LockException("Unexpected error occured", e); } finally { if (transactionId != null) { arangoCollection.db().commitStreamTransaction(transactionId); } }
774
512
1,286
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/cassandra/shedlock-provider-cassandra/src/main/java/net/javacrumbs/shedlock/provider/cassandra/CassandraLockProvider.java
Builder
build
class Builder { private CqlIdentifier table = CqlIdentifier.fromCql(DEFAULT_TABLE); private ColumnNames columnNames = new ColumnNames("name", "lockUntil", "lockedAt", "lockedBy"); private CqlSession cqlSession; private ConsistencyLevel consistencyLevel = ConsistencyLevel.QUORUM; private ConsistencyLevel serialConsistencyLevel = ConsistencyLevel.SERIAL; private CqlIdentifier keyspace; public Builder withTableName(@NonNull String table) { return withTableName(CqlIdentifier.fromCql(table)); } public Builder withTableName(@NonNull CqlIdentifier table) { this.table = table; return this; } public Builder withColumnNames(ColumnNames columnNames) { this.columnNames = columnNames; return this; } public Builder withCqlSession(@NonNull CqlSession cqlSession) { this.cqlSession = cqlSession; return this; } public Builder withConsistencyLevel(@NonNull ConsistencyLevel consistencyLevel) { this.consistencyLevel = consistencyLevel; return this; } /** * Since Shedlock internally uses CAS (Compare And Set) operations This * configuration helps to have a granular control on the CAS consistency. * * @return Builder */ public Builder withSerialConsistencyLevel(@NonNull ConsistencyLevel serialConsistencyLevel) { this.serialConsistencyLevel = serialConsistencyLevel; return this; } public Builder withKeyspace(@NonNull CqlIdentifier keyspace) { this.keyspace = keyspace; return this; } public CassandraLockProvider.Configuration build() {<FILL_FUNCTION_BODY>} }
return new CassandraLockProvider.Configuration( cqlSession, table, columnNames, consistencyLevel, serialConsistencyLevel, keyspace);
456
37
493
<methods>public void clearCache() ,public Optional<net.javacrumbs.shedlock.core.SimpleLock> lock(net.javacrumbs.shedlock.core.LockConfiguration) <variables>private final net.javacrumbs.shedlock.support.LockRecordRegistry lockRecordRegistry,private final non-sealed net.javacrumbs.shedlock.support.StorageAccessor storageAccessor
lukas-krecan_ShedLock
ShedLock/providers/cassandra/shedlock-provider-cassandra/src/main/java/net/javacrumbs/shedlock/provider/cassandra/CassandraStorageAccessor.java
CassandraStorageAccessor
find
class CassandraStorageAccessor extends AbstractStorageAccessor { private final String hostname; private final CqlIdentifier table; private final CqlIdentifier keyspace; private final String lockName; private final String lockUntil; private final String lockedAt; private final String lockedBy; private final CqlSession cqlSession; private final ConsistencyLevel consistencyLevel; private final ConsistencyLevel serialConsistencyLevel; CassandraStorageAccessor(@NonNull Configuration configuration) { requireNonNull(configuration, "configuration can not be null"); this.hostname = Utils.getHostname(); this.table = configuration.getTable(); this.keyspace = configuration.getKeyspace(); this.lockName = configuration.getColumnNames().getLockName(); this.lockUntil = configuration.getColumnNames().getLockUntil(); this.lockedAt = configuration.getColumnNames().getLockedAt(); this.lockedBy = configuration.getColumnNames().getLockedBy(); this.cqlSession = configuration.getCqlSession(); this.consistencyLevel = configuration.getConsistencyLevel(); this.serialConsistencyLevel = configuration.getSerialConsistencyLevel(); } @Override public boolean insertRecord(@NonNull LockConfiguration lockConfiguration) { if (find(lockConfiguration.getName()).isPresent()) { return false; } try { return insert(lockConfiguration.getName(), lockConfiguration.getLockAtMostUntil()); } catch (QueryExecutionException e) { logger.warn("Error on insert", e); return false; } } @Override public boolean updateRecord(@NonNull LockConfiguration lockConfiguration) { Optional<Lock> lock = find(lockConfiguration.getName()); if (lock.isEmpty() || lock.get().lockUntil().isAfter(ClockProvider.now())) { return false; } try { return update(lockConfiguration.getName(), lockConfiguration.getLockAtMostUntil()); } catch (QueryExecutionException e) { logger.warn("Error on update", e); return false; } } @Override public void unlock(@NonNull LockConfiguration lockConfiguration) { updateUntil(lockConfiguration.getName(), lockConfiguration.getUnlockTime()); } @Override public boolean extend(@NonNull LockConfiguration lockConfiguration) { Optional<Lock> lock = find(lockConfiguration.getName()); if (lock.isEmpty() || lock.get().lockUntil().isBefore(ClockProvider.now()) || !lock.get().lockedBy().equals(hostname)) { logger.trace("extend false"); return false; } return updateUntil(lockConfiguration.getName(), lockConfiguration.getLockAtMostUntil()); } /** * Find existing row by primary key lock.name * * @param name * lock name * @return optional lock row or empty */ Optional<Lock> find(String name) {<FILL_FUNCTION_BODY>} /** * Insert new lock row * * @param name * lock name * @param until * new until instant value */ private boolean insert(String name, Instant until) { return execute(QueryBuilder.insertInto(keyspace, table) .value(lockName, literal(name)) .value(lockUntil, literal(until)) .value(lockedAt, literal(ClockProvider.now())) .value(lockedBy, literal(hostname)) .ifNotExists() .build()); } /** * Update existing lock row * * @param name * lock name * @param until * new until instant value */ private boolean update(String name, Instant until) { return execute(QueryBuilder.update(keyspace, table) .setColumn(lockUntil, literal(until)) .setColumn(lockedAt, literal(ClockProvider.now())) .setColumn(lockedBy, literal(hostname)) .whereColumn(lockName) .isEqualTo(literal(name)) .ifColumn(lockUntil) .isLessThan(literal(ClockProvider.now())) .build()); } /** * Updates lock.until field where lockConfiguration.name * * @param name * lock name * @param until * new until instant value */ private boolean updateUntil(String name, Instant until) { return execute(QueryBuilder.update(keyspace, table) .setColumn(lockUntil, literal(until)) .whereColumn(lockName) .isEqualTo(literal(name)) .ifColumn(lockUntil) .isGreaterThanOrEqualTo(literal(ClockProvider.now())) .ifColumn(lockedBy) .isEqualTo(literal(hostname)) .build()); } private boolean execute(SimpleStatement statement) { return cqlSession .execute(statement .setConsistencyLevel(consistencyLevel) .setSerialConsistencyLevel(serialConsistencyLevel)) .wasApplied(); } }
SimpleStatement selectStatement = QueryBuilder.selectFrom(keyspace, table) .column(lockUntil) .column(lockedAt) .column(lockedBy) .whereColumn(lockName) .isEqualTo(literal(name)) .build() .setConsistencyLevel(consistencyLevel) .setSerialConsistencyLevel(serialConsistencyLevel); ResultSet resultSet = cqlSession.execute(selectStatement); Row row = resultSet.one(); if (row != null) { return Optional.of(new Lock(row.getInstant(lockUntil), row.getInstant(lockedAt), row.getString(lockedBy))); } else { return Optional.empty(); }
1,316
191
1,507
<methods>public non-sealed void <init>() <variables>protected final Logger logger
lukas-krecan_ShedLock
ShedLock/providers/couchbase/shedlock-provider-couchbase-javaclient3/src/main/java/net/javacrumbs/shedlock/provider/couchbase/javaclient3/CouchbaseLockProvider.java
CouchbaseAccessor
updateRecord
class CouchbaseAccessor extends AbstractStorageAccessor { private final Collection collection; CouchbaseAccessor(Collection collection) { this.collection = collection; } @Override public boolean insertRecord(@NonNull LockConfiguration lockConfiguration) { JsonObject content = JsonObject.create() .put(LOCK_NAME, lockConfiguration.getName()) .put(LOCK_UNTIL, toIsoString(lockConfiguration.getLockAtMostUntil())) .put(LOCKED_AT, toIsoString(ClockProvider.now())) .put(LOCKED_BY, getHostname()); try { collection.insert(lockConfiguration.getName(), content); } catch (DocumentExistsException e) { return false; } return true; } private Instant parse(Object instant) { return Instant.parse((String) instant); } @Override public boolean updateRecord(@NonNull LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} @Override public boolean extend(@NonNull LockConfiguration lockConfiguration) { GetResult result = collection.get(lockConfiguration.getName()); JsonObject document = result.contentAsObject(); Instant lockUntil = parse(document.get(LOCK_UNTIL)); Instant now = ClockProvider.now(); if (lockUntil.isBefore(now) || !document.get(LOCKED_BY).equals(getHostname())) { return false; } document.put(LOCK_UNTIL, toIsoString(lockConfiguration.getLockAtMostUntil())); try { collection.replace( lockConfiguration.getName(), document, ReplaceOptions.replaceOptions().cas(result.cas())); } catch (CasMismatchException e) { return false; } return true; } @Override public void unlock(@NonNull LockConfiguration lockConfiguration) { GetResult result = collection.get(lockConfiguration.getName()); JsonObject document = result.contentAsObject(); document.put(LOCK_UNTIL, toIsoString(lockConfiguration.getUnlockTime())); collection.replace(lockConfiguration.getName(), document); } }
GetResult result = collection.get(lockConfiguration.getName()); JsonObject document = result.contentAsObject(); Instant lockUntil = parse(document.get(LOCK_UNTIL)); Instant now = ClockProvider.now(); if (lockUntil.isAfter(now)) { return false; } document.put(LOCK_UNTIL, toIsoString(lockConfiguration.getLockAtMostUntil())); document.put(LOCKED_AT, toIsoString(now)); document.put(LOCKED_BY, getHostname()); try { collection.replace( lockConfiguration.getName(), document, ReplaceOptions.replaceOptions().cas(result.cas())); } catch (CasMismatchException e) { return false; } return true;
551
205
756
<methods>public void clearCache() ,public Optional<net.javacrumbs.shedlock.core.SimpleLock> lock(net.javacrumbs.shedlock.core.LockConfiguration) <variables>private final net.javacrumbs.shedlock.support.LockRecordRegistry lockRecordRegistry,private final non-sealed net.javacrumbs.shedlock.support.StorageAccessor storageAccessor
lukas-krecan_ShedLock
ShedLock/providers/datastore/shedlock-provider-datastore/src/main/java/net/javacrumbs/shedlock/provider/datastore/DatastoreStorageAccessor.java
DatastoreStorageAccessor
updateOwn
class DatastoreStorageAccessor extends AbstractStorageAccessor { private static final Logger log = LoggerFactory.getLogger(DatastoreStorageAccessor.class); private final Datastore datastore; private final String hostname; private final String entityName; private final DatastoreLockProvider.FieldNames fieldNames; public DatastoreStorageAccessor(DatastoreLockProvider.Configuration configuration) { requireNonNull(configuration); this.datastore = configuration.getDatastore(); this.hostname = Utils.getHostname(); this.entityName = configuration.getEntityName(); this.fieldNames = configuration.getFieldNames(); } @Override public boolean insertRecord(LockConfiguration config) { return insert(config.getName(), config.getLockAtMostUntil()); } @Override public boolean updateRecord(LockConfiguration config) { return updateExisting(config.getName(), config.getLockAtMostUntil()); } @Override public void unlock(LockConfiguration config) { updateOwn(config.getName(), config.getUnlockTime()); } @Override public boolean extend(LockConfiguration config) { return updateOwn(config.getName(), config.getLockAtMostUntil()); } private boolean insert(String name, Instant until) { return doInTxn(txn -> { KeyFactory keyFactory = this.datastore.newKeyFactory().setKind(this.entityName); Key key = keyFactory.newKey(name); Entity entity = Entity.newBuilder(key) .set(this.fieldNames.lockUntil(), fromInstant(until)) .set(this.fieldNames.lockedAt(), fromInstant(ClockProvider.now())) .set(this.fieldNames.lockedBy(), this.hostname) .build(); txn.add(entity); return Optional.of(true); }) .orElse(false); } private boolean updateExisting(String name, Instant until) { return doInTxn(txn -> get(name, txn) .filter(entity -> { var now = ClockProvider.now(); var lockUntilTs = nullableTimestamp(entity, this.fieldNames.lockUntil()); return lockUntilTs != null && lockUntilTs.isBefore(now); }) .map(entity -> { txn.put(Entity.newBuilder(entity) .set(this.fieldNames.lockUntil(), fromInstant(until)) .set(this.fieldNames.lockedAt(), fromInstant(ClockProvider.now())) .set(this.fieldNames.lockedBy(), this.hostname) .build()); return true; })) .orElse(false); } private boolean updateOwn(String name, Instant until) {<FILL_FUNCTION_BODY>} public Optional<Lock> findLock(String name) { return get(name) .map(entity -> new Lock( entity.getKey().getName(), nullableTimestamp(entity, this.fieldNames.lockedAt()), nullableTimestamp(entity, this.fieldNames.lockUntil()), nullableString(entity, this.fieldNames.lockedBy()))); } private Optional<Entity> get(String name) { KeyFactory keyFactory = this.datastore.newKeyFactory().setKind(this.entityName); Key key = keyFactory.newKey(name); return ofNullable(this.datastore.get(key)); } private Optional<Entity> get(String name, Transaction txn) { KeyFactory keyFactory = this.datastore.newKeyFactory().setKind(this.entityName); Key key = keyFactory.newKey(name); return ofNullable(txn.get(key)); } private <T> Optional<T> doInTxn(Function<Transaction, Optional<T>> work) { var txn = this.datastore.newTransaction(); try { var result = work.apply(txn); txn.commit(); return result; } catch (DatastoreException ex) { log.debug("Unable to perform a transactional unit of work: {}", ex.getMessage()); return Optional.empty(); } finally { if (txn.isActive()) { txn.rollback(); } } } private static String nullableString(Entity entity, String property) { return entity.contains(property) ? entity.getString(property) : null; } private static Instant nullableTimestamp(Entity entity, String property) { return entity.contains(property) ? toInstant(entity.getTimestamp(property)) : null; } private static Timestamp fromInstant(Instant instant) { return Timestamp.of(java.sql.Timestamp.from(requireNonNull(instant))); } private static Instant toInstant(Timestamp timestamp) { return requireNonNull(timestamp).toSqlTimestamp().toInstant(); } public record Lock(String name, Instant lockedAt, Instant lockedUntil, String lockedBy) {} }
return doInTxn(txn -> get(name, txn) .filter(entity -> this.hostname.equals(nullableString(entity, this.fieldNames.lockedBy()))) .filter(entity -> { var now = ClockProvider.now(); var lockUntilTs = nullableTimestamp(entity, this.fieldNames.lockUntil()); return lockUntilTs != null && (lockUntilTs.isAfter(now) || lockUntilTs.equals(now)); }) .map(entity -> { txn.put(Entity.newBuilder(entity) .set(this.fieldNames.lockUntil(), fromInstant(until)) .build()); return true; })) .orElse(false);
1,311
195
1,506
<methods>public non-sealed void <init>() <variables>protected final Logger logger
lukas-krecan_ShedLock
ShedLock/providers/dynamodb/shedlock-provider-dynamodb2/src/main/java/net/javacrumbs/shedlock/provider/dynamodb2/DynamoDBLockProvider.java
DynamoDBLockProvider
lock
class DynamoDBLockProvider implements LockProvider { static final String LOCK_UNTIL = "lockUntil"; static final String LOCKED_AT = "lockedAt"; static final String LOCKED_BY = "lockedBy"; static final String ID = "_id"; private static final String OBTAIN_LOCK_QUERY = "set " + LOCK_UNTIL + " = :lockUntil, " + LOCKED_AT + " = :lockedAt, " + LOCKED_BY + " = :lockedBy"; private static final String OBTAIN_LOCK_CONDITION = LOCK_UNTIL + " <= :lockedAt or attribute_not_exists(" + LOCK_UNTIL + ")"; private static final String RELEASE_LOCK_QUERY = "set " + LOCK_UNTIL + " = :lockUntil"; private final String hostname; private final DynamoDbClient dynamoDbClient; private final String tableName; /** * Uses DynamoDB to coordinate locks * * @param dynamoDbClient * v2 of DynamoDB client * @param tableName * the lock table name */ public DynamoDBLockProvider(@NonNull DynamoDbClient dynamoDbClient, @NonNull String tableName) { this.dynamoDbClient = requireNonNull(dynamoDbClient, "dynamoDbClient can not be null"); this.tableName = requireNonNull(tableName, "tableName can not be null"); this.hostname = Utils.getHostname(); } @Override @NonNull public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} private static AttributeValue attr(String lockUntilIso) { return AttributeValue.builder().s(lockUntilIso).build(); } private Instant now() { return ClockProvider.now(); } private static final class DynamoDBLock extends AbstractSimpleLock { private final DynamoDbClient dynamoDbClient; private final String tableName; private DynamoDBLock(DynamoDbClient dynamoDbClient, String tableName, LockConfiguration lockConfiguration) { super(lockConfiguration); this.dynamoDbClient = dynamoDbClient; this.tableName = tableName; } @Override public void doUnlock() { // Set lockUntil to now or lockAtLeastUntil whichever is later String unlockTimeIso = toIsoString(lockConfiguration.getUnlockTime()); Map<String, AttributeValue> key = singletonMap(ID, attr(lockConfiguration.getName())); Map<String, AttributeValue> attributeUpdates = singletonMap(":lockUntil", attr(unlockTimeIso)); UpdateItemRequest request = UpdateItemRequest.builder() .tableName(tableName) .key(key) .updateExpression(RELEASE_LOCK_QUERY) .expressionAttributeValues(attributeUpdates) .returnValues(ReturnValue.UPDATED_NEW) .build(); dynamoDbClient.updateItem(request); } } }
String nowIso = toIsoString(now()); String lockUntilIso = toIsoString(lockConfiguration.getLockAtMostUntil()); Map<String, AttributeValue> key = singletonMap(ID, attr(lockConfiguration.getName())); Map<String, AttributeValue> attributeUpdates = Map.of(":lockUntil", attr(lockUntilIso), ":lockedAt", attr(nowIso), ":lockedBy", attr(hostname)); UpdateItemRequest request = UpdateItemRequest.builder() .tableName(tableName) .key(key) .updateExpression(OBTAIN_LOCK_QUERY) .conditionExpression(OBTAIN_LOCK_CONDITION) .expressionAttributeValues(attributeUpdates) .returnValues(ReturnValue.UPDATED_NEW) .build(); try { // There are three possible situations: // 1. The lock document does not exist yet - it is inserted - we have the lock // 2. The lock document exists and lockUtil <= now - it is updated - we have the // lock // 3. The lock document exists and lockUtil > now - // ConditionalCheckFailedException is thrown dynamoDbClient.updateItem(request); return Optional.of(new DynamoDBLock(dynamoDbClient, tableName, lockConfiguration)); } catch (ConditionalCheckFailedException e) { // Condition failed. This means there was a lock with lockUntil > now. return Optional.empty(); }
809
380
1,189
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/dynamodb/shedlock-provider-dynamodb2/src/main/java/net/javacrumbs/shedlock/provider/dynamodb2/DynamoDBUtils.java
DynamoDBUtils
createLockTable
class DynamoDBUtils { /** * Creates a locking table with the given name. * * <p> * This method does not check if a table with the given name exists already. * * @param ddbClient * v2 of DynamoDBClient * @param tableName * table to be used * @param throughput * AWS {@link ProvisionedThroughput throughput requirements} for the * given lock setup * @return the table name * @throws ResourceInUseException * The operation conflicts with the resource's availability. You * attempted to recreate an existing table. */ public static String createLockTable(DynamoDbClient ddbClient, String tableName, ProvisionedThroughput throughput) {<FILL_FUNCTION_BODY>} }
CreateTableRequest request = CreateTableRequest.builder() .tableName(tableName) .keySchema(KeySchemaElement.builder() .attributeName(ID) .keyType(KeyType.HASH) .build()) .attributeDefinitions(AttributeDefinition.builder() .attributeName(ID) .attributeType(ScalarAttributeType.S) .build()) .provisionedThroughput(throughput) .build(); ddbClient.createTable(request); return tableName;
215
136
351
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/elasticsearch/shedlock-provider-elasticsearch8/src/main/java/net/javacrumbs/shedlock/provider/elasticsearch8/ElasticsearchLockProvider.java
ElasticsearchLockProvider
lock
class ElasticsearchLockProvider implements LockProvider { static final String SCHEDLOCK_DEFAULT_INDEX = "shedlock"; static final String LOCK_UNTIL = "lockUntil"; static final String LOCKED_AT = "lockedAt"; static final String LOCKED_BY = "lockedBy"; static final String NAME = "name"; private static final String UPDATE_SCRIPT = "if (ctx._source." + LOCK_UNTIL + " <= " + "params." + LOCKED_AT + ") { " + "ctx._source." + LOCKED_BY + " = params." + LOCKED_BY + "; " + "ctx._source." + LOCKED_AT + " = params." + LOCKED_AT + "; " + "ctx._source." + LOCK_UNTIL + " = params." + LOCK_UNTIL + "; " + "} else { " + "ctx.op = 'none' " + "}"; private final ElasticsearchClient client; private final String hostname; private final String index; private ElasticsearchLockProvider(@NonNull ElasticsearchClient client, @NonNull String index) { this.client = client; this.hostname = getHostname(); this.index = index; } public ElasticsearchLockProvider(@NonNull ElasticsearchClient client) { this(client, SCHEDLOCK_DEFAULT_INDEX); } @Override @NonNull public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} private Map<String, JsonData> lockObject(String name, Instant lockUntil, Instant lockedAt) { return Map.of( NAME, JsonData.of(name), LOCKED_BY, JsonData.of(hostname), LOCKED_AT, JsonData.of(lockedAt.toEpochMilli()), LOCK_UNTIL, JsonData.of(lockUntil.toEpochMilli())); } private final class ElasticsearchSimpleLock extends AbstractSimpleLock { private ElasticsearchSimpleLock(LockConfiguration lockConfiguration) { super(lockConfiguration); } @Override public void doUnlock() { // Set lockUtil to now or lockAtLeastUntil whichever is later try { Map<String, JsonData> lockObject = Collections.singletonMap( "unlockTime", JsonData.of(lockConfiguration.getUnlockTime().toEpochMilli())); UpdateRequest<Lock, Lock> updateRequest = UpdateRequest.of(ur -> ur.index(index) .id(lockConfiguration.getName()) .refresh(Refresh.True) .script(sc -> sc.inline(in -> in.lang("painless") .source("ctx._source.lockUntil = params.unlockTime") .params(lockObject)))); client.update(updateRequest, Lock.class); } catch (IOException | ElasticsearchException e) { throw new LockException("Unexpected exception occurred", e); } } } private static final class Lock { private final String name; private final String lockedBy; private final long lockedAt; private final long lockUntil; public Lock(String name, String lockedBy, Instant lockedAt, Instant lockUntil) { this.name = name; this.lockedBy = lockedBy; this.lockedAt = lockedAt.toEpochMilli(); this.lockUntil = lockUntil.toEpochMilli(); } public String getName() { return name; } public String getLockedBy() { return lockedBy; } public long getLockedAt() { return lockedAt; } public long getLockUntil() { return lockUntil; } } }
try { Instant now = now(); Instant lockAtMostUntil = lockConfiguration.getLockAtMostUntil(); Map<String, JsonData> lockObject = lockObject(lockConfiguration.getName(), lockAtMostUntil, now); // The object exist only to have some type we can work with Lock pojo = new Lock(lockConfiguration.getName(), hostname, now, lockAtMostUntil); UpdateRequest<Lock, Lock> updateRequest = UpdateRequest.of(ur -> ur.index(index) .id(lockConfiguration.getName()) .refresh(Refresh.True) .script(sc -> sc.inline( in -> in.lang("painless").source(UPDATE_SCRIPT).params(lockObject))) .upsert(pojo)); UpdateResponse<Lock> res = client.update(updateRequest, Lock.class); if (res.result() != Result.NoOp) { return Optional.of(new ElasticsearchSimpleLock(lockConfiguration)); } else { // nothing happened return Optional.empty(); } } catch (IOException | ElasticsearchException e) { if ((e instanceof ElasticsearchException && ((ElasticsearchException) e).status() == 409) || (e instanceof ResponseException && ((ResponseException) e) .getResponse() .getStatusLine() .getStatusCode() == 409)) { return Optional.empty(); } else { throw new LockException("Unexpected exception occurred", e); } }
983
384
1,367
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/etcd/shedlock-provider-etcd-jetcd/src/main/java/net/javacrumbs/shedlock/provider/etcd/jetcd/EtcdLockProvider.java
EtcdTemplate
revoke
class EtcdTemplate { private final KV kvClient; private final Lease leaseClient; private EtcdTemplate(Client client) { this.kvClient = client.getKVClient(); this.leaseClient = client.getLeaseClient(); } public Long createLease(long lockUntilInSeconds) { try { return leaseClient.grant(lockUntilInSeconds).get().getID(); } catch (Exception e) { throw new LockException("Failed create lease", e); } } public Optional<Long> tryToLock(String key, String value, Instant lockAtMostUntil) { Long leaseId = createLease(getSecondsUntil(lockAtMostUntil)); try { ByteSequence lockKey = toByteSequence(key); PutOption putOption = putOptionWithLeaseId(leaseId); // Version is the version of the key. // A deletion resets the version to zero and any modification of the key // increases its // version. Txn txn = kvClient.txn() .If(new Cmp(lockKey, Cmp.Op.EQUAL, CmpTarget.version(0))) .Then(Op.put(lockKey, toByteSequence(value), putOption)) .Else(Op.get(lockKey, DEFAULT)); TxnResponse tr = txn.commit().get(); if (tr.isSucceeded()) { return Optional.of(leaseId); } else { revoke(leaseId); return Optional.empty(); } } catch (Exception e) { revoke(leaseId); throw new LockException("Failed to set lock " + key, e); } } public void revoke(Long leaseId) {<FILL_FUNCTION_BODY>} /** * Set the provided leaseId lease for the key-value pair similar to the CLI * command * * <p> * etcdctl put key value --lease <leaseId> * * <p> * If the key has already been put with an other leaseId earlier, the old * leaseId will be timed out and then removed, eventually. */ public void putWithLeaseId(String key, String value, Long leaseId) { ByteSequence lockKey = toByteSequence(key); ByteSequence lockValue = toByteSequence(value); PutOption putOption = putOptionWithLeaseId(leaseId); kvClient.put(lockKey, lockValue, putOption); } private ByteSequence toByteSequence(String key) { return ByteSequence.from(key.getBytes(UTF_8)); } private PutOption putOptionWithLeaseId(Long leaseId) { return PutOption.newBuilder().withLeaseId(leaseId).build(); } }
try { leaseClient.revoke(leaseId).get(); } catch (Exception e) { throw new LockException("Failed to revoke lease " + leaseId, e); }
724
51
775
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/hazelcast/shedlock-provider-hazelcast4/src/main/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLock.java
HazelcastLock
toString
class HazelcastLock implements Serializable { private final String name; private final Instant lockAtMostUntil; private final Instant lockAtLeastUntil; /** * Moment when the lock is expired, so unlockable. The first value of this is * {@link #lockAtMostUntil}. */ private final Instant timeToLive; private HazelcastLock( final String name, final Instant lockAtMostUntil, final Instant lockAtLeastUntil, final Instant timeToLive) { this.name = name; this.lockAtMostUntil = lockAtMostUntil; this.lockAtLeastUntil = lockAtLeastUntil; this.timeToLive = timeToLive; } boolean isExpired(Instant now) { return !now.isBefore(getTimeToLive()); } /** * Instantiate {@link HazelcastLock} with {@link LockConfiguration} and * Hazelcast member UUID. * * @param configuration * @return the new instance of {@link HazelcastLock}. */ static HazelcastLock fromConfigurationWhereTtlIsUntilTime(final LockConfiguration configuration) { return new HazelcastLock( configuration.getName(), configuration.getLockAtMostUntil(), configuration.getLockAtLeastUntil(), configuration.getLockAtMostUntil()); } /** * Copy an existing {@link HazelcastLock} and change its time to live. * * @param lock * @return the new instance of {@link HazelcastLock}. */ static HazelcastLock fromLockWhereTtlIsReduceToLeastTime(final HazelcastLock lock) { return new HazelcastLock(lock.name, lock.lockAtMostUntil, lock.lockAtLeastUntil, lock.lockAtLeastUntil); } String getName() { return name; } Instant getLockAtLeastUntil() { return lockAtLeastUntil; } Instant getTimeToLive() { return timeToLive; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "HazelcastLock{" + "name='" + name + '\'' + ", lockAtMostUntil=" + lockAtMostUntil + ", lockAtLeastUntil=" + lockAtLeastUntil + ", timeToLive=" + timeToLive + '}';
562
68
630
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/hazelcast/shedlock-provider-hazelcast4/src/main/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLockProvider.java
HazelcastLockProvider
lock
class HazelcastLockProvider implements LockProvider { private static final Logger log = LoggerFactory.getLogger(HazelcastLockProvider.class); static final String LOCK_STORE_KEY_DEFAULT = "shedlock_storage"; private static final Duration DEFAULT_LOCK_LEASE_TIME = Duration.ofSeconds(30); /** * Key used for get the lock container (an {@link IMap}) inside * {@link #hazelcastInstance}. By default : {@link #LOCK_STORE_KEY_DEFAULT} */ private final String lockStoreKey; /** Instance of the Hazelcast engine used by the application. */ private final HazelcastInstance hazelcastInstance; private final long lockLeaseTimeMs; /** * Instantiate the provider. * * @param hazelcastInstance * The Hazelcast engine used by the application. */ public HazelcastLockProvider(@NonNull HazelcastInstance hazelcastInstance) { this(hazelcastInstance, LOCK_STORE_KEY_DEFAULT); } /** * Instantiate the provider. * * @param hazelcastInstance * The Hazelcast engine used by the application * @param lockStoreKey * The key where the locks are stored (by default * {@link #LOCK_STORE_KEY_DEFAULT}). */ public HazelcastLockProvider(@NonNull HazelcastInstance hazelcastInstance, @NonNull String lockStoreKey) { this(hazelcastInstance, lockStoreKey, DEFAULT_LOCK_LEASE_TIME); } /** * Instantiate the provider. * * @param hazelcastInstance * The com.hazelcast.core.Hazelcast engine used by the application * @param lockStoreKey * The key where the locks are stored (by default * {@link #LOCK_STORE_KEY_DEFAULT}). * @param lockLeaseTime * When lock is being obtained there is a Hazelcast lock used to make * it thread-safe. This lock should be released quite fast but if the * process dies while holding the lock, it is held forever. * lockLeaseTime is used as a safety-net for such situations. */ public HazelcastLockProvider( @NonNull HazelcastInstance hazelcastInstance, @NonNull String lockStoreKey, @NonNull Duration lockLeaseTime) { this.hazelcastInstance = hazelcastInstance; this.lockStoreKey = lockStoreKey; this.lockLeaseTimeMs = lockLeaseTime.toMillis(); } @Override @NonNull public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} private long keyLockTime(LockConfiguration lockConfiguration) { Duration between = Duration.between(ClockProvider.now(), lockConfiguration.getLockAtMostUntil()); return between.toMillis(); } private boolean tryLock(final LockConfiguration lockConfiguration, final Instant now) { final String lockName = lockConfiguration.getName(); final HazelcastLock lock = getLock(lockName); if (isUnlocked(lock)) { log.debug("lock - lock obtained, it wasn't locked : conf={}", lockConfiguration); addNewLock(lockConfiguration); return true; } else if (lock.isExpired(now)) { log.debug( "lock - lock obtained, it was locked but expired : oldLock={}; conf={}", lock, lockConfiguration); replaceLock(lockName, lockConfiguration); return true; } else { log.debug("lock - already locked : currentLock={}; conf={}", lock, lockConfiguration); return false; } } private IMap<String, HazelcastLock> getStore() { return hazelcastInstance.getMap(lockStoreKey); } HazelcastLock getLock(final String lockName) { return getStore().get(lockName); } private void removeLock(final String lockName) { getStore().delete(lockName); log.debug("lock store - lock deleted : {}", lockName); } private void addNewLock(final LockConfiguration lockConfiguration) { final HazelcastLock lock = HazelcastLock.fromConfigurationWhereTtlIsUntilTime(lockConfiguration); log.trace("lock store - new lock created from configuration : {}", lockConfiguration); final String lockName = lockConfiguration.getName(); getStore().put(lockName, lock); log.debug("lock store - new lock added : {}", lock); } private void replaceLock(final String lockName, final LockConfiguration lockConfiguration) { log.debug("lock store - replace lock : {}", lockName); removeLock(lockName); addNewLock(lockConfiguration); } private boolean isUnlocked(final HazelcastLock lock) { return lock == null; } /** * Unlock the lock with its name. * * @param lockConfiguration * the name of the lock to unlock. */ /* package */ void unlock(LockConfiguration lockConfiguration) { String lockName = lockConfiguration.getName(); log.trace("unlock - attempt : {}", lockName); final Instant now = ClockProvider.now(); final IMap<String, HazelcastLock> store = getStore(); try { store.lock(lockName, lockLeaseTimeMs, TimeUnit.MILLISECONDS); final HazelcastLock lock = getLock(lockName); unlockProperly(lock, now); } finally { store.unlock(lockName); } } private void unlockProperly(final HazelcastLock lock, final Instant now) { if (isUnlocked(lock)) { log.debug("unlock - it is already unlocked"); return; } final String lockName = lock.getName(); final Instant lockAtLeastInstant = lock.getLockAtLeastUntil(); if (!now.isBefore(lockAtLeastInstant)) { removeLock(lockName); log.debug("unlock - done : {}", lock); } else { log.debug("unlock - it doesn't unlock, least time is not passed : {}", lock); final HazelcastLock newLock = HazelcastLock.fromLockWhereTtlIsReduceToLeastTime(lock); getStore().put(lockName, newLock); } } }
log.trace("lock - Attempt : {}", lockConfiguration); final Instant now = ClockProvider.now(); final String lockName = lockConfiguration.getName(); final IMap<String, HazelcastLock> store = getStore(); try { // lock the map key entry store.lock(lockName, keyLockTime(lockConfiguration), TimeUnit.MILLISECONDS); // just one thread at a time, in the cluster, can run this code // each thread waits until the lock to be unlock if (tryLock(lockConfiguration, now)) { return Optional.of(new HazelcastSimpleLock(this, lockConfiguration)); } } finally { // released the map lock for the others threads store.unlock(lockName); } return Optional.empty();
1,671
200
1,871
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/ignite/shedlock-provider-ignite/src/main/java/net/javacrumbs/shedlock/provider/ignite/IgniteLockProvider.java
IgniteLockProvider
extend
class IgniteLockProvider implements ExtensibleLockProvider { /** Default ShedLock cache name. */ public static final String DEFAULT_SHEDLOCK_CACHE_NAME = "shedLock"; /** ShedLock cache. */ private final IgniteCache<String, LockValue> cache; /** * @param ignite * Ignite instance. */ public IgniteLockProvider(Ignite ignite) { this(ignite, DEFAULT_SHEDLOCK_CACHE_NAME); } /** * @param ignite * Ignite instance. * @param shedLockCacheName * ShedLock cache name to use instead of default. */ public IgniteLockProvider(Ignite ignite, String shedLockCacheName) { this.cache = ignite.getOrCreateCache(shedLockCacheName); } /** {@inheritDoc} */ @Override public Optional<SimpleLock> lock(LockConfiguration lockCfg) { Instant now = Instant.now(); String key = lockCfg.getName(); LockValue newVal = new LockValue(now, lockCfg.getLockAtMostUntil(), getHostname()); LockValue oldVal = cache.get(key); if (oldVal == null) { if (cache.putIfAbsent(key, newVal)) return Optional.of(new IgniteLock(lockCfg, this)); return Optional.empty(); } if (!now.isBefore(oldVal.getLockUntil()) && cache.replace(key, oldVal, newVal)) return Optional.of(new IgniteLock(lockCfg, this)); return Optional.empty(); } /** * If there is a lock with given name and hostname, try to use * {@link IgniteCache#replace} to set lockUntil to * {@link LockConfiguration#getLockAtMostUntil}. * * @param lockCfg * Lock configuration. * @return New lock if succeed extended. Empty, otherwise. */ private Optional<SimpleLock> extend(LockConfiguration lockCfg) {<FILL_FUNCTION_BODY>} /** * If there is a lock with given name and hostname, try to use * {@link IgniteCache#replace} to set lockUntil to {@code now}. * * @param lockCfg * Lock configuration. */ private void unlock(LockConfiguration lockCfg) { String key = lockCfg.getName(); LockValue oldVal = cache.get(key); if (oldVal != null && oldVal.getLockedBy().equals(getHostname())) { LockValue newVal = oldVal.withLockUntil(lockCfg.getUnlockTime()); cache.replace(key, oldVal, newVal); } } /** Ignite lock. */ private static final class IgniteLock extends AbstractSimpleLock { /** Ignite lock provider. */ private final IgniteLockProvider lockProvider; /** * @param lockCfg * Lock configuration. * @param lockProvider * Ignite lock provider. */ private IgniteLock(LockConfiguration lockCfg, IgniteLockProvider lockProvider) { super(lockCfg); this.lockProvider = lockProvider; } /** {@inheritDoc} */ @Override public void doUnlock() { lockProvider.unlock(lockConfiguration); } /** {@inheritDoc} */ @Override public Optional<SimpleLock> doExtend(LockConfiguration newLockConfiguration) { return lockProvider.extend(newLockConfiguration); } } }
Instant now = Instant.now(); String key = lockCfg.getName(); LockValue oldVal = cache.get(key); if (oldVal == null || !oldVal.getLockedBy().equals(getHostname()) || !oldVal.getLockUntil().isAfter(now)) return Optional.empty(); LockValue newVal = oldVal.withLockUntil(lockCfg.getLockAtMostUntil()); if (cache.replace(key, oldVal, newVal)) return Optional.of(new IgniteLock(lockCfg, this)); return Optional.empty();
924
153
1,077
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/inmemory/shedlock-provider-inmemory/src/main/java/net/javacrumbs/shedlock/provider/inmemory/InMemoryLockProvider.java
InMemoryLockProvider
doExtend
class InMemoryLockProvider implements ExtensibleLockProvider { private final Map<String, LockRecord> locks = new HashMap<>(); private final Logger logger = LoggerFactory.getLogger(getClass()); @Override public Optional<SimpleLock> lock(LockConfiguration lockConfiguration) { synchronized (locks) { String lockName = lockConfiguration.getName(); if (isLocked(lockName)) { return Optional.empty(); } else { LockRecord lockRecord = new LockRecord(lockConfiguration.getLockAtMostUntil()); locks.put(lockName, lockRecord); logger.debug("Locked {}", lockConfiguration); return Optional.of(new InMemoryLock(lockConfiguration)); } } } boolean isLocked(String lockName) { synchronized (locks) { LockRecord lockRecord = locks.get(lockName); return lockRecord != null && lockRecord.lockedUntil.isAfter(now()); } } private void doUnlock(LockConfiguration lockConfiguration) { synchronized (locks) { locks.put(lockConfiguration.getName(), new LockRecord(lockConfiguration.getLockAtLeastUntil())); logger.debug("Unlocked {}", lockConfiguration); } } private Optional<SimpleLock> doExtend(LockConfiguration newConfiguration) {<FILL_FUNCTION_BODY>} private record LockRecord(Instant lockedUntil) {} private class InMemoryLock extends AbstractSimpleLock { private InMemoryLock(LockConfiguration lockConfiguration) { super(lockConfiguration); } @Override protected void doUnlock() { InMemoryLockProvider.this.doUnlock(lockConfiguration); } @Override protected Optional<SimpleLock> doExtend(LockConfiguration newConfiguration) { return InMemoryLockProvider.this.doExtend(newConfiguration); } } }
synchronized (locks) { String lockName = newConfiguration.getName(); if (isLocked(lockName)) { locks.put(lockName, new LockRecord(newConfiguration.getLockAtMostUntil())); logger.debug("Extended {}", newConfiguration); return Optional.of(new InMemoryLock(newConfiguration)); } else { return Optional.empty(); } }
476
102
578
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/jdbc/shedlock-provider-jdbc-internal/src/main/java/net/javacrumbs/shedlock/provider/jdbc/internal/AbstractJdbcStorageAccessor.java
AbstractJdbcStorageAccessor
insertRecord
class AbstractJdbcStorageAccessor extends AbstractStorageAccessor { private final String tableName; public AbstractJdbcStorageAccessor(@NonNull String tableName) { this.tableName = requireNonNull(tableName, "tableName can not be null"); } @Override public boolean insertRecord(@NonNull LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} @Override public boolean updateRecord(@NonNull LockConfiguration lockConfiguration) { String sql = "UPDATE " + tableName + " SET lock_until = ?, locked_at = ?, locked_by = ? WHERE name = ? AND lock_until <= ?"; return executeCommand( sql, statement -> { Timestamp now = Timestamp.from(ClockProvider.now()); statement.setTimestamp(1, Timestamp.from(lockConfiguration.getLockAtMostUntil())); statement.setTimestamp(2, now); statement.setString(3, getHostname()); statement.setString(4, lockConfiguration.getName()); statement.setTimestamp(5, now); int updatedRows = statement.executeUpdate(); return updatedRows > 0; }, this::handleUpdateException); } @Override public boolean extend(@NonNull LockConfiguration lockConfiguration) { String sql = "UPDATE " + tableName + " SET lock_until = ? WHERE name = ? AND locked_by = ? AND lock_until > ? "; logger.debug("Extending lock={} until={}", lockConfiguration.getName(), lockConfiguration.getLockAtMostUntil()); return executeCommand( sql, statement -> { statement.setTimestamp(1, Timestamp.from(lockConfiguration.getLockAtMostUntil())); statement.setString(2, lockConfiguration.getName()); statement.setString(3, getHostname()); statement.setTimestamp(4, Timestamp.from(ClockProvider.now())); return statement.executeUpdate() > 0; }, this::handleUnlockException); } @Override public void unlock(@NonNull LockConfiguration lockConfiguration) { String sql = "UPDATE " + tableName + " SET lock_until = ? WHERE name = ?"; executeCommand( sql, statement -> { statement.setTimestamp(1, Timestamp.from(lockConfiguration.getUnlockTime())); statement.setString(2, lockConfiguration.getName()); statement.executeUpdate(); return null; }, this::handleUnlockException); } protected abstract <T> T executeCommand( String sql, SqlFunction<PreparedStatement, T> body, BiFunction<String, SQLException, T> exceptionHandler); boolean handleInsertionException(String sql, SQLException e) { if (e instanceof SQLIntegrityConstraintViolationException) { // lock record already exists } else { // can not throw exception here, some drivers (Postgres) do not throw // SQLIntegrityConstraintViolationException on duplicate key // we will try update in the next step, so if there is another problem, an // exception will be // thrown there logger.debug("Exception thrown when inserting record", e); } return false; } boolean handleUpdateException(String sql, SQLException e) { logger.debug("Unexpected exception when updating lock record", e); throw new LockException("Unexpected exception when locking", e); } boolean handleUnlockException(String sql, SQLException e) { throw new LockException("Unexpected exception when unlocking", e); } @FunctionalInterface public interface SqlFunction<T, R> { R apply(T t) throws SQLException; } }
// Try to insert if the record does not exist (not optimal, but the simplest // platform agnostic // way) String sql = "INSERT INTO " + tableName + "(name, lock_until, locked_at, locked_by) VALUES(?, ?, ?, ?)"; return executeCommand( sql, statement -> { statement.setString(1, lockConfiguration.getName()); statement.setTimestamp(2, Timestamp.from(lockConfiguration.getLockAtMostUntil())); statement.setTimestamp(3, Timestamp.from(ClockProvider.now())); statement.setString(4, getHostname()); int insertedRows = statement.executeUpdate(); return insertedRows > 0; }, this::handleInsertionException);
924
190
1,114
<methods>public non-sealed void <init>() <variables>protected final Logger logger
lukas-krecan_ShedLock
ShedLock/providers/jdbc/shedlock-provider-jdbc-micronaut/src/main/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/MicronautJdbcStorageAccessor.java
MicronautJdbcStorageAccessor
executeCommand
class MicronautJdbcStorageAccessor extends AbstractJdbcStorageAccessor { private final TransactionOperations<Connection> transactionManager; private final TransactionDefinition.Propagation propagation = TransactionDefinition.Propagation.REQUIRES_NEW; MicronautJdbcStorageAccessor( @NonNull TransactionOperations<Connection> transactionManager, @NonNull String tableName) { super(tableName); this.transactionManager = requireNonNull(transactionManager, "transactionManager can not be null"); } @Override protected <T> T executeCommand( String sql, SqlFunction<PreparedStatement, T> body, BiFunction<String, SQLException, T> exceptionHandler) {<FILL_FUNCTION_BODY>} }
return transactionManager.execute(TransactionDefinition.of(propagation), status -> { try (PreparedStatement statement = status.getConnection().prepareStatement(sql)) { return body.apply(statement); } catch (SQLException e) { return exceptionHandler.apply(sql, e); } });
187
82
269
<methods>public void <init>(java.lang.String) ,public boolean extend(net.javacrumbs.shedlock.core.LockConfiguration) ,public boolean insertRecord(net.javacrumbs.shedlock.core.LockConfiguration) ,public void unlock(net.javacrumbs.shedlock.core.LockConfiguration) ,public boolean updateRecord(net.javacrumbs.shedlock.core.LockConfiguration) <variables>private final non-sealed java.lang.String tableName
lukas-krecan_ShedLock
ShedLock/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateLockProvider.java
Builder
build
class Builder { private JdbcTemplate jdbcTemplate; private DatabaseProduct databaseProduct; private PlatformTransactionManager transactionManager; private String tableName = DEFAULT_TABLE_NAME; private TimeZone timeZone; private String lockedByValue = Utils.getHostname(); private ColumnNames columnNames = new ColumnNames("name", "lock_until", "locked_at", "locked_by"); private boolean dbUpperCase = false; private boolean useDbTime = false; private Integer isolationLevel; private boolean throwUnexpectedException = false; public Builder withJdbcTemplate(@NonNull JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; return this; } public Builder withTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; return this; } public Builder withTableName(@NonNull String tableName) { this.tableName = tableName; return this; } public Builder withTimeZone(TimeZone timeZone) { this.timeZone = timeZone; return this; } public Builder withColumnNames(ColumnNames columnNames) { this.columnNames = columnNames; return this; } public Builder withDbUpperCase(final boolean dbUpperCase) { this.dbUpperCase = dbUpperCase; return this; } /** * This is only needed if your database product can't be automatically detected. * * @param databaseProduct * Database product * @return ConfigurationBuilder */ public Builder withDatabaseProduct(final DatabaseProduct databaseProduct) { this.databaseProduct = databaseProduct; return this; } /** * Value stored in 'locked_by' column. Please use only for debugging purposes. */ public Builder withLockedByValue(String lockedBy) { this.lockedByValue = lockedBy; return this; } public Builder usingDbTime() { this.useDbTime = true; return this; } /** * Sets the isolation level for ShedLock. See {@link java.sql.Connection} for * constant definitions. for constant definitions */ public Builder withIsolationLevel(int isolationLevel) { this.isolationLevel = isolationLevel; return this; } public Builder withThrowUnexpectedException(boolean throwUnexpectedException) { this.throwUnexpectedException = throwUnexpectedException; return this; } public JdbcTemplateLockProvider.Configuration build() {<FILL_FUNCTION_BODY>} }
return new JdbcTemplateLockProvider.Configuration( jdbcTemplate, databaseProduct, transactionManager, dbUpperCase ? tableName.toUpperCase() : tableName, timeZone, dbUpperCase ? columnNames.toUpperCase() : columnNames, lockedByValue, useDbTime, isolationLevel, throwUnexpectedException);
670
99
769
<methods>public void clearCache() ,public Optional<net.javacrumbs.shedlock.core.SimpleLock> lock(net.javacrumbs.shedlock.core.LockConfiguration) <variables>private final net.javacrumbs.shedlock.support.LockRecordRegistry lockRecordRegistry,private final non-sealed net.javacrumbs.shedlock.support.StorageAccessor storageAccessor
lukas-krecan_ShedLock
ShedLock/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateStorageAccessor.java
JdbcTemplateStorageAccessor
unlock
class JdbcTemplateStorageAccessor extends AbstractStorageAccessor { private final NamedParameterJdbcTemplate jdbcTemplate; private final TransactionTemplate transactionTemplate; private final Configuration configuration; private SqlStatementsSource sqlStatementsSource; JdbcTemplateStorageAccessor(@NonNull Configuration configuration) { requireNonNull(configuration, "configuration can not be null"); this.jdbcTemplate = new NamedParameterJdbcTemplate(configuration.getJdbcTemplate()); this.configuration = configuration; PlatformTransactionManager transactionManager = configuration.getTransactionManager() != null ? configuration.getTransactionManager() : new DataSourceTransactionManager( configuration.getJdbcTemplate().getDataSource()); this.transactionTemplate = new TransactionTemplate(transactionManager); this.transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); if (configuration.getIsolationLevel() != null) { this.transactionTemplate.setIsolationLevel(configuration.getIsolationLevel()); } } @Override public boolean insertRecord(@NonNull LockConfiguration lockConfiguration) { try { String sql = sqlStatementsSource().getInsertStatement(); return execute(sql, lockConfiguration); } catch (DuplicateKeyException | ConcurrencyFailureException | TransactionSystemException e) { logger.debug("Duplicate key", e); return false; } catch (DataIntegrityViolationException | BadSqlGrammarException | UncategorizedSQLException e) { if (configuration.isThrowUnexpectedException()) { throw e; } logger.error("Unexpected exception", e); return false; } } @Override public boolean updateRecord(@NonNull LockConfiguration lockConfiguration) { String sql = sqlStatementsSource().getUpdateStatement(); try { return execute(sql, lockConfiguration); } catch (ConcurrencyFailureException e) { logger.debug("Serialization exception", e); return false; } catch (DataIntegrityViolationException | TransactionSystemException | UncategorizedSQLException e) { if (configuration.isThrowUnexpectedException()) { throw e; } logger.error("Unexpected exception", e); return false; } } @Override public boolean extend(@NonNull LockConfiguration lockConfiguration) { String sql = sqlStatementsSource().getExtendStatement(); logger.debug("Extending lock={} until={}", lockConfiguration.getName(), lockConfiguration.getLockAtMostUntil()); return execute(sql, lockConfiguration); } @Override public void unlock(@NonNull LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} private void doUnlock(LockConfiguration lockConfiguration) { String sql = sqlStatementsSource().getUnlockStatement(); execute(sql, lockConfiguration); } @SuppressWarnings("ConstantConditions") private boolean execute(String sql, LockConfiguration lockConfiguration) throws TransactionException { return transactionTemplate.execute(status -> jdbcTemplate.update(sql, params(lockConfiguration)) > 0); } @NonNull private Map<String, Object> params(@NonNull LockConfiguration lockConfiguration) { return sqlStatementsSource().params(lockConfiguration); } private SqlStatementsSource sqlStatementsSource() { synchronized (configuration) { if (sqlStatementsSource == null) { sqlStatementsSource = SqlStatementsSource.create(configuration); } return sqlStatementsSource; } } }
for (int i = 0; i < 10; i++) { try { doUnlock(lockConfiguration); return; } catch (ConcurrencyFailureException | TransactionSystemException e) { logger.info("Unlock failed due to TransactionSystemException - retrying attempt {}", i + 1); } }
889
86
975
<methods>public non-sealed void <init>() <variables>protected final Logger logger
lukas-krecan_ShedLock
ShedLock/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/OracleServerTimeStatementsSource.java
OracleServerTimeStatementsSource
params
class OracleServerTimeStatementsSource extends SqlStatementsSource { private static final String now = "SYS_EXTRACT_UTC(SYSTIMESTAMP)"; private static final String lockAtMostFor = now + " + :lockAtMostFor"; private static final long millisecondsInDay = 24 * 60 * 60 * 1000; OracleServerTimeStatementsSource(JdbcTemplateLockProvider.Configuration configuration) { super(configuration); } @Override String getInsertStatement() { return "MERGE INTO " + tableName() + " USING (SELECT 1 FROM dual) ON (" + name() + " = :name) WHEN MATCHED THEN UPDATE SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now + " WHEN NOT MATCHED THEN INSERT(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)"; } @Override public String getUpdateStatement() { return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now; } @Override public String getUnlockStatement() { String lockAtLeastFor = lockedAt() + " + :lockAtLeastFor"; return "UPDATE " + tableName() + " SET " + lockUntil() + " = CASE WHEN " + lockAtLeastFor + " > " + now + " THEN " + lockAtLeastFor + " ELSE " + now + " END WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy"; } @Override public String getExtendStatement() { return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now; } @Override @NonNull Map<String, Object> params(@NonNull LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} }
return Map.of( "name", lockConfiguration.getName(), "lockedBy", configuration.getLockedByValue(), "lockAtMostFor", ((double) lockConfiguration.getLockAtMostFor().toMillis()) / millisecondsInDay, "lockAtLeastFor", ((double) lockConfiguration.getLockAtLeastFor().toMillis()) / millisecondsInDay);
656
107
763
<methods>public java.lang.String getExtendStatement() ,public java.lang.String getUnlockStatement() ,public java.lang.String getUpdateStatement() <variables>protected final non-sealed net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration configuration,private static final Logger logger
lukas-krecan_ShedLock
ShedLock/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresSqlStatementsSource.java
PostgresSqlStatementsSource
getInsertStatement
class PostgresSqlStatementsSource extends SqlStatementsSource { PostgresSqlStatementsSource(JdbcTemplateLockProvider.Configuration configuration) { super(configuration); } @Override String getInsertStatement() {<FILL_FUNCTION_BODY>} }
return super.getInsertStatement() + " ON CONFLICT (" + name() + ") DO UPDATE " + "SET " + lockUntil() + " = :lockUntil, " + lockedAt() + " = :now, " + lockedBy() + " = :lockedBy " + "WHERE " + tableName() + "." + lockUntil() + " <= :now";
69
92
161
<methods>public java.lang.String getExtendStatement() ,public java.lang.String getUnlockStatement() ,public java.lang.String getUpdateStatement() <variables>protected final non-sealed net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration configuration,private static final Logger logger
lukas-krecan_ShedLock
ShedLock/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/SqlStatementsSource.java
SqlStatementsSource
getDatabaseProduct
class SqlStatementsSource { protected final Configuration configuration; private static final Logger logger = LoggerFactory.getLogger(SqlStatementsSource.class); SqlStatementsSource(Configuration configuration) { this.configuration = configuration; } static SqlStatementsSource create(Configuration configuration) { DatabaseProduct databaseProduct = getDatabaseProduct(configuration); if (configuration.getUseDbTime()) { var statementsSource = databaseProduct.getDbTimeStatementSource(configuration); logger.debug("Using {}", statementsSource.getClass().getSimpleName()); return statementsSource; } else { if (Objects.equals(databaseProduct, DatabaseProduct.POSTGRES_SQL)) { logger.debug("Using PostgresSqlStatementsSource"); return new PostgresSqlStatementsSource(configuration); } else { logger.debug("Using SqlStatementsSource"); return new SqlStatementsSource(configuration); } } } private static DatabaseProduct getDatabaseProduct(final Configuration configuration) {<FILL_FUNCTION_BODY>} @NonNull Map<String, Object> params(@NonNull LockConfiguration lockConfiguration) { return Map.of( "name", lockConfiguration.getName(), "lockUntil", timestamp(lockConfiguration.getLockAtMostUntil()), "now", timestamp(ClockProvider.now()), "lockedBy", configuration.getLockedByValue(), "unlockTime", timestamp(lockConfiguration.getUnlockTime())); } @NonNull private Object timestamp(Instant time) { TimeZone timeZone = configuration.getTimeZone(); if (timeZone == null) { return Timestamp.from(time); } else { Calendar calendar = Calendar.getInstance(); calendar.setTime(Date.from(time)); calendar.setTimeZone(timeZone); return calendar; } } String getInsertStatement() { return "INSERT INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + ") VALUES(:name, :lockUntil, :now, :lockedBy)"; } public String getUpdateStatement() { return "UPDATE " + tableName() + " SET " + lockUntil() + " = :lockUntil, " + lockedAt() + " = :now, " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= :now"; } public String getExtendStatement() { return "UPDATE " + tableName() + " SET " + lockUntil() + " = :lockUntil WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > :now"; } public String getUnlockStatement() { return "UPDATE " + tableName() + " SET " + lockUntil() + " = :unlockTime WHERE " + name() + " = :name"; } String name() { return configuration.getColumnNames().getName(); } String lockUntil() { return configuration.getColumnNames().getLockUntil(); } String lockedAt() { return configuration.getColumnNames().getLockedAt(); } String lockedBy() { return configuration.getColumnNames().getLockedBy(); } String tableName() { return configuration.getTableName(); } }
if (configuration.getDatabaseProduct() != null) { return configuration.getDatabaseProduct(); } try { String jdbcProductName = configuration.getJdbcTemplate().execute((ConnectionCallback<String>) connection -> connection.getMetaData().getDatabaseProductName()); return DatabaseProduct.matchProductName(jdbcProductName); } catch (Exception e) { logger.debug("Can not determine database product name " + e.getMessage()); return DatabaseProduct.UNKNOWN; }
872
129
1,001
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/jdbc/shedlock-provider-jdbc/src/main/java/net/javacrumbs/shedlock/provider/jdbc/JdbcStorageAccessor.java
JdbcStorageAccessor
executeCommand
class JdbcStorageAccessor extends AbstractJdbcStorageAccessor { private final DataSource dataSource; JdbcStorageAccessor(@NonNull DataSource dataSource, @NonNull String tableName) { super(tableName); this.dataSource = requireNonNull(dataSource, "dataSource can not be null"); } @Override protected <T> T executeCommand( String sql, SqlFunction<PreparedStatement, T> body, BiFunction<String, SQLException, T> exceptionHandler) {<FILL_FUNCTION_BODY>} }
try (Connection connection = dataSource.getConnection()) { boolean originalAutocommit = connection.getAutoCommit(); if (!originalAutocommit) { connection.setAutoCommit(true); } try (PreparedStatement statement = connection.prepareStatement(sql)) { return body.apply(statement); } catch (SQLException e) { return exceptionHandler.apply(sql, e); } finally { // Cleanup if (!originalAutocommit) { connection.setAutoCommit(false); } } } catch (SQLException e) { return exceptionHandler.apply(sql, e); }
140
167
307
<methods>public void <init>(java.lang.String) ,public boolean extend(net.javacrumbs.shedlock.core.LockConfiguration) ,public boolean insertRecord(net.javacrumbs.shedlock.core.LockConfiguration) ,public void unlock(net.javacrumbs.shedlock.core.LockConfiguration) ,public boolean updateRecord(net.javacrumbs.shedlock.core.LockConfiguration) <variables>private final non-sealed java.lang.String tableName
lukas-krecan_ShedLock
ShedLock/providers/jdbc/shedlock-provider-jooq/src/main/java/net/javacrumbs/shedlock/provider/jooq/JooqStorageAccessor.java
JooqStorageAccessor
extend
class JooqStorageAccessor extends AbstractStorageAccessor { private final DSLContext dslContext; private final Shedlock t = SHEDLOCK; JooqStorageAccessor(DSLContext dslContext) { this.dslContext = dslContext; } @Override public boolean insertRecord(@NonNull LockConfiguration lockConfiguration) { return dslContext.transactionResult(tx -> tx.dsl() .insertInto(t) .set(data(lockConfiguration)) .onConflictDoNothing() .execute() > 0); } @Override public boolean updateRecord(@NonNull LockConfiguration lockConfiguration) { return dslContext.transactionResult(tx -> tx.dsl() .update(t) .set(data(lockConfiguration)) .where(t.NAME.eq(lockConfiguration.getName()).and(t.LOCK_UNTIL.le(now()))) .execute() > 0); } @Override public void unlock(LockConfiguration lockConfiguration) { Field<LocalDateTime> lockAtLeastFor = t.LOCKED_AT.add(DayToSecond.valueOf(lockConfiguration.getLockAtLeastFor())); dslContext.transaction(tx -> tx.dsl() .update(t) .set( t.LOCK_UNTIL, when(lockAtLeastFor.gt(now()), lockAtLeastFor).otherwise(now())) .where(t.NAME.eq(lockConfiguration.getName()).and(t.LOCKED_BY.eq(getHostname()))) .execute()); } @Override public boolean extend(@NonNull LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} private Map<? extends TableField<Record, ? extends Serializable>, Serializable> data( LockConfiguration lockConfiguration) { return Map.of( t.NAME, lockConfiguration.getName(), t.LOCK_UNTIL, nowPlus(lockConfiguration.getLockAtMostFor()), t.LOCKED_AT, now(), t.LOCKED_BY, getHostname()); } private Field<LocalDateTime> now() { return currentLocalDateTime(inline(6)); } private Field<LocalDateTime> nowPlus(Duration duration) { return localDateTimeAdd(now(), DayToSecond.valueOf(duration)); } }
return dslContext.transactionResult(tx -> tx.dsl() .update(t) .set(t.LOCK_UNTIL, nowPlus(lockConfiguration.getLockAtMostFor())) .where(t.NAME.eq(lockConfiguration.getName()) .and(t.LOCKED_BY.eq(getHostname())) .and(t.LOCK_UNTIL.gt(now()))) .execute() > 0);
610
113
723
<methods>public non-sealed void <init>() <variables>protected final Logger logger
lukas-krecan_ShedLock
ShedLock/providers/memcached/shedlock-provider-memcached-spy/src/main/java/net/javacrumbs/shedlock/provider/memcached/spy/MemcachedLockProvider.java
MemcachedLockProvider
lock
class MemcachedLockProvider implements LockProvider { /** KEY PREFIX */ private static final String KEY_PREFIX = "shedlock"; /** ENV DEFAULT */ private static final String ENV_DEFAULT = "default"; private final MemcachedClient client; private final String env; /** * Create MemcachedLockProvider * * @param client * Spy.memcached.MemcachedClient */ public MemcachedLockProvider(@NonNull MemcachedClient client) { this(client, ENV_DEFAULT); } /** * Create MemcachedLockProvider * * @param client * Spy.memcached.MemcachedClient * @param env * is part of the key and thus makes sure there is not key conflict * between multiple ShedLock instances running on the same memcached */ public MemcachedLockProvider(@NonNull MemcachedClient client, @NonNull String env) { this.client = client; this.env = env; } @Override @NonNull public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} private static long getSecondUntil(Instant instant) { long millis = Duration.between(ClockProvider.now(), instant).toMillis(); return millis / 1000; } static String buildKey(String lockName, String env) { String k = String.format("%s:%s:%s", KEY_PREFIX, env, lockName); StringUtils.validateKey(k, false); return k; } private static String buildValue() { return String.format("ADDED:%s@%s", toIsoString(ClockProvider.now()), getHostname()); } private static final class MemcachedLock extends AbstractSimpleLock { private final String key; private final MemcachedClient client; private MemcachedLock( @NonNull String key, @NonNull MemcachedClient client, @NonNull LockConfiguration lockConfiguration) { super(lockConfiguration); this.key = key; this.client = client; } @Override protected void doUnlock() { long keepLockFor = getSecondUntil(lockConfiguration.getLockAtLeastUntil()); if (keepLockFor <= 0) { OperationStatus status = client.delete(key).getStatus(); if (!status.isSuccess()) { throw new LockException("Can not remove node. " + status.getMessage()); } } else { OperationStatus status = client.replace(key, (int) keepLockFor, buildValue()).getStatus(); if (!status.isSuccess()) { throw new LockException("Can not replace node. " + status.getMessage()); } } } } }
long expireTime = getSecondUntil(lockConfiguration.getLockAtMostUntil()); String key = buildKey(lockConfiguration.getName(), this.env); OperationStatus status = client.add(key, (int) expireTime, buildValue()).getStatus(); if (status.isSuccess()) { return Optional.of(new MemcachedLock(key, client, lockConfiguration)); } return Optional.empty();
735
105
840
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/mongo/shedlock-provider-mongo-reactivestreams/src/main/java/net/javacrumbs/shedlock/provider/mongo/reactivestreams/ReactiveStreamsMongoLockProvider.java
ReactiveStreamsMongoLockProvider
lock
class ReactiveStreamsMongoLockProvider implements ExtensibleLockProvider { static final String LOCK_UNTIL = "lockUntil"; static final String LOCKED_AT = "lockedAt"; static final String LOCKED_BY = "lockedBy"; static final String ID = "_id"; static final String DEFAULT_SHEDLOCK_COLLECTION_NAME = "shedLock"; private final String hostname; private final MongoCollection<Document> collection; /** Uses Mongo to coordinate locks */ public ReactiveStreamsMongoLockProvider(MongoDatabase mongoDatabase) { this(mongoDatabase.getCollection(DEFAULT_SHEDLOCK_COLLECTION_NAME)); } /** * Uses Mongo to coordinate locks * * @param collection * Mongo collection to be used */ public ReactiveStreamsMongoLockProvider(MongoCollection<Document> collection) { this.collection = collection; this.hostname = Utils.getHostname(); } @Override public Optional<SimpleLock> lock(LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} private Optional<SimpleLock> extend(LockConfiguration lockConfiguration) { Instant now = now(); Bson update = set(LOCK_UNTIL, lockConfiguration.getLockAtMostUntil()); Document updatedDocument = execute(getCollection() .findOneAndUpdate( and(eq(ID, lockConfiguration.getName()), gt(LOCK_UNTIL, now), eq(LOCKED_BY, hostname)), update)); if (updatedDocument != null) { return Optional.of(new ReactiveMongoLock(lockConfiguration, this)); } else { return Optional.empty(); } } private void unlock(LockConfiguration lockConfiguration) { // Set lockUtil to now or lockAtLeastUntil whichever is later execute(getCollection() .findOneAndUpdate( eq(ID, lockConfiguration.getName()), combine(set(LOCK_UNTIL, lockConfiguration.getUnlockTime())))); } @Nullable static <T> T execute(Publisher<T> command) { SingleLockableSubscriber<T> subscriber = new SingleLockableSubscriber<>(); command.subscribe(subscriber); subscriber.await(); Throwable error = subscriber.getError(); if (error != null) { if (error instanceof RuntimeException) { throw (RuntimeException) error; } else { throw new LockException("Error when executing Mongo statement", error); } } else { return subscriber.getValue(); } } private MongoCollection<Document> getCollection() { return collection; } private Instant now() { return ClockProvider.now(); } private static final class ReactiveMongoLock extends AbstractSimpleLock { private final ReactiveStreamsMongoLockProvider mongoLockProvider; private ReactiveMongoLock( LockConfiguration lockConfiguration, ReactiveStreamsMongoLockProvider mongoLockProvider) { super(lockConfiguration); this.mongoLockProvider = mongoLockProvider; } @Override public void doUnlock() { mongoLockProvider.unlock(lockConfiguration); } @Override public Optional<SimpleLock> doExtend(LockConfiguration newLockConfiguration) { return mongoLockProvider.extend(newLockConfiguration); } } }
Instant now = now(); Bson update = combine( set(LOCK_UNTIL, lockConfiguration.getLockAtMostUntil()), set(LOCKED_AT, now), set(LOCKED_BY, hostname)); try { // There are three possible situations: // 1. The lock document does not exist yet - it is inserted - we have the lock // 2. The lock document exists and lockUtil <= now - it is updated - we have the // lock // 3. The lock document exists and lockUtil > now - Duplicate key exception is // thrown execute(getCollection() .findOneAndUpdate( and(eq(ID, lockConfiguration.getName()), lte(LOCK_UNTIL, now)), update, new FindOneAndUpdateOptions().upsert(true))); return Optional.of(new ReactiveMongoLock(lockConfiguration, this)); } catch (MongoServerException e) { if (e.getCode() == 11000) { // duplicate key // Upsert attempts to insert when there were no filter matches. // This means there was a lock with matching ID with lockUntil > now. return Optional.empty(); } else { throw e; } }
879
307
1,186
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/mongo/shedlock-provider-mongo-reactivestreams/src/main/java/net/javacrumbs/shedlock/provider/mongo/reactivestreams/SingleLockableSubscriber.java
SingleLockableSubscriber
await
class SingleLockableSubscriber<T> implements Subscriber<T> { @Nullable private T value; @Nullable private Throwable error; private final CountDownLatch latch = new CountDownLatch(1); @Override public void onSubscribe(Subscription subscription) { subscription.request(1); } @Override public void onNext(T document) { value = document; } @Override public void onError(Throwable throwable) { this.error = throwable; onComplete(); } @Override public void onComplete() { latch.countDown(); } @Nullable T getValue() { return value; } @Nullable Throwable getError() { return error; } void await() {<FILL_FUNCTION_BODY>} }
try { int timeout = 20; if (!latch.await(timeout, TimeUnit.SECONDS)) { this.error = new TimeoutException("Did not get response in " + timeout + " seconds."); } } catch (InterruptedException e) { this.error = e; }
239
83
322
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/mongo/shedlock-provider-mongo/src/main/java/net/javacrumbs/shedlock/provider/mongo/MongoLockProvider.java
MongoLockProvider
lock
class MongoLockProvider implements ExtensibleLockProvider { static final String LOCK_UNTIL = "lockUntil"; static final String LOCKED_AT = "lockedAt"; static final String LOCKED_BY = "lockedBy"; static final String ID = "_id"; static final String DEFAULT_SHEDLOCK_COLLECTION_NAME = "shedLock"; private final String hostname; private final MongoCollection<Document> collection; /** Uses Mongo to coordinate locks */ public MongoLockProvider(MongoDatabase mongoDatabase) { this(mongoDatabase.getCollection(DEFAULT_SHEDLOCK_COLLECTION_NAME)); } /** * Uses Mongo to coordinate locks * * @param collection * Mongo collection to be used */ public MongoLockProvider(MongoCollection<Document> collection) { this.collection = collection; this.hostname = Utils.getHostname(); } @Override public Optional<SimpleLock> lock(LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} private Optional<SimpleLock> extend(LockConfiguration lockConfiguration) { Instant now = now(); Bson update = set(LOCK_UNTIL, lockConfiguration.getLockAtMostUntil()); Document updatedDocument = getCollection() .findOneAndUpdate( and(eq(ID, lockConfiguration.getName()), gt(LOCK_UNTIL, now), eq(LOCKED_BY, hostname)), update); if (updatedDocument != null) { return Optional.of(new MongoLock(lockConfiguration, this)); } else { return Optional.empty(); } } private void unlock(LockConfiguration lockConfiguration) { // Set lockUtil to now or lockAtLeastUntil whichever is later getCollection() .findOneAndUpdate( eq(ID, lockConfiguration.getName()), combine(set(LOCK_UNTIL, lockConfiguration.getUnlockTime()))); } private MongoCollection<Document> getCollection() { return collection; } private Instant now() { return ClockProvider.now(); } private static final class MongoLock extends AbstractSimpleLock { private final MongoLockProvider mongoLockProvider; private MongoLock(LockConfiguration lockConfiguration, MongoLockProvider mongoLockProvider) { super(lockConfiguration); this.mongoLockProvider = mongoLockProvider; } @Override public void doUnlock() { mongoLockProvider.unlock(lockConfiguration); } @Override public Optional<SimpleLock> doExtend(LockConfiguration newLockConfiguration) { return mongoLockProvider.extend(newLockConfiguration); } } }
Instant now = now(); Bson update = combine( set(LOCK_UNTIL, lockConfiguration.getLockAtMostUntil()), set(LOCKED_AT, now), set(LOCKED_BY, hostname)); try { // There are three possible situations: // 1. The lock document does not exist yet - it is inserted - we have the lock // 2. The lock document exists and lockUtil <= now - it is updated - we have the // lock // 3. The lock document exists and lockUtil > now - Duplicate key exception is // thrown getCollection() .findOneAndUpdate( and(eq(ID, lockConfiguration.getName()), lte(LOCK_UNTIL, now)), update, new FindOneAndUpdateOptions().upsert(true)); return Optional.of(new MongoLock(lockConfiguration, this)); } catch (MongoServerException e) { if (e.getCode() == 11000) { // duplicate key // Upsert attempts to insert when there were no filter matches. // This means there was a lock with matching ID with lockUntil > now. return Optional.empty(); } else { throw e; } }
696
303
999
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/neo4j/shedlock-provider-neo4j/src/main/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jStorageAccessor.java
Neo4jStorageAccessor
createLockNameUniqueConstraint
class Neo4jStorageAccessor extends AbstractStorageAccessor { private final String collectionName; private final Driver driver; private final String databaseName; public Neo4jStorageAccessor(@NonNull Driver driver, @NonNull String collectionName, @Nullable String databaseName) { this.collectionName = requireNonNull(collectionName, "collectionName can not be null"); this.driver = requireNonNull(driver, "driver can not be null"); this.databaseName = databaseName; createLockNameUniqueConstraint(); } private void createLockNameUniqueConstraint() {<FILL_FUNCTION_BODY>} @Override public boolean insertRecord(@NonNull LockConfiguration lockConfiguration) { // Try to insert if the record does not exists String cypher = String.format( "CREATE (lock:%s {name: $lockName, lock_until: $lockUntil, locked_at: $now, locked_by: $lockedBy })", collectionName); Map<String, Object> parameters = createParameterMap(lockConfiguration); return executeCommand( cypher, result -> { int insertedNodes = result.consume().counters().nodesCreated(); return insertedNodes > 0; }, parameters, this::handleInsertionException); } private Map<String, Object> createParameterMap(@NonNull LockConfiguration lockConfiguration) { return Map.of( "lockName", lockConfiguration.getName(), "lockedBy", getHostname(), "now", ClockProvider.now().toString(), "lockUntil", lockConfiguration.getLockAtMostUntil().toString()); } @Override public boolean updateRecord(@NonNull LockConfiguration lockConfiguration) { String cypher = String.format( "MATCH (lock:%s) " + "WHERE lock.name = $lockName AND lock.lock_until <= $now " + "SET lock._LOCK_ = true " + "WITH lock as l " + "WHERE l.lock_until <= $now " + "SET l.lock_until = $lockUntil, l.locked_at = $now, l.locked_by = $lockedBy " + "REMOVE l._LOCK_ ", collectionName); Map<String, Object> parameters = createParameterMap(lockConfiguration); return executeCommand( cypher, statement -> { int updatedProperties = statement.consume().counters().propertiesSet(); return updatedProperties > 1; // ignore explicit lock when counting the updated properties }, parameters, this::handleUpdateException); } @Override public boolean extend(@NonNull LockConfiguration lockConfiguration) { String cypher = String.format( "MATCH (lock:%s) " + "WHERE lock.name = $lockName AND lock.locked_by = $lockedBy AND lock.lock_until > $now " + "SET lock._LOCK_ = true " + "WITH lock as l " + "WHERE l.name = $lockName AND l.locked_by = $lockedBy AND l.lock_until > $now " + "SET l.lock_until = $lockUntil " + "REMOVE l._LOCK_ ", collectionName); Map<String, Object> parameters = createParameterMap(lockConfiguration); logger.debug("Extending lock={} until={}", lockConfiguration.getName(), lockConfiguration.getLockAtMostUntil()); return executeCommand( cypher, statement -> { int updatedProperties = statement.consume().counters().propertiesSet(); return updatedProperties > 1; // ignore the explicit lock when counting the updated properties }, parameters, this::handleUnlockException); } @Override public void unlock(@NonNull LockConfiguration lockConfiguration) { String cypher = String.format( "MATCH (lock:%s) WHERE lock.name = $lockName " + "SET lock.lock_until = $lockUntil ", collectionName); Map<String, Object> parameters = Map.of( "lockName", lockConfiguration.getName(), "lockUntil", lockConfiguration.getUnlockTime().toString()); executeCommand(cypher, statement -> null, parameters, this::handleUnlockException); } private <T> T executeCommand( String cypher, Function<Result, T> body, Map<String, Object> parameters, BiFunction<String, Exception, T> exceptionHandler) { try (Session session = getSession(); Transaction transaction = session.beginTransaction()) { Result result = transaction.run(cypher, parameters); T apply = body.apply(result); transaction.commit(); return apply; } catch (Exception e) { return exceptionHandler.apply(cypher, e); } } private Session getSession() { return databaseName == null ? driver.session() : driver.session(SessionConfig.forDatabase(databaseName)); } boolean handleInsertionException(String cypher, Exception e) { // lock record already exists return false; } boolean handleUpdateException(String cypher, Exception e) { throw new LockException("Unexpected exception when locking", e); } boolean handleUnlockException(String cypher, Exception e) { throw new LockException("Unexpected exception when unlocking", e); } }
try (Session session = getSession(); Transaction transaction = session.beginTransaction()) { transaction.run(String.format( "CREATE CONSTRAINT UNIQUE_%s_name IF NOT EXISTS FOR (lock:%s) REQUIRE lock.name IS UNIQUE", collectionName, collectionName)); transaction.commit(); }
1,346
89
1,435
<methods>public non-sealed void <init>() <variables>protected final Logger logger
lukas-krecan_ShedLock
ShedLock/providers/opensearch/shedlock-provider-opensearch/src/main/java/net/javacrumbs/shedlock/provider/opensearch/OpenSearchLockProvider.java
OpenSearchSimpleLock
doUnlock
class OpenSearchSimpleLock extends AbstractSimpleLock { private OpenSearchSimpleLock(LockConfiguration lockConfiguration) { super(lockConfiguration); } @Override public void doUnlock() {<FILL_FUNCTION_BODY>} }
// Set lockUtil to now or lockAtLeastUntil whichever is later try { UpdateRequest ur = updateRequest(lockConfiguration) .script(new Script( ScriptType.INLINE, "painless", "ctx._source.lockUntil = params.unlockTime", Collections.singletonMap( "unlockTime", lockConfiguration.getUnlockTime().toEpochMilli()))); highLevelClient.update(ur, RequestOptions.DEFAULT); } catch (IOException | OpenSearchException e) { throw new LockException("Unexpected exception occurred", e); }
65
154
219
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/AbstractR2dbcStorageAccessor.java
AbstractR2dbcStorageAccessor
insertRecordReactive
class AbstractR2dbcStorageAccessor extends AbstractStorageAccessor { private final String tableName; public AbstractR2dbcStorageAccessor(@NonNull String tableName) { this.tableName = requireNonNull(tableName, "tableName can not be null"); } @Override public boolean insertRecord(@NonNull LockConfiguration lockConfiguration) { return Boolean.TRUE.equals( Mono.from(insertRecordReactive(lockConfiguration)).block()); } @Override public boolean updateRecord(@NonNull LockConfiguration lockConfiguration) { return Boolean.TRUE.equals( Mono.from(updateRecordReactive(lockConfiguration)).block()); } @Override public boolean extend(@NonNull LockConfiguration lockConfiguration) { return Boolean.TRUE.equals(Mono.from(extendReactive(lockConfiguration)).block()); } @Override public void unlock(@NonNull LockConfiguration lockConfiguration) { Mono.from(unlockReactive(lockConfiguration)).block(); } public Publisher<Boolean> insertRecordReactive(@NonNull LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} public Publisher<Boolean> updateRecordReactive(@NonNull LockConfiguration lockConfiguration) { String sql = "UPDATE " + tableName + " SET lock_until = " + toParameter(1, "lock_until") + ", locked_at = " + toParameter(2, "locked_at") + ", locked_by = " + toParameter(3, "locked_by") + " WHERE name = " + toParameter(4, "name") + " AND lock_until <= " + toParameter(5, "now"); return executeCommand( sql, statement -> { Instant now = ClockProvider.now(); bind(statement, 0, "lock_until", lockConfiguration.getLockAtMostUntil()); bind(statement, 1, "locked_at", now); bind(statement, 2, "locked_by", getHostname()); bind(statement, 3, "name", lockConfiguration.getName()); bind(statement, 4, "now", now); return Mono.from(statement.execute()) .flatMap(it -> Mono.from(it.getRowsUpdated())) .map(it -> it > 0); }, this::handleUpdateException); } public Publisher<Boolean> extendReactive(@NonNull LockConfiguration lockConfiguration) { String sql = "UPDATE " + tableName + " SET lock_until = " + toParameter(1, "lock_until") + " WHERE name = " + toParameter(2, "name") + " AND locked_by = " + toParameter(3, "locked_by") + " AND lock_until > " + toParameter(4, "now"); logger.debug("Extending lock={} until={}", lockConfiguration.getName(), lockConfiguration.getLockAtMostUntil()); return executeCommand( sql, statement -> { bind(statement, 0, "lock_until", lockConfiguration.getLockAtMostUntil()); bind(statement, 1, "name", lockConfiguration.getName()); bind(statement, 2, "locked_by", getHostname()); bind(statement, 3, "now", ClockProvider.now()); return Mono.from(statement.execute()) .flatMap(it -> Mono.from(it.getRowsUpdated())) .map(it -> it > 0); }, this::handleUnlockException); } public Publisher<Void> unlockReactive(@NonNull LockConfiguration lockConfiguration) { String sql = "UPDATE " + tableName + " SET lock_until = " + toParameter(1, "lock_until") + " WHERE name = " + toParameter(2, "name"); return executeCommand( sql, statement -> { bind(statement, 0, "lock_until", lockConfiguration.getUnlockTime()); bind(statement, 1, "name", lockConfiguration.getName()); return Mono.from(statement.execute()) .flatMap(it -> Mono.from(it.getRowsUpdated())) .then(); }, (s, t) -> handleUnlockException(s, t).then()); } protected abstract <T> Mono<T> executeCommand( String sql, Function<Statement, Mono<T>> body, BiFunction<String, Throwable, Mono<T>> exceptionHandler); protected abstract String toParameter(int index, String name); protected abstract void bind(Statement statement, int index, String name, Object value); Mono<Boolean> handleInsertionException(String sql, Throwable e) { if (e instanceof R2dbcDataIntegrityViolationException) { // lock record already exists } else { // can not throw exception here, some drivers (Postgres) do not throw // SQLIntegrityConstraintViolationException on duplicate key // we will try update in the next step, su if there is another problem, an // exception will be // thrown there logger.debug("Exception thrown when inserting record", e); } return Mono.just(false); } Mono<Boolean> handleUpdateException(String sql, Throwable e) { return Mono.error(new LockException("Unexpected exception when locking", e)); } Mono<Boolean> handleUnlockException(String sql, Throwable e) { return Mono.error(new LockException("Unexpected exception when unlocking", e)); } }
// Try to insert if the record does not exist (not optimal, but the simplest // platform agnostic // way) String sql = "INSERT INTO " + tableName + "(name, lock_until, locked_at, locked_by) VALUES(" + toParameter(1, "name") + ", " + toParameter(2, "lock_until") + ", " + toParameter(3, "locked_at") + ", " + toParameter(4, "locked_by") + ")"; return executeCommand( sql, statement -> { bind(statement, 0, "name", lockConfiguration.getName()); bind(statement, 1, "lock_until", lockConfiguration.getLockAtMostUntil()); bind(statement, 2, "locked_at", ClockProvider.now()); bind(statement, 3, "locked_by", getHostname()); return Mono.from(statement.execute()) .flatMap(it -> Mono.from(it.getRowsUpdated())) .map(it -> it > 0); }, this::handleInsertionException);
1,388
277
1,665
<methods>public non-sealed void <init>() <variables>protected final Logger logger
lukas-krecan_ShedLock
ShedLock/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/R2dbcAdapter.java
R2dbcAdapter
create
class R2dbcAdapter { private static final String MSSQL_NAME = "Microsoft SQL Server"; private static final String MYSQL_NAME = "MySQL"; private static final String JASYNC_MYSQL_NAME = "Jasync-MySQL"; private static final String MARIA_NAME = "MariaDB"; private static final String ORACLE_NAME = "Oracle Database"; static R2dbcAdapter create(@NonNull String driver) {<FILL_FUNCTION_BODY>} private static Instant toInstant(Instant date) { return date; } private static LocalDateTime toLocalDate(Instant date) { return LocalDateTime.ofInstant(date, ZoneId.systemDefault()); } private static void bindByName(Statement statement, int index, String name, Object value) { statement.bind(name, value); } private static void bindByIndex(Statement statement, int index, String name, Object value) { statement.bind(index, value); } protected abstract String toParameter(int index, String name); public abstract void bind(Statement statement, int index, String name, Object value); private static class DefaultR2dbcAdapter extends R2dbcAdapter { private final ParameterResolver parameterResolver; private final Function<Instant, Object> dateConverter; private final ValueBinder binder; private DefaultR2dbcAdapter( @NonNull ParameterResolver parameterResolver, @NonNull Function<Instant, Object> dateConverter, @NonNull ValueBinder binder) { this.parameterResolver = parameterResolver; this.dateConverter = dateConverter; this.binder = binder; } @Override protected String toParameter(int index, String name) { return parameterResolver.resolve(index, name); } @Override public void bind(Statement statement, int index, String name, Object value) { binder.bind(statement, index, name, normalizeValue(value)); } private Object normalizeValue(Object value) { if (value instanceof Instant) { return dateConverter.apply((Instant) value); } else { return value; } } } @FunctionalInterface private interface ParameterResolver { String resolve(int index, String name); } @FunctionalInterface private interface ValueBinder { void bind(Statement statement, int index, String name, Object value); } }
return switch (driver) { case MSSQL_NAME -> new DefaultR2dbcAdapter( (index, name) -> "@" + name, R2dbcAdapter::toLocalDate, R2dbcAdapter::bindByName); case MYSQL_NAME, JASYNC_MYSQL_NAME, MARIA_NAME -> new DefaultR2dbcAdapter( (index, name) -> "?", R2dbcAdapter::toLocalDate, R2dbcAdapter::bindByIndex); case ORACLE_NAME -> new DefaultR2dbcAdapter( (index, name) -> ":" + name, R2dbcAdapter::toLocalDate, R2dbcAdapter::bindByName); default -> new DefaultR2dbcAdapter( (index, name) -> "$" + index, R2dbcAdapter::toInstant, R2dbcAdapter::bindByIndex); };
624
219
843
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/R2dbcStorageAccessor.java
R2dbcStorageAccessor
executeCommand
class R2dbcStorageAccessor extends AbstractR2dbcStorageAccessor { private final ConnectionFactory connectionFactory; private R2dbcAdapter adapter; R2dbcStorageAccessor(@NonNull ConnectionFactory connectionFactory, @NonNull String tableName) { super(tableName); this.connectionFactory = requireNonNull(connectionFactory, "dataSource can not be null"); } @Override protected <T> Mono<T> executeCommand( String sql, Function<Statement, Mono<T>> body, BiFunction<String, Throwable, Mono<T>> exceptionHandler) {<FILL_FUNCTION_BODY>} @Override protected String toParameter(int index, String name) { return getAdapter().toParameter(index, name); } @Override protected void bind(Statement statement, int index, String name, Object value) { getAdapter().bind(statement, index, name, value); } private R2dbcAdapter getAdapter() { synchronized (this) { if (adapter == null) { adapter = R2dbcAdapter.create(connectionFactory.getMetadata().getName()); } return adapter; } } }
return Mono.usingWhen( Mono.from(connectionFactory.create()).doOnNext(it -> it.setAutoCommit(true)), conn -> body.apply(conn.createStatement(sql)) .onErrorResume(throwable -> exceptionHandler.apply(sql, throwable)), Connection::close, (connection, throwable) -> Mono.from(connection.close()).then(exceptionHandler.apply(sql, throwable)), connection -> Mono.from(connection.close()).then());
300
131
431
<methods>public void <init>(java.lang.String) ,public boolean extend(net.javacrumbs.shedlock.core.LockConfiguration) ,public Publisher<java.lang.Boolean> extendReactive(net.javacrumbs.shedlock.core.LockConfiguration) ,public boolean insertRecord(net.javacrumbs.shedlock.core.LockConfiguration) ,public Publisher<java.lang.Boolean> insertRecordReactive(net.javacrumbs.shedlock.core.LockConfiguration) ,public void unlock(net.javacrumbs.shedlock.core.LockConfiguration) ,public Publisher<java.lang.Void> unlockReactive(net.javacrumbs.shedlock.core.LockConfiguration) ,public boolean updateRecord(net.javacrumbs.shedlock.core.LockConfiguration) ,public Publisher<java.lang.Boolean> updateRecordReactive(net.javacrumbs.shedlock.core.LockConfiguration) <variables>private final non-sealed java.lang.String tableName
lukas-krecan_ShedLock
ShedLock/providers/redis/shedlock-provider-redis-jedis4/src/main/java/net/javacrumbs/shedlock/provider/redis/jedis4/JedisLockProvider.java
JedisLockProvider
lock
class JedisLockProvider implements ExtensibleLockProvider { private static final String KEY_PREFIX = "job-lock"; private static final String ENV_DEFAULT = "default"; private final JedisTemplate jedisTemplate; private final String environment; public JedisLockProvider(@NonNull Pool<Jedis> jedisPool) { this(jedisPool, ENV_DEFAULT); } /** * Creates JedisLockProvider * * @param jedisPool * Jedis connection pool * @param environment * environment is part of the key and thus makes sure there is not * key conflict between multiple ShedLock instances running on the * same Redis */ public JedisLockProvider(@NonNull Pool<Jedis> jedisPool, @NonNull String environment) { this.jedisTemplate = new JedisPoolTemplate(jedisPool); this.environment = environment; } /** * Creates JedisLockProvider * * @param jedisCommands * implementation of JedisCommands. * @param environment * environment is part of the key and thus makes sure there is not * key conflict between multiple ShedLock instances running on the * same Redis */ public JedisLockProvider(@NonNull JedisCommands jedisCommands, @NonNull String environment) { this.jedisTemplate = new JedisCommandsTemplate(jedisCommands); this.environment = environment; } @Override @NonNull public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} private Optional<SimpleLock> extend(LockConfiguration lockConfiguration) { long expireTime = getMsUntil(lockConfiguration.getLockAtMostUntil()); String key = buildKey(lockConfiguration.getName(), this.environment); String rez = extendKeyExpiration(key, expireTime); if ("OK".equals(rez)) { return Optional.of(new RedisLock(key, this, lockConfiguration)); } return Optional.empty(); } private String extendKeyExpiration(String key, long expiration) { return jedisTemplate.set(key, buildValue(), setParams().xx().px(expiration)); } private void deleteKey(String key) { jedisTemplate.del(key); } private static final class RedisLock extends AbstractSimpleLock { private final String key; private final JedisLockProvider jedisLockProvider; private RedisLock(String key, JedisLockProvider jedisLockProvider, LockConfiguration lockConfiguration) { super(lockConfiguration); this.key = key; this.jedisLockProvider = jedisLockProvider; } @Override public void doUnlock() { long keepLockFor = getMsUntil(lockConfiguration.getLockAtLeastUntil()); // lock at least until is in the past if (keepLockFor <= 0) { try { jedisLockProvider.deleteKey(key); } catch (Exception e) { throw new LockException("Can not remove node", e); } } else { jedisLockProvider.extendKeyExpiration(key, keepLockFor); } } @Override @NonNull protected Optional<SimpleLock> doExtend(@NonNull LockConfiguration newConfiguration) { return jedisLockProvider.extend(newConfiguration); } } private static long getMsUntil(Instant instant) { return Duration.between(ClockProvider.now(), instant).toMillis(); } static String buildKey(String lockName, String env) { return String.format("%s:%s:%s", KEY_PREFIX, env, lockName); } private static String buildValue() { return String.format("ADDED:%s@%s", toIsoString(ClockProvider.now()), getHostname()); } private interface JedisTemplate { String set(String key, String value, SetParams setParams); void del(String key); } private record JedisPoolTemplate(Pool<Jedis> jedisPool) implements JedisTemplate { @Override public String set(String key, String value, SetParams setParams) { try (Jedis jedis = jedisPool.getResource()) { return jedis.set(key, value, setParams); } } @Override public void del(String key) { try (Jedis jedis = jedisPool.getResource()) { jedis.del(key); } } } private record JedisCommandsTemplate(JedisCommands jedisCommands) implements JedisTemplate { @Override public String set(String key, String value, SetParams setParams) { return jedisCommands.set(key, value, setParams); } @Override public void del(String key) { jedisCommands.del(key); } } }
long expireTime = getMsUntil(lockConfiguration.getLockAtMostUntil()); String key = buildKey(lockConfiguration.getName(), this.environment); String rez = jedisTemplate.set(key, buildValue(), setParams().nx().px(expireTime)); if ("OK".equals(rez)) { return Optional.of(new RedisLock(key, this, lockConfiguration)); } return Optional.empty();
1,330
114
1,444
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/redis/shedlock-provider-redis-quarkus2/src/main/java/net/javacrumbs/shedlock/provider/redis/quarkus/QuarkusRedisLockProvider.java
RedisLock
doUnlock
class RedisLock extends AbstractSimpleLock { private final String key; private final QuarkusRedisLockProvider quarkusLockProvider; private RedisLock(String key, QuarkusRedisLockProvider jedisLockProvider, LockConfiguration lockConfiguration) { super(lockConfiguration); this.key = key; this.quarkusLockProvider = jedisLockProvider; } @Override public void doUnlock() {<FILL_FUNCTION_BODY>} @Override @NonNull protected Optional<SimpleLock> doExtend(@NonNull LockConfiguration newConfiguration) { return quarkusLockProvider.extend(newConfiguration); } }
long keepLockFor = getMillisUntil(lockConfiguration.getLockAtLeastUntil()); // lock at least until is in the past if (keepLockFor <= 0) { try { quarkusLockProvider.deleteKey(key); } catch (Exception e) { throw new LockException("Can not remove key", e); } } else { quarkusLockProvider.extendKeyExpiration(key, keepLockFor); }
172
116
288
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/redis/shedlock-provider-redis-spring/src/main/java/net/javacrumbs/shedlock/provider/redis/spring/ReactiveRedisLockProvider.java
ReactiveRedisLock
doUnlock
class ReactiveRedisLock extends AbstractSimpleLock { private final String key; private final ReactiveStringRedisTemplate redisTemplate; private static String createKey(String keyPrefix, String environment, String lockName) { return String.format("%s:%s:%s", keyPrefix, environment, lockName); } private static String createValue(Instant now) { return String.format("ADDED:%s@%s", toIsoString(now), getHostname()); } private ReactiveRedisLock( String key, ReactiveStringRedisTemplate redisTemplate, LockConfiguration lockConfiguration) { super(lockConfiguration); this.key = key; this.redisTemplate = redisTemplate; } @Override protected void doUnlock() {<FILL_FUNCTION_BODY>} }
Instant now = ClockProvider.now(); Duration expirationTime = Duration.between(now, lockConfiguration.getLockAtLeastUntil()); if (expirationTime.isNegative() || expirationTime.isZero()) { try { redisTemplate.delete(key).block(); } catch (Exception e) { throw new LockException("Can not remove node", e); } } else { String value = createValue(now); redisTemplate .opsForValue() .setIfPresent(key, value, expirationTime) .block(); }
214
153
367
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/redis/shedlock-provider-redis-spring/src/main/java/net/javacrumbs/shedlock/provider/redis/spring/RedisLockProvider.java
RedisLock
tryToSetExpiration
class RedisLock extends AbstractSimpleLock { private final String key; private final StringRedisTemplate redisTemplate; private RedisLock(String key, StringRedisTemplate redisTemplate, LockConfiguration lockConfiguration) { super(lockConfiguration); this.key = key; this.redisTemplate = redisTemplate; } @Override public void doUnlock() { Expiration keepLockFor = getExpiration(lockConfiguration.getLockAtLeastUntil()); // lock at least until is in the past if (keepLockFor.getExpirationTimeInMilliseconds() <= 0) { try { redisTemplate.delete(key); } catch (Exception e) { throw new LockException("Can not remove node", e); } } else { tryToSetExpiration(this.redisTemplate, key, keepLockFor, SetOption.SET_IF_PRESENT); } } } String buildKey(String lockName) { return String.format("%s:%s:%s", keyPrefix, environment, lockName); } private static Boolean tryToSetExpiration( StringRedisTemplate template, String key, Expiration expiration, SetOption option) {<FILL_FUNCTION_BODY>
return template.execute( connection -> { byte[] serializedKey = ((RedisSerializer<String>) template.getKeySerializer()).serialize(key); byte[] serializedValue = ((RedisSerializer<String>) template.getValueSerializer()) .serialize(String.format("ADDED:%s@%s", toIsoString(ClockProvider.now()), getHostname())); return connection.set(serializedKey, serializedValue, expiration, option); }, false);
320
125
445
<no_super_class>
lukas-krecan_ShedLock
ShedLock/providers/spanner/shedlock-provider-spanner/src/main/java/net/javacrumbs/shedlock/provider/spanner/SpannerStorageAccessor.java
SpannerStorageAccessor
unlock
class SpannerStorageAccessor extends AbstractStorageAccessor { private final String table; private final String name; private final String lockedBy; private final String lockUntil; private final String lockedAt; private final String hostname; private final DatabaseClient databaseClient; /** * Constructs a {@code SpannerStorageAccessor} using the specified configuration. * * @param configuration The lock provider configuration. */ public SpannerStorageAccessor(SpannerLockProvider.Configuration configuration) { TableConfiguration tableConfiguration = configuration.getTableConfiguration(); this.lockUntil = tableConfiguration.getLockUntil(); this.lockedAt = tableConfiguration.getLockedAt(); this.lockedBy = tableConfiguration.getLockedBy(); this.table = tableConfiguration.getTableName(); this.name = tableConfiguration.getLockName(); this.databaseClient = configuration.getDatabaseClient(); this.hostname = configuration.getHostname(); } /** * Attempts to insert a lock record into the Spanner table. * * @param lockConfiguration The lock configuration. * @return {@code true} if the lock was successfully inserted, otherwise {@code false}. */ @Override public boolean insertRecord(@NonNull LockConfiguration lockConfiguration) { return Boolean.TRUE.equals( databaseClient.readWriteTransaction().run(tx -> findLock(tx, lockConfiguration.getName()) .map(lock -> false) // Lock already exists, so we return false. .orElseGet(() -> { tx.buffer(buildMutation(lockConfiguration, newInsertBuilder(table))); return true; }))); } /** * Attempts to update an existing lock record in the Spanner table. * * @param lockConfiguration The lock configuration. * @return {@code true} if the lock was successfully updated, otherwise {@code false}. */ @Override public boolean updateRecord(@NonNull LockConfiguration lockConfiguration) { return Boolean.TRUE.equals(databaseClient.readWriteTransaction().run(tx -> { return findLock(tx, lockConfiguration.getName()) .filter(lock -> lock.lockedUntil().compareTo(now()) <= 0) .map(lock -> { tx.buffer(buildMutation(lockConfiguration, newUpdateBuilder(table))); return true; }) .orElse(false); })); } private Mutation buildMutation(LockConfiguration lockConfiguration, WriteBuilder builder) { return builder.set(name) .to(lockConfiguration.getName()) .set(lockUntil) .to(toTimestamp(lockConfiguration.getLockAtMostUntil())) .set(lockedAt) .to(now()) .set(lockedBy) .to(hostname) .build(); } /** * Extends the lock until time of an existing lock record if the current host holds the lock. * * @param lockConfiguration The lock configuration. * @return {@code true} if the lock was successfully extended, otherwise {@code false}. */ @Override public boolean extend(@NonNull LockConfiguration lockConfiguration) { return Boolean.TRUE.equals( databaseClient.readWriteTransaction().run(tx -> findLock(tx, lockConfiguration.getName()) .filter(lock -> hostname.equals(lock.lockedBy())) .filter(lock -> lock.lockedUntil().compareTo(now()) > 0) .map(lock -> { tx.buffer(newUpdateBuilder(table) .set(name) .to(lockConfiguration.getName()) .set(lockUntil) .to(toTimestamp(lockConfiguration.getLockAtMostUntil())) .build()); return true; }) .orElse(false))); } /** * Unlocks the lock by updating the lock record's lock until time to the unlock time. * * @param lockConfiguration The lock configuration to unlock. */ @Override public void unlock(@NonNull LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} /** * Finds the lock in the Spanner table. * * @param tx The tx context to use for the read. * @param lockName The name of the lock to find. * @return An {@code Optional<Lock>} containing the lock if found, otherwise empty. */ Optional<Lock> findLock(TransactionContext tx, String lockName) { return Optional.ofNullable(tx.readRow(table, Key.of(lockName), List.of(name, lockUntil, lockedBy, lockedAt))) .map(this::newLock); } Lock newLock(@NonNull Struct row) { return new Lock( row.getString(name), row.getString(lockedBy), row.getTimestamp(lockedAt), row.getTimestamp(lockUntil)); } /** * Converts {@code Instant} to {@code Timestamp}. * * @param instant The instant to convert. * @return The corresponding {@code Timestamp}. */ private Timestamp toTimestamp(Instant instant) { return Timestamp.ofTimeSecondsAndNanos(instant.getEpochSecond(), instant.getNano()); } /** * Inner class representing a lock record from Spanner. */ record Lock(String lockName, String lockedBy, Timestamp lockedAt, Timestamp lockedUntil) {} }
databaseClient.readWriteTransaction().run(tx -> { findLock(tx, lockConfiguration.getName()) .filter(lock -> hostname.equals(lock.lockedBy())) .ifPresent(lock -> tx.buffer(newUpdateBuilder(table) .set(name) .to(lockConfiguration.getName()) .set(lockUntil) .to(toTimestamp(lockConfiguration.getUnlockTime())) .build())); return null; // need a return to commit the transaction });
1,374
130
1,504
<methods>public non-sealed void <init>() <variables>protected final Logger logger
lukas-krecan_ShedLock
ShedLock/providers/zookeeper/shedlock-provider-zookeeper-curator/src/main/java/net/javacrumbs/shedlock/provider/zookeeper/curator/ZookeeperCuratorLockProvider.java
ZookeeperCuratorLockProvider
tryLock
class ZookeeperCuratorLockProvider implements LockProvider { public static final String DEFAULT_PATH = "/shedlock"; private final String path; private final CuratorFramework client; private static final Logger logger = LoggerFactory.getLogger(ZookeeperCuratorLockProvider.class); public ZookeeperCuratorLockProvider(@NonNull CuratorFramework client) { this(client, DEFAULT_PATH); } public ZookeeperCuratorLockProvider(@NonNull CuratorFramework client, @NonNull String path) { this.client = requireNonNull(client); this.path = PathUtils.validatePath(path); } @Override @NonNull public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) { String nodePath = getNodePath(lockConfiguration.getName()); try { Stat stat = new Stat(); byte[] data = client.getData().storingStatIn(stat).forPath(nodePath); if (isLocked(data)) { return Optional.empty(); } else { return tryLock(lockConfiguration, nodePath, stat); } } catch (KeeperException.NoNodeException e) { // node does not exists if (createNode(lockConfiguration, nodePath)) { return Optional.of(new CuratorLock(nodePath, client, lockConfiguration)); } else { logger.trace("Node not created, must have been created by a parallel process"); return Optional.empty(); } } catch (Exception e) { throw new LockException("Can not obtain lock node", e); } } private Optional<SimpleLock> tryLock(LockConfiguration lockConfiguration, String nodePath, Stat stat) throws Exception {<FILL_FUNCTION_BODY>} private boolean createNode(LockConfiguration lockConfiguration, String nodePath) { try { client.create() .creatingParentsIfNeeded() .withMode(CreateMode.PERSISTENT) .forPath(nodePath, serialize(lockConfiguration.getLockAtMostUntil())); return true; } catch (KeeperException.NodeExistsException e) { return false; } catch (Exception e) { throw new LockException("Can not create node", e); } } boolean isLocked(String nodePath) throws Exception { byte[] data = client.getData().forPath(nodePath); return isLocked(data); } private boolean isLocked(byte[] data) { if (data == null || data.length == 0) { // most likely created by previous version of the library return true; } try { Instant lockedUntil = parse(data); return lockedUntil.isAfter(ClockProvider.now()); } catch (DateTimeParseException e) { // most likely created by previous version of the library logger.debug("Can not parse date", e); return true; } } private static byte[] serialize(Instant date) { return toIsoString(date).getBytes(UTF_8); } private static Instant parse(byte[] data) { return Instant.parse(new String(data, UTF_8)); } String getNodePath(String lockName) { return path + "/" + lockName; } private static final class CuratorLock extends AbstractSimpleLock { private final String nodePath; private final CuratorFramework client; private CuratorLock(String nodePath, CuratorFramework client, LockConfiguration lockConfiguration) { super(lockConfiguration); this.nodePath = nodePath; this.client = client; } @Override public void doUnlock() { try { Instant unlockTime = lockConfiguration.getUnlockTime(); client.setData().forPath(nodePath, serialize(unlockTime)); } catch (Exception e) { throw new LockException("Can not remove node", e); } } } }
try { client.setData() .withVersion(stat.getVersion()) .forPath(nodePath, serialize(lockConfiguration.getLockAtMostUntil())); return Optional.of(new CuratorLock(nodePath, client, lockConfiguration)); } catch (KeeperException.BadVersionException e) { logger.trace("Node value can not be set, must have been set by a parallel process"); return Optional.empty(); }
1,010
114
1,124
<no_super_class>
lukas-krecan_ShedLock
ShedLock/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/AbstractSimpleLock.java
AbstractSimpleLock
extend
class AbstractSimpleLock implements SimpleLock { private boolean valid = true; protected final LockConfiguration lockConfiguration; protected AbstractSimpleLock(LockConfiguration lockConfiguration) { this.lockConfiguration = lockConfiguration; } @Override public final void unlock() { checkValidity(); doUnlock(); valid = false; } protected abstract void doUnlock(); @Override public Optional<SimpleLock> extend(Duration lockAtMostFor, Duration lockAtLeastFor) {<FILL_FUNCTION_BODY>} protected Optional<SimpleLock> doExtend(LockConfiguration newConfiguration) { throw new UnsupportedOperationException(); } private void checkValidity() { if (!valid) { throw new IllegalStateException( "Lock " + lockConfiguration.getName() + " is not valid, it has already been unlocked or extended"); } } }
checkValidity(); Optional<SimpleLock> result = doExtend( new LockConfiguration(ClockProvider.now(), lockConfiguration.getName(), lockAtMostFor, lockAtLeastFor)); valid = false; return result;
229
61
290
<no_super_class>
lukas-krecan_ShedLock
ShedLock/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/DefaultLockManager.java
DefaultLockManager
executeWithLock
class DefaultLockManager implements LockManager { private static final Logger logger = LoggerFactory.getLogger(DefaultLockManager.class); private final LockingTaskExecutor lockingTaskExecutor; private final LockConfigurationExtractor lockConfigurationExtractor; public DefaultLockManager(LockProvider lockProvider, LockConfigurationExtractor lockConfigurationExtractor) { this(new DefaultLockingTaskExecutor(lockProvider), lockConfigurationExtractor); } public DefaultLockManager( LockingTaskExecutor lockingTaskExecutor, LockConfigurationExtractor lockConfigurationExtractor) { this.lockingTaskExecutor = requireNonNull(lockingTaskExecutor); this.lockConfigurationExtractor = requireNonNull(lockConfigurationExtractor); } @Override public void executeWithLock(Runnable task) {<FILL_FUNCTION_BODY>} }
Optional<LockConfiguration> lockConfigOptional = lockConfigurationExtractor.getLockConfiguration(task); if (lockConfigOptional.isEmpty()) { logger.debug("No lock configuration for {}. Executing without lock.", task); task.run(); } else { lockingTaskExecutor.executeWithLock(task, lockConfigOptional.get()); }
204
88
292
<no_super_class>
lukas-krecan_ShedLock
ShedLock/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/DefaultLockingTaskExecutor.java
DefaultLockingTaskExecutor
executeWithLock
class DefaultLockingTaskExecutor implements LockingTaskExecutor { private static final Logger logger = LoggerFactory.getLogger(DefaultLockingTaskExecutor.class); private final LockProvider lockProvider; public DefaultLockingTaskExecutor(LockProvider lockProvider) { this.lockProvider = requireNonNull(lockProvider); } @Override public void executeWithLock(Runnable task, LockConfiguration lockConfig) { try { executeWithLock((Task) task::run, lockConfig); } catch (RuntimeException | Error e) { throw e; } catch (Throwable throwable) { // Should not happen throw new IllegalStateException(throwable); } } @Override public void executeWithLock(Task task, LockConfiguration lockConfig) throws Throwable { executeWithLock( () -> { task.call(); return null; }, lockConfig); } @Override public <T> TaskResult<T> executeWithLock(TaskWithResult<T> task, LockConfiguration lockConfig) throws Throwable {<FILL_FUNCTION_BODY>} }
String lockName = lockConfig.getName(); if (alreadyLockedBy(lockName)) { logger.debug("Already locked '{}'", lockName); return TaskResult.result(task.call()); } Optional<SimpleLock> lock = lockProvider.lock(lockConfig); if (lock.isPresent()) { try { LockAssert.startLock(lockName); LockExtender.startLock(lock.get()); logger.debug( "Locked '{}', lock will be held at most until {}", lockName, lockConfig.getLockAtMostUntil()); return TaskResult.result(task.call()); } finally { LockAssert.endLock(); SimpleLock activeLock = LockExtender.endLock(); if (activeLock != null) { activeLock.unlock(); } else { // This should never happen, but I do not know any better way to handle the null // case. logger.warn("No active lock, please report this as a bug."); lock.get().unlock(); } if (logger.isDebugEnabled()) { Instant lockAtLeastUntil = lockConfig.getLockAtLeastUntil(); Instant now = ClockProvider.now(); if (lockAtLeastUntil.isAfter(now)) { logger.debug("Task finished, lock '{}' will be released at {}", lockName, lockAtLeastUntil); } else { logger.debug("Task finished, lock '{}' released", lockName); } } } } else { logger.debug("Not executing '{}'. It's locked.", lockName); return TaskResult.notExecuted(); }
285
420
705
<no_super_class>
lukas-krecan_ShedLock
ShedLock/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockAssert.java
TestHelper
makeAllAssertsPass
class TestHelper { private static final String TEST_LOCK_NAME = "net.javacrumbs.shedlock.core.test-lock"; /** * If pass is set to true, all LockAssert.assertLocked calls in current thread * will pass. To be used in unit tests only <code> * LockAssert.TestHelper.makeAllAssertsPass(true) * </code> */ public static void makeAllAssertsPass(boolean pass) {<FILL_FUNCTION_BODY>} }
if (pass) { if (!LockAssert.alreadyLockedBy(TEST_LOCK_NAME)) { LockAssert.startLock(TEST_LOCK_NAME); } } else { if (LockAssert.alreadyLockedBy(TEST_LOCK_NAME)) { LockAssert.endLock(); } }
135
84
219
<no_super_class>
lukas-krecan_ShedLock
ShedLock/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockConfiguration.java
LockConfiguration
getUnlockTime
class LockConfiguration { private final Instant createdAt; private final String name; /** * The lock is held until this duration passes, after that it's automatically * released (the process holding it has most likely died without releasing the * lock) Can be ignored by providers which can detect dead processes (like * Zookeeper) */ private final Duration lockAtMostFor; /** * The lock will be held at least this duration even if the task holding the * lock finishes earlier. */ private final Duration lockAtLeastFor; /** * Creates LockConfiguration. There are two types of lock providers. One that * uses "db time" which requires relative values of lockAtMostFor and * lockAtLeastFor (currently it's only JdbcTemplateLockProvider). Second type of * lock provider uses absolute time calculated from `createdAt`. * * @param createdAt * @param name * @param lockAtMostFor * @param lockAtLeastFor */ public LockConfiguration(Instant createdAt, String name, Duration lockAtMostFor, Duration lockAtLeastFor) { this.createdAt = Objects.requireNonNull(createdAt); this.name = Objects.requireNonNull(name); this.lockAtMostFor = Objects.requireNonNull(lockAtMostFor); this.lockAtLeastFor = Objects.requireNonNull(lockAtLeastFor); if (lockAtLeastFor.compareTo(lockAtMostFor) > 0) { throw new IllegalArgumentException("lockAtLeastFor is longer than lockAtMostFor for lock '" + name + "'."); } if (lockAtMostFor.isNegative()) { throw new IllegalArgumentException("lockAtMostFor is negative '" + name + "'."); } if (name.isEmpty()) { throw new IllegalArgumentException("lock name can not be empty"); } } public String getName() { return name; } public Instant getLockAtMostUntil() { return createdAt.plus(lockAtMostFor); } public Instant getLockAtLeastUntil() { return createdAt.plus(lockAtLeastFor); } /** Returns either now or lockAtLeastUntil whichever is later. */ public Instant getUnlockTime() {<FILL_FUNCTION_BODY>} public Duration getLockAtLeastFor() { return lockAtLeastFor; } public Duration getLockAtMostFor() { return lockAtMostFor; } @Override public String toString() { return "LockConfiguration{" + "name='" + name + '\'' + ", lockAtMostFor=" + lockAtMostFor + ", lockAtLeastFor=" + lockAtLeastFor + '}'; } }
Instant now = now(); Instant lockAtLeastUntil = getLockAtLeastUntil(); return lockAtLeastUntil.isAfter(now) ? lockAtLeastUntil : now;
723
51
774
<no_super_class>
lukas-krecan_ShedLock
ShedLock/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockExtender.java
LockExtender
extendActiveLock
class LockExtender { // Using deque here instead of a simple thread local to be able to handle nested // locks. private static final ThreadLocal<Deque<SimpleLock>> activeLocks = ThreadLocal.withInitial(LinkedList::new); private LockExtender() {} /** * Extends active lock. Is based on a thread local variable, so it might not * work in case of async processing. In case of nested locks, extends the * innermost lock. * * @throws LockCanNotBeExtendedException * when the lock can not be extended due to expired lock * @throws NoActiveLockException * when there is no active lock in the thread local * @throws UnsupportedOperationException * when the LockProvider does not support lock extension. */ public static void extendActiveLock(Duration lockAtMostFor, Duration lockAtLeastFor) {<FILL_FUNCTION_BODY>} private static Deque<SimpleLock> locks() { return activeLocks.get(); } static void startLock(SimpleLock lock) { locks().addLast(lock); } @Nullable static SimpleLock endLock() { SimpleLock lock = locks().pollLast(); // we want to clean up the thread local variable when there are no locks if (locks().isEmpty()) { activeLocks.remove(); } return lock; } public static class LockExtensionException extends RuntimeException { public LockExtensionException(String message) { super(message); } } public static class NoActiveLockException extends LockExtensionException { public NoActiveLockException() { super( "No active lock in current thread, please make sure that you execute LockExtender.extendActiveLock in locked context."); } } public static class LockCanNotBeExtendedException extends LockExtensionException { public LockCanNotBeExtendedException() { super("Lock can not be extended, most likely it already expired."); } } }
SimpleLock lock = locks().peekLast(); if (lock == null) throw new NoActiveLockException(); Optional<SimpleLock> newLock = lock.extend(lockAtMostFor, lockAtLeastFor); if (newLock.isPresent()) { // removing and adding here should be safe as it's a thread local variable and // the changes are // only visible in the current thread. locks().removeLast(); locks().addLast(newLock.get()); } else { throw new LockCanNotBeExtendedException(); }
511
140
651
<no_super_class>
lukas-krecan_ShedLock
ShedLock/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/KeepAliveLockProvider.java
KeepAliveLock
extendForNextPeriod
class KeepAliveLock extends AbstractSimpleLock { private final Duration lockExtensionPeriod; private SimpleLock lock; private Duration remainingLockAtLeastFor; private final ScheduledFuture<?> future; private boolean active = true; private Instant currentLockAtMostUntil; private KeepAliveLock( LockConfiguration lockConfiguration, SimpleLock lock, ScheduledExecutorService executorService) { super(lockConfiguration); this.lock = lock; this.lockExtensionPeriod = lockConfiguration.getLockAtMostFor().dividedBy(2); this.remainingLockAtLeastFor = lockConfiguration.getLockAtLeastFor(); this.currentLockAtMostUntil = lockConfiguration.getLockAtMostUntil(); long extensionPeriodMs = lockExtensionPeriod.toMillis(); this.future = executorService.scheduleAtFixedRate( this::extendForNextPeriod, extensionPeriodMs, extensionPeriodMs, MILLISECONDS); } private void extendForNextPeriod() {<FILL_FUNCTION_BODY>} private void stop() { active = false; future.cancel(false); } @Override protected void doUnlock() { synchronized (this) { logger.trace("Unlocking lock {}", lockConfiguration.getName()); stop(); lock.unlock(); } } @Override protected Optional<SimpleLock> doExtend(LockConfiguration newConfiguration) { throw new UnsupportedOperationException("Manual extension of KeepAliveLock is not supported (yet)"); } }
// We can have a race-condition when we extend the lock but the `lock` field is // accessed // before we update it. synchronized (this) { if (!active) { return; } if (currentLockAtMostUntil.isBefore(now())) { // Failsafe for cases when we are not able to extend the lock and it expires // before the // extension // In such case someone else might have already obtained the lock so we can't // extend it. stop(); return; } remainingLockAtLeastFor = remainingLockAtLeastFor.minus(lockExtensionPeriod); if (remainingLockAtLeastFor.isNegative()) { remainingLockAtLeastFor = Duration.ZERO; } currentLockAtMostUntil = now().plus(lockConfiguration.getLockAtMostFor()); Optional<SimpleLock> extendedLock = lock.extend(lockConfiguration.getLockAtMostFor(), remainingLockAtLeastFor); if (extendedLock.isPresent()) { lock = extendedLock.get(); logger.trace( "Lock {} extended for {}", lockConfiguration.getName(), lockConfiguration.getLockAtMostFor()); } else { logger.warn("Can't extend lock {}", lockConfiguration.getName()); stop(); } }
395
339
734
<no_super_class>
lukas-krecan_ShedLock
ShedLock/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/StorageBasedLockProvider.java
StorageBasedLockProvider
doLock
class StorageBasedLockProvider implements ExtensibleLockProvider { private final StorageAccessor storageAccessor; private final LockRecordRegistry lockRecordRegistry = new LockRecordRegistry(); protected StorageBasedLockProvider(StorageAccessor storageAccessor) { this.storageAccessor = storageAccessor; } /** Clears cache of existing lock records. */ public void clearCache() { lockRecordRegistry.clear(); } @Override public Optional<SimpleLock> lock(LockConfiguration lockConfiguration) { boolean lockObtained = doLock(lockConfiguration); if (lockObtained) { return Optional.of(new StorageLock(lockConfiguration, storageAccessor)); } else { return Optional.empty(); } } /** * Sets lockUntil according to LockConfiguration if current lockUntil &lt;= now */ protected boolean doLock(LockConfiguration lockConfiguration) {<FILL_FUNCTION_BODY>} private static class StorageLock extends AbstractSimpleLock { private final StorageAccessor storageAccessor; StorageLock(LockConfiguration lockConfiguration, StorageAccessor storageAccessor) { super(lockConfiguration); this.storageAccessor = storageAccessor; } @Override public void doUnlock() { storageAccessor.unlock(lockConfiguration); } @Override public Optional<SimpleLock> doExtend(LockConfiguration newConfig) { if (storageAccessor.extend(newConfig)) { return Optional.of(new StorageLock(newConfig, storageAccessor)); } else { return Optional.empty(); } } } }
String name = lockConfiguration.getName(); boolean tryToCreateLockRecord = !lockRecordRegistry.lockRecordRecentlyCreated(name); if (tryToCreateLockRecord) { // create record in case it does not exist yet if (storageAccessor.insertRecord(lockConfiguration)) { lockRecordRegistry.addLockRecord(name); // we were able to create the record, we have the lock return true; } // we were not able to create the record, it already exists, let's put it to the // cache so we // do not try again lockRecordRegistry.addLockRecord(name); } // let's try to update the record, if successful, we have the lock try { return storageAccessor.updateRecord(lockConfiguration); } catch (Exception e) { // There are some users that start the app before they have the DB ready. // If they use JDBC, insertRecord returns false, the record is stored in the // recordRegistry // and the insert is not attempted again. We are assuming that the DB still does // not exist // when update is attempted. Unlike insert, update throws the exception, and we // clear the // cache here. if (tryToCreateLockRecord) { lockRecordRegistry.removeLockRecord(name); } throw e; }
405
337
742
<no_super_class>
lukas-krecan_ShedLock
ShedLock/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/Utils.java
Utils
initHostname
class Utils { /** * A {@link DateTimeFormatter} like {@link DateTimeFormatter#ISO_INSTANT} with * the exception that it always appends exactly three fractional digits (nano * seconds). * * <p> * This is required in order to guarantee natural sorting, which enables us to * use <code>&lt;= * </code> comparision in queries. * * <pre> * 2018-12-07T12:30:37.000Z * 2018-12-07T12:30:37.810Z * 2018-12-07T12:30:37.819Z * 2018-12-07T12:30:37.820Z * </pre> * * <p> * When using variable fractional digit count as done in * {@link DateTimeFormatter#ISO_INSTANT ISO_INSTANT} and * {@link DateTimeFormatter#ISO_OFFSET_DATE_TIME ISO_OFFSET_DATE_TIME} the * following sorting occurs: * * <pre> * 2018-12-07T12:30:37.819Z * 2018-12-07T12:30:37.81Z * 2018-12-07T12:30:37.820Z * 2018-12-07T12:30:37Z * </pre> * * @see <a href="https://stackoverflow.com/a/5098252">natural sorting of ISO * 8601 time format</a> */ private static final DateTimeFormatter formatter = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendInstant(3) .toFormatter(); private static final String hostname = initHostname(); private Utils() {} public static String getHostname() { return hostname; } public static String toIsoString(Instant instant) { OffsetDateTime utc = instant.atOffset(ZoneOffset.UTC); return formatter.format(utc); } private static String initHostname() {<FILL_FUNCTION_BODY>} }
try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { return "unknown"; }
642
42
684
<no_super_class>
lukas-krecan_ShedLock
ShedLock/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/AbstractLockConfiguration.java
AbstractLockConfiguration
setImportMetadata
class AbstractLockConfiguration implements ImportAware { protected AnnotationAttributes annotationAttributes; @Override public void setImportMetadata(AnnotationMetadata importMetadata) {<FILL_FUNCTION_BODY>} protected int getOrder() { return annotationAttributes.getNumber("order"); } }
this.annotationAttributes = AnnotationAttributes.fromMap( importMetadata.getAnnotationAttributes(EnableSchedulerLock.class.getName(), false)); if (this.annotationAttributes == null) { throw new IllegalArgumentException( "@EnableSchedulerLock is not present on importing class " + importMetadata.getClassName()); }
75
83
158
<no_super_class>
lukas-krecan_ShedLock
ShedLock/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/MethodProxyLockConfiguration.java
MethodProxyLockConfiguration
proxyScheduledLockAopBeanPostProcessor
class MethodProxyLockConfiguration extends AbstractLockConfiguration { @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) MethodProxyScheduledLockAdvisor proxyScheduledLockAopBeanPostProcessor( @Lazy LockProvider lockProvider, @Lazy ExtendedLockConfigurationExtractor lockConfigurationExtractor) {<FILL_FUNCTION_BODY>} }
MethodProxyScheduledLockAdvisor advisor = new MethodProxyScheduledLockAdvisor( lockConfigurationExtractor, new DefaultLockingTaskExecutor(lockProvider)); advisor.setOrder(getOrder()); return advisor;
93
60
153
<methods>public void setImportMetadata(AnnotationMetadata) <variables>protected AnnotationAttributes annotationAttributes
lukas-krecan_ShedLock
ShedLock/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/MethodProxyScheduledLockAdvisor.java
LockingInterceptor
invoke
class LockingInterceptor implements MethodInterceptor { private final ExtendedLockConfigurationExtractor lockConfigurationExtractor; private final LockingTaskExecutor lockingTaskExecutor; LockingInterceptor( ExtendedLockConfigurationExtractor lockConfigurationExtractor, LockingTaskExecutor lockingTaskExecutor) { this.lockConfigurationExtractor = lockConfigurationExtractor; this.lockingTaskExecutor = lockingTaskExecutor; } @Override @Nullable public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>} @Nullable private static Object toOptional(TaskResult<Object> result) { if (result.wasExecuted()) { return result.getResult(); } else { return Optional.empty(); } } }
Class<?> returnType = invocation.getMethod().getReturnType(); if (returnType.isPrimitive() && !void.class.equals(returnType)) { throw new LockingNotSupportedException("Can not lock method returning primitive value"); } LockConfiguration lockConfiguration = lockConfigurationExtractor .getLockConfiguration(invocation.getThis(), invocation.getMethod(), invocation.getArguments()) .get(); TaskResult<Object> result = lockingTaskExecutor.executeWithLock(invocation::proceed, lockConfiguration); if (Optional.class.equals(returnType)) { return toOptional(result); } else { return result.getResult(); }
205
175
380
<no_super_class>
lukas-krecan_ShedLock
ShedLock/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/RegisterDefaultTaskSchedulerPostProcessor.java
RegisterDefaultTaskSchedulerPostProcessor
postProcessBeanDefinitionRegistry
class RegisterDefaultTaskSchedulerPostProcessor implements BeanDefinitionRegistryPostProcessor, Ordered, BeanFactoryAware { private BeanFactory beanFactory; private static final Logger logger = LoggerFactory.getLogger(RegisterDefaultTaskSchedulerPostProcessor.class); @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {<FILL_FUNCTION_BODY>} @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {} @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } }
ListableBeanFactory listableBeanFactory = (ListableBeanFactory) this.beanFactory; if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors(listableBeanFactory, TaskScheduler.class).length == 0) { String[] scheduledExecutorsBeanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( listableBeanFactory, ScheduledExecutorService.class); if (scheduledExecutorsBeanNames.length != 1) { logger.debug("Registering default TaskScheduler"); registry.registerBeanDefinition( DEFAULT_TASK_SCHEDULER_BEAN_NAME, rootBeanDefinition(ConcurrentTaskScheduler.class).getBeanDefinition()); if (scheduledExecutorsBeanNames.length != 0) { logger.warn("Multiple ScheduledExecutorService found, do not know which one to use."); } } else { logger.debug( "Registering default TaskScheduler with existing ScheduledExecutorService {}", scheduledExecutorsBeanNames[0]); registry.registerBeanDefinition( DEFAULT_TASK_SCHEDULER_BEAN_NAME, rootBeanDefinition(ConcurrentTaskScheduler.class) .addPropertyReference("scheduledExecutor", scheduledExecutorsBeanNames[0]) .getBeanDefinition()); } }
198
329
527
<no_super_class>
lukas-krecan_ShedLock
ShedLock/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SchedulerLockConfigurationSelector.java
SchedulerLockConfigurationSelector
selectImports
class SchedulerLockConfigurationSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata metadata) {<FILL_FUNCTION_BODY>} }
AnnotationAttributes attributes = AnnotationAttributes.fromMap( metadata.getAnnotationAttributes(EnableSchedulerLock.class.getName(), false)); InterceptMode mode = attributes.getEnum("interceptMode"); if (mode == PROXY_METHOD) { return new String[] { AutoProxyRegistrar.class.getName(), LockConfigurationExtractorConfiguration.class.getName(), MethodProxyLockConfiguration.class.getName() }; } else if (mode == PROXY_SCHEDULER) { return new String[] { AutoProxyRegistrar.class.getName(), LockConfigurationExtractorConfiguration.class.getName(), SchedulerProxyLockConfiguration.class.getName(), RegisterDefaultTaskSchedulerPostProcessor.class.getName() }; } else { throw new UnsupportedOperationException("Unknown mode " + mode); }
45
211
256
<no_super_class>
lukas-krecan_ShedLock
ShedLock/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyLockConfiguration.java
SchedulerProxyLockConfiguration
proxyScheduledLockAopBeanPostProcessor
class SchedulerProxyLockConfiguration extends AbstractLockConfiguration { @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) SchedulerProxyScheduledLockAdvisor proxyScheduledLockAopBeanPostProcessor( @Lazy LockProvider lockProvider, @Lazy ExtendedLockConfigurationExtractor lockConfigurationExtractor) {<FILL_FUNCTION_BODY>} }
SchedulerProxyScheduledLockAdvisor advisor = new SchedulerProxyScheduledLockAdvisor( new DefaultLockManager(lockProvider, lockConfigurationExtractor)); advisor.setOrder(getOrder()); return advisor;
97
62
159
<methods>public void setImportMetadata(AnnotationMetadata) <variables>protected AnnotationAttributes annotationAttributes
lukas-krecan_ShedLock
ShedLock/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyScheduledLockAdvisor.java
LockingInterceptor
invoke
class LockingInterceptor implements MethodInterceptor { private final LockManager lockManager; private LockingInterceptor(LockManager lockManager) { this.lockManager = lockManager; } @Override public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>} }
Object[] arguments = invocation.getArguments(); if (arguments.length >= 1 && arguments[0] instanceof Runnable) { arguments[0] = new LockableRunnable((Runnable) arguments[0], lockManager); } else { logger.warn("Task scheduler first argument should be Runnable"); } return invocation.proceed();
88
94
182
<no_super_class>
lukas-krecan_ShedLock
ShedLock/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/StringToDurationConverter.java
StringToDurationConverter
convert
class StringToDurationConverter implements Converter<String, Duration> { static final StringToDurationConverter INSTANCE = new StringToDurationConverter(); private static final Pattern ISO8601 = Pattern.compile("^[\\+\\-]?P.*$"); private static final Pattern SIMPLE = Pattern.compile("^([\\+\\-]?\\d+)([a-zA-Z]{0,2})$"); private static final Map<String, ChronoUnit> UNITS; static { Map<String, ChronoUnit> units = new LinkedHashMap<>(); units.put("us", ChronoUnit.MICROS); units.put("ns", ChronoUnit.NANOS); units.put("ms", ChronoUnit.MILLIS); units.put("s", ChronoUnit.SECONDS); units.put("m", ChronoUnit.MINUTES); units.put("h", ChronoUnit.HOURS); units.put("d", ChronoUnit.DAYS); units.put("", ChronoUnit.MILLIS); UNITS = Collections.unmodifiableMap(units); } @Override public Duration convert(String source) {<FILL_FUNCTION_BODY>} private ChronoUnit getUnit(String value) { ChronoUnit unit = UNITS.get(value.toLowerCase()); Assert.state(unit != null, "Unknown unit '" + value + "'"); return unit; } }
try { if (ISO8601.matcher(source).matches()) { return Duration.parse(source); } Matcher matcher = SIMPLE.matcher(source); Assert.state(matcher.matches(), "'" + source + "' is not a valid duration"); long amount = Long.parseLong(matcher.group(1)); ChronoUnit unit = getUnit(matcher.group(2)); return Duration.of(amount, unit); } catch (Exception ex) { throw new IllegalStateException("'" + source + "' is not a valid duration", ex); }
388
158
546
<no_super_class>
RaiMan_SikuliX1
SikuliX1/API/src/main/java/jxgrabkey/JXGrabKey.java
JXGrabKey
addHotkeyListener
class JXGrabKey { private static final int SLEEP_WHILE_LISTEN_EXITS = 100; private static boolean debug; private static JXGrabKey instance; private static Thread thread; private static Vector<HotkeyListener> listeners = new Vector<HotkeyListener>(); /** * This constructor starts a seperate Thread for the main listen loop. */ private JXGrabKey() { thread = new Thread(){ @Override public void run() { listen(); debugCallback("-- listen()"); } }; thread.start(); } /** * Retrieves the singleton. Initializes it, if not yet done. * * @return */ public static synchronized JXGrabKey getInstance(){ if(instance == null){ instance = new JXGrabKey(); } return instance; } /** * Adds a HotkeyListener. * * @param listener */ public void addHotkeyListener(HotkeyListener listener){<FILL_FUNCTION_BODY>} /** * Removes a HotkeyListener. * * @param listener */ public void removeHotkeyListener(HotkeyListener listener){ if(listener == null){ throw new IllegalArgumentException("listener must not be null"); } JXGrabKey.listeners.remove(listener); } /** * Unregisters all hotkeys, removes all HotkeyListeners, * stops the main listen loop and deinitializes the singleton. */ public void cleanUp(){ clean(); if(thread.isAlive()){ while(thread.isAlive()){ try { Thread.sleep(SLEEP_WHILE_LISTEN_EXITS); } catch (InterruptedException e) { debugCallback("cleanUp() - InterruptedException: "+e.getMessage()); } } instance = null; //next time getInstance is called, reinitialize JXGrabKey } if(listeners.size() > 0){ listeners.clear(); } } /** * Registers a X11 hotkey. * * @param id * @param x11Mask * @param x11Keysym * @throws jxgrabkey.HotkeyConflictException */ public void registerX11Hotkey(int id, int x11Mask, int x11Keysym) throws HotkeyConflictException{ registerHotkey(id, x11Mask, x11Keysym); } /** * Converts an AWT hotkey into a X11 hotkey and registers it. * * @param id * @param awtMask * @param awtKey * @throws jxgrabkey.HotkeyConflictException */ public void registerAwtHotkey(int id, int awtMask, int awtKey) throws HotkeyConflictException{ debugCallback("++ registerAwtHotkey("+id+", 0x"+ Integer.toHexString(awtMask)+", 0x"+ Integer.toHexString(awtKey)+")"); int x11Mask = X11MaskDefinitions.awtMaskToX11Mask(awtMask); int x11Keysym = X11KeysymDefinitions.awtKeyToX11Keysym(awtKey); debugCallback("registerAwtHotkey() - converted AWT mask '"+ KeyEvent.getKeyModifiersText(awtMask)+"' (0x"+Integer.toHexString(awtMask)+ ") to X11 mask (0x"+Integer.toHexString(x11Mask)+")"); debugCallback("registerAwtHotkey() - converted AWT key '"+ KeyEvent.getKeyText(awtKey)+"' (0x"+Integer.toHexString(awtKey)+ ") to X11 keysym (0x"+Integer.toHexString(x11Keysym)+")"); registerHotkey(id, x11Mask, x11Keysym); debugCallback("-- registerAwtHotkey()"); } /** * Enables/Disables printing of debug messages. * * @param enabled */ public static void setDebugOutput(boolean enabled){ debug = enabled; setDebug(enabled); } /** * Notifies HotkeyListeners about a received KeyEvent. * * This method is used by the C++ code. * Do not use this method from externally. * * @param id */ public static void fireKeyEvent(int id){ for(int i = 0; i < listeners.size(); i++){ listeners.get(i).onHotkey(id); } } /** * Either gives debug messages to a HotkeyListenerDebugEnabled if registered, * or prints to console otherwise. * Does only print if debug is enabled. * * This method is both used by the C++ and Java code, so it should not be synchronized. * Don't use this method from externally. * * @param debugmessage */ public static void debugCallback(String debugmessage){ if(debug){ debugmessage.trim(); if(debugmessage.charAt(debugmessage.length()-1) != '\n'){ debugmessage += "\n"; }else{ while(debugmessage.endsWith("\n\n")){ debugmessage = debugmessage.substring(0, debugmessage.length()-1); } } boolean found = false; for(HotkeyListener l : listeners){ if(l instanceof HotkeyListenerDebugEnabled){ ((HotkeyListenerDebugEnabled)l).debugCallback(debugmessage); found = true; } } if(found == false){ System.out.print(debugmessage); } } } /** * This method unregisters a hotkey. * If the hotkey is not yet registered, nothing will happen. * * @param id */ public native void unregisterHotKey(int id); private native void listen(); private static native void setDebug(boolean debug); private native void clean(); private native void registerHotkey(int id, int mask, int key) throws HotkeyConflictException; }
if(listener == null){ throw new IllegalArgumentException("listener must not be null"); } JXGrabKey.listeners.add(listener);
1,653
45
1,698
<no_super_class>
RaiMan_SikuliX1
SikuliX1/API/src/main/java/jxgrabkey/X11MaskDefinitions.java
X11MaskDefinitions
awtMaskToX11Mask
class X11MaskDefinitions { public static final int X11_SHIFT_MASK = 1 << 0; public static final int X11_LOCK_MASK = 1 << 1; public static final int X11_CONTROL_MASK = 1 << 2; public static final int X11_MOD1_MASK = 1 << 3; public static final int X11_MOD2_MASK = 1 << 4; public static final int X11_MOD3_MASK = 1 << 5; public static final int X11_MOD4_MASK = 1 << 6; public static final int X11_MOD5_MASK = 1 << 7; private X11MaskDefinitions() { } /** * Converts an AWT mask into a X11 mask. * * @param awtMask * @return */ public static int awtMaskToX11Mask(int awtMask) {<FILL_FUNCTION_BODY>} }
int x11Mask = 0; if ((awtMask & InputEvent.SHIFT_MASK) != 0 || (awtMask & InputEvent.SHIFT_DOWN_MASK) != 0) { x11Mask |= X11MaskDefinitions.X11_SHIFT_MASK; } if ((awtMask & InputEvent.ALT_MASK) != 0 || (awtMask & InputEvent.ALT_DOWN_MASK) != 0) { x11Mask |= X11MaskDefinitions.X11_MOD1_MASK; } if ((awtMask & InputEvent.CTRL_MASK) != 0 || (awtMask & InputEvent.CTRL_DOWN_MASK) != 0) { x11Mask |= X11MaskDefinitions.X11_CONTROL_MASK; } if ((awtMask & InputEvent.META_MASK) != 0 || (awtMask & InputEvent.META_DOWN_MASK) != 0) { x11Mask |= X11MaskDefinitions.X11_MOD2_MASK; } if ((awtMask & InputEvent.ALT_GRAPH_MASK) != 0 || (awtMask & InputEvent.ALT_GRAPH_DOWN_MASK) != 0) { x11Mask |= X11MaskDefinitions.X11_MOD5_MASK; } return x11Mask;
263
381
644
<no_super_class>
RaiMan_SikuliX1
SikuliX1/API/src/main/java/org/sikuli/basics/GenericHotkeyManager.java
GenericHotkeyManager
_removeHotkey
class GenericHotkeyManager extends HotkeyManager { HotkeyController controller = null; @Override public boolean _addHotkey(int keyCode, int modifiers, HotkeyListener callback) { if (controller == null) { controller = HotkeyController.get(); } return !controller.addHotkey(callback, keyCode, modifiers).isEmpty(); } @Override public boolean _removeHotkey(int keyCode, int modifiers) {<FILL_FUNCTION_BODY>} @Override public int _removeAll(Map<String, Integer[]> hotkeys, boolean isTerminating) { if (controller == null) { return 0; } controller.setTerminating(isTerminating); for (Integer[] keyMods : hotkeys.values()) { if (!controller.removeHotkey(keyMods[0], keyMods[1])) { return -1; } } return hotkeys.size(); } @Override public void cleanUp() { if (controller != null) { controller.stop(); } } }
if (controller == null) { return false; } return controller.removeHotkey(keyCode, modifiers);
288
35
323
<methods>public non-sealed void <init>() ,public abstract boolean _addHotkey(int, int, org.sikuli.basics.HotkeyListener) ,public abstract int _removeAll(Map<java.lang.String,java.lang.Integer[]>, boolean) ,public abstract boolean _removeHotkey(int, int) ,public boolean addHotkey(java.lang.String, org.sikuli.basics.HotkeyListener) ,public boolean addHotkey(char, int, org.sikuli.basics.HotkeyListener) ,public boolean addHotkey(java.lang.String, int, org.sikuli.basics.HotkeyListener) ,public abstract void cleanUp() ,public java.lang.String getHotKeyText(java.lang.String) ,public static org.sikuli.basics.HotkeyManager getInstance() ,public boolean removeHotkey(java.lang.String) ,public boolean removeHotkey(char, int) ,public boolean removeHotkey(java.lang.String, int) ,public static void reset(boolean) <variables>private static final java.lang.String HotkeyTypeAbort,private static int HotkeyTypeAbortKey,private static int HotkeyTypeAbortMod,private static final java.lang.String HotkeyTypeCapture,private static int HotkeyTypeCaptureKey,private static int HotkeyTypeCaptureMod,private static org.sikuli.basics.HotkeyManager _instance,private static Map<java.lang.String,java.lang.Integer[]> hotkeys,private static Map<java.lang.String,java.lang.Integer[]> hotkeysGlobal
RaiMan_SikuliX1
SikuliX1/API/src/main/java/org/sikuli/basics/HotkeyListener.java
HotkeyListener
invokeHotkeyPressed
class HotkeyListener { /** * Override this to implement your own hotkey handler. * * @param e HotkeyEvent */ abstract public void hotkeyPressed(HotkeyEvent e); /** * INTERNAL USE: system specific handler implementation * * @param e HotkeyEvent */ public void invokeHotkeyPressed(final HotkeyEvent e) {<FILL_FUNCTION_BODY>} }
Thread hotkeyThread = new Thread() { @Override public void run() { hotkeyPressed(e); } }; hotkeyThread.start();
116
48
164
<no_super_class>
RaiMan_SikuliX1
SikuliX1/API/src/main/java/org/sikuli/basics/LinuxHotkeyManager.java
MyHotkeyHandler
_addHotkey
class MyHotkeyHandler implements jxgrabkey.HotkeyListener { public void onHotkey(int id) { Debug.log(4, "Hotkey pressed"); HotkeyData data = _idCallbackMap.get(id); HotkeyEvent e = new HotkeyEvent(data.key, data.modifiers); data.listener.invokeHotkeyPressed(e); } } ; private Map<Integer, HotkeyData> _idCallbackMap = new HashMap<Integer, HotkeyData>(); private int _gHotkeyId = 1; public boolean _addHotkey(int keyCode, int modifiers, HotkeyListener listener) {<FILL_FUNCTION_BODY>
JXGrabKey grabKey = JXGrabKey.getInstance(); if (_gHotkeyId == 1) { grabKey.addHotkeyListener(new MyHotkeyHandler()); } _removeHotkey(keyCode, modifiers); int id = _gHotkeyId++; HotkeyData data = new HotkeyData(keyCode, modifiers, listener); _idCallbackMap.put(id, data); try { //JXGrabKey.setDebugOutput(true); grabKey.registerAwtHotkey(id, modifiers, keyCode); } catch (HotkeyConflictException e) { Debug.error("Hot key conflicts"); return false; } return true;
179
187
366
<methods>public non-sealed void <init>() ,public abstract boolean _addHotkey(int, int, org.sikuli.basics.HotkeyListener) ,public abstract int _removeAll(Map<java.lang.String,java.lang.Integer[]>, boolean) ,public abstract boolean _removeHotkey(int, int) ,public boolean addHotkey(java.lang.String, org.sikuli.basics.HotkeyListener) ,public boolean addHotkey(char, int, org.sikuli.basics.HotkeyListener) ,public boolean addHotkey(java.lang.String, int, org.sikuli.basics.HotkeyListener) ,public abstract void cleanUp() ,public java.lang.String getHotKeyText(java.lang.String) ,public static org.sikuli.basics.HotkeyManager getInstance() ,public boolean removeHotkey(java.lang.String) ,public boolean removeHotkey(char, int) ,public boolean removeHotkey(java.lang.String, int) ,public static void reset(boolean) <variables>private static final java.lang.String HotkeyTypeAbort,private static int HotkeyTypeAbortKey,private static int HotkeyTypeAbortMod,private static final java.lang.String HotkeyTypeCapture,private static int HotkeyTypeCaptureKey,private static int HotkeyTypeCaptureMod,private static org.sikuli.basics.HotkeyManager _instance,private static Map<java.lang.String,java.lang.Integer[]> hotkeys,private static Map<java.lang.String,java.lang.Integer[]> hotkeysGlobal
RaiMan_SikuliX1
SikuliX1/API/src/main/java/org/sikuli/basics/Settings.java
Settings
setShowActions
class Settings { public static boolean experimental = false; public static boolean FindProfiling = false; public static boolean InputFontMono = false; public static int InputFontSize = 14; //TODO Proxy as command line options public static String proxyName = ""; public static String proxyIP = ""; public static InetAddress proxyAddress = null; public static String proxyPort = ""; public static boolean proxyChecked = false; public static Proxy proxy = null; public static boolean ThrowException = true; // throw FindFailed exception public static float AutoWaitTimeout = 3f; // in seconds public static float WaitScanRate = 3f; // frames per second public static float ObserveScanRate = 3f; // frames per second public static int ObserveMinChangedPixels = 50; // in pixels public static int RepeatWaitTime = 1; // wait 1 second for visual to vanish after action public static double MinSimilarity = 0.7; public static float AlwaysResize = 0; public static int DefaultPadding = 50; public static boolean AutoDetectKeyboardLayout = true; public static boolean CheckLastSeen = true; public static float CheckLastSeenSimilar = 0.95f; public static org.sikuli.script.ImageCallback ImageCallback = null; private static int ImageCache = 64; public static void setImageCache(int max) { if (ImageCache > max) { Image.clearCache(max); } ImageCache = max; } public static int getImageCache() { return ImageCache; } public static double DelayValue = 0.3; public static double DelayBeforeMouseDown = DelayValue; public static double DelayAfterDrag = DelayValue; public static double DelayBeforeDrag = -DelayValue; public static double DelayBeforeDrop = DelayValue; // setting to false reverses the wheel direction public static boolean WheelNatural = true; //setting to false supresses error message in RobotDesktop public static boolean checkMousePosition = true; /** * Specify a delay between the key presses in seconds as 0.nnn. This only * applies to the next type and is then reset to 0 again. A value &gt; 1 is cut * to 1.0 (max delay of 1 second) */ public static double TypeDelay = 0.0; /** * Specify a delay between the mouse down and up in seconds as 0.nnn. This * only applies to the next click action and is then reset to 0 again. A value * &gt; 1 is cut to 1.0 (max delay of 1 second) */ public static double ClickDelay = 0.0; public static boolean ClickTypeHack = false; public static String BundlePath = null; public static boolean OverwriteImages = false; public static final String OcrLanguageDefault = "eng"; public static String OcrLanguage = OcrLanguageDefault; public static String OcrDataPath = null; public static boolean OcrTextSearch = true; public static boolean OcrTextRead = true; public static boolean SwitchToText = false; public static boolean TRUE = true; public static boolean FALSE = false; public static float SlowMotionDelay = 2.0f; // in seconds public static float MoveMouseDelay = 0.5f; // in seconds private static float MoveMouseDelaySaved = MoveMouseDelay; private static boolean ShowActions = false; public static boolean isShowActions() { return ShowActions; } public static void setShowActions(boolean ShowActions) {<FILL_FUNCTION_BODY>} /** * true = highlight every match (default: false) (show red rectangle around) * for DefaultHighlightTime seconds (default: 2) */ public static boolean Highlight = false; public static float DefaultHighlightTime = 2f; public static String DefaultHighlightColor = "RED"; public static boolean HighlightTransparent = false; public static double WaitAfterHighlight = 0.3; public static boolean ActionLogs = true; public static boolean InfoLogs = true; public static boolean DebugLogs = false; public static boolean ProfileLogs = false; public static boolean TraceLogs = false; public static boolean LogTime = false; public static boolean UserLogs = true; public static String UserLogPrefix = "user"; public static boolean UserLogTime = true; public static String getFilePathSeperator() { return File.separator; } public static String getPathSeparator() { if (isWindows()) { return ";"; } return ":"; } public static String getDataPath() { return Commons.getAppDataPath().getAbsolutePath(); } public static final int ISWINDOWS = 0; public static final int ISMAC = 1; public static final int ISLINUX = 2; public static OS getOS() { if (isWindows()) { return OS.WINDOWS; } else if (isMac()) { return OS.MAC; } else if (isLinux()) { return OS.LINUX; } else { return OS.NOT_SUPPORTED; } } public static boolean isWindows() { return Commons.runningWindows(); } public static boolean isLinux() { return Commons.runningLinux(); } public static boolean isMac() { return Commons.runningMac(); } public static String getOSVersion() { return System.getProperty("os.version"); } public static String getTimestamp() { return (new Date()).getTime() + ""; } public static String getVersion() { return Commons.getSXVersion(); } public static String getVersionBuild() { return Commons.getSXVersionLong(); } }
if (ShowActions) { MoveMouseDelaySaved = MoveMouseDelay; } else { MoveMouseDelay = MoveMouseDelaySaved; } Settings.ShowActions = ShowActions;
1,523
53
1,576
<no_super_class>
RaiMan_SikuliX1
SikuliX1/API/src/main/java/org/sikuli/guide/AnimationFactory.java
NewAnimator
actionPerformed
class NewAnimator implements ActionListener { Timer timer; boolean looping = false; boolean animationRunning = false; Visual sklComponent; NewAnimator(Visual sklComponent) { this.sklComponent = sklComponent; } protected void init() { } public void start() { init(); timer = new Timer(25, this); timer.start(); animationRunning = true; } protected boolean isRunning() { return animationRunning; } public void setLooping(boolean looping) { this.looping = looping; } AnimationListener listener; public void setListener(AnimationListener listener) { this.listener = listener; } protected void animate() { } @Override public void actionPerformed(ActionEvent e) {<FILL_FUNCTION_BODY>} }
if (isRunning()) { Rectangle r = sklComponent.getBounds(); //setActualLocation((int) x, (int) y); animate(); r.add(sklComponent.getBounds()); if (sklComponent.getTopLevelAncestor() != null) { sklComponent.getTopLevelAncestor().repaint(r.x, r.y, r.width, r.height); } } else { timer.stop(); if (looping) { start(); } else { animationRunning = false; if (listener != null) { listener.animationCompleted(); } } }
242
185
427
<no_super_class>
RaiMan_SikuliX1
SikuliX1/API/src/main/java/org/sikuli/guide/Animator.java
CircleAnimatoOld
actionPerformed
class CircleAnimatoOld extends Animator{ int repeatCount; int count; LinearInterpolation funcr; Point origin; int radius; public CircleAnimatoOld(Visual comp, int radius){ super(comp); repeatCount = duration / cycle; count = 0; funcr = new LinearInterpolation(0,(float) (2*Math.PI),repeatCount); origin = comp.getLocation(); this.radius = radius; } @Override public void actionPerformed(ActionEvent e) {<FILL_FUNCTION_BODY>} }
float r = funcr.getValue(count); int x = (int) (origin.x + (int) radius * Math.sin(r)); int y= (int) (origin.y + (int) radius * Math.cos(r)); Point p = new Point(x,y); Rectangle r1 = comp.getBounds(); comp.setLocation(p); // r1 stores the union of the bounds before/after the animated step Rectangle r2 = comp.getBounds(); r1.add(r2); comp.getParent().getParent().repaint(r1.x,r1.y,r1.width,r1.height); //repaint(r1); // comp.getParent().invalidate(); // comp.repaint(); if (count == repeatCount) count = 0; else count++;
165
232
397
<methods>public void <init>(org.sikuli.guide.Visual) ,public boolean isPlayed() ,public boolean isRunning() ,public void start() ,public void stop() <variables>org.sikuli.guide.Visual comp,int cycle,int duration,boolean played,javax.swing.Timer timer
RaiMan_SikuliX1
SikuliX1/API/src/main/java/org/sikuli/guide/ClickableWindow.java
ClickableWindow
toFront
class ClickableWindow extends OverlayTransparentWindow implements MouseListener, Transition, GlobalMouseMotionListener { Guide guide; JPanel jp = null; ArrayList<SxClickable> clickables = new ArrayList<SxClickable>(); private SxClickable lastClicked; private Rectangle maxR; Point clickLocation; GlobalMouseMotionTracker mouseTracker; TransitionListener token; Cursor handCursor = new Cursor(Cursor.HAND_CURSOR); Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR); Cursor hourglassCursor = new Cursor(Cursor.WAIT_CURSOR); Cursor currentCursor = null; public ClickableWindow(Guide guide) { super(new Color(0.1f, 0f, 0f, 0.005f), null); this.guide = guide; jp = getJPanel(); mouseTracker = GlobalMouseMotionTracker.getInstance(); mouseTracker.addListener(this); setVisible(false); setFocusableWindowState(false); addMouseListener(this); addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { // stop the global mouse tracker's timer thread mouseTracker.stop(); } }); } @Override public void toFront() {<FILL_FUNCTION_BODY>} public void addClickable(SxClickable c) { clickables.add(c); SxClickable c1 = new SxClickable(null); c1.setLocationRelativeToComponent(c, Layout.OVER); jp.add(c1); } public void addClickableRegion(Region region, String name) { SxClickable c = new SxClickable(region); c.setName(name); addClickable(c); } @Override public void mouseClicked(MouseEvent e) { Debug.log("[ClickableWindow] clicked on " + e.getX() + "," + e.getY()); Point p = e.getPoint(); lastClicked = null; for (SxClickable c : clickables) { if (c.getActualBounds().contains(p)) { lastClicked = c; p.x -= c.getX(); p.y -= c.getY(); c.globalMouseClicked(p); } } if (lastClicked != null) { if (token != null) { setVisible(false); token.transitionOccurred(this); } } } //<editor-fold defaultstate="collapsed" desc="MouseEvents not used"> @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseReleased(MouseEvent arg0) { } //</editor-fold> @Override public String waitForTransition(TransitionListener token) { this.token = token; maxR = clickables.get(0).getBounds(); if (clickables.size() > 1) { for (SxClickable c : clickables.subList(1, clickables.size())) { maxR = maxR.union(c.getActualBounds()); } } setBounds(maxR); setVisible(true); mouseTracker.start(); return "Next"; } @Override public void globalMouseMoved(int x, int y) { Point p = new Point(x, y); SxClickable cc = null; for (SxClickable c : clickables) { if (c.getBounds().contains(p)) { c.setMouseOver(true); cc = c; } else { c.setMouseOver(false); } } //TODO keep moving to (0,0) to nullify the dragged move bug if (cc != null) { setLocation(0, 0); setSize(cc.getActualLocation().x+cc.getActualWidth(), cc.getActualLocation().y+cc.getActualHeight()); } else { setBounds(maxR); } } @Override public void globalMouseIdled(int x, int y) { } public SxClickable getLastClicked() { return lastClicked; } public ArrayList<SxClickable> getClickables() { return clickables; } public void clear() { clickables.clear(); getContentPane().removeAll(); } }
// if (Settings.isMac()) { // // this call is necessary to allow clicks to go through the window (ignoreMouse == true) // if (Guide.JavaVersion < 7) { // SysUtil.getOSUtil().bringWindowToFront(this, true); // } else { // } // } super.toFront();
1,249
94
1,343
<methods>public void <init>() ,public void <init>(java.awt.Color, org.sikuli.util.EventObserver) ,public void addObserver(org.sikuli.util.EventObserver) ,public void close() ,public javax.swing.JPanel getJPanel() ,public java.awt.Graphics2D getJPanelGraphics() ,public void notifyObserver() ,public void setOpacity(float) <variables>private java.awt.Color _col,private java.awt.Graphics2D _currG2D,private org.sikuli.util.EventObserver _obs,private javax.swing.JPanel _panel,private org.sikuli.util.OverlayTransparentWindow _win
RaiMan_SikuliX1
SikuliX1/API/src/main/java/org/sikuli/guide/GlobalMouseMotionTracker.java
GlobalMouseMotionTracker
actionPerformed
class GlobalMouseMotionTracker implements ActionListener { final static int IDLE_COUNT_THRESHOLD = 200; // this keeps track of how many times the cursor stays stationary int idle_count; Location lastLocation = null; static GlobalMouseMotionTracker _instance = null; static public GlobalMouseMotionTracker getInstance(){ if (_instance == null){ _instance = new GlobalMouseMotionTracker(); } return _instance; } ArrayList<GlobalMouseMotionListener> listeners = new ArrayList<GlobalMouseMotionListener>(); public void addListener(GlobalMouseMotionListener listener){ listeners.add(listener); } Timer timer; private GlobalMouseMotionTracker(){ timer = new Timer(10, this); } public void start(){ timer.start(); //Debug.info("[GlobalMouseMotionTracker] started"); } public void stop(){ timer.stop(); //Debug.info("[GlobalMouseMotionTracker] stopped"); } @Override public void actionPerformed(ActionEvent arg) {<FILL_FUNCTION_BODY>} }
Location newLocation = Env.getMouseLocation(); //Debug.info("Mouse loction: " + newLocation); if (lastLocation != null){ if (lastLocation.x != newLocation.x || lastLocation.y != newLocation.y){ for (GlobalMouseMotionListener listener : listeners){ listener.globalMouseMoved(newLocation.x,newLocation.y); } idle_count = 0; }else{ idle_count++; } //Debug.info("idle: " + idle_count); if (idle_count > IDLE_COUNT_THRESHOLD){ for (GlobalMouseMotionListener listener : listeners){ listener.globalMouseIdled(newLocation.x,newLocation.y); } idle_count = 0; } } lastLocation = newLocation;
306
230
536
<no_super_class>
RaiMan_SikuliX1
SikuliX1/API/src/main/java/org/sikuli/guide/HTMLTextPane.java
HTMLTextPane
setText
class HTMLTextPane extends JTextPane { int maximum_width; String text; public Dimension preferredDimension; Visual comp = null; String htmltxt; public HTMLTextPane(Visual comp) { this.comp = comp; maximum_width = comp.maxWidth - 10; init(); } public HTMLTextPane() { maximum_width = 400; init(); } private void init() { setContentType("text/html"); } @Override public void setText(String text) {<FILL_FUNCTION_BODY>} @Override public String getText() { return this.text; } }
this.text = text; if (comp != null) { maximum_width = comp.maxWidth - 2 * comp.PADDING_X; htmltxt = "<html><div style='" + comp.getStyleString() + "'>" + text + "</div></html>"; } else { htmltxt = "<html><font size=5>"+text+"</font></html>"; } super.setText(htmltxt); JTextPane tp = new JTextPane(); tp.setText(htmltxt); if (getPreferredSize().getWidth() > maximum_width) { // hack to limit the width of the text to width if (comp != null) { htmltxt = "<html><div style='width:" + maximum_width + ";" + comp.getStyleString() + "'>" + text + "</div></html>"; } else { htmltxt = "<html><div width='"+maximum_width+"'><font size=5>"+text+"</font></div></html>"; } super.setText(htmltxt); } setSize(getPreferredSize());
188
308
496
<methods>public void <init>() ,public void <init>(javax.swing.text.StyledDocument) ,public javax.swing.text.Style addStyle(java.lang.String, javax.swing.text.Style) ,public javax.swing.text.AttributeSet getCharacterAttributes() ,public javax.swing.text.MutableAttributeSet getInputAttributes() ,public javax.swing.text.Style getLogicalStyle() ,public javax.swing.text.AttributeSet getParagraphAttributes() ,public javax.swing.text.Style getStyle(java.lang.String) ,public javax.swing.text.StyledDocument getStyledDocument() ,public java.lang.String getUIClassID() ,public void insertComponent(java.awt.Component) ,public void insertIcon(javax.swing.Icon) ,public void removeStyle(java.lang.String) ,public void replaceSelection(java.lang.String) ,public void setCharacterAttributes(javax.swing.text.AttributeSet, boolean) ,public void setDocument(javax.swing.text.Document) ,public final void setEditorKit(javax.swing.text.EditorKit) ,public void setLogicalStyle(javax.swing.text.Style) ,public void setParagraphAttributes(javax.swing.text.AttributeSet, boolean) ,public void setStyledDocument(javax.swing.text.StyledDocument) <variables>private static final java.lang.String uiClassID
RaiMan_SikuliX1
SikuliX1/API/src/main/java/org/sikuli/guide/Run.java
Run
testButton
class Run { Guide guide = null; static Screen scr; static Visual sgc; public static void main(String[] args) throws FindFailed { Run sgr = new Run(); sgr.scr = new Screen(); ImagePath.add("org.sikuli.script.RunTime/ImagesAPI.sikuli"); sgr.setUp(); sgr.testButton(); sgr.tearDown(); } private void setUp() { guide = new Guide(); // App.focus("safari"); } private void tearDown() { System.out.println(guide.showNow(2f)); guide = null; } public void testButton() throws FindFailed {<FILL_FUNCTION_BODY>} }
Debug.on(3); Visual vis = guide.text("text"); // vis.setTarget(scr.getCenter().grow(100)); String img = "idea"; // Match match = scr.find(img); // match.highlight(2); vis.setTarget(img); vis.setLayout(Visual.Layout.RIGHT); vis.setTextColor(Color.red); // g.setLocationRelativeToRegion(scr.getCenter().grow(100), Visual.Layout.BOTTOM); // g.setFontSize(12); // g.setColor(Color.white); // g.setTextColor(Color.black);
202
177
379
<no_super_class>
RaiMan_SikuliX1
SikuliX1/API/src/main/java/org/sikuli/guide/ShadowRenderer.java
ShadowRenderer
createShadowImage
class ShadowRenderer { Visual source; public ShadowRenderer(Visual source, int shadowSize){ this.source = source; sourceActualSize = source.getActualSize(); this.shadowSize = shadowSize; } float shadowOpacity = 0.8f; int shadowSize = 10; Color shadowColor = Color.black; BufferedImage createShadowMask(BufferedImage image){ BufferedImage mask = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = mask.createGraphics(); g2d.drawImage(image, 0, 0, null); // Ar = As*Ad - Cr = Cs*Ad -> extract 'Ad' g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, shadowOpacity)); g2d.setColor(shadowColor); g2d.fillRect(0, 0, image.getWidth(), image.getHeight()); g2d.dispose(); return mask; } ConvolveOp getBlurOp(int size) { float[] data = new float[size * size]; float value = 1 / (float) (size * size); for (int i = 0; i < data.length; i++) { data[i] = value; } return new ConvolveOp(new Kernel(size, size, data)); } BufferedImage shadowImage = null; Dimension sourceActualSize = null; public BufferedImage createShadowImage(){<FILL_FUNCTION_BODY>} public void paintComponent(Graphics g){ Graphics2D g2d = (Graphics2D)g; // create shadow image if the size of the source component has changed since last rendering attempt if (shadowImage == null || source.getActualHeight() != sourceActualSize.height || source.getActualWidth() != sourceActualSize.width){ createShadowImage(); sourceActualSize = source.getActualSize(); } //Debug.info("[Shadow] painting shadow" + shadowImage); g2d.drawImage(shadowImage, 0, 0, null, null); } }
BufferedImage image = new BufferedImage(source.getActualWidth() + shadowSize * 2, source.getActualHeight() + shadowSize * 2, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); g2.translate(shadowSize,shadowSize); source.paintPlain(g2); shadowImage = new BufferedImage(image.getWidth(),image.getHeight(),BufferedImage.TYPE_INT_ARGB); getBlurOp(shadowSize).filter(createShadowMask(image), shadowImage); g2.dispose(); //Debug.info("[Shadow] shadowImage: " + shadowImage); return shadowImage;
571
182
753
<no_super_class>
RaiMan_SikuliX1
SikuliX1/API/src/main/java/org/sikuli/guide/SxAnchor.java
SxAnchor
startTracking
class SxAnchor extends Visual { Region region; ArrayList<AnchorListener> listeners = new ArrayList<AnchorListener>(); private boolean animateAnchoring = false; Pattern pattern = null; Tracker tracker = null; public SxAnchor() { super(); setForeground(Color.black); } public SxAnchor(Pattern pattern) { super(); this.pattern = pattern; setTracker(pattern); } public SxAnchor(Region region) { super(); if (region != null) { this.region = region; setActualBounds(region.getRect()); } setForeground(Color.black); } public Pattern getPattern() { return pattern; } public void setAnimateAnchoring(boolean animateAnchoring) { this.animateAnchoring = animateAnchoring; } public boolean isAnimateAnchoring() { return animateAnchoring; } public interface AnchorListener { public void anchored(); public void found(SxAnchor source); // public class AnchorAdapter implements AnchorListener { // public void anchored(){}; // public void found(){}; // } } public void addListener(AnchorListener listener) { listeners.add(listener); } public void found(Rectangle bounds) { for (AnchorListener listener : listeners) { listener.found(this); } if (isAnimateAnchoring()) { Point center = new Point(); center.x = (int) (bounds.x + bounds.width / 2); center.y = (int) (bounds.y + bounds.height / 2); moveTo(center, new AnimationListener() { public void animationCompleted() { anchored(); } }); } else { setActualLocation(bounds.x, bounds.y); anchored(); } } public void anchored() { for (AnchorListener listener : listeners) { listener.anchored(); } // this implements the default behavior for fadein entrance when // the anchor pattern is found and anchored for the first time addFadeinAnimation(); startAnimation(); } public void setTracker(Pattern pattern) { setOpacity(0f); tracker = new Tracker(pattern); BufferedImage img; try { img = pattern.getBImage(); setActualSize(img.getWidth(), img.getHeight()); tracker.setAnchor(this); } catch (Exception e) { e.printStackTrace(); } } public void startTracking() {<FILL_FUNCTION_BODY>} public void stopTracking() { if (tracker != null) { tracker.stopTracking(); } } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; //<editor-fold defaultstate="collapsed" desc="TODO not used currently"> /* if (editable) { * if (true) { * Rectangle r = getActualBounds(); * g2d.setColor(getForeground()); * g2d.drawRect(0, 0, r.width - 1, r.height - 1); * g2d.setColor(Color.white); * g2d.drawRect(1, 1, r.width - 3, r.height - 3); * g2d.setColor(getForeground()); * g2d.drawRect(2, 2, r.width - 5, r.height - 5); * g2d.setColor(Color.white); * g2d.drawRect(3, 3, r.width - 7, r.height - 7); * } else { * Rectangle r = getActualBounds(); * g2d.setColor(Color.red); * g2d.setStroke(new BasicStroke(3f)); * g2d.drawRect(1, 1, r.width - 3, r.height - 3); * } * }*/ //</editor-fold> } }
if (tracker != null) { //Debug.info("[SxAnchor] start tracking"); tracker.start(); }
1,131
40
1,171
<methods>public void <init>() ,public org.sikuli.guide.Visual above() ,public org.sikuli.guide.Visual above(int) ,public void addAnimation(org.sikuli.guide.NewAnimator) ,public void addAnimationListener(org.sikuli.guide.AnimationListener) ,public void addCircleAnimation(java.awt.Point, float) ,public void addFadeinAnimation() ,public void addFadeoutAnimation() ,public void addFollower(org.sikuli.guide.Visual) ,public void addMoveAnimation(java.awt.Point, java.awt.Point) ,public void addResizeAnimation(java.awt.Dimension, java.awt.Dimension) ,public void addSlideAnimation(java.awt.Point, org.sikuli.guide.Visual.Layout) ,public void animationCompleted() ,public org.sikuli.guide.Visual below() ,public org.sikuli.guide.Visual below(int) ,public java.lang.Object clone() ,public org.sikuli.guide.Animator createMoveAnimator(int, int) ,public org.sikuli.guide.Animator createSlidingAnimator(int, int) ,public java.awt.Rectangle getActualBounds() ,public int getActualHeight() ,public java.awt.Point getActualLocation() ,public java.awt.Dimension getActualSize() ,public int getActualWidth() ,public java.awt.Point getCenter() ,public static java.lang.String getColorHex(java.awt.Color) ,public java.awt.Rectangle getFollowerBounds() ,public ArrayList<org.sikuli.guide.Visual> getFollowers() ,public org.sikuli.guide.Visual getLeader() ,public org.sikuli.script.Region getRegion() ,public org.sikuli.script.Region getTarget() ,public java.lang.String getText() ,public boolean isAutoLayoutEnabled() ,public boolean isAutoMoveEnabled() ,public boolean isAutoResizeEnabled() ,public boolean isAutoVisibilityEnabled() ,public org.sikuli.guide.Visual left() ,public org.sikuli.guide.Visual left(int) ,public void moveTo(java.awt.Point) ,public void moveTo(java.awt.Point, org.sikuli.guide.AnimationListener) ,public void offsetLocation(int, int) ,public void paint(java.awt.Graphics) ,public void paintPlain(java.awt.Graphics) ,public void popin() ,public void popout() ,public void removeFollower(org.sikuli.guide.Visual) ,public void removeFrom(java.awt.Container) ,public void removeFromLeader() ,public void resizeTo(java.awt.Dimension) ,public org.sikuli.guide.Visual right() ,public org.sikuli.guide.Visual right(int) ,public void setActualBounds(java.awt.Rectangle) ,public void setActualLocation(java.awt.Point) ,public void setActualLocation(int, int) ,public void setActualSize(int, int) ,public void setActualSize(java.awt.Dimension) ,public void setAutoLayoutEnabled(boolean) ,public void setAutoMoveEnabled(boolean) ,public void setAutoResizeEnabled(boolean) ,public void setAutoVisibilityEnabled(boolean) ,public org.sikuli.guide.Visual setColor(java.awt.Color) ,public org.sikuli.guide.Visual setColor(int, int, int) ,public org.sikuli.guide.Visual setColors(java.awt.Color, java.awt.Color, java.awt.Color, java.awt.Color, java.awt.Color) ,public org.sikuli.guide.Visual setColors(int[], int[], int[], int[]) ,public void setEmphasisAnimation(org.sikuli.guide.Animator) ,public void setEntranceAnimation(org.sikuli.guide.Animator) ,public org.sikuli.guide.Visual setFont(java.lang.String, int) ,public org.sikuli.guide.Visual setFontSize(int) ,public void setGuide(org.sikuli.guide.Guide) ,public void setHorizontalAlignmentWithRegion(org.sikuli.script.Region, float) ,public org.sikuli.guide.Visual setLayout(org.sikuli.guide.Visual.Layout) ,public org.sikuli.guide.Visual setLocationRelative(org.sikuli.guide.Visual.Layout) ,public void setLocationRelativeToComponent(org.sikuli.guide.Visual, org.sikuli.guide.Visual.Layout) ,public void setLocationRelativeToComponent(org.sikuli.guide.Visual, int, int) ,public void setLocationRelativeToComponent(org.sikuli.guide.Visual, float, float) ,public void setLocationRelativeToComponent(org.sikuli.guide.Visual) ,public void setLocationRelativeToPoint(java.awt.Point, org.sikuli.guide.Visual.Layout) ,public org.sikuli.guide.Visual setLocationRelativeToRegion(org.sikuli.script.Region, org.sikuli.guide.Visual.Layout) ,public void setMargin(int, int, int, int) ,public org.sikuli.guide.Visual setMaxWidth(int) ,public void setMovable(boolean) ,public void setOffset(int, int) ,public void setOpacity(float) ,public org.sikuli.guide.Visual setScale(float) ,public void setShadow(int, int) ,public void setShadowDefault() ,public org.sikuli.guide.Visual setStroke(int) ,public org.sikuli.guide.Visual setTarget(RCPS) ,public org.sikuli.guide.Visual setText(java.lang.String) ,public org.sikuli.guide.Visual setTextColor(java.awt.Color) ,public org.sikuli.guide.Visual setTextColor(int, int, int) ,public void setVerticalAlignmentWithRegion(org.sikuli.script.Region, float) ,public void setVisible(boolean) ,public void setZoomLevel(float) ,public void startAnimation() ,public void stopAnimation() ,public java.lang.String toString() ,public void updateComponent() <variables>public int PADDING_X,public int PADDING_Y,private java.awt.Rectangle actualBounds,org.sikuli.guide.AnimationListener animationListener,boolean animationRunning,org.sikuli.guide.Visual.AnimationSequence animationSequence,private boolean autoLayoutEnabled,private boolean autoMoveEnabled,private boolean autoResizeEnabled,private boolean autoVisibilityEnabled,org.sikuli.guide.Visual.AutoLayout autolayout,org.sikuli.guide.ComponentMover cm,java.awt.Color color,java.awt.Color colorBack,java.awt.Color colorFrame,java.awt.Color colorFront,java.awt.Color colorText,org.sikuli.guide.Guide currentGuide,public org.sikuli.guide.Visual.Layout currentLayout,public static java.awt.Color defColor,public static java.awt.Color defColorBack,public static java.awt.Color defColorFrame,public static java.awt.Color defColorFront,public static java.awt.Color defColorText,public static java.lang.String defFont,public static int defFontSize,static int defMaxWidth,private int defShadowOffset,private int defShadowSize,public static int defStroke,org.sikuli.guide.Animator emphasis_anim,org.sikuli.guide.Animator entrance_anim,private ArrayList<org.sikuli.guide.Visual> followers,java.lang.String fontName,int fontSize,public boolean hasChanged,public org.sikuli.guide.Visual.Layout layout,org.sikuli.guide.Visual leader,org.sikuli.guide.Visual.Margin margin,int maxWidth,int offsetx,int offsety,float opacity,int shadowOffset,org.sikuli.guide.ShadowRenderer shadowRenderer,int shadowSize,int stroke,org.sikuli.guide.Visual targetComponent,org.sikuli.script.Pattern targetPattern,org.sikuli.script.Region targetRegion,java.lang.String text,float zoomLevel
RaiMan_SikuliX1
SikuliX1/API/src/main/java/org/sikuli/guide/SxArea.java
SxArea
componentMoved
class SxArea extends Visual implements ComponentListener{ ArrayList<Region> regions = new ArrayList<Region>(); ArrayList<Visual> landmarks = new ArrayList<Visual>(); public SxArea(){ super(); // default to transparent so it can be faded in when it becomes visible later setOpacity(0); } public static final int BOUNDING = 0; public static final int INTERSECTION = 1; int relationship = BOUNDING; public void setRelationship(int relationship){ this.relationship = relationship; } int mode = 0; public static int VERTICAL = 1; public static int HORIZONTAL = 2; public void setMode(int mode){ this.mode = mode; } // update the bounds to the union of all the rectangles void updateBounds(){ Rectangle rect = null; Screen s = new Screen(); for (Visual comp : landmarks){ if (rect == null){ rect = new Rectangle(comp.getBounds()); continue; }else { if (relationship == BOUNDING){ rect.add(comp.getBounds()); }else if (relationship == INTERSECTION){ rect = rect.intersection(comp.getBounds()); } } } if (rect.width<0 || rect.height<=0){ setVisible(false); }else{ setVisible(true); // for (Visual sklComp : getFollowers()) // hack to get the locations of the followers to update if (mode == 0){ setActualLocation(rect.x,rect.y); setActualSize(rect.getSize()); } else if (mode == VERTICAL){ setActualLocation(rect.x,0); setActualSize(rect.width, s.h); } else if (mode == HORIZONTAL){ setActualLocation(0, rect.y); setActualSize(s.w, rect.height); } } updateVisibility(); } public void addLandmark(Visual comp){ landmarks.add(comp); updateBounds(); comp.addComponentListener(this); } public void addRegion(Region region){ if (regions.isEmpty()){ setActualBounds(region.getRect()); }else{ Rectangle bounds = getBounds(); bounds.add(region.getRect()); setActualBounds(bounds); } regions.add(region); } public void paintComponent(Graphics g){ super.paintComponent(g); Graphics2D g2d = (Graphics2D)g; if (false){ Rectangle r = getActualBounds(); g2d.setColor(Color.black); g2d.drawRect(0,0,r.width-1,r.height-1); //g2d.setColor(Color.white); g2d.setColor(Color.green); g2d.setStroke(new BasicStroke(3f)); g2d.drawRect(1,1,r.width-3,r.height-3); } } private void updateVisibility(){ boolean allHidden = true; for (Visual landmark : landmarks){ allHidden = allHidden && !landmark.isVisible(); } if (allHidden){ //Debug.info("SxArea is hidden"); } setVisible(!allHidden); // if area is visible, do fadein if (isVisible()){ addFadeinAnimation(); startAnimation(); } } @Override public void componentHidden(ComponentEvent e) { updateVisibility(); } @Override public void componentMoved(ComponentEvent e) {<FILL_FUNCTION_BODY>} @Override public void componentResized(ComponentEvent e) { } @Override public void componentShown(ComponentEvent e) { setVisible(true); } }
Rectangle r = getBounds(); updateBounds(); r.add(getBounds()); if (getTopLevelAncestor() != null) getTopLevelAncestor().repaint(r.x,r.y,r.width,r.height);
1,063
72
1,135
<methods>public void <init>() ,public org.sikuli.guide.Visual above() ,public org.sikuli.guide.Visual above(int) ,public void addAnimation(org.sikuli.guide.NewAnimator) ,public void addAnimationListener(org.sikuli.guide.AnimationListener) ,public void addCircleAnimation(java.awt.Point, float) ,public void addFadeinAnimation() ,public void addFadeoutAnimation() ,public void addFollower(org.sikuli.guide.Visual) ,public void addMoveAnimation(java.awt.Point, java.awt.Point) ,public void addResizeAnimation(java.awt.Dimension, java.awt.Dimension) ,public void addSlideAnimation(java.awt.Point, org.sikuli.guide.Visual.Layout) ,public void animationCompleted() ,public org.sikuli.guide.Visual below() ,public org.sikuli.guide.Visual below(int) ,public java.lang.Object clone() ,public org.sikuli.guide.Animator createMoveAnimator(int, int) ,public org.sikuli.guide.Animator createSlidingAnimator(int, int) ,public java.awt.Rectangle getActualBounds() ,public int getActualHeight() ,public java.awt.Point getActualLocation() ,public java.awt.Dimension getActualSize() ,public int getActualWidth() ,public java.awt.Point getCenter() ,public static java.lang.String getColorHex(java.awt.Color) ,public java.awt.Rectangle getFollowerBounds() ,public ArrayList<org.sikuli.guide.Visual> getFollowers() ,public org.sikuli.guide.Visual getLeader() ,public org.sikuli.script.Region getRegion() ,public org.sikuli.script.Region getTarget() ,public java.lang.String getText() ,public boolean isAutoLayoutEnabled() ,public boolean isAutoMoveEnabled() ,public boolean isAutoResizeEnabled() ,public boolean isAutoVisibilityEnabled() ,public org.sikuli.guide.Visual left() ,public org.sikuli.guide.Visual left(int) ,public void moveTo(java.awt.Point) ,public void moveTo(java.awt.Point, org.sikuli.guide.AnimationListener) ,public void offsetLocation(int, int) ,public void paint(java.awt.Graphics) ,public void paintPlain(java.awt.Graphics) ,public void popin() ,public void popout() ,public void removeFollower(org.sikuli.guide.Visual) ,public void removeFrom(java.awt.Container) ,public void removeFromLeader() ,public void resizeTo(java.awt.Dimension) ,public org.sikuli.guide.Visual right() ,public org.sikuli.guide.Visual right(int) ,public void setActualBounds(java.awt.Rectangle) ,public void setActualLocation(java.awt.Point) ,public void setActualLocation(int, int) ,public void setActualSize(int, int) ,public void setActualSize(java.awt.Dimension) ,public void setAutoLayoutEnabled(boolean) ,public void setAutoMoveEnabled(boolean) ,public void setAutoResizeEnabled(boolean) ,public void setAutoVisibilityEnabled(boolean) ,public org.sikuli.guide.Visual setColor(java.awt.Color) ,public org.sikuli.guide.Visual setColor(int, int, int) ,public org.sikuli.guide.Visual setColors(java.awt.Color, java.awt.Color, java.awt.Color, java.awt.Color, java.awt.Color) ,public org.sikuli.guide.Visual setColors(int[], int[], int[], int[]) ,public void setEmphasisAnimation(org.sikuli.guide.Animator) ,public void setEntranceAnimation(org.sikuli.guide.Animator) ,public org.sikuli.guide.Visual setFont(java.lang.String, int) ,public org.sikuli.guide.Visual setFontSize(int) ,public void setGuide(org.sikuli.guide.Guide) ,public void setHorizontalAlignmentWithRegion(org.sikuli.script.Region, float) ,public org.sikuli.guide.Visual setLayout(org.sikuli.guide.Visual.Layout) ,public org.sikuli.guide.Visual setLocationRelative(org.sikuli.guide.Visual.Layout) ,public void setLocationRelativeToComponent(org.sikuli.guide.Visual, org.sikuli.guide.Visual.Layout) ,public void setLocationRelativeToComponent(org.sikuli.guide.Visual, int, int) ,public void setLocationRelativeToComponent(org.sikuli.guide.Visual, float, float) ,public void setLocationRelativeToComponent(org.sikuli.guide.Visual) ,public void setLocationRelativeToPoint(java.awt.Point, org.sikuli.guide.Visual.Layout) ,public org.sikuli.guide.Visual setLocationRelativeToRegion(org.sikuli.script.Region, org.sikuli.guide.Visual.Layout) ,public void setMargin(int, int, int, int) ,public org.sikuli.guide.Visual setMaxWidth(int) ,public void setMovable(boolean) ,public void setOffset(int, int) ,public void setOpacity(float) ,public org.sikuli.guide.Visual setScale(float) ,public void setShadow(int, int) ,public void setShadowDefault() ,public org.sikuli.guide.Visual setStroke(int) ,public org.sikuli.guide.Visual setTarget(RCPS) ,public org.sikuli.guide.Visual setText(java.lang.String) ,public org.sikuli.guide.Visual setTextColor(java.awt.Color) ,public org.sikuli.guide.Visual setTextColor(int, int, int) ,public void setVerticalAlignmentWithRegion(org.sikuli.script.Region, float) ,public void setVisible(boolean) ,public void setZoomLevel(float) ,public void startAnimation() ,public void stopAnimation() ,public java.lang.String toString() ,public void updateComponent() <variables>public int PADDING_X,public int PADDING_Y,private java.awt.Rectangle actualBounds,org.sikuli.guide.AnimationListener animationListener,boolean animationRunning,org.sikuli.guide.Visual.AnimationSequence animationSequence,private boolean autoLayoutEnabled,private boolean autoMoveEnabled,private boolean autoResizeEnabled,private boolean autoVisibilityEnabled,org.sikuli.guide.Visual.AutoLayout autolayout,org.sikuli.guide.ComponentMover cm,java.awt.Color color,java.awt.Color colorBack,java.awt.Color colorFrame,java.awt.Color colorFront,java.awt.Color colorText,org.sikuli.guide.Guide currentGuide,public org.sikuli.guide.Visual.Layout currentLayout,public static java.awt.Color defColor,public static java.awt.Color defColorBack,public static java.awt.Color defColorFrame,public static java.awt.Color defColorFront,public static java.awt.Color defColorText,public static java.lang.String defFont,public static int defFontSize,static int defMaxWidth,private int defShadowOffset,private int defShadowSize,public static int defStroke,org.sikuli.guide.Animator emphasis_anim,org.sikuli.guide.Animator entrance_anim,private ArrayList<org.sikuli.guide.Visual> followers,java.lang.String fontName,int fontSize,public boolean hasChanged,public org.sikuli.guide.Visual.Layout layout,org.sikuli.guide.Visual leader,org.sikuli.guide.Visual.Margin margin,int maxWidth,int offsetx,int offsety,float opacity,int shadowOffset,org.sikuli.guide.ShadowRenderer shadowRenderer,int shadowSize,int stroke,org.sikuli.guide.Visual targetComponent,org.sikuli.script.Pattern targetPattern,org.sikuli.script.Region targetRegion,java.lang.String text,float zoomLevel