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
|
|---|---|---|---|---|---|---|---|---|---|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/GlobalParamsController.java
|
GlobalParamsController
|
findById
|
class GlobalParamsController {
@Autowired
private GlobalParamsService globalParamsService;
@WebAspect
@Operation(summary = "更新全局参数", description = "新增或更新对应的全局参数")
@PutMapping
public RespModel<String> save(@Validated @RequestBody GlobalParamsDTO globalParamsDTO) {
globalParamsService.save(globalParamsDTO.convertTo());
return new RespModel<>(RespEnum.UPDATE_OK);
}
@WebAspect
@Operation(summary = "查找全局参数", description = "查找对应项目id的全局参数列表")
@Parameter(name = "projectId", description = "项目id")
@GetMapping("/list")
public RespModel<List<GlobalParams>> findByProjectId(@RequestParam(name = "projectId") int projectId) {
return new RespModel<>(RespEnum.SEARCH_OK, globalParamsService.findAll(projectId));
}
@WebAspect
@Operation(summary = "删除全局参数", description = "删除对应id的全局参数")
@Parameter(name = "id", description = "id")
@DeleteMapping
public RespModel<String> delete(@RequestParam(name = "id") int id) {
if (globalParamsService.delete(id)) {
return new RespModel<>(RespEnum.DELETE_OK);
} else {
return new RespModel<>(RespEnum.DELETE_FAIL);
}
}
@WebAspect
@Operation(summary = "查看全局参数信息", description = "查看对应id的全局参数")
@Parameter(name = "id", description = "id")
@GetMapping
public RespModel<GlobalParams> findById(@RequestParam(name = "id") int id) {<FILL_FUNCTION_BODY>}
}
|
GlobalParams globalParams = globalParamsService.findById(id);
if (globalParams != null) {
return new RespModel<>(RespEnum.SEARCH_OK, globalParams);
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
| 477
| 79
| 556
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/JobsController.java
|
JobsController
|
findByProjectId
|
class JobsController {
@Autowired
private JobsService jobsService;
@WebAspect
@Operation(summary = "更新定时任务信息", description = "新增或更新定时任务的信息")
@PutMapping
public RespModel<String> save(@Validated @RequestBody JobsDTO jobsDTO) throws SonicException {
return jobsService.saveJobs(jobsDTO.convertTo());
}
@WebAspect
@Operation(summary = "更改定时任务状态", description = "更改定时任务的状态")
@Parameters(value = {
@Parameter(name = "id", description = "定时任务id"),
@Parameter(name = "type", description = "状态类型"),
})
@GetMapping("/updateStatus")
public RespModel<String> updateStatus(@RequestParam(name = "id") int id, @RequestParam(name = "type") int type) {
return jobsService.updateStatus(id, type);
}
@WebAspect
@Operation(summary = "删除定时任务", description = "删除对应id的定时任务")
@Parameter(name = "id", description = "定时任务id")
@DeleteMapping
public RespModel<String> delete(@RequestParam(name = "id") int id) {
return jobsService.delete(id);
}
@WebAspect
@Operation(summary = "查询定时任务列表", description = "查找对应项目id的定时任务列表")
@Parameters(value = {
@Parameter(name = "projectId", description = "项目id"),
@Parameter(name = "page", description = "页码"),
@Parameter(name = "pageSize", description = "页数据大小")
})
@GetMapping("/list")
public RespModel<CommentPage<Jobs>> findByProjectId(@RequestParam(name = "projectId") int projectId
, @RequestParam(name = "page") int page
, @RequestParam(name = "pageSize") int pageSize) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "查询定时任务详细信息", description = "查找对应id的定时任务详细信息")
@Parameter(name = "id", description = "定时任务id")
@GetMapping
public RespModel<Jobs> findById(@RequestParam(name = "id") int id) {
Jobs jobs = jobsService.findById(id);
if (jobs != null) {
return new RespModel<>(RespEnum.SEARCH_OK, jobs);
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
}
@WebAspect
@Operation(summary = "查询系统定时任务详细信息", description = "查找系统定时任务详细信息")
@GetMapping("/findSysJobs")
public RespModel<List<JSONObject>> findSysJobs() {
return new RespModel<>(RespEnum.SEARCH_OK, jobsService.findSysJobs());
}
@WebAspect
@Operation(summary = "更新系统定时任务", description = "更新系统定时任务")
@Parameters(value = {
@Parameter(name = "type", description = "类型"),
@Parameter(name = "cron", description = "cron表达式")
})
@PutMapping("/updateSysJob")
public RespModel updateSysJob(@RequestBody JSONObject jsonObject) {
jobsService.updateSysJob(jsonObject.getString("type"), jsonObject.getString("cron"));
return new RespModel<>(RespEnum.HANDLE_OK);
}
}
|
Page<Jobs> pageable = new Page<>(page, pageSize);
return new RespModel<>(
RespEnum.SEARCH_OK,
CommentPage.convertFrom(jobsService.findByProjectId(projectId, pageable))
);
| 934
| 68
| 1,002
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ModulesController.java
|
ModulesController
|
delete
|
class ModulesController {
@Autowired
private ModulesService modulesService;
@WebAspect
@Operation(summary = "更新模块信息", description = "新增或更新对应的模块信息")
@PutMapping
public RespModel<String> save(@Validated @RequestBody ModulesDTO modules) {
modulesService.save(modules.convertTo());
return new RespModel<>(RespEnum.UPDATE_OK);
}
@WebAspect
@Operation(summary = "查找模块列表", description = "查找对应项目id的模块列表")
@Parameter(name = "projectId", description = "项目id")
@GetMapping("/list")
public RespModel<List<ModulesDTO>> findByProjectId(@RequestParam(name = "projectId") int projectId) {
return new RespModel<>(
RespEnum.SEARCH_OK,
modulesService.findByProjectId(projectId)
.stream().map(TypeConverter::convertTo).collect(Collectors.toList())
);
}
@WebAspect
@Operation(summary = "删除模块", description = "删除对应id的模块")
@Parameter(name = "id", description = "模块id")
@DeleteMapping
public RespModel<String> delete(@RequestParam(name = "id") int id) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "查看模块信息", description = "查看对应id的模块信息")
@Parameter(name = "id", description = "模块id")
@GetMapping
public RespModel<ModulesDTO> findById(@RequestParam(name = "id") int id) {
Modules modules = modulesService.findById(id);
if (modules != null) {
return new RespModel<>(RespEnum.SEARCH_OK, modules.convertTo());
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
}
}
|
if (modulesService.delete(id)) {
return new RespModel<>(RespEnum.DELETE_OK);
} else {
return new RespModel<>(RespEnum.DELETE_FAIL);
}
| 520
| 60
| 580
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/PackageController.java
|
PackageController
|
findAll
|
class PackageController {
@Autowired
private PackagesService packagesService;
@WebAspect
@Operation(summary = "添加安装包信息", description = "添加安装包信息")
@PutMapping
public RespModel<String> save(@Validated @RequestBody PackageDTO pkg) {
packagesService.save(pkg.convertTo());
return new RespModel<>(RespEnum.UPDATE_OK);
}
@WebAspect
@Operation(summary = "查找所有安装包", description = "查找所有安装包")
@GetMapping("/list")
public RespModel<CommentPage<PackageDTO>> findAll(@RequestParam(name = "projectId") int projectId,
@RequestParam(name = "branch", required = false) String branch,
@RequestParam(name = "platform", required = false) String platform,
@RequestParam(name = "packageName", required = false) String packageName,
@RequestParam(name = "page") int page,
@RequestParam(name = "pageSize") int pageSize) {<FILL_FUNCTION_BODY>}
}
|
Page<Packages> pageable = new Page<>(page, pageSize);
return new RespModel<>(RespEnum.SEARCH_OK, packagesService.findByProjectId(projectId, branch, platform,
packageName, pageable));
| 282
| 65
| 347
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ProjectsController.java
|
ProjectsController
|
findById
|
class ProjectsController {
@Autowired
private ProjectsService projectsService;
@WebAspect
@Operation(summary = "更新项目信息", description = "新增或更新项目信息")
@PutMapping
public RespModel<String> save(@Validated @RequestBody ProjectsDTO projects) {
projectsService.save(projects.convertTo());
return new RespModel<>(RespEnum.UPDATE_OK);
}
@WebAspect
@WhiteUrl
@Operation(summary = "查找所有项目", description = "查找所有项目列表")
@GetMapping("/list")
public RespModel<List<ProjectsDTO>> findAll() {
return new RespModel<>(
RespEnum.SEARCH_OK,
projectsService.findAll().stream().map(TypeConverter::convertTo).collect(Collectors.toList())
);
}
@WebAspect
@Operation(summary = "查询项目信息", description = "查找对应id下的详细信息")
@Parameter(name = "id", description = "项目id")
@GetMapping
public RespModel<?> findById(@RequestParam(name = "id") int id) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "删除", description = "删除对应id下的详细信息")
@Parameter(name = "id", description = "项目id")
@DeleteMapping
public RespModel<String> delete(@RequestParam(name = "id") int id) throws SonicException {
projectsService.delete(id);
return new RespModel<>(RespEnum.DELETE_OK);
}
}
|
Projects projects = projectsService.findById(id);
if (projects != null) {
return new RespModel<>(RespEnum.SEARCH_OK, projects.convertTo());
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
| 423
| 79
| 502
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/PublicStepsController.java
|
PublicStepsController
|
findByProjectId
|
class PublicStepsController {
@Autowired
private PublicStepsService publicStepsService;
@Autowired
private TestCasesService testCasesService;
@WebAspect
@Operation(summary = "查询公共步骤列表1", description = "查找对应项目id下的公共步骤列表(分页)")
@Parameters(value = {
@Parameter(name = "projectId", description = "项目id"),
@Parameter(name = "page", description = "页码"),
@Parameter(name = "pageSize", description = "页数据大小")
})
@GetMapping("/list")
public RespModel<CommentPage<PublicStepsDTO>> findByProjectId(@RequestParam(name = "projectId") int projectId,
@RequestParam(name = "page") int page,
@RequestParam(name = "pageSize") int pageSize) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "查询公共步骤列表2", description = "查找对应项目id下的公共步骤列表(不分页,只查询id和name)")
@Parameters(value = {
@Parameter(name = "projectId", description = "项目id"),
@Parameter(name = "platform", description = "平台"),
})
@GetMapping("/findNameByProjectId")
public RespModel<List<Map<String, Object>>> findByProjectId(@RequestParam(name = "projectId") int projectId,
@RequestParam(name = "platform") int platform) {
return new RespModel<>(RespEnum.SEARCH_OK, publicStepsService.findByProjectIdAndPlatform(projectId, platform));
}
@WebAspect
@Operation(summary = "更新公共步骤信息", description = "新增或更新公共步骤信息")
@PutMapping
public RespModel<String> save(@Validated @RequestBody PublicStepsDTO publicStepsDTO) {
return new RespModel(RespEnum.UPDATE_OK, publicStepsService.savePublicSteps(publicStepsDTO));
}
@WebAspect
@Operation(summary = "删除公共步骤", description = "删除对应公共步骤id,包含的操作步骤不会被删除")
@Parameter(name = "id", description = "公共步骤id")
@DeleteMapping
public RespModel<String> delete(@RequestParam(name = "id") int id) {
if (publicStepsService.delete(id)) {
return new RespModel<>(RespEnum.DELETE_OK);
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
}
@WebAspect
@Operation(summary = "删除公共步骤检查", description = "返回引用公共步骤的用例")
@Parameter(name = "id", description = "公共步骤id")
@GetMapping("deleteCheck")
public RespModel<List<TestCases>> deleteCheck(@RequestParam(name = "id") int id) {
return new RespModel<>(RespEnum.SEARCH_OK, testCasesService.listByPublicStepsId(id));
}
@WebAspect
@Operation(summary = "查找公共步骤信息", description = "查询对应公共步骤的详细信息")
@Parameter(name = "id", description = "公共步骤id")
@GetMapping
public RespModel<?> findById(@RequestParam(name = "id") int id) {
PublicStepsDTO publicStepsDTO = publicStepsService.findById(id, false);
if (publicStepsDTO != null) {
return new RespModel<>(RespEnum.SEARCH_OK, publicStepsDTO);
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
}
@WebAspect
@Operation(summary = "复制公共步骤", description = "复制对应公共步骤,步骤也会同步")
@Parameter(name = "id", description = "公共步骤Id")
@GetMapping("/copy")
public RespModel<String> copyPublicSteps(@RequestParam(name = "id") int id) {
publicStepsService.copyPublicSetpsIds(id);
return new RespModel<>(RespEnum.COPY_OK);
}
}
|
Page<PublicSteps> pageable = new Page<>(page, pageSize);
return new RespModel<>(
RespEnum.SEARCH_OK,
publicStepsService.findByProjectId(projectId, pageable)
);
| 1,120
| 64
| 1,184
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ResourcesController.java
|
ResourcesController
|
listResources
|
class ResourcesController {
@Autowired
private ResourcesService resourcesService;
@WebAspect
@Operation(summary = "查询所有资源连接", description = "查询所有资源连接")
@GetMapping("/list")
@Parameters(value = {
@Parameter(name = "page", description = "页码"),
@Parameter(name = "pageSize", description = "每页请求数量")
})
public RespModel<CommentPage<ResourcesDTO>> listResources(@RequestParam(name = "page") int page,
@RequestParam(name = "pageSize") int pageSize,
@RequestParam(name = "path", required = false) String path) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "刷新请求资源列表", description = "查询所有资源连接")
@PostMapping("/refresh")
public RespModel<CommentPage<ResourcesDTO>> refreshResources() {
resourcesService.init();
return listResources(1, 20, null);
}
@WebAspect
@Operation(summary = "编辑资源鉴权状态", description = "编辑资源鉴权状态")
@PutMapping("/edit")
public RespModel<String> editResources(@RequestBody ResourceParam resourceParam) {
resourcesService.updateResourceAuth(resourceParam.getId(), resourceParam.getNeedAuth());
return RespModel.result(RespEnum.UPDATE_OK);
}
@WebAspect
@Operation(summary = "查询当前角色下资源鉴权转态", description = "查询当前角色下资源鉴权转态")
@GetMapping("/roleResource")
@Parameters(value = {
@Parameter(name = "roleId", description = "角色 id")
})
public RespModel<List<ResourcesDTO>> listRoleResource(@RequestParam(name = "roleId") Integer roleId) {
return RespModel.result(RespEnum.SEARCH_OK, resourcesService.listRoleResource(roleId));
}
}
|
Page<Resources> pageable = new Page<>(page, pageSize);
return RespModel.result(RespEnum.SEARCH_OK, resourcesService.listResource(pageable, path, false));
| 509
| 53
| 562
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ResultDetailController.java
|
ResultDetailController
|
findAll
|
class ResultDetailController {
@Autowired
private ResultDetailService resultDetailService;
@WebAspect
@Operation(summary = "保存测试结果", description = "保存测试结果")
@PostMapping
public RespModel<String> save(@RequestBody JSONObject jsonObject) {
resultDetailService.saveByTransport(jsonObject);
return new RespModel<>(RespEnum.HANDLE_OK);
}
@WebAspect
@Operation(summary = "查找测试结果详情", description = "查找对应测试结果详情")
@Parameters(value = {
@Parameter(name = "caseId", description = "测试用例id"),
@Parameter(name = "resultId", description = "测试结果id"),
@Parameter(name = "deviceId", description = "设备id"),
@Parameter(name = "type", description = "类型"),
@Parameter(name = "page", description = "页码")
})
@GetMapping("/list")
public RespModel<CommentPage<ResultDetail>> findAll(@RequestParam(name = "caseId") int caseId,
@RequestParam(name = "resultId") int resultId,
@RequestParam(name = "deviceId") int deviceId,
@RequestParam(name = "type") String type,
@RequestParam(name = "page") int page) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "查找测试结果详情2", description = "查找对应测试结果详情")
@Parameters(value = {
@Parameter(name = "caseId", description = "测试用例id"),
@Parameter(name = "resultId", description = "测试结果id"),
@Parameter(name = "deviceId", description = "设备id"),
@Parameter(name = "type", description = "类型"),
})
@GetMapping("/listAll")
public RespModel<List<ResultDetail>> findAll(@RequestParam(name = "caseId") int caseId,
@RequestParam(name = "resultId") int resultId,
@RequestParam(name = "deviceId") int deviceId,
@RequestParam(name = "type") String type) {
return new RespModel<>(RespEnum.SEARCH_OK,
resultDetailService.findAll(resultId, caseId, type, deviceId));
}
}
|
Page<ResultDetail> pageable = new Page<>(page, 20);
return new RespModel<>(RespEnum.SEARCH_OK,
CommentPage.convertFrom(
resultDetailService.findAll(resultId, caseId, type, deviceId, pageable))
);
| 599
| 75
| 674
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ResultsController.java
|
ResultsController
|
delete
|
class ResultsController {
@Autowired
private ResultsService resultsService;
@WebAspect
@Operation(summary = "查询测试结果列表", description = "查找对应项目id下的测试结果列表")
@Parameters(value = {
@Parameter(name = "projectId", description = "项目id"),
@Parameter(name = "page", description = "页码"),
@Parameter(name = "pageSize", description = "页数据大小")
})
@GetMapping("/list")
public RespModel<CommentPage<Results>> findByProjectId(@RequestParam(name = "projectId") int projectId,
@RequestParam(name = "page") int page,
@RequestParam(name = "pageSize") int pageSize) {
Page<Results> pageable = new Page<>(page, pageSize);
return new RespModel<>(
RespEnum.SEARCH_OK,
CommentPage.convertFrom(resultsService.findByProjectId(projectId, pageable))
);
}
@WebAspect
@Operation(summary = "删除测试结果", description = "删除对应的测试结果id以及测试结果详情")
@Parameter(name = "id", description = "测试结果id")
@DeleteMapping
public RespModel<String> delete(@RequestParam(name = "id") int id) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "查询测试结果信息", description = "查询对应id的测试结果信息")
@Parameter(name = "id", description = "测试结果id")
@GetMapping
public RespModel<Results> findById(@RequestParam(name = "id") int id) {
return new RespModel<>(RespEnum.SEARCH_OK, resultsService.findById(id));
}
@WebAspect
@Operation(summary = "清理测试结果", description = "按照指定天数前的测试结果")
@GetMapping("/clean")
public RespModel<String> clean(@RequestParam(name = "day") int day) {
resultsService.clean(day);
return new RespModel<>(0, "result.clean");
}
@WebAspect
@Operation(summary = "统计测试结果", description = "统计测试结果")
@GetMapping("/subResultCount")
public RespModel<String> subResultCount(@RequestParam(name = "id") int id) {
resultsService.subResultCount(id);
return new RespModel<>(RespEnum.HANDLE_OK);
}
@WebAspect
@Operation(summary = "查询测试结果用例状态", description = "查询对应id的测试结果用例状态")
@Parameter(name = "id", description = "测试结果id")
@GetMapping("/findCaseStatus")
public RespModel<JSONArray> findCaseStatus(@RequestParam(name = "id") int id) {
JSONArray result = resultsService.findCaseStatus(id);
if (result == null) {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
} else {
return new RespModel<>(RespEnum.SEARCH_OK, result);
}
}
@WebAspect
@Operation(summary = "查询报表", description = "查找前端首页报表信息")
@Parameters(value = {
@Parameter(name = "projectId", description = "项目id"),
@Parameter(name = "startTime", description = "起始时间"),
@Parameter(name = "endTime", description = "结束时间")
})
@GetMapping("/chart")
public RespModel<JSONObject> chart(@RequestParam(name = "projectId") int projectId,
@RequestParam(name = "startTime") String startTime,
@RequestParam(name = "endTime") String endTime) {
return new RespModel<>(RespEnum.SEARCH_OK, resultsService.chart(startTime, endTime, projectId));
}
@WebAspect
@Operation(summary = "发送日报", description = "发送所有项目日报")
@GetMapping("/sendDayReport")
public RespModel<String> sendDayReport() {
resultsService.sendDayReport();
return new RespModel<>(RespEnum.HANDLE_OK);
}
@WebAspect
@Operation(summary = "发送周报", description = "发送所有项目周报")
@GetMapping("/sendWeekReport")
public RespModel<String> sendWeekReport() {
resultsService.sendWeekReport();
return new RespModel<>(RespEnum.HANDLE_OK);
}
}
|
if (resultsService.delete(id)) {
return new RespModel<>(RespEnum.DELETE_OK);
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
| 1,175
| 61
| 1,236
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/RolesController.java
|
RolesController
|
deleteCheck
|
class RolesController {
@Autowired
private RolesServices rolesServices;
@WebAspect
@Operation(summary = "查询所有角色信息", description = "查询所有角色信息")
@GetMapping("/list")
@Parameters(value = {
@Parameter(name = "page", description = "页码"),
@Parameter(name = "pageSize", description = "每页请求数量"),
@Parameter(name = "isAll", description = "是否全部"),
@Parameter(name = "roleName", description = "角色名称"),
})
public RespModel<CommentPage<RolesDTO>> listResources(@RequestParam(name = "page") int page,
@RequestParam(name = "pageSize", required = false, defaultValue = "20") int pageSize,
@RequestParam(name = "isAll", required = false) boolean isAll,
@RequestParam(name = "roleName", required = false) String roleName) {
Page<Roles> pageable = new Page<>(page, pageSize);
if (isAll) {
pageable.setSize(1000L);
}
return RespModel.result(RespEnum.SEARCH_OK, rolesServices.listRoles(pageable, roleName));
}
@WebAspect
@Operation(summary = "编辑或新增角色", description = "编辑或新增角色")
@PutMapping("/edit")
public RespModel<String> editResources(@RequestBody RolesDTO rolesDTO) {
rolesServices.save(rolesDTO);
return RespModel.result(RespEnum.UPDATE_OK);
}
@WebAspect
@Operation(summary = "删除角色", description = "返回当前第一页角色")
@Parameter(name = "id", description = "角色id")
@DeleteMapping("/delete")
public RespModel<CommentPage<RolesDTO>> deleteCheck(@RequestParam(name = "id") int id) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "编辑角色资源鉴权状态", description = "编辑是否成功")
@Parameters(value = {
@Parameter(name = "roleId", description = "角色 id"),
@Parameter(name = "resId", description = "资源 id"),
@Parameter(name = "hasAuth", description = "是否有权限")
})
@PutMapping("/update")
public RespModel<String> editResourceRoles(@RequestParam(name = "roleId") int roleId,
@RequestParam(name = "resId") int resId,
@RequestParam(name = "hasAuth") boolean hasAuth) {
rolesServices.editResourceRoles(roleId, resId, hasAuth);
return RespModel.result(RespEnum.UPDATE_OK);
}
}
|
rolesServices.delete(id);
Page<Roles> pageable = new Page<>(1, 20);
return RespModel.result(RespEnum.SEARCH_OK, rolesServices.listRoles(pageable, null));
| 716
| 64
| 780
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ScriptsController.java
|
ScriptsController
|
findById
|
class ScriptsController {
@Autowired
private ScriptsService scriptsService;
@WebAspect
@Operation(summary = "查找脚本模板列表", description = "查找对应项目id的脚本列表")
@Parameters(value = {
@Parameter(name = "projectId", description = "项目id"),
@Parameter(name = "name", description = "名称"),
@Parameter(name = "page", description = "页码"),
@Parameter(name = "pageSize", description = "页数据大小")
})
@GetMapping("/list")
public RespModel<CommentPage<Scripts>> findAll(@RequestParam(name = "projectId", required = false) Integer projectId,
@RequestParam(name = "name", required = false) String name,
@RequestParam(name = "page") int page,
@RequestParam(name = "pageSize") int pageSize) {
Page<Scripts> pageable = new Page<>(page, pageSize);
return new RespModel<>(
RespEnum.SEARCH_OK,
CommentPage.convertFrom(scriptsService
.findByProjectId(projectId, name, pageable))
);
}
@WebAspect
@Operation(summary = "查找脚本详情", description = "查找对应id的对应脚本详细信息")
@Parameter(name = "id", description = "id")
@GetMapping
public RespModel<Scripts> findById(@RequestParam(name = "id") int id) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "删除脚本模板", description = "删除对应id")
@Parameter(name = "id", description = "id")
@DeleteMapping
public RespModel<String> delete(@RequestParam(name = "id") int id) {
if (scriptsService.delete(id)) {
return new RespModel<>(RespEnum.DELETE_OK);
} else {
return new RespModel<>(RespEnum.DELETE_FAIL);
}
}
@WebAspect
@Operation(summary = "更新脚本信息", description = "新增或更新对应的脚本信息")
@PutMapping
public RespModel<String> save(@Validated @RequestBody ScriptsDTO scriptsDTO) {
scriptsService.save(scriptsDTO.convertTo());
return new RespModel<>(RespEnum.UPDATE_OK);
}
}
|
Scripts scripts = scriptsService.findById(id);
if (scripts != null) {
return new RespModel<>(RespEnum.SEARCH_OK, scripts);
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
| 631
| 75
| 706
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/TestCasesController.java
|
TestCasesController
|
findAll
|
class TestCasesController {
@Autowired
private TestCasesService testCasesService;
@Autowired
private JWTTokenTool jwtTokenTool;
@Autowired
private TestSuitesService testSuitesService;
@WebAspect
@Operation(summary = "查询测试用例列表", description = "查找对应项目id下的测试用例列表")
@Parameters(value = {
@Parameter(name = "projectId", description = "项目id"),
@Parameter(name = "platform", description = "平台类型"),
@Parameter(name = "name", description = "用例名称"),
@Parameter(name = "moduleIds", description = "模块Id"),
@Parameter(name = "caseAuthorNames", description = "用例作者列表"),
@Parameter(name = "page", description = "页码"),
@Parameter(name = "pageSize", description = "页数据大小"),
@Parameter(name = "idSort", description = "控制id排序方式"),
@Parameter(name = "editTimeSort", description = "控制editTime排序方式")
})
@GetMapping("/list")
public RespModel<CommentPage<TestCasesDTO>> findAll(@RequestParam(name = "projectId") int projectId,
@RequestParam(name = "platform") int platform,
@RequestParam(name = "name", required = false) String name,
@RequestParam(name = "moduleIds[]", required = false) List<Integer> moduleIds,
@RequestParam(name = "caseAuthorNames[]", required = false) List<String> caseAuthorNames,
@RequestParam(name = "page") int page,
@RequestParam(name = "pageSize") int pageSize,
@RequestParam(name = "idSort", required = false) String idSort,
@RequestParam(value = "editTimeSort", required = false) String editTimeSort) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "查询测试用例列表", description = "不分页的测试用例列表")
@Parameters(value = {
@Parameter(name = "projectId", description = "项目id"),
@Parameter(name = "platform", description = "平台类型"),
})
@GetMapping("/listAll")
public RespModel<List<TestCases>> findAll(@RequestParam(name = "projectId") int projectId,
@RequestParam(name = "platform") int platform) {
return new RespModel<>(RespEnum.SEARCH_OK,
testCasesService.findAll(projectId, platform));
}
@WebAspect
@Operation(summary = "删除测试用例", description = "删除对应用例id,用例下的操作步骤的caseId重置为0")
@Parameter(name = "id", description = "用例id")
@DeleteMapping
public RespModel<String> delete(@RequestParam(name = "id") int id) {
if (testCasesService.delete(id)) {
return new RespModel<>(RespEnum.DELETE_OK);
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
}
@WebAspect
@Operation(summary = "删除测试用例检查", description = "返回被引用的测试套件")
@Parameter(name = "id", description = "用例id")
@GetMapping("deleteCheck")
public RespModel<List<TestSuites>> deleteCheck(@RequestParam(name = "id") int id) {
return new RespModel<>(RespEnum.SEARCH_OK, testSuitesService.listTestSuitesByTestCasesId(id));
}
@WebAspect
@Operation(summary = "更新测试用例信息", description = "新增或更改测试用例信息")
@PutMapping
public RespModel<String> save(@Validated @RequestBody TestCasesDTO testCasesDTO, HttpServletRequest request) {
if (request.getHeader("SonicToken") != null) {
String token = request.getHeader("SonicToken");
String userName = jwtTokenTool.getUserName(token);
if (userName != null) {
testCasesDTO.setDesigner(userName);
}
}
// 修改时,更新修改时间
if (!StringUtils.isEmpty(testCasesDTO.getId())) {
testCasesDTO.setEditTime(new Date());
}
testCasesService.save(testCasesDTO.convertTo());
return new RespModel<>(RespEnum.UPDATE_OK);
}
@WebAspect
@Operation(summary = "查询测试用例详情", description = "查找对应用例id的用例详情")
@Parameter(name = "id", description = "用例id")
@GetMapping
public RespModel<TestCasesDTO> findById(@RequestParam(name = "id") int id) {
TestCasesDTO testCases = testCasesService.findById(id);
if (testCases != null) {
return new RespModel<>(RespEnum.SEARCH_OK, testCases);
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
}
@WebAspect
@Operation(summary = "批量查询用例", description = "查找id列表的用例信息,可以传多个ids[]")
@Parameter(name = "ids[]", description = "id列表")
@GetMapping("/findByIdIn")
public RespModel<List<TestCases>> findByIdIn(@RequestParam(name = "ids[]") List<Integer> ids) {
return new RespModel<>(RespEnum.SEARCH_OK,
testCasesService.findByIdIn(ids));
}
//记得翻译
@WebAspect
@Operation(summary = "复制测试用例", description = "复制对应用例id的用例详情")
@Parameter(name = "id", description = "用例id")
@GetMapping("/copy")
public RespModel<String> copyTestById(@RequestParam(name = "id") Integer id) {
testCasesService.copyTestById(id);
return new RespModel<>(RespEnum.COPY_OK);
}
@WebAspect
@Operation(summary = "查询用例所有的作者列表", description = "查找对应项目id下对应平台的所有作者列表")
@Parameters(value = {
@Parameter(name = "projectId", description = "项目id"),
@Parameter(name = "platform", description = "平台类型"),
})
@GetMapping("/listAllCaseAuthor")
public RespModel<List<String>> findAllCaseAuthor(@RequestParam(name = "projectId") int projectId,
@RequestParam(name = "platform") int platform) {
return new RespModel<>(
RespEnum.SEARCH_OK,
testCasesService.findAllCaseAuthor(projectId, platform)
);
}
}
|
Page<TestCases> pageable = new Page<>(page, pageSize);
return new RespModel<>(
RespEnum.SEARCH_OK,
testCasesService.findAll(projectId, platform, name, moduleIds, caseAuthorNames,
pageable, idSort, editTimeSort)
);
| 1,812
| 82
| 1,894
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/TestSuitesController.java
|
TestSuitesController
|
delete
|
class TestSuitesController {
@Autowired
private TestSuitesService testSuitesService;
@Autowired
private JWTTokenTool jwtTokenTool;
@WebAspect
@Operation(summary = "运行测试套件", description = "运行指定项目的指定测试套件")
@Parameter(name = "id", description = "测试套件id")
@GetMapping("/runSuite")
public RespModel<Integer> runSuite(@RequestParam(name = "id") int id
, HttpServletRequest request) {
String strike = "SYSTEM";
if (request.getHeader("SonicToken") != null) {
String token = request.getHeader("SonicToken");
String userName = jwtTokenTool.getUserName(token);
if (userName != null) {
strike = userName;
}
}
return testSuitesService.runSuite(id, strike);
}
@WebAspect
@Operation(summary = "停止测试套件运行", description = "停止测试套件运行")
@Parameter(name = "resultId", description = "测试结果Id")
@GetMapping("/forceStopSuite")
public RespModel<String> forceStopSuite(@RequestParam(name = "resultId") int resultId
, HttpServletRequest request) {
String strike = "SYSTEM";
if (request.getHeader("SonicToken") != null) {
String token = request.getHeader("SonicToken");
String userName = jwtTokenTool.getUserName(token);
if (userName != null) {
strike = userName;
}
}
return testSuitesService.forceStopSuite(resultId, strike);
}
@WebAspect
@Operation(summary = "删除测试套件", description = "删除指定id的测试套件")
@Parameter(name = "id", description = "测试套件id")
@DeleteMapping
public RespModel<String> delete(@RequestParam(name = "id") int id) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "更新测试套件", description = "更新或新增测试套件")
@PutMapping
public RespModel<String> save(@Validated @RequestBody TestSuitesDTO testSuitesDTO) {
testSuitesService.saveTestSuites(testSuitesDTO);
return new RespModel<>(RespEnum.UPDATE_OK);
}
@WebAspect
@Operation(summary = "查询测试套件列表", description = "用于查询对应项目id下的测试套件列表")
@Parameter(name = "projectId", description = "项目id")
@GetMapping("/list")
public RespModel<CommentPage<TestSuitesDTO>> findByProjectId(@RequestParam(name = "projectId") int projectId
, @RequestParam(name = "name") String name
, @RequestParam(name = "page") int page
, @RequestParam(name = "pageSize") int pageSize) {
Page<TestSuites> pageable = new Page<>(page, pageSize);
return new RespModel<>(RespEnum.SEARCH_OK, testSuitesService.findByProjectId(projectId, name, pageable));
}
@WebAspect
@Operation(summary = "查询测试套件列表", description = "用于查询对应项目id下的测试套件列表(不分页)")
@Parameter(name = "projectId", description = "项目id")
@GetMapping("/listAll")
public RespModel<List<TestSuitesDTO>> findByProjectId(@RequestParam(name = "projectId") int projectId) {
return new RespModel<>(RespEnum.SEARCH_OK, testSuitesService.findByProjectId(projectId));
}
@WebAspect
@Operation(summary = "测试套件详情", description = "查看测试套件的配置信息详情")
@Parameter(name = "id", description = "测试套件id")
@GetMapping
public RespModel<?> findById(@RequestParam(name = "id") int id) {
TestSuitesDTO testSuitesDTO = testSuitesService.findById(id);
if (testSuitesDTO != null) {
return new RespModel<>(RespEnum.SEARCH_OK, testSuitesDTO);
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
}
}
|
if (testSuitesService.delete(id)) {
return new RespModel<>(RespEnum.DELETE_OK);
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
| 1,167
| 64
| 1,231
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/UsersController.java
|
UsersController
|
listResources
|
class UsersController {
@Autowired
private UsersService usersService;
@Autowired
private RolesServices rolesServices;
@Autowired
private JWTTokenTool jwtTokenTool;
@WebAspect
@WhiteUrl
@Operation(summary = "获取登录配置", description = "获取登录信息配置")
@GetMapping("/loginConfig")
public RespModel<?> getLoginConfig() {
return new RespModel(RespEnum.SEARCH_OK, usersService.getLoginConfig());
}
@WebAspect
@Operation(summary = "生成用户对外Token", description = "生成用户对外Token")
@GetMapping("/generateToken")
public RespModel<String> generateToken(@RequestParam(name = "day") int day, HttpServletRequest request) {
String token = request.getHeader("SonicToken");
if (token != null) {
return new RespModel(RespEnum.HANDLE_OK, jwtTokenTool.getToken(jwtTokenTool.getUserName(token), day));
} else {
return new RespModel(RespEnum.UPDATE_FAIL);
}
}
@WebAspect
@WhiteUrl
@Operation(summary = "登录", description = "用户登录")
@PostMapping("/login")
public RespModel<String> login(@Validated @RequestBody UserInfo userInfo) {
String token = usersService.login(userInfo);
if (token != null) {
return new RespModel<>(2000, "ok.login", token);
} else {
return new RespModel<>(2001, "fail.login");
}
}
@WebAspect
@WhiteUrl
@Operation(summary = "注册", description = "注册用户")
@PostMapping("/register")
public RespModel<String> register(@Validated @RequestBody UsersDTO users) throws SonicException {
usersService.register(users.convertTo());
return new RespModel<>(2000, "ok.register");
}
@WebAspect
@WhiteUrl
@Operation(summary = "获取用户信息", description = "获取token的用户信息")
@GetMapping
public RespModel<?> getUserInfo(HttpServletRequest request) {
if (request.getHeader("SonicToken") != null) {
String token = request.getHeader("SonicToken");
Users users = usersService.getUserInfo(token);
UsersDTO usersDTO = users.convertTo();
if (!Objects.isNull(users.getUserRole())) {
Roles roles = rolesServices.findById(users.getUserRole());
if (!Objects.isNull(roles)) {
usersDTO.setRole(roles.getId());
usersDTO.setRoleName(roles.getRoleName());
}
}
return new RespModel<>(RespEnum.SEARCH_OK, usersDTO);
} else {
return new RespModel<>(RespEnum.UNAUTHORIZED);
}
}
@WebAspect
@WhiteUrl
@Operation(summary = "修改密码", description = "修改token的用户密码")
@PutMapping
public RespModel<String> changePwd(HttpServletRequest request, @Validated @RequestBody ChangePwd changePwd) {
if (request.getHeader("SonicToken") != null) {
String token = request.getHeader("SonicToken");
return usersService.resetPwd(token, changePwd);
} else {
return new RespModel<>(RespEnum.UNAUTHORIZED);
}
}
@WebAspect
@Operation(summary = "查询所有用户信息", description = "查询所有用户信息")
@GetMapping("/list")
@Parameters(value = {
@Parameter(name = "page", description = "页码"),
@Parameter(name = "pageSize", description = "每页请求数量"),
@Parameter(name = "userName", description = "角色名称"),
})
public RespModel<CommentPage<UsersDTO>> listResources(@RequestParam(name = "page") int page,
@RequestParam(name = "pageSize", required = false, defaultValue = "20") int pageSize,
@RequestParam(name = "userName", required = false) String userName) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "修改用户角色", description = "修改用户角色")
@PutMapping("/changeRole")
@Parameters(value = {
@Parameter(name = "roleId", description = "角色 id"),
@Parameter(name = "userId", description = "用户 id"),
})
public RespModel<Boolean> changeRole(@RequestParam(name = "roleId") Integer roleId,
@RequestParam(name = "userId") Integer userId) {
return RespModel.result(RespEnum.UPDATE_OK, usersService.updateUserRole(userId, roleId));
}
}
|
Page<Users> pageable = new Page<>(page, pageSize);
return RespModel.result(RespEnum.SEARCH_OK, usersService.listUsers(pageable, userName));
| 1,288
| 52
| 1,340
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/VersionsController.java
|
VersionsController
|
delete
|
class VersionsController {
@Autowired
private VersionsService versionsService;
@WebAspect
@Operation(summary = "更新版本迭代", description = "新增或更改版本迭代信息")
@PutMapping
public RespModel<String> save(@Validated @RequestBody VersionsDTO versionsDTO) {
versionsService.save(versionsDTO.convertTo());
return new RespModel<>(RespEnum.UPDATE_OK);
}
@WebAspect
@Operation(summary = "查询版本迭代列表", description = "用于查询对应项目id下的版本迭代列表")
@Parameter(name = "projectId", description = "项目id")
@GetMapping("/list")
public RespModel<List<Versions>> findByProjectId(@RequestParam(name = "projectId") int projectId) {
return new RespModel<>(RespEnum.SEARCH_OK, versionsService.findByProjectId(projectId));
}
@WebAspect
@Operation(summary = "删除版本迭代", description = "删除指定id的版本迭代")
@Parameter(name = "id", description = "版本迭代id")
@DeleteMapping
public RespModel<String> delete(@RequestParam(name = "id") int id) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "查询版本迭代信息", description = "查询指定id的版本迭代的详细信息")
@Parameter(name = "id", description = "版本迭代id")
@GetMapping
public RespModel<Versions> findById(@RequestParam(name = "id") int id) {
Versions versions = versionsService.findById(id);
if (versions != null) {
return new RespModel<>(RespEnum.SEARCH_OK, versions);
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
}
}
|
if (versionsService.delete(id)) {
return new RespModel<>(RespEnum.DELETE_OK);
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
| 510
| 61
| 571
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/base/CommentPage.java
|
CommentPage
|
convertFrom
|
class CommentPage<T> implements Serializable {
/**
* 页大小
*/
private long size;
/**
* 页内容
*/
private List<T> content;
/**
* 当前页码
*/
private long number;
/**
* 页内容总个数
*/
private long totalElements;
/**
* 总页数
*/
private long totalPages;
public static <T> CommentPage<T> convertFrom(Page<T> page) {<FILL_FUNCTION_BODY>}
/**
* Page的数据会被content替代
*/
public static <T> CommentPage<T> convertFrom(Page<?> page, List<T> content) {
return new CommentPage<>(
page.getSize(), content, page.getCurrent() - 1, page.getTotal(), page.getPages()
);
}
public static <T> CommentPage<T> emptyPage() {
return new CommentPage<>(0, new ArrayList<>(), 0, 0, 0);
}
}
|
return new CommentPage<>(
page.getSize(), page.getRecords(), page.getCurrent() - 1, page.getTotal(), page.getPages()
);
| 285
| 46
| 331
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Devices.java
|
Devices
|
newDeletedDevice
|
class Devices implements Serializable, TypeConverter<Devices, DevicesDTO> {
@TableId(value = "id", type = IdType.AUTO)
@IsAutoIncrement
private Integer id;
@TableField
@Column(value = "agent_id", isNull = false, comment = "所属agent的id")
private Integer agentId;
@TableField
@Column(comment = "cpu架构", defaultValue = "")
private String cpu;
@TableField
@Column(value = "img_url", comment = "手机封面", defaultValue = "")
private String imgUrl;
@TableField
@Column(comment = "制造商", defaultValue = "")
private String manufacturer;
@TableField
@Column(comment = "手机型号", defaultValue = "")
private String model;
@TableField
@Column(comment = "设备名称", defaultValue = "")
private String name;
@TableField
@Column(comment = "设备安装app的密码", defaultValue = "")
private String password;
@TableField
@Column(isNull = false, comment = "系统类型 1:android 2:ios")
private Integer platform;
@TableField
@Column(value = "is_hm", isNull = false, comment = "是否为鸿蒙类型 1:鸿蒙 0:非鸿蒙", defaultValue = "0")
private Integer isHm;
@TableField
@Column(comment = "设备分辨率", defaultValue = "")
private String size;
@TableField
@Column(comment = "设备状态", defaultValue = "")
private String status;
@TableField
@Column(value = "ud_id", comment = "设备序列号", defaultValue = "")
@Index(value = "IDX_UD_ID", columns = {"ud_id"})
private String udId;
@TableField
@Column(comment = "设备系统版本", defaultValue = "")
private String version;
@TableField
@Column(value = "nick_name", comment = "设备备注", defaultValue = "")
private String nickName;
@TableField
@Column(comment = "设备当前占用者", defaultValue = "")
private String user;
@TableField
@Column(value = "chi_name", comment = "中文设备", defaultValue = "")
String chiName;
@TableField
@Column(defaultValue = "0", comment = "设备温度")
Integer temperature;
@TableField
@Column(defaultValue = "0", comment = "设备电池电压")
Integer voltage;
@TableField
@Column(defaultValue = "0", comment = "设备电量")
Integer level;
@TableField
@Column(defaultValue = "0", comment = "HUB位置")
Integer position;
public static Devices newDeletedDevice(int id) {<FILL_FUNCTION_BODY>}
}
|
String tips = "Device does not exist.";
return new Devices()
.setAgentId(0)
.setStatus("DISCONNECTED")
.setPlatform(0)
.setIsHm(0)
.setId(id)
.setVersion("unknown")
.setSize("unknown")
.setCpu("unknown")
.setManufacturer("unknown")
.setName(tips)
.setModel(tips)
.setChiName(tips)
.setNickName(tips)
.setName(tips)
.setUser(tips)
.setUdId(tips)
.setPosition(0)
.setTemperature(0)
.setVoltage(0)
.setLevel(0);
| 777
| 206
| 983
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Elements.java
|
Elements
|
newDeletedElement
|
class Elements implements Serializable, TypeConverter<Elements, ElementsDTO> {
@TableId(value = "id", type = IdType.AUTO)
@IsAutoIncrement
private Integer id;
@TableField
@Column(value = "ele_name", isNull = false, comment = "控件名称")
private String eleName;
@TableField
@Column(value = "ele_type", isNull = false, comment = "控件类型")
private String eleType;
@TableField
@Column(value = "ele_value", type = MySqlTypeConstant.LONGTEXT, comment = "控件内容")
private String eleValue;
@TableField
@Column(value = "project_id", isNull = false, comment = "所属项目id")
@Index(value = "IDX_PROJECT_ID", columns = {"project_id"})
private Integer projectId;
@TableField
@Column(value = "module_id", isNull = true, comment = "所属项目id", defaultValue = "0")
@Index(value = "IDX_MODULE_ID", columns = {"module_id"})
private Integer moduleId;
public static Elements newDeletedElement(int id) {<FILL_FUNCTION_BODY>}
}
|
String tips = "Element does not exist.";
return new Elements()
.setId(id)
.setEleName(tips)
.setModuleId(0)
.setEleType("id")
.setEleValue(tips)
.setProjectId(0);
| 330
| 80
| 410
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/DevicesDTO.java
|
DevicesDTO
|
getPosition
|
class DevicesDTO implements Serializable, TypeConverter<DevicesDTO, Devices> {
@Schema(description = "id", example = "1")
Integer id;
@Schema(description = "设备名称", example = "My HUAWEI")
String name;
@Schema(description = "设备备注", example = "My HUAWEI")
String nickName;
@Schema(description = "型号", example = "HUAWEI MATE 40")
String model;
@Schema(description = "序列号", example = "random")
String udId;
@Schema(description = "设备状态", example = "ONLINE")
String status;
@Schema(description = "所属Agent", example = "1")
Integer agentId;
@Schema(description = "设备系统", example = "1")
Integer platform;
@Schema(description = "鸿蒙类型", example = "0")
Integer isHm;
@Schema(description = "分辨率", example = "1080x1920")
String size;
@Schema(description = "系统版本", example = "12")
String version;
@Schema(description = "cpu", example = "arm64")
String cpu;
@Schema(description = "制造商", example = "HUAWEI")
String manufacturer;
@Schema(description = "安装密码", example = "123456")
String password;
@Schema(description = "设备图片路径")
String imgUrl;
@JsonIgnore
@JSONField(serialize = false)
Set<TestSuitesDTO> testSuites;
@Schema(description = "设备占用者")
String user;
@Getter(AccessLevel.NONE)
@Schema(description = "设备温度", example = "33")
Integer temperature;
@Getter(AccessLevel.NONE)
@Schema(description = "设备电池电压", example = "33")
Integer voltage;
@Getter(AccessLevel.NONE)
@Schema(description = "设备电量", example = "33")
Integer level;
@Getter(AccessLevel.NONE)
@Schema(description = "HUB位置", example = "1")
Integer position;
@Schema(description = "中文设备", example = "荣耀全网通")
String chiName;
public int getPosition() {<FILL_FUNCTION_BODY>}
public int getVoltage() {
if (voltage == null) {
return 0;
}
return voltage;
}
public int getTemperature() {
if (temperature == null) {
return 0;
}
return temperature;
}
public int getLevel() {
if (level == null) {
return 0;
}
return level;
}
}
|
if (position == null) {
return 0;
}
return position;
| 751
| 26
| 777
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/DeviceDetailChange.java
|
DeviceDetailChange
|
toString
|
class DeviceDetailChange implements Serializable {
@Positive
@Schema(description = "设备id", required = true, example = "1")
private int id;
@NotNull
@Schema(description = "设备安装密码", required = true, example = "123456")
private String password;
@NotNull
@Schema(description = "设备备注", required = true, example = "123456")
private String nickName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "DeviceDetailChange{" +
"id=" + id +
", password='" + password + '\'' +
", nickName='" + nickName + '\'' +
'}';
| 270
| 52
| 322
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/StepSort.java
|
StepSort
|
toString
|
class StepSort implements Serializable {
@NotNull
@Schema(description = "测试用例id", required = true, example = "1")
private int caseId;
@NotNull
@Schema(description = "拖拽方向", required = true, example = "up | down")
private String direction;
@Positive
@Schema(description = "移动后被影响的第一个步骤sort序号", required = true, example = "1")
private int startId;
@Positive
@Schema(description = "移动后被影响的最后一个步骤sort序号", required = true, example = "9")
private int endId;
public int getCaseId() {
return caseId;
}
public void setCaseId(int caseId) {
this.caseId = caseId;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public int getStartId() {
return startId;
}
public void setStartId(int startId) {
this.startId = startId;
}
public int getEndId() {
return endId;
}
public void setEndId(int endId) {
this.endId = endId;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "StepSort{" +
"caseId=" + caseId +
", direction='" + direction + '\'' +
", startId=" + startId +
", endId=" + endId +
'}';
| 363
| 61
| 424
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/UpdateDeviceImg.java
|
UpdateDeviceImg
|
toString
|
class UpdateDeviceImg implements Serializable {
@Positive
@Schema(description = "设备id", required = true, example = "1")
private int id;
@NotNull
@Schema(description = "设备图片Url", required = true, example = "123456")
private String imgUrl;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "UpdateDeviceImg{" +
"id=" + id +
", imgUrl='" + imgUrl + '\'' +
'}';
| 193
| 41
| 234
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/quartz/QuartzJob.java
|
QuartzJob
|
executeInternal
|
class QuartzJob extends QuartzJobBean implements Job {
@Autowired
private JobsService jobsService;
@Autowired
private TestSuitesService testSuitesService;
@Autowired
private ResultsService resultsService;
@Autowired
private FolderFeignClient folderFeignClient;
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) {<FILL_FUNCTION_BODY>}
}
|
JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap();
int type = dataMap.getInt("type");
switch (type) {
case JobType.TEST_JOB -> {
Jobs jobs = jobsService.findById(dataMap.getInt("id"));
if (jobs != null) {
RespModel<Integer> r;
try {
r = testSuitesService.runSuite(jobs.getSuiteId(), "SYSTEM");
} catch (Throwable e) {
log.info(e.fillInStackTrace().toString());
return;
}
if (r.getCode() == 3001) {
log.info("Test suite " + jobs.getSuiteId() + " deleted. " + r);
jobsService.delete(dataMap.getInt("id"));
} else {
log.info("Job start: Test suite " + jobs.getSuiteId() + " " + r);
}
} else {
log.info("Job id :" + dataMap.getInt("id") + " not found! ");
}
}
case JobType.CLEAN_FILE_JOB -> {
int day = Math.abs((int) ((jobExecutionContext.getNextFireTime().getTime() -
new Date().getTime()) / (1000 * 3600 * 24))) + 1;
RespModel<String> r = folderFeignClient.delete(day);
log.info("Clear file job..." + r);
}
case JobType.CLEAN_RESULT_JOB -> {
int day = Math.abs((int) ((jobExecutionContext.getNextFireTime().getTime() -
new Date().getTime()) / (1000 * 3600 * 24))) + 1;
resultsService.clean(day);
log.info("Clean result job...");
}
case JobType.SEND_DAY_REPORT -> {
resultsService.sendDayReport();
log.info("Send day report...");
}
case JobType.SEND_WEEK_REPORT -> {
resultsService.sendWeekReport();
log.info("Send week report...");
}
}
| 114
| 567
| 681
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/AgentsServiceImpl.java
|
AgentsServiceImpl
|
update
|
class AgentsServiceImpl extends SonicServiceImpl<AgentsMapper, Agents> implements AgentsService {
@Autowired
private DevicesService devicesService;
@Autowired
private AlertRobotsServiceImpl alertRobotsService;
@Autowired
private AgentsMapper agentsMapper;
@Override
public List<Agents> findAgents() {
return list();
}
@Override
public void update(int id, String name, int highTemp, int highTempTime, int robotType, String robotToken, String robotSecret, int[] alertRobotIds) {<FILL_FUNCTION_BODY>}
public void resetDevice(int id) {
List<Devices> devicesList = devicesService.listByAgentId(id);
for (Devices devices : devicesList) {
if ((!devices.getStatus().equals(DeviceStatus.OFFLINE))
&& (!devices.getStatus().equals(DeviceStatus.DISCONNECTED))) {
devices.setStatus(DeviceStatus.OFFLINE);
devicesService.save(devices);
}
}
}
@Override
public void saveAgents(JSONObject jsonObject) {
if (jsonObject.getInteger("agentId") != null && jsonObject.getInteger("agentId") != 0) {
if (existsById(jsonObject.getInteger("agentId"))) {
Agents oldAgent = findById(jsonObject.getInteger("agentId"));
oldAgent.setStatus(AgentStatus.ONLINE);
oldAgent.setHost(jsonObject.getString("host"));
oldAgent.setPort(jsonObject.getInteger("port"));
oldAgent.setVersion(jsonObject.getString("version"));
oldAgent.setSystemType(jsonObject.getString("systemType"));
if (jsonObject.getInteger("hasHub") != null) {
oldAgent.setHasHub(jsonObject.getInteger("hasHub"));
}
save(oldAgent);
}
}
}
@Override
public void saveAgents(Agents agents) {
save(agents);
}
@Override
@Transactional
public boolean updateAgentsByLockVersion(Agents agents) {
return lambdaUpdate()
.eq(Agents::getId, agents.getId())
.eq(Agents::getLockVersion, agents.getLockVersion())
.update(agents.setLockVersion(agents.getLockVersion() + 1));
}
@Deprecated
@Override
public boolean offLine(int id) {
if (existsById(id)) {
Agents agentOffLine = findById(id);
agentOffLine
.setStatus(AgentStatus.OFFLINE);
updateAgentsByLockVersion(agentOffLine);
resetDevice(agentOffLine.getId());
return true;
} else {
return false;
}
}
@Override
public Agents auth(String key) {
Agents agents = findBySecretKey(key);
if (agents != null) {
resetDevice(agents.getId());
}
return agents;
}
@Override
public Agents findById(int id) {
return baseMapper.selectById(id);
}
@Override
public Agents findBySecretKey(String secretKey) {
return lambdaQuery().eq(Agents::getSecretKey, secretKey).one();
}
@Override
public void errCall(int id, String udId, int tem, int type) {
alertRobotsService.sendErrorDevice(id, type, tem, udId);
}
}
|
if (id == 0) {
Agents agents = new Agents();
agents.setName(name);
agents.setHost("unknown");
agents.setStatus(AgentStatus.OFFLINE);
agents.setVersion("unknown");
agents.setPort(0);
agents.setSystemType("unknown");
agents.setHighTemp(highTemp);
agents.setHighTempTime(highTempTime);
agents.setRobotType(robotType);
agents.setRobotToken(robotToken);
agents.setRobotSecret(robotSecret);
agents.setSecretKey(UUID.randomUUID().toString());
agents.setHasHub(0);
agents.setAlertRobotIds(alertRobotIds);
save(agents);
} else {
Agents ag = findById(id);
if (ObjectUtils.isNotEmpty(ag)) {
ag.setName(name);
ag.setHighTemp(highTemp);
ag.setHighTempTime(highTempTime);
ag.setRobotType(robotType);
ag.setRobotToken(robotToken);
ag.setRobotSecret(robotSecret);
ag.setAlertRobotIds(alertRobotIds);
save(ag);
JSONObject result = new JSONObject();
result.put("msg", "settings");
result.put("highTemp", highTemp);
result.put("highTempTime", highTempTime);
TransportWorker.send(id, result);
}
}
| 904
| 381
| 1,285
|
<methods>public non-sealed void <init>() ,public boolean save(org.cloud.sonic.controller.models.domain.Agents) <variables>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/AlertRobotsServiceImpl.java
|
AlertRobotsServiceImpl
|
send
|
class AlertRobotsServiceImpl extends SonicServiceImpl<AlertRobotsMapper, AlertRobots> implements AlertRobotsService {
@Value("${robot.client.host}")
private String clientHost;
@Autowired
private RobotFactory robotFactory;
@Autowired
private RestTemplate restTemplate;
@Override
public CommentPage<AlertRobots> findRobots(Page<AlertRobots> page, Integer projectId, String scene) {
return CommentPage.convertFrom(findRobots(projectId, scene).page(page));
}
@Override
public List<AlertRobots> findAllRobots(Integer projectId, String scene) {
return findRobots(projectId, scene).list();
}
private LambdaQueryChainWrapper<AlertRobots> findRobots(Integer projectId, String scene) {
var query = lambdaQuery();
query.eq(null != scene, AlertRobots::getScene, scene);
query.and(null != projectId,
it -> it.eq(AlertRobots::getProjectId, projectId).or(
p -> p.apply("1 = (select global_robot from projects where id = {0})", projectId).isNull(AlertRobots::getProjectId)
)
);
return query;
}
@Override
public void sendResultFinishReport(int suitId, String suiteName, int pass, int warn, int fail, int projectId, int resultId) {
var robots = baseMapper.computeTestsuiteRobots(suitId);
if (robots.isEmpty()) return;
var msg = new TestSuiteMessage(suiteName, pass, warn, fail, projectId, resultId, clientHost + "/Home/" + projectId + "/ResultDetail/" + resultId);
send(robots, msg);
}
@Override
public void sendProjectReportMessage(int projectId, String projectName, Date startDate, Date endDate, boolean isWeekly, int pass, int warn, int fail) {
var robots = findRobots(projectId, SCENE_SUMMARY).list();
if (robots.isEmpty()) return;
var total = pass + warn + fail;
var rate = total > 0 ? BigDecimal.valueOf(((float) pass / total) * 100).setScale(2, RoundingMode.HALF_UP).doubleValue() : 0;
var url = clientHost + "/Home/" + projectId;
var msg = new ProjectSummaryMessage(projectId, projectName, startDate, endDate, pass, warn, fail, rate, total, url, isWeekly);
send(robots, msg);
}
@Override
public void sendErrorDevice(int agentId, int errorType, int tem, String udId) {
var robots = baseMapper.computeAgentRobots(agentId);
if (robots.isEmpty()) return;
var msg = new DeviceMessage(errorType, new BigDecimal(BigInteger.valueOf(tem), 1), udId);
send(robots, msg);
}
private void send(List<AlertRobots> robots, Message message) {<FILL_FUNCTION_BODY>}
@Override
public String getDefaultNoticeTemplate(int type, String scene) {
var messenger = robotFactory.getRobotMessenger(type);
var template = switch (scene) {
case SCENE_AGENT -> messenger.getDefaultDeviceMessageTemplate();
case SCENE_SUMMARY -> messenger.getDefaultProjectSummaryTemplate();
case SCENE_TESTSUITE -> messenger.getDefaultTestSuiteTemplate();
default -> null;
};
if (null == template) {
return "";
} else if (template instanceof SpelExpression) {
return RobotMessenger.templateParserContext.getExpressionPrefix() + template.getExpressionString() + RobotMessenger.templateParserContext.getExpressionSuffix();
} else {
return template.getExpressionString();
}
}
}
|
for (var robot : robots) {
try {
var messenger = robotFactory.getRobotMessenger(robot.getRobotType(), robot.getMuteRule(), message);
if (messenger == null) continue;
var template = robot.getTemplate();
messenger.sendMessage(restTemplate, robot.getRobotToken(), robot.getRobotSecret(), template, message);
} catch (Exception e) {
log.warn("send messaget to robot {} failed, skipping", robot, e);
}
}
| 1,024
| 139
| 1,163
|
<methods>public non-sealed void <init>() ,public boolean save(org.cloud.sonic.controller.models.domain.AlertRobots) <variables>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ConfListServiceImpl.java
|
ConfListServiceImpl
|
save
|
class ConfListServiceImpl extends SonicServiceImpl<ConfListMapper, ConfList> implements ConfListService {
@Override
public ConfList searchByKey(String key) {
return lambdaQuery().eq(ConfList::getConfKey, key).last("limit 1").one();
}
@Override
public void save(String key, String content, String extra) {<FILL_FUNCTION_BODY>}
}
|
ConfList conf = searchByKey(key);
if (conf == null) {
conf = new ConfList();
}
conf.setContent(content)
.setConfKey(key)
.setExtra(extra);
saveOrUpdate(conf);
| 107
| 70
| 177
|
<methods>public non-sealed void <init>() ,public boolean save(org.cloud.sonic.controller.models.domain.ConfList) <variables>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ElementsServiceImpl.java
|
ElementsServiceImpl
|
findAllStepsByElementsId
|
class ElementsServiceImpl extends SonicServiceImpl<ElementsMapper, Elements> implements ElementsService {
@Autowired
private ElementsMapper elementsMapper;
@Autowired
private StepsService stepsService;
@Autowired
private TestCasesService testCasesService;
@Autowired
private StepsElementsMapper stepsElementsMapper;
@Autowired
private ModulesMapper modulesMapper;
@Override
public CommentPage<ElementsDTO> findAll(int projectId, String type, List<String> eleTypes, String name, String value, List<Integer> moduleIds, Page<Elements> pageable) {
LambdaQueryChainWrapper<Elements> lambdaQuery = new LambdaQueryChainWrapper<>(elementsMapper);
if (type != null && type.length() > 0) {
switch (type) {
case "normal" -> lambdaQuery.and(
l -> l.ne(Elements::getEleType, "point").ne(Elements::getEleType, "image").ne(Elements::getEleType, "poco")
);
case "poco" ->
lambdaQuery.and(i -> i.eq(Elements::getEleType, "poco").or().eq(Elements::getEleType, "xpath").or().eq(Elements::getEleType, "cssSelector"));
case "point" -> lambdaQuery.eq(Elements::getEleType, "point");
case "image" -> lambdaQuery.eq(Elements::getEleType, "image");
}
}
lambdaQuery.eq(Elements::getProjectId, projectId)
.in(eleTypes != null, Elements::getEleType, eleTypes)
.in(moduleIds != null && moduleIds.size() > 0, Elements::getModuleId, moduleIds)
.like(!StringUtils.isEmpty(name), Elements::getEleName, name)
.like(!StringUtils.isEmpty(value), Elements::getEleValue, value)
.orderByDesc(Elements::getId);
//写入对应模块信息
Page<Elements> page = lambdaQuery.page(pageable);
List<ElementsDTO> elementsDTOS = page.getRecords()
.stream().map(e -> findEleDetail(e)).collect(Collectors.toList());
return CommentPage.convertFrom(page, elementsDTOS);
}
@Transactional
private ElementsDTO findEleDetail(Elements elements) {
if (elements.getModuleId() != null && elements.getModuleId() != 0) {
Modules modules = modulesMapper.selectById(elements.getModuleId());
if (modules != null) {
return elements.convertTo().setModulesDTO(modules.convertTo());
}
}
return elements.convertTo();
}
@Override
public List<StepsDTO> findAllStepsByElementsId(int elementsId) {<FILL_FUNCTION_BODY>}
@Override
@Transactional(rollbackFor = Exception.class)
public RespModel delete(int id) {
if (existsById(id)) {
new LambdaUpdateChainWrapper<StepsElements>(stepsElementsMapper).eq(StepsElements::getElementsId, id)
.set(StepsElements::getElementsId, 0).update();
baseMapper.deleteById(id);
return new RespModel<>(RespEnum.DELETE_OK);
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
}
@Override
public Elements findById(int id) {
return baseMapper.selectById(id);
}
@Override
public boolean deleteByProjectId(int projectId) {
return baseMapper.delete(new LambdaQueryWrapper<Elements>().eq(Elements::getProjectId, projectId)) > 0;
}
/**
* 复制控件元素
*
* @param id 元素id
*/
@Override
@Transactional(rollbackFor = Exception.class)
public RespModel<String> copy(int id) {
Elements element = elementsMapper.selectById(id);
element.setId(null).setEleName(element.getEleName() + "_copy");
save(element);
return new RespModel<>(RespEnum.COPY_OK);
}
@Override
public Boolean newStepBeLinkedEle(StepsDTO stepsDTO, Steps step) {
for (ElementsDTO elements : stepsDTO.getElements()) {
stepsElementsMapper.insert(new StepsElements()
.setElementsId(elements.getId())
.setStepsId(step.getId()));
}
return true;
}
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean updateEleModuleByModuleId(Integer module) {
List<Elements> elements = lambdaQuery().eq(Elements::getModuleId, module).list();
if (elements == null) {
return true;
}
for (Elements element : elements) {
save(element.setModuleId(0));
}
return true;
}
}
|
return stepsService.listStepsByElementsId(elementsId).stream().map(e -> {
StepsDTO stepsDTO = e.convertTo();
if (0 == stepsDTO.getCaseId()) {
return stepsDTO.setTestCasesDTO(new TestCasesDTO().setId(0).setName("unknown"));
}
return stepsDTO.setTestCasesDTO(testCasesService.findById(stepsDTO.getCaseId()));
}).collect(Collectors.toList());
| 1,319
| 133
| 1,452
|
<methods>public non-sealed void <init>() ,public boolean save(org.cloud.sonic.controller.models.domain.Elements) <variables>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/JobsServiceImpl.java
|
JobsServiceImpl
|
delete
|
class JobsServiceImpl extends SonicServiceImpl<JobsMapper, Jobs> implements JobsService {
@Autowired
private QuartzHandler quartzHandler;
@Autowired
private JobsMapper jobsMapper;
private static final String TEST_JOB = "testJob";
@Override
@Transactional(rollbackFor = Exception.class)
public RespModel<String> saveJobs(Jobs jobs) throws SonicException {
jobs.setStatus(JobStatus.ENABLE);
jobs.setType(TEST_JOB);
save(jobs);
CronTrigger trigger = quartzHandler.getTrigger(jobs);
try {
if (trigger != null) {
quartzHandler.updateScheduleJob(jobs);
} else {
quartzHandler.createScheduleJob(jobs);
}
return new RespModel<>(RespEnum.HANDLE_OK);
} catch (RuntimeException | SchedulerException e) {
e.printStackTrace();
throw new SonicException("error.cron");
}
}
@Override
public RespModel<String> updateStatus(int id, int type) {
if (existsById(id)) {
try {
Jobs jobs = findById(id);
switch (type) {
case JobStatus.DISABLE:
quartzHandler.pauseScheduleJob(jobs);
jobs.setStatus(JobStatus.DISABLE);
save(jobs);
return new RespModel<>(2000, "job.disable");
case JobStatus.ENABLE:
quartzHandler.resumeScheduleJob(jobs);
jobs.setStatus(JobStatus.ENABLE);
save(jobs);
return new RespModel<>(2000, "job.enable");
case JobStatus.ONCE:
quartzHandler.runScheduleJob(jobs);
return new RespModel<>(2000, "job.start");
default:
return new RespModel<>(3000, "job.params.invalid");
}
} catch (RuntimeException | SchedulerException e) {
e.printStackTrace();
return new RespModel<>(3000, "job.handle.fail");
}
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
}
@Transactional(rollbackFor = Exception.class)
@Override
public RespModel<String> delete(int id) {<FILL_FUNCTION_BODY>}
@Override
public Page<Jobs> findByProjectId(int projectId, Page<Jobs> pageable) {
return lambdaQuery()
.eq(Jobs::getProjectId, projectId)
.eq(Jobs::getType, TEST_JOB)
.orderByDesc(Jobs::getId)
.page(pageable);
}
@Override
public Jobs findById(int id) {
return lambdaQuery()
.eq(Jobs::getId, id)
.eq(Jobs::getType, TEST_JOB)
.one();
}
@Override
public Jobs findByType(String type) {
return lambdaQuery()
.eq(Jobs::getType, type)
.one();
}
@Override
public void updateSysJob(String type, String cron) {
Jobs jobs = lambdaQuery()
.eq(Jobs::getType, type)
.one();
if (jobs != null) {
jobs.setCronExpression(cron);
save(jobs);
}
quartzHandler.updateSysScheduleJob(type, cron);
}
@Override
public List<JSONObject> findSysJobs() {
return quartzHandler.findSysJobs();
}
}
|
Jobs jobs = baseMapper.selectById(id);
try {
quartzHandler.deleteScheduleJob(jobs);
} catch (SchedulerException e) {
return new RespModel<>(RespEnum.DELETE_FAIL);
}
int count = baseMapper.deleteById(id);
if (count > 0) {
return new RespModel<>(RespEnum.DELETE_OK);
}
return new RespModel<>(RespEnum.ID_NOT_FOUND);
| 982
| 130
| 1,112
|
<methods>public non-sealed void <init>() ,public boolean save(org.cloud.sonic.controller.models.domain.Jobs) <variables>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ModulesServiceImpl.java
|
ModulesServiceImpl
|
delete
|
class ModulesServiceImpl extends SonicServiceImpl<ModulesMapper, Modules> implements ModulesService {
@Autowired
private ModulesMapper modulesMapper;
@Autowired
private ElementsService elementsService;
@Autowired
private TestCasesService testCasesService;
@Override
@Transactional(rollbackFor = Exception.class)
public boolean delete(int id) {<FILL_FUNCTION_BODY>}
@Override
public List<Modules> findByProjectId(int projectId) {
return lambdaQuery().eq(Modules::getProjectId, projectId).list();
}
@Override
public Modules findById(int id) {
return modulesMapper.selectById(id);
}
@Override
public boolean deleteByProjectId(int projectId) {
return baseMapper.delete(new LambdaQueryWrapper<Modules>().eq(Modules::getProjectId, projectId)) > 0;
}
}
|
int i = modulesMapper.deleteById(id);
elementsService.updateEleModuleByModuleId(id);
testCasesService.updateTestCaseModuleByModuleId(id);
return i > 0;
| 249
| 54
| 303
|
<methods>public non-sealed void <init>() ,public boolean save(org.cloud.sonic.controller.models.domain.Modules) <variables>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/PackagesServiceImpl.java
|
PackagesServiceImpl
|
findByProjectId
|
class PackagesServiceImpl extends SonicServiceImpl<PackagesMapper, Packages> implements PackagesService {
@Override
public String findOne(int projectId, String branch, String platform) {
Packages packages = lambdaQuery().eq(Packages::getProjectId, projectId)
.eq(StringUtils.isNotBlank(platform), Packages::getPlatform, platform)
.like(StringUtils.isNotBlank(branch), Packages::getBranch, branch)
.orderByDesc(Packages::getId).last("LIMIT 1").one();
if (packages != null) {
return packages.getUrl();
} else {
return "";
}
}
@Override
public CommentPage<PackageDTO> findByProjectId(int projectId, String branch, String platform, String packageName,
Page<Packages> pageable) {<FILL_FUNCTION_BODY>}
}
|
Page<Packages> page = lambdaQuery().eq(Packages::getProjectId, projectId)
.eq(StringUtils.isNotBlank(platform), Packages::getPlatform, platform)
.like(StringUtils.isNotBlank(branch), Packages::getBranch, branch)
.like(StringUtils.isNotBlank(packageName), Packages::getPkgName, packageName)
.orderByDesc(Packages::getId)
.page(pageable);
List<PackageDTO> packageDTOList = page.getRecords()
.stream().map(TypeConverter::convertTo).collect(Collectors.toList());
return CommentPage.convertFrom(page, packageDTOList);
| 224
| 177
| 401
|
<methods>public non-sealed void <init>() ,public boolean save(org.cloud.sonic.controller.models.domain.Packages) <variables>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ProjectsServiceImpl.java
|
ProjectsServiceImpl
|
delete
|
class ProjectsServiceImpl extends SonicServiceImpl<ProjectsMapper, Projects> implements ProjectsService {
@Autowired
private ElementsService elementsService;
@Autowired
private GlobalParamsService globalParamsService;
@Autowired
private ModulesService modulesService;
@Autowired
private VersionsService versionsService;
@Autowired
private PublicStepsService publicStepsService;
@Autowired
private ResultsService resultsService;
@Autowired
private ResultDetailService resultDetailService;
@Autowired
private StepsService stepsService;
@Autowired
private TestSuitesService testSuitesService;
@Autowired
private TestCasesService testCasesService;
@Autowired
private ScriptsService scriptsService;
@Override
public Projects findById(int id) {
return baseMapper.selectById(id);
}
@Override
public List<Projects> findAll() {
return list();
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(int id) throws SonicException {<FILL_FUNCTION_BODY>}
}
|
try {
testSuitesService.deleteByProjectId(id);
publicStepsService.deleteByProjectId(id);
testCasesService.deleteByProjectId(id);
stepsService.deleteByProjectId(id);
elementsService.deleteByProjectId(id);
modulesService.deleteByProjectId(id);
globalParamsService.deleteByProjectId(id);
List<Results> resultsList = resultsService.findByProjectId(id);
for (Results results : resultsList) {
resultDetailService.deleteByResultId(results.getId());
}
resultsService.deleteByProjectId(id);
versionsService.deleteByProjectId(id);
scriptsService.deleteByProjectId(id);
baseMapper.deleteById(id);
} catch (Exception e) {
e.printStackTrace();
throw new SonicException("project.delete.fail");
}
| 305
| 227
| 532
|
<methods>public non-sealed void <init>() ,public boolean save(org.cloud.sonic.controller.models.domain.Projects) <variables>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ResourcesServiceImpl.java
|
ResourcesServiceImpl
|
updateResourceAuth
|
class ResourcesServiceImpl extends SonicServiceImpl<ResourcesMapper, Resources> implements ResourcesService {
@Resource
private RoleResourcesMapper roleResourcesMapper;
@Value("${spring.version}")
private String version;
@Override
@Transactional
public void init() {
RequestMappingHandlerMapping requestMappingHandlerMapping = SpringTool.getApplicationContext().getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
Map<String, Resources> parentMap = new HashMap<>();
map.forEach((key, value) -> {
String beanName = value.getBean().toString();
Resources parentResource = parentMap.getOrDefault(beanName, processParent(beanName, parentMap));
if (parentResource == null) {
return;
}
processResource(parentResource, key, value);
});
processUnusedResource();
}
private void processUnusedResource() {
// 将不需要的 url 全部标记为 white
lambdaUpdate().ne(Resources::getVersion, version)
.set(Resources::getWhite, UrlType.WHITE)
.update();
}
private Resources processParent(String beanName, Map<String, Resources> parentMap) {
Tag api = SpringTool.getBean(beanName).getClass().getAnnotation(Tag.class);
if (api == null) {
return null;
}
RequestMapping requestMapping = AopUtils.getTargetObject(SpringTool.getBean(beanName)).getClass().getAnnotation(RequestMapping.class);
if (requestMapping == null) {
return null;
}
boolean needInsert = false;
String res = requestMapping.value()[0];
Resources parentResource = searchByPath(res, UrlType.PARENT);
if (parentResource == null) {
parentResource = new Resources();
parentResource.setNeedAuth(UrlType.PARENT);
parentResource.setMethod("parent");
parentMap.put(beanName, parentResource);
needInsert = true;
}
String tag = api.name();
parentResource.setDesc(tag);
parentResource.setPath(res);
parentResource.setVersion(version);
// 每次扫描都把parent 设置为正常资源
parentResource.setWhite(UrlType.NORMAL);
if (needInsert) {
insert(parentResource);
} else {
parentResource.setUpdateTime(null);
updateById(parentResource);
}
return parentResource;
}
private void processResource(Resources parentResource, RequestMappingInfo key, HandlerMethod value) {
String path = (String) key.getPatternsCondition().getPatterns().toArray()[0];
String method = key.getMethodsCondition().getMethods().toArray()[0].toString();
boolean needInsert = false;
Resources resource = lambdaQuery().eq(Resources::getPath, path)
.eq(Resources::getMethod, method)
.last("limit 1")
.one();
if (resource == null) {
resource = new Resources();
//初始化说有资源不需要鉴权
resource.setNeedAuth(UrlType.WHITE);
needInsert = true;
if (path.equals("/devices/stopDebug")) {
resource.setNeedAuth(UrlType.NORMAL);
}
}
resource.setParentId(parentResource.getId());
resource.setMethod(method);
resource.setPath(path);
resource.setVersion(version);
Operation apiOperation = value.getMethodAnnotation(Operation.class);
WhiteUrl whiteUrl = value.getMethodAnnotation(WhiteUrl.class);
if (apiOperation == null) {
resource.setDesc("未设置");
} else {
resource.setDesc(apiOperation.summary());
}
//标记相关资源加白
resource.setWhite(whiteUrl == null ? UrlType.NORMAL : UrlType.WHITE);
if (needInsert) {
insert(resource);
} else {
resource.setUpdateTime(null);
updateById(resource);
}
}
@Override
public Resources searchByPath(String path, Integer parentId) {
return lambdaQuery().eq(Resources::getPath, path)
.eq(Resources::getParentId, parentId)
.orderByAsc(Resources::getId)
.last("limit 1")
.one();
}
@Override
public Resources search(String path, String method) {
return lambdaQuery().eq(Resources::getPath, path)
.eq(Resources::getMethod, method)
.gt(Resources::getParentId, UrlType.PARENT)
.orderByAsc(Resources::getId)
.last("limit 1")
.one();
}
public int insert(Resources resources) {
return getBaseMapper().insert(resources);
}
@Override
public void updateResourceAuth(Integer id, Boolean needAuth) {<FILL_FUNCTION_BODY>}
@Override
public CommentPage<ResourcesDTO> listResource(Page<Resources> page, String path, boolean isAll) {
if (isAll) {
page.setSize(10000);
page.setCurrent(1);
}
Page<Resources> resources = lambdaQuery()
.gt(Resources::getParentId, UrlType.PARENT)
.eq(Resources::getWhite, UrlType.NORMAL)
.like(!StringUtils.isEmpty(path), Resources::getPath, path)
.orderByDesc(Resources::getId)
.page(page);
List<ResourcesDTO> resourcesDTOList = resources.getRecords().stream()
.map(TypeConverter::convertTo).collect(Collectors.toList());
return CommentPage.convertFrom(page, resourcesDTOList);
}
private List<ResourcesDTO> listParentResource() {
return lambdaQuery().eq(Resources::getParentId, UrlType.PARENT)
.eq(Resources::getWhite, UrlType.NORMAL)
.orderByDesc(Resources::getId)
.list().stream()
.map(TypeConverter::convertTo).collect(Collectors.toList());
}
@Override
public List<ResourcesDTO> listRoleResource(Integer roleId) {
CommentPage<ResourcesDTO> commentPage = listResource(new Page<>(), null, true);
List<ResourcesDTO> parentListResource = listParentResource();
Map<Integer, ResourcesDTO> mapParent = parentListResource.stream().collect(Collectors.toMap(ResourcesDTO::getId, Function.identity(), (a, b) -> a));
List<RoleResources> roleResourcesList = lambdaQuery(roleResourcesMapper).eq(RoleResources::getRoleId, roleId).list();
Map<Integer, RoleResources> map = null;
if (!CollectionUtils.isEmpty(roleResourcesList)) {
map = roleResourcesList.stream().collect(Collectors.toMap(RoleResources::getResId, Function.identity(), (a, b) -> a));
}
Map<Integer, RoleResources> finalMap = map;
commentPage.getContent().stream().forEach(a -> {
//判断当前资源是否具有权限
if (finalMap != null && finalMap.containsKey(a.getId())) {
a.setHasAuth(true);
} else {
a.setHasAuth(false);
}
// 构建权限树
ResourcesDTO parent = mapParent.get(a.getParentId());
if (parent != null) {
if (parent.getChild() == null) {
parent.setChild(new ArrayList<>());
}
parent.getChild().add(a);
}
});
return parentListResource;
}
}
|
lambdaUpdate().eq(Resources::getId, id)
.set(Resources::getNeedAuth, needAuth ? UrlType.NORMAL : UrlType.WHITE)
.update();
| 1,989
| 51
| 2,040
|
<methods>public non-sealed void <init>() ,public boolean save(org.cloud.sonic.controller.models.domain.Resources) <variables>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ResultDetailServiceImpl.java
|
ResultDetailServiceImpl
|
findAll
|
class ResultDetailServiceImpl extends SonicServiceImpl<ResultDetailMapper, ResultDetail> implements ResultDetailService {
@Autowired
private ResultDetailMapper resultDetailMapper;
@Autowired
private DevicesService devicesService;
@Autowired
private ResultsService resultsService;
@Override
public void saveByTransport(JSONObject jsonMsg) {
Devices resultDevice = devicesService.findByAgentIdAndUdId(jsonMsg.getInteger("agentId")
, jsonMsg.getString("udId"));
ResultDetail resultInfo = new ResultDetail();
resultInfo.setType(jsonMsg.getString("msg"));
resultInfo.setLog(jsonMsg.getString("log"));
resultInfo.setDes(jsonMsg.getString("des"));
resultInfo.setStatus(jsonMsg.getInteger("status"));
resultInfo.setResultId(jsonMsg.getInteger("rid"));
resultInfo.setCaseId(jsonMsg.getInteger("cid"));
resultInfo.setTime(jsonMsg.getDate("time"));
resultInfo.setDeviceId(resultDevice == null ? 0 : resultDevice.getId());
if (resultInfo.getType().equals("status")) {
baseMapper.delete(new LambdaQueryWrapper<ResultDetail>()
.eq(ResultDetail::getResultId, resultInfo.getResultId())
.eq(ResultDetail::getType, resultInfo.getType())
.eq(ResultDetail::getCaseId, resultInfo.getCaseId())
.eq(ResultDetail::getDeviceId, resultInfo.getDeviceId())
);
}
save(resultInfo);
if (jsonMsg.getString("msg").equals("status")) {
resultsService.suiteResult(jsonMsg.getInteger("rid"));
}
}
@Override
public Page<ResultDetail> findAll(int resultId, int caseId, String type, int deviceId, Page<ResultDetail> pageable) {<FILL_FUNCTION_BODY>}
@Override
public List<ResultDetail> findAll(int resultId, int caseId, String type, int deviceId) {
LambdaQueryChainWrapper<ResultDetail> lambdaQuery = lambdaQuery();
if (resultId != 0) {
lambdaQuery.eq(ResultDetail::getResultId, resultId);
}
if (caseId != 0) {
lambdaQuery.eq(ResultDetail::getCaseId, caseId);
}
if (type != null && type.length() > 0) {
lambdaQuery.eq(ResultDetail::getType, type);
}
if (deviceId != 0) {
lambdaQuery.eq(ResultDetail::getDeviceId, deviceId);
}
return lambdaQuery.orderByAsc(ResultDetail::getTime).list();
}
@Override
public void deleteByResultId(int resultId) {
baseMapper.delete(new QueryWrapper<ResultDetail>().eq("result_id", resultId));
}
@Override
public List<JSONObject> findTimeByResultIdGroupByCaseId(int resultId) {
return resultDetailMapper.findTimeByResultIdGroupByCaseId(resultId);
}
@Override
public List<JSONObject> findStatusByResultIdGroupByCaseId(int resultId) {
return resultDetailMapper.findStatusByResultIdGroupByCaseId(resultId);
}
@Override
public List<JSONObject> findTopCases(String startTime, String endTime, int projectId) {
return resultDetailMapper.findTopCases(startTime, endTime, projectId);
}
@Override
public List<JSONObject> findTopDevices(String startTime, String endTime, int projectId) {
return resultDetailMapper.findTopDevices(startTime, endTime, projectId);
}
}
|
LambdaQueryChainWrapper<ResultDetail> lambdaQuery = lambdaQuery();
if (resultId != 0) {
lambdaQuery.eq(ResultDetail::getResultId, resultId);
}
if (caseId != 0) {
lambdaQuery.eq(ResultDetail::getCaseId, caseId);
}
if (type != null && type.length() > 0) {
lambdaQuery.eq(ResultDetail::getType, type);
}
if (deviceId != 0) {
lambdaQuery.eq(ResultDetail::getDeviceId, deviceId);
}
return lambdaQuery.orderByAsc(ResultDetail::getTime)
.page(pageable);
| 951
| 183
| 1,134
|
<methods>public non-sealed void <init>() ,public boolean save(org.cloud.sonic.controller.models.domain.ResultDetail) <variables>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/RolesServiceImpl.java
|
RolesServiceImpl
|
saveResourceRoles
|
class RolesServiceImpl extends SonicServiceImpl<RolesMapper, Roles> implements RolesServices {
@Resource
private RoleResourcesMapper roleResourcesMapper;
@Override
@Transactional
public void save(RolesDTO rolesDTO) {
Roles roles = rolesDTO.convertTo();
if (rolesDTO.getId() == null) {
save(roles);
} else {
lambdaUpdate().eq(Roles::getId, roles.getId())
.update(roles);
}
}
@Override
public CommentPage<RolesDTO> listRoles(Page<Roles> page, String roleName) {
Page<Roles> roles = lambdaQuery()
.like(!StringUtils.isEmpty(roleName), Roles::getRoleName, roleName)
.orderByDesc(Roles::getId)
.page(page);
List<RolesDTO> rolesDTOList = roles.getRecords().stream()
.map(TypeConverter::convertTo).collect(Collectors.toList());
return CommentPage.convertFrom(page, rolesDTOList);
}
@Override
public Map<Integer, Roles> mapRoles() {
return lambdaQuery()
.orderByDesc(Roles::getId)
.list()
.stream()
.collect(Collectors.toMap(Roles::getId, Function.identity(), (a, b) -> a));
}
@Override
public Roles findById(Integer roleId) {
return getById(roleId);
}
@Transactional
public void editResourceRoles(Integer roleId, Integer resId, boolean hasAuth) {
if (hasAuth) {
roleResourcesMapper.insert(RoleResources.builder().roleId(roleId).resId(resId).build());
} else {
roleResourcesMapper.delete(new LambdaQueryWrapper<RoleResources>()
.eq(RoleResources::getRoleId, roleId)
.eq(RoleResources::getResId, resId));
}
}
@Override
@Transactional
public void saveResourceRoles(Integer roleId, List<Integer> resId) {<FILL_FUNCTION_BODY>}
@Transactional
@Override
public void delete(Integer roleId) {
getBaseMapper().deleteById(roleId);
}
@Override
public boolean checkUserHasResourceAuthorize(String userName, String path, String method) {
int count = roleResourcesMapper.checkUserHasResourceAuthorize(userName, path, method);
return count > 0;
}
}
|
// 先查询目前角色下所有权限
List<RoleResources> roleResourcesList = lambdaQuery(roleResourcesMapper).eq(RoleResources::getRoleId, roleId).list();
List<Integer> roleResourceIds = roleResourcesList.stream().map(RoleResources::getResId).collect(Collectors.toList());
List<Integer> roleResourceCopyIds = roleResourceIds.stream().collect(Collectors.toList());
//移除当前角色不需要资源
roleResourceIds.removeAll(resId);
roleResourcesMapper.delete(new LambdaQueryWrapper<RoleResources>().eq(RoleResources::getRoleId, roleId).in(RoleResources::getResId, roleResourceIds));
//添加当前角色下新权限
resId.removeAll(roleResourceCopyIds);
resId.stream().map(id -> RoleResources.builder().roleId(roleId).resId(id).build())
.forEach(e -> roleResourcesMapper.insert(e));
| 658
| 242
| 900
|
<methods>public non-sealed void <init>() ,public boolean save(org.cloud.sonic.controller.models.domain.Roles) <variables>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ScriptsServiceImpl.java
|
ScriptsServiceImpl
|
findByProjectId
|
class ScriptsServiceImpl extends SonicServiceImpl<ScriptsMapper, Scripts> implements ScriptsService {
@Autowired
private ScriptsMapper scriptsMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public boolean delete(int id) {
return scriptsMapper.deleteById(id) > 0;
}
@Override
public Page<Scripts> findByProjectId(Integer projectId, String name, Page<Scripts> pageable) {<FILL_FUNCTION_BODY>}
@Override
public Scripts findById(int id) {
return scriptsMapper.selectById(id);
}
@Override
public boolean deleteByProjectId(int projectId) {
return baseMapper.delete(new LambdaQueryWrapper<Scripts>().eq(Scripts::getProjectId, projectId)) > 0;
}
}
|
return lambdaQuery().eq((projectId != null && projectId != 0), Scripts::getProjectId, projectId)
.like((name != null && name.length() > 0), Scripts::getName, name)
.orderByDesc(Scripts::getId)
.page(pageable);
| 219
| 78
| 297
|
<methods>public non-sealed void <init>() ,public boolean save(org.cloud.sonic.controller.models.domain.Scripts) <variables>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/UsersServiceImpl.java
|
UsersServiceImpl
|
login
|
class UsersServiceImpl extends SonicServiceImpl<UsersMapper, Users> implements UsersService {
private final Logger logger = LoggerFactory.getLogger(UsersServiceImpl.class);
@Autowired
private JWTTokenTool jwtTokenTool;
@Autowired
private UsersMapper usersMapper;
@Autowired
private RolesServices rolesServices;
@Value("${sonic.user.ldap.enable}")
private boolean ldapEnable;
@Value("${sonic.user.normal.enable}")
private boolean normalEnable;
@Value("${sonic.user.register.enable}")
private boolean registerEnable;
@Value("${sonic.user.ldap.userId}")
private String userId;
@Value("${sonic.user.ldap.userBaseDN}")
private String userBaseDN;
@Value("${sonic.user.ldap.objectClass}")
private String objectClass;
@Autowired
@Lazy
private LdapTemplate ldapTemplate;
@Override
public JSONObject getLoginConfig() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("registerEnable", registerEnable);
jsonObject.put("normalEnable", normalEnable);
jsonObject.put("ldapEnable", ldapEnable);
return jsonObject;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void register(Users users) throws SonicException {
if (registerEnable) {
try {
users.setPassword(DigestUtils.md5DigestAsHex(users.getPassword().getBytes()));
save(users);
} catch (Exception e) {
e.printStackTrace();
throw new SonicException("register.repeat.username");
}
} else {
throw new SonicException("register.disable");
}
}
@Override
public String login(UserInfo userInfo) {<FILL_FUNCTION_BODY>}
private boolean checkLdapAuthenticate(UserInfo userInfo, boolean create) {
if (!ldapEnable) return false;
String username = userInfo.getUserName();
String password = userInfo.getPassword();
if (password.isEmpty()) return false;
logger.info("login check content username {}", username);
AndFilter filter = new AndFilter();
filter.and(new EqualsFilter("objectclass", objectClass)).and(new EqualsFilter(userId, username));
try {
boolean authResult = ldapTemplate.authenticate(userBaseDN, filter.toString(), password);
if (create && authResult) {
save(buildUser(userInfo));
}
return authResult;
} catch (Exception e) {
logger.info("ldap login failed, cause: {}", e.getMessage());
return false;
}
}
private Users buildUser(UserInfo userInfo) {
Users users = new Users();
users.setUserName(userInfo.getUserName());
users.setPassword("");
users.setSource(UserLoginType.LDAP);
return users;
}
@Override
public Users getUserInfo(String token) {
String name = jwtTokenTool.getUserName(token);
if (name != null) {
Users users = findByUserName(name);
users.setPassword("");
return users;
} else {
return null;
}
}
@Override
public RespModel<String> resetPwd(String token, ChangePwd changePwd) {
String name = jwtTokenTool.getUserName(token);
if (name != null) {
Users users = findByUserName(name);
if (users != null) {
if (DigestUtils.md5DigestAsHex(changePwd.getOldPwd().getBytes()).equals(users.getPassword())) {
users.setPassword(DigestUtils.md5DigestAsHex(changePwd.getNewPwd().getBytes()));
save(users);
return new RespModel(2000, "password.change.ok");
} else {
return new RespModel(4001, "password.auth.fail");
}
} else {
return new RespModel(RespEnum.UNAUTHORIZED);
}
} else {
return new RespModel(RespEnum.UNAUTHORIZED);
}
}
@Override
public Users findByUserName(String userName) {
Assert.hasText(userName, "userName must not be null");
return lambdaQuery().eq(Users::getUserName, userName).one();
}
@Override
public CommentPage<UsersDTO> listUsers(Page<Users> page, String userName) {
Page<Users> users = lambdaQuery()
.like(!StringUtils.isEmpty(userName), Users::getUserName, userName)
.orderByDesc(Users::getId)
.page(page);
Map<Integer, Roles> rolesMap = rolesServices.mapRoles();
final Roles emptyRole = new Roles();
List<UsersDTO> rolesDTOList = users.getRecords().stream()
.map(e -> {
UsersDTO usersDTO = e.convertTo();
Roles role = rolesMap.getOrDefault(e.getUserRole(), emptyRole);
usersDTO.setRole(role.getId())
.setRoleName(role.getRoleName());
usersDTO.setPassword("");
return usersDTO;
}).collect(Collectors.toList());
return CommentPage.convertFrom(page, rolesDTOList);
}
@Override
public boolean updateUserRole(Integer userId, Integer roleId) {
return lambdaUpdate().eq(Users::getId, userId)
.set(Users::getUserRole, roleId)
.update();
}
}
|
Users users = findByUserName(userInfo.getUserName());
String token = null;
if (users == null) {
if (checkLdapAuthenticate(userInfo, true)) {
token = jwtTokenTool.getToken(userInfo.getUserName());
}
} else if (normalEnable && UserLoginType.LOCAL.equals(users.getSource()) && DigestUtils.md5DigestAsHex(userInfo.getPassword().getBytes()).equals(users.getPassword())) {
token = jwtTokenTool.getToken(users.getUserName());
users.setPassword("");
logger.info("user: " + userInfo.getUserName() + " login! token:" + token);
} else {
if (checkLdapAuthenticate(userInfo, false)) {
token = jwtTokenTool.getToken(users.getUserName());
logger.info("ldap user: " + userInfo.getUserName() + "login! token:" + token);
}
}
return token;
| 1,522
| 261
| 1,783
|
<methods>public non-sealed void <init>() ,public boolean save(org.cloud.sonic.controller.models.domain.Users) <variables>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/base/SonicServiceImpl.java
|
SonicServiceImpl
|
getIdField
|
class SonicServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> {
protected boolean existsById(Serializable id) {
Field idField = getIdField(getDomainClass());
Objects.requireNonNull(idField, "There is not @TableId field in Object");
return baseMapper.selectCount(new QueryWrapper<T>().eq("id", id)) > 0;
}
/**
* 如果id属性为空就insert,否则update
*/
@Override
public boolean save(T domain) {
try {
Field idField = getIdField(getDomainClass());
Objects.requireNonNull(idField, "There is not @TableId field in Object");
Integer id = (Integer) idField.get(domain);
// 如果id为0,则设置为null
if (id == null || id.equals(0)) {
idField.set(domain, null);
return baseMapper.insert(domain) > 0;
}
return baseMapper.updateById(domain) > 0;
} catch (IllegalAccessException e) {
throw new ServerErrorException("Handle id in Object failed.");
}
}
protected <T> LambdaUpdateChainWrapper<T> lambdaUpdate(BaseMapper<T> baseMapper) {
return ChainWrappers.lambdaUpdateChain(baseMapper);
}
protected <T> LambdaQueryChainWrapper<T> lambdaQuery(BaseMapper<T> baseMapper) {
return ChainWrappers.lambdaQueryChain(baseMapper);
}
@SuppressWarnings("unchecked")
private Class<T> getDomainClass() {
ParameterizedType type = ReflectionTool.getParameterizedTypeBySuperClass(SonicServiceImpl.class, this.getClass());
Objects.requireNonNull(type, "Cannot fetch actual type because parameterized type is null");
return (Class<T>) type.getActualTypeArguments()[1];
}
private Field getIdField(Class<T> clazz) {<FILL_FUNCTION_BODY>}
}
|
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if (field.getAnnotation(TableId.class) != null) {
return field;
}
}
return null;
| 524
| 72
| 596
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/BytesTool.java
|
BytesTool
|
sendText
|
class BytesTool {
public static Map<Integer, Session> agentSessionMap = new HashMap<>();
public static void sendText(Session session, String message) {<FILL_FUNCTION_BODY>}
}
|
if (session == null || !session.isOpen()) {
return;
}
synchronized (session) {
try {
session.getBasicRemote().sendText(message);
} catch (IllegalStateException | IOException e) {
log.error("WebSocket send msg failed...");
}
}
| 55
| 83
| 138
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/NullableIntArrayTypeHandler.java
|
NullableIntArrayTypeHandler
|
parseString
|
class NullableIntArrayTypeHandler implements TypeHandler<int[]> {
@Override
public void setParameter(PreparedStatement preparedStatement, int i, int[] param, JdbcType jdbcType) throws SQLException {
if (null == param) {
preparedStatement.setNull(i, jdbcType.TYPE_CODE);
} else {
preparedStatement.setString(i, Arrays.stream(param).mapToObj(Integer::toString).collect(Collectors.joining(",")));
}
}
@Override
public int[] getResult(ResultSet resultSet, String s) throws SQLException {
return parseString(resultSet.getString(s));
}
@Override
public int[] getResult(ResultSet resultSet, int i) throws SQLException {
return parseString(resultSet.getString(i));
}
@Override
public int[] getResult(CallableStatement callableStatement, int i) throws SQLException {
return parseString(callableStatement.getString(i));
}
private int[] parseString(String ret) {<FILL_FUNCTION_BODY>}
}
|
if (ret == null) return null;
try {
return Arrays.stream(ret.split(",", 0)).mapToInt(Integer::valueOf).toArray();
} catch (NumberFormatException e) {
return new int[0];
}
| 278
| 69
| 347
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/PortTool.java
|
PortTool
|
getPort
|
class PortTool {
public static int port = 0;
public static Integer getPort() {<FILL_FUNCTION_BODY>}
}
|
if (port == 0) {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(0);
port = serverSocket.getLocalPort();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return port;
| 38
| 80
| 118
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/SpringTool.java
|
SpringTool
|
setApplicationContext
|
class SpringTool implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {<FILL_FUNCTION_BODY>}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
}
|
if (SpringTool.applicationContext == null) {
SpringTool.applicationContext = applicationContext;
}
| 143
| 31
| 174
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/robot/Message.java
|
Message
|
getFormat
|
class Message {
public final Calendar now = Calendar.getInstance();
public Object ext = null;
public SimpleDateFormat format = null;
public SimpleDateFormat getFormat(String pattern) {<FILL_FUNCTION_BODY>}
public SimpleDateFormat getFormat() {
if (null == format) {
format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
return format;
}
}
|
if (null == format) {
format = new SimpleDateFormat(pattern);
} else {
format.applyPattern(pattern);
}
return format;
| 115
| 45
| 160
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/robot/RobotFactory.java
|
RobotFactory
|
getRobotMessenger
|
class RobotFactory {
@Autowired
private ApplicationContext context;
/**
* @param robotType 机器人种类
* @author ayumi760405
* @des 取得推送机器人实作
* @date 2022/12/20 18:20
*/
public RobotMessenger getRobotMessenger(int robotType) {<FILL_FUNCTION_BODY>}
public RobotMessenger getRobotMessenger(int robotType, String muteRule, Message message) {
if (!muteRule.isEmpty()) {
var mute = RobotMessenger.parseTemplate(muteRule).getValue(RobotMessenger.ctx, message, String.class);
if ("true".equals(mute)) {
return null;
}
}
return getRobotMessenger(robotType);
}
}
|
RobotMessenger robotMessenger;
switch (robotType) {
case RobotType.DingTalk -> robotMessenger = context.getBean(DingTalkImpl.class);
case RobotType.WeChat -> robotMessenger = context.getBean(WeChatImpl.class);
case RobotType.FeiShu -> robotMessenger = context.getBean(FeiShuImpl.class);
case RobotType.YouSpace -> robotMessenger = context.getBean(YouSpaceImpl.class);
case RobotType.Telegram -> robotMessenger = context.getBean(TelegramImpl.class);
case RobotType.LineNotify -> robotMessenger = context.getBean(LineNotifyImpl.class);
case RobotType.SlackNotify -> robotMessenger = context.getBean(SlackNotifyImpl.class);
case RobotType.WebHook -> robotMessenger = context.getBean(WebhookImpl.class);
default -> throw new SonicException("Unsupported robot type");
}
return robotMessenger;
| 235
| 281
| 516
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/robot/vendor/DingTalkImpl.java
|
DingTalkMsgExt
|
signAndSend
|
class DingTalkMsgExt {
@Value("${robot.img.success}")
public String successUrl;
//警告时的图片url
@Value("${robot.img.warning}")
public String warningUrl;
//失败时的图片url
@Value("${robot.img.error}")
public String errorUrl;
}
@Autowired
private DingTalkMsgExt ext;
Expression templateTestSuiteMessage = RobotMessenger.parseTemplate("""
#{
{
msgtype: 'link',
link: {
title: '测试套件:' + suiteName + '运行完毕!',
text: '通过数:'+pass+'
异常数:'+warn+'
失败数:'+fail,
messageUrl: url,
picUrl: (fail > 0 ? ext.errorUrl : (warn > 0 ? ext.warningUrl : ext.successUrl))
}
}
}""");
Expression templateProjectSummaryMessage = RobotMessenger.parseTemplate("""
#{
{
msgtype: 'markdown',
markdown: {
title: 'Sonic云真机测试平台'+(isWeekly?'周':'日')+'报',
text: '### Sonic云真机测试平台'+(isWeekly ? '周': '日')+'报
> ###### 项目:'+projectName+'
> ###### 时间:'+getFormat().format(startDate)+' ~ '+getFormat().format(endDate)+'
> ###### 共测试:'+total+'次
> ###### 通过数:<font color=#67C23A>'+pass+'</font>
> ###### 异常数:<font color='+(warn==0?'#67C23A':'#F56C6C')+'>'+warn+'</font>
> ###### 失败数:<font color='+(warn==0?'#67C23A':'#F56C6C')+'>'+fail+'</font>
> ###### 测试通过率:'+rate+'%
> ###### 详细统计:[点击查看]('+url+')'
}
}
}""");
Expression templateDeviceMessage = RobotMessenger.parseTemplate("""
#{
{ msgtype: 'markdown',
markdown: {
title: '设备温度异常通知',
text: '### Sonic设备高温'+(errorType == 1 ? '预警' : '超时,已关机!')+'
> ###### 设备序列号:'+udId+'
> ###### 电池温度:<font color=#F56C6C>'+tem+' ℃</font>'
}
}
}""");
/**
* @param restTemplate RestTemplate
* @param token 机器人token
* @param secret 机器人密钥
* @param jsonObject 通知内容
* @author ZhouYiXun
* @des 钉钉官方签名方法
* @date 2021/8/20 18:20
*/
private void signAndSend(RestTemplate restTemplate, String token, String secret, Map<?, ?> jsonObject) {<FILL_FUNCTION_BODY>
|
try {
String path = "";
if (!StringUtils.isEmpty(secret)) {
Long timestamp = System.currentTimeMillis();
String stringToSign = timestamp + "\n" + secret;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
String sign = URLEncoder.encode(new String(Base64.getEncoder().encode(signData)), StandardCharsets.UTF_8);
path = "×tamp=" + timestamp + "&sign=" + sign;
}
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(token + path, jsonObject, JSONObject.class);
log.info("robot result: " + responseEntity.getBody());
} catch (Exception e) {
log.warn("robot send failed, cause: " + e.getMessage());
}
| 891
| 269
| 1,160
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/robot/vendor/FeiShuImpl.java
|
FeiShuImpl
|
sendMessage
|
class FeiShuImpl implements RobotMessenger {
Expression templateTestSuiteMessage = RobotMessenger.parseTemplate("""
**测试套件: #{suiteName} 运行完毕!**
通过数:#{pass}
异常数:#{warn}
失败数:#{fail}
测试报告:[点击查看](#{url})""");
Expression templateProjectSummaryMessage = RobotMessenger.parseTemplate("""
**Sonic云真机测试平台#{isWeekly ? '周': '日'}报**
项目:#{projectName}
时间:#{getFormat().format(startDate)} ~ #{getFormat().format(endDate)}
共测试:#{total}次
通过数:#{pass}
异常数:#{warn}
失败数:#{fail}
测试通过率:#{rate}%
详细统计:[点击查看](#{url})""");
Expression templateDeviceMessage = RobotMessenger.parseTemplate("""
**Sonic设备高温#{errorType == 1 ? '预警' : '超时,已关机!'}**
设备序列号:#{udId}
电池温度:#{tem}℃""");
/**
* @param restTemplate RestTemplate
* @param token 机器人token
* @param jsonObject 通知内容
*/
private void signAndSend(RestTemplate restTemplate, String token, String secret, JSONObject jsonObject) {
try {
if (!StringUtils.isEmpty(secret)) {
String timestamp = String.valueOf(System.currentTimeMillis()).substring(0, 10);
String stringToSign = timestamp + "\n" + secret;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] signData = mac.doFinal(new byte[]{});
String sign = new String(Base64.getEncoder().encode(signData));
jsonObject.put("timestamp", timestamp);
jsonObject.put("sign", sign);
}
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(token, jsonObject, JSONObject.class);
log.info("robot result: " + responseEntity.getBody());
} catch (Exception e) {
log.warn("robot send failed, cause: " + e.getMessage());
}
}
@Override
public void sendMessage(RestTemplate restTemplate, String token, String secret, Expression messageTemplate, Message msg) {<FILL_FUNCTION_BODY>}
@Override
public Expression getDefaultTestSuiteTemplate() {
return templateTestSuiteMessage;
}
@Override
public Expression getDefaultProjectSummaryTemplate() {
return templateProjectSummaryMessage;
}
@Override
public Expression getDefaultDeviceMessageTemplate() {
return templateDeviceMessage;
}
}
|
String content = messageTemplate.getValue(ctx, msg, String.class);
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg_type", "interactive");
JSONObject card = new JSONObject();
JSONObject config = new JSONObject();
config.put("wide_screen_mode", true);
card.put("config", config);
JSONObject element = new JSONObject();
element.put("tag", "markdown");
List<JSONObject> elementList = new ArrayList<>();
element.put("content", content);
elementList.add(element);
card.put("elements", elementList);
jsonObject.put("card", card);
this.signAndSend(restTemplate, token, secret, jsonObject);
| 784
| 186
| 970
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/robot/vendor/LineNotifyImpl.java
|
LineNotifyImpl
|
signAndSend
|
class LineNotifyImpl implements RobotMessenger {
//line notify的host
private static final String LINE_NOTIFY_HOST = "https://notify-api.line.me/api/notify";
Expression templateTestSuiteMessage = RobotMessenger.parseTemplate("""
*Sonic云真机测试报告*
测试套件: #{suiteName} 运行完毕!
通过数:#{pass}
异常数:#{warn>0?' `'+warn+'`':warn}
失败数:#{fail>0?' `'+fail+'`':fail}
测试报告: #{url}
""");
Expression templateProjectSummaryMessage = RobotMessenger.parseTemplate("""
*Sonic云真机测试平台#{isWeekly ? '周': '日'}报*
项目:#{projectName}
时间:#{getFormat().format(startDate)} ~ #{getFormat().format(endDate)}
共测试:#{total}次
通过数:#{pass}
异常数:#{warn>0?' `'+warn+'`':warn}
失败数:#{fail>0?' `'+fail+'`':fail}
测试通过率:#{rate}%
详细统计:#{url}
""");
Expression templateDeviceMessage = RobotMessenger.parseTemplate("""
*设备温度异常通知*
Sonic设备高温#{errorType == 1 ? '预警' : '超时,已关机!'}
设备序列号:#{udId}
电池温度:#{tem}℃""");
/**
* @param restTemplate RestTemplate
* @param token 机器人token
* @param message 通知内容
* @author ayumi760405
* @des Line Notify 传送讯息方法
* @date 2022/12/29
*/
private void signAndSend(RestTemplate restTemplate, String token, String message) {<FILL_FUNCTION_BODY>}
@Override
public void sendMessage(RestTemplate restTemplate, String token, String secret, Expression messageTemplate, Message msg) {
String content = messageTemplate.getValue(ctx, msg, String.class);
signAndSend(restTemplate, token, content);
}
@Override
public Expression getDefaultTestSuiteTemplate() {
return templateTestSuiteMessage;
}
@Override
public Expression getDefaultProjectSummaryTemplate() {
return templateProjectSummaryMessage;
}
@Override
public Expression getDefaultDeviceMessageTemplate() {
return templateDeviceMessage;
}
}
|
try {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + token);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> requestMap = new LinkedMultiValueMap<String, String>();
requestMap.add("message", message);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(requestMap, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(LINE_NOTIFY_HOST, entity, String.class);
log.info("robot result: " + responseEntity.getBody());
} catch (Exception e) {
log.warn("robot send failed, cause: " + e.getMessage());
}
| 701
| 206
| 907
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/robot/vendor/SlackNotifyImpl.java
|
SlackNotifyImpl
|
signAndSend
|
class SlackNotifyImpl implements RobotMessenger {
Expression templateTestSuiteMessage = RobotMessenger.parseTemplate("""
#{
{
text: '测试套件:' + suiteName + '运行完毕!',
blocks: {
{ type: 'section',
text: {
type: 'mrkdwn',
text: '*测试套件:' + suiteName + '运行完毕!*
通过数:'+pass+'
异常数:'+warn+'
失败数:'+fail+'
测试报告:'+url
}
}
}
}
}""");
Expression templateProjectSummaryMessage = RobotMessenger.parseTemplate("""
#{
{
text: 'Sonic云真机测试平台'+(isWeekly?'周':'日')+'报',
blocks: {
{ type: 'section',
text: {
type: 'mrkdwn',
text: '*Sonic云真机测试平台'+(isWeekly ? '周': '日')+'报*
项目:'+projectName+'
时间:'+getFormat().format(startDate)+' ~ '+getFormat().format(endDate)+'
共测试:'+total+'次
通过数:'+pass+'
异常数:'+warn+'
失败数:'+fail+'
测试通过率:'+rate+'%
详细统计:'+url
}
}
}
}
}""");
Expression templateDeviceMessage = RobotMessenger.parseTemplate("""
#{
{
text: '设备温度异常通知',
blocks: {
{ type: 'section',
text: {
type: 'mrkdwn',
text: '*Sonic设备高温'+(errorType == 1 ? '预警' : '超时,已关机!')+'*
设备序列号:'+udId+'
电池温度:'+tem+'℃'
}
}
}
}
}""");
/**
* @param restTemplate RestTemplate
* @param token 机器人token
* @param secret 机器人密钥
* @param content 通知内容
* @author young(stephenwang1011)
* @des SLACK发送测试通知
* @date 2023/2/14
*/
private void signAndSend(RestTemplate restTemplate, String token, String secret, Object content) {<FILL_FUNCTION_BODY>}
@Override
public void sendMessage(RestTemplate restTemplate, String token, String secret, Expression messageTemplate, Message msg) {
Map<?, ?> content = messageTemplate.getValue(ctx, msg, Map.class);
signAndSend(restTemplate, token, secret, content);
}
@Override
public Expression getDefaultTestSuiteTemplate() {
return templateTestSuiteMessage;
}
@Override
public Expression getDefaultProjectSummaryTemplate() {
return templateProjectSummaryMessage;
}
@Override
public Expression getDefaultDeviceMessageTemplate() {
return templateDeviceMessage;
}
}
|
try {
ResponseEntity<String> responseEntity = restTemplate.postForEntity(token, content, String.class);
log.info("robot result: " + responseEntity.getBody());
} catch (Exception e) {
log.warn("robot send failed, cause: " + e.getMessage());
}
| 850
| 81
| 931
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/robot/vendor/TelegramImpl.java
|
TelegramImpl
|
sendMessage
|
class TelegramImpl implements RobotMessenger {
Expression templateTestSuiteMessage = RobotMessenger.parseTemplate("""
<strong>测试套件: #{suiteName} 运行完毕!</strong>
<i>通过数:#{pass}</i>
<i>异常数:#{warn}</i>
<i>失败数:#{fail}</i>
<b>测试报告:<a href="#{url}">点击查看</a></b>""");
Expression templateProjectSummaryMessage = RobotMessenger.parseTemplate("""
<strong> Sonic云真机测试平台#{isWeekly ? '周': '日'}报</strong>
<i> 项目:#{projectName}</i>
<i> 时间:#{getFormat().format(startDate)} ~ #{getFormat().format(endDate)}</i>
<i> 共测试:#{total}次</i>
<i> 通过数:#{pass}</i>
<i> 异常数:#{warn}</i>
<i> 失败数:#{fail}</i>
<i> 测试通过率:#{rate}%</i>
<b>详细统计:<a href="#{url}">点击查看</a></b>""");
Expression templateDeviceMessage = RobotMessenger.parseTemplate("""
<strong> Sonic设备高温#{errorType == 1 ? '预警' : '超时,已关机!'}</strong>
<i> 设备序列号:#{udId}</i>
<i> 电池温度:#{tem}" ℃</i>""");
/**
* @param restTemplate RestTemplate
* @param token 机器人token
* @param content 通知内容
* @author ayumi760405
* @des Telegram电报机器人传送讯息方法
* @date 2022/12/20
*/
private void signAndSend(RestTemplate restTemplate, String token, String content) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("parse_mode", "html");
jsonObject.put("text", content);
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(token, jsonObject, JSONObject.class);
log.info("robot result: " + responseEntity.getBody());
} catch (Exception e) {
log.warn("robot send failed, cause: " + e.getMessage());
}
}
@Override
public void sendMessage(RestTemplate restTemplate, String token, String secret, Expression messageTemplate, Message msg) {<FILL_FUNCTION_BODY>}
@Override
public Expression getDefaultTestSuiteTemplate() {
return templateTestSuiteMessage;
}
@Override
public Expression getDefaultProjectSummaryTemplate() {
return templateProjectSummaryMessage;
}
@Override
public Expression getDefaultDeviceMessageTemplate() {
return templateDeviceMessage;
}
}
|
String content = messageTemplate.getValue(ctx, msg, String.class);
this.signAndSend(restTemplate, token, content);
| 794
| 36
| 830
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/robot/vendor/WeChatImpl.java
|
WeChatImpl
|
signAndSend
|
class WeChatImpl implements RobotMessenger {
Expression templateTestSuiteMessage = RobotMessenger.parseTemplate("""
**测试套件: #{suiteName} 运行完毕!**
通过数:#{pass}
异常数:#{warn}
失败数:#{fail}
测试报告:[点击查看](#{url})""");
Expression templateProjectSummaryMessage = RobotMessenger.parseTemplate("""
### Sonic云真机测试平台#{isWeekly ? '周': '日'}报
> ###### 项目:#{projectName}
> ###### 时间:#{getFormat().format(startDate)} ~ #{getFormat().format(endDate)}
> ###### 共测试:#{total}次
> ###### 通过数:<font color="info">#{pass}</font>
> ###### 异常数:<font color="#{warn == 0 ? 'info' : 'warning'}">#{warn}</font>
> ###### 失败数:<font color="#{fail == 0 ? 'info' : 'warning'}">#{fail}</font>
> ###### 测试通过率:#{rate}%
> ###### 详细统计:[点击查看](#{url})""");
Expression templateDeviceMessage = RobotMessenger.parseTemplate("""
### Sonic设备高温#{errorType == 1 ? '预警' : '超时,已关机!'}
> ###### 设备序列号:#{udId}
> ###### 电池温度:<font color="warning">#{tem}℃</font>""");
/**
* @param restTemplate RestTemplate
* @param token 机器人token
* @param content 通知内容
* @author ZhouYiXun
* @des 企业微信机器人传送讯息方法
* @date 2021/8/20 18:20
*/
private void signAndSend(RestTemplate restTemplate, String token, String content) {<FILL_FUNCTION_BODY>}
@Override
public void sendMessage(RestTemplate restTemplate, String token, String secret, Expression messageTemplate, Message msg) {
String content = messageTemplate.getValue(ctx, msg, String.class);
this.signAndSend(restTemplate, token, content);
}
@Override
public Expression getDefaultTestSuiteTemplate() {
return templateTestSuiteMessage;
}
@Override
public Expression getDefaultProjectSummaryTemplate() {
return templateProjectSummaryMessage;
}
@Override
public Expression getDefaultDeviceMessageTemplate() {
return templateDeviceMessage;
}
}
|
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msgtype", "markdown");
JSONObject markdown = new JSONObject();
markdown.put("content", content);
jsonObject.put("markdown", markdown);
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(token, jsonObject, JSONObject.class);
log.info("robot result: " + responseEntity.getBody());
} catch (Exception e) {
log.warn("robot send failed, cause: " + e.getMessage());
}
| 717
| 144
| 861
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/robot/vendor/WebhookImpl.java
|
WebhookImpl
|
sendMessage
|
class WebhookImpl implements RobotMessenger {
@Override
public void sendMessage(RestTemplate restTemplate, String token, String secret, Expression messageTemplate, Message message) {<FILL_FUNCTION_BODY>}
@Override
public Expression getDefaultTestSuiteTemplate() {
return null;
}
@Override
public Expression getDefaultProjectSummaryTemplate() {
return null;
}
@Override
public Expression getDefaultDeviceMessageTemplate() {
return null;
}
}
|
if (messageTemplate == null) {
ResponseEntity<Object> responseEntity = restTemplate.getForEntity(token, Object.class);
log.info("robot result: " + responseEntity.getBody());
} else {
Object content = messageTemplate.getValue(ctx, message);
ResponseEntity<Object> responseEntity = restTemplate.postForEntity(token, content, Object.class);
log.info("robot result: " + responseEntity.getBody());
}
| 133
| 119
| 252
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/robot/vendor/YouSpaceImpl.java
|
YouSpaceImpl
|
signAndSend
|
class YouSpaceImpl implements RobotMessenger {
Expression templateTestSuiteMessage = RobotMessenger.parseTemplate("""
#{
{
businessId: '测试套件: ' + suiteName + '运行完毕!',
titleZone: {type: 0, text: '测试套件: ' + suiteName + '运行完毕!'},
contentZone: {
{type: 'textView', data: { text: '通过数:' + pass, level: 1}},
{type: 'textView', data: { text: '异常数:' + warn, level: 1}},
{type: 'textView', data: { text: '失败数:' + fail, level: 1}},
{type: 'buttonView', data: {mode: 0, text: '点击查看测试报告', url: url}}
}
}
}""");
Expression templateProjectSummaryMessage = RobotMessenger.parseTemplate("""
#{
{
businessId: 'Sonic云真机测试平台'+(isWeekly?'周':'日')+'报',
titleZone: {type: 0, text: 'Sonic云真机测试平台'+(isWeekly?'周':'日')+'报'},
contentZone: {
{type: 'textView', data: {text: '项目:' + projectName, level: 1}},
{type: 'textView', data: {text: '时间:' + getFormat().format(startDate) + ' ~ ' + getFormat().format(endDate), level: 1}},
{type: 'textView', data: {text: '共测试:' + total, level: 1}},
{type: 'textView', data: {text: '通过数:' + pass, level: 1}},
{type: 'textView', data: {text: '异常数:' + warn, level: 1}},
{type: 'textView', data: {text: '失败数:' + fail, level: 1}},
{type: 'textView', data: {text: '测试通过率:' + rate, level: 1}},
{type: 'buttonView', data: {mode: 0, text: '点击查看', url: url}}
}
}
}""");
Expression templateDeviceMessage = RobotMessenger.parseTemplate("""
#{
{
businessId: 'Sonic设备高温'+(errorType==1?'预警':'超时,已关机!'),
titleZone: {type: 0, text: 'Sonic设备高温'+(errorType==1?'预警':'超时,已关机!')},
contentZone: {
{type: 'textView', data: {text: '设备序列号:' + udId, level: 1}},
{type: 'textView', data: {text: '电池温度:' + tem + ' ℃', level: 1}}
}
}
}""");
/**
* @param restTemplate RestTemplate
* @param token 机器人token
* @param jsonObject 通知内容
* @author ZhouYiXun
* @des 友空间签名方法
* @date 2021/8/20 18:20
*/
private void signAndSend(RestTemplate restTemplate, String token, Map<?, ?> jsonObject) {<FILL_FUNCTION_BODY>}
@Override
public void sendMessage(RestTemplate restTemplate, String token, String secret, Expression messageTemplate, Message msg) {
Map<?, ?> json = messageTemplate.getValue(ctx, msg, Map.class);
this.signAndSend(restTemplate, token, json);
}
@Override
public Expression getDefaultTestSuiteTemplate() {
return templateTestSuiteMessage;
}
@Override
public Expression getDefaultProjectSummaryTemplate() {
return templateProjectSummaryMessage;
}
@Override
public Expression getDefaultDeviceMessageTemplate() {
return templateDeviceMessage;
}
}
|
try {
JSONObject you = new JSONObject();
you.put("timestamp", System.currentTimeMillis());
String encoded_content = Base64.getEncoder().encodeToString(JSONObject.toJSONString(jsonObject).getBytes(StandardCharsets.UTF_8));
you.put("content", encoded_content);
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(token, you, JSONObject.class);
log.info("robot result: " + responseEntity.getBody());
} catch (Exception e) {
log.warn("robot send failed, cause: " + e.getMessage());
}
| 1,028
| 159
| 1,187
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/transport/TransportServer.java
|
TransportServer
|
onMessage
|
class TransportServer {
@Autowired
private AgentsService agentsService;
@Autowired
private DevicesService devicesService;
@Autowired
private ResultsService resultsService;
@Autowired
private ResultDetailService resultDetailService;
@Autowired
private TestCasesService testCasesService;
@Autowired
private ConfListService confListService;
@OnOpen
public void onOpen(Session session, @PathParam("agentKey") String agentKey) throws IOException {
log.info("Session: {} is requesting auth server.", session.getId());
if (agentKey == null || agentKey.length() == 0) {
log.info("Session: {} missing key.", session.getId());
session.close();
return;
}
Agents authResult = agentsService.auth(agentKey);
if (authResult == null) {
log.info("Session: {} auth failed...", session.getId());
JSONObject auth = new JSONObject();
auth.put("msg", "auth");
auth.put("result", "fail");
BytesTool.sendText(session, auth.toJSONString());
session.close();
} else {
log.info("Session: {} auth successful!", session.getId());
JSONObject auth = new JSONObject();
auth.put("msg", "auth");
auth.put("result", "pass");
auth.put("id", authResult.getId());
auth.put("highTemp", authResult.getHighTemp());
auth.put("highTempTime", authResult.getHighTempTime());
auth.put("remoteTimeout", confListService.searchByKey(ConfType.REMOTE_DEBUG_TIMEOUT).getContent());
BytesTool.sendText(session, auth.toJSONString());
}
}
@OnMessage
public void onMessage(String message, Session session) {<FILL_FUNCTION_BODY>}
/**
* 查找 & 封装步骤对象
*
* @param jsonMsg websocket消息
* @return 步骤对象
*/
private JSONObject findSteps(JSONObject jsonMsg, String msg) {
JSONObject j = testCasesService.findSteps(jsonMsg.getInteger("caseId"));
JSONObject steps = new JSONObject();
steps.put("cid", jsonMsg.getInteger("caseId"));
steps.put("msg", msg);
steps.put("pf", j.get("pf"));
steps.put("steps", j.get("steps"));
steps.put("gp", j.get("gp"));
steps.put("sessionId", jsonMsg.getString("sessionId"));
steps.put("pwd", jsonMsg.getString("pwd"));
steps.put("udId", jsonMsg.getString("udId"));
return steps;
}
@OnClose
public void onClose(Session session) {
log.info("Agent: {} disconnected.", session.getId());
for (Map.Entry<Integer, Session> entry : BytesTool.agentSessionMap.entrySet()) {
if (entry.getValue().equals(session)) {
int agentId = entry.getKey();
agentsService.offLine(agentId);
}
}
BytesTool.agentSessionMap.remove(session);
}
@OnError
public void onError(Session session, Throwable error) {
log.info("Agent: {},on error", session.getId());
log.error(error.getMessage());
}
}
|
JSONObject jsonMsg = JSON.parseObject(message);
if (jsonMsg.getString("msg").equals("ping")) {
Session agentSession = BytesTool.agentSessionMap.get(jsonMsg.getInteger("agentId"));
if (agentSession != null) {
JSONObject pong = new JSONObject();
pong.put("msg", "pong");
BytesTool.sendText(agentSession, pong.toJSONString());
}
return;
}
log.info("Session :{} send message: {}", session.getId(), jsonMsg);
switch (jsonMsg.getString("msg")) {
case "battery": {
devicesService.refreshDevicesBattery(jsonMsg);
break;
}
case "debugUser":
devicesService.updateDevicesUser(jsonMsg);
break;
case "heartBeat":
Agents agentsOnline = agentsService.findById(jsonMsg.getInteger("agentId"));
if (agentsOnline.getStatus() != AgentStatus.ONLINE) {
agentsOnline.setStatus(AgentStatus.ONLINE);
agentsService.saveAgents(agentsOnline);
}
break;
case "agentInfo": {
Session agentSession = BytesTool.agentSessionMap.get(jsonMsg.getInteger("agentId"));
if (agentSession != null) {
try {
agentSession.close();
} catch (IOException e) {
e.printStackTrace();
}
BytesTool.agentSessionMap.remove(jsonMsg.getInteger("agentId"));
}
BytesTool.agentSessionMap.put(jsonMsg.getInteger("agentId"), session);
jsonMsg.remove("msg");
agentsService.saveAgents(jsonMsg);
}
break;
case "subResultCount":
resultsService.subResultCount(jsonMsg.getInteger("rid"));
break;
case "deviceDetail":
devicesService.deviceStatus(jsonMsg);
break;
case "step":
case "perform":
case "record":
case "status":
resultDetailService.saveByTransport(jsonMsg);
break;
case "findSteps":
JSONObject steps = findSteps(jsonMsg, "runStep");
Session agentSession = BytesTool.agentSessionMap.get(jsonMsg.getInteger("agentId"));
if (agentSession != null) {
BytesTool.sendText(agentSession, steps.toJSONString());
}
break;
case "errCall":
agentsService.errCall(jsonMsg.getInteger("agentId"), jsonMsg.getString("udId"), jsonMsg.getInteger("tem"), jsonMsg.getInteger("type"));
break;
}
| 872
| 678
| 1,550
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/transport/TransportWorker.java
|
TransportWorker
|
send
|
class TransportWorker {
private static DiscoveryClient discoveryClient = SpringTool.getBean(DiscoveryClient.class);
private static RestTemplate restTemplate = SpringTool.getBean(RestTemplate.class);
public static void send(int agentId, JSONObject jsonObject) {<FILL_FUNCTION_BODY>}
}
|
List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("sonic-server-controller");
for (ServiceInstance i : serviceInstanceList) {
restTemplate.postForEntity(
String.format("http://%s:%d/exchange/send?id=%d", i.getHost(), i.getPort(), agentId),
jsonObject, JSONObject.class);
}
| 80
| 100
| 180
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-folder/src/main/java/org/cloud/sonic/folder/config/SpringDocConfig.java
|
SpringDocConfig
|
springDocOpenAPI
|
class SpringDocConfig {
@Value("${spring.version}")
private String version;
@Bean
public OpenAPI springDocOpenAPI() {<FILL_FUNCTION_BODY>}
}
|
return new OpenAPI()
.info(new Info().title("Controller REST API")
.version(version)
.contact(new Contact().name("SonicCloudOrg")
.email("soniccloudorg@163.com"))
.description("Folder of Sonic Cloud Real Machine Platform")
.termsOfService("https://github.com/SonicCloudOrg/sonic-server/blob/main/LICENSE")
.license(new License().name("AGPL v3")
.url("https://github.com/SonicCloudOrg/sonic-server/blob/main/LICENSE")));
| 55
| 154
| 209
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-folder/src/main/java/org/cloud/sonic/folder/config/WebConfig.java
|
WebConfig
|
addResourceHandlers
|
class WebConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {<FILL_FUNCTION_BODY>}
}
|
registry.addResourceHandler("/keepFiles/**")
.addResourceLocations("file:///" + System.getProperty("user.dir") + "/keepFiles/");
registry.addResourceHandler("/imageFiles/**")
.addResourceLocations("file:///" + System.getProperty("user.dir") + "/imageFiles/");
registry.addResourceHandler("/recordFiles/**")
.addResourceLocations("file:///" + System.getProperty("user.dir") + "/recordFiles/");
registry.addResourceHandler("/logFiles/**")
.addResourceLocations("file:///" + System.getProperty("user.dir") + "/logFiles/");
registry.addResourceHandler("/packageFiles/**")
.addResourceLocations("file:///" + System.getProperty("user.dir") + "/packageFiles/");
super.addResourceHandlers(registry);
| 45
| 210
| 255
|
<methods>public void <init>() ,public org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping beanNameHandlerMapping(org.springframework.format.support.FormattingConversionService, org.springframework.web.servlet.resource.ResourceUrlProvider) ,public org.springframework.web.servlet.HandlerMapping defaultServletHandlerMapping() ,public org.springframework.web.servlet.FlashMapManager flashMapManager() ,public final org.springframework.context.ApplicationContext getApplicationContext() ,public final jakarta.servlet.ServletContext getServletContext() ,public org.springframework.web.servlet.HandlerExceptionResolver handlerExceptionResolver(org.springframework.web.accept.ContentNegotiationManager) ,public org.springframework.web.servlet.function.support.HandlerFunctionAdapter handlerFunctionAdapter() ,public org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter httpRequestHandlerAdapter() ,public org.springframework.web.servlet.LocaleResolver localeResolver() ,public org.springframework.web.accept.ContentNegotiationManager mvcContentNegotiationManager() ,public org.springframework.format.support.FormattingConversionService mvcConversionService() ,public org.springframework.web.servlet.handler.HandlerMappingIntrospector mvcHandlerMappingIntrospector() ,public org.springframework.util.PathMatcher mvcPathMatcher() ,public org.springframework.web.util.pattern.PathPatternParser mvcPatternParser() ,public org.springframework.web.servlet.resource.ResourceUrlProvider mvcResourceUrlProvider() ,public org.springframework.web.method.support.CompositeUriComponentsContributor mvcUriComponentsContributor(org.springframework.format.support.FormattingConversionService, org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter) ,public org.springframework.web.util.UrlPathHelper mvcUrlPathHelper() ,public org.springframework.validation.Validator mvcValidator() ,public org.springframework.web.servlet.ViewResolver mvcViewResolver(org.springframework.web.accept.ContentNegotiationManager) ,public org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter requestMappingHandlerAdapter(org.springframework.web.accept.ContentNegotiationManager, org.springframework.format.support.FormattingConversionService, org.springframework.validation.Validator) ,public org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping requestMappingHandlerMapping(org.springframework.web.accept.ContentNegotiationManager, org.springframework.format.support.FormattingConversionService, org.springframework.web.servlet.resource.ResourceUrlProvider) ,public org.springframework.web.servlet.HandlerMapping resourceHandlerMapping(org.springframework.web.accept.ContentNegotiationManager, org.springframework.format.support.FormattingConversionService, org.springframework.web.servlet.resource.ResourceUrlProvider) ,public org.springframework.web.servlet.function.support.RouterFunctionMapping routerFunctionMapping(org.springframework.format.support.FormattingConversionService, org.springframework.web.servlet.resource.ResourceUrlProvider) ,public void setApplicationContext(org.springframework.context.ApplicationContext) ,public void setServletContext(jakarta.servlet.ServletContext) ,public org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter simpleControllerHandlerAdapter() ,public org.springframework.web.servlet.ThemeResolver themeResolver() ,public org.springframework.web.servlet.HandlerMapping viewControllerHandlerMapping(org.springframework.format.support.FormattingConversionService, org.springframework.web.servlet.resource.ResourceUrlProvider) ,public org.springframework.web.servlet.RequestToViewNameTranslator viewNameTranslator() <variables>private org.springframework.context.ApplicationContext applicationContext,private List<org.springframework.web.method.support.HandlerMethodArgumentResolver> argumentResolvers,private org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer asyncSupportConfigurer,private org.springframework.web.accept.ContentNegotiationManager contentNegotiationManager,private Map<java.lang.String,org.springframework.web.cors.CorsConfiguration> corsConfigurations,private static final boolean gsonPresent,private List<java.lang.Object> interceptors,private static final boolean jackson2CborPresent,private static final boolean jackson2Present,private static final boolean jackson2SmilePresent,private static final boolean jackson2XmlPresent,private static final boolean jaxb2Present,private static final boolean jsonbPresent,private static final boolean kotlinSerializationCborPresent,private static final boolean kotlinSerializationJsonPresent,private static final boolean kotlinSerializationProtobufPresent,private List<HttpMessageConverter<?>> messageConverters,private org.springframework.web.servlet.config.annotation.PathMatchConfigurer pathMatchConfigurer,private List<org.springframework.web.method.support.HandlerMethodReturnValueHandler> returnValueHandlers,private static final boolean romePresent,private jakarta.servlet.ServletContext servletContext
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-folder/src/main/java/org/cloud/sonic/folder/controller/FilesController.java
|
FilesController
|
delete
|
class FilesController {
private ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
@Autowired
private FileTool fileTool;
/**
* @param day 文件保留天数
* @return org.cloud.sonic.common.http.RespModel
* @author ZhouYiXun
* @des 删除本地文件
* @date 2021/8/21 21:47
*/
@WebAspect
@DeleteMapping
public RespModel<String> delete(@RequestParam(name = "day") int day) {<FILL_FUNCTION_BODY>}
}
|
long timeMillis = Calendar.getInstance().getTimeInMillis();
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
List<String> fileList = Arrays.asList("imageFiles", "recordFiles", "logFiles", "packageFiles");
cachedThreadPool.execute(() -> {
for (String fileType : fileList) {
File f = new File(fileType);
File[] type = f.listFiles();
if (type != null) {
for (File dateFile : type) {
try {
if (timeMillis - sf.parse(dateFile.getName()).getTime()
> day * 86400000L) {
log.info("clean begin! " + dateFile.getPath());
fileTool.deleteDir(dateFile);
}
} catch (ParseException e) {
log.info("Parse file name error, cause: " + dateFile.getPath());
log.error(e.getMessage());
}
}
}
}
});
return new RespModel<>(2000, "file.clean");
| 166
| 282
| 448
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-folder/src/main/java/org/cloud/sonic/folder/controller/UploadController.java
|
UploadController
|
uploadFiles
|
class UploadController {
@Autowired
private FileTool fileTool;
@WebAspect
@Operation(summary = "上传文件", description = "上传文件到服务器")
@Parameters(value = {
@Parameter(name = "file", description = "文件"),
@Parameter(name = "type", description = "文件类型(只能为keepFiles、imageFiles、recordFiles、logFiles、packageFiles)"),
})
@PostMapping
public RespModel<String> uploadFiles(@RequestParam(name = "file") MultipartFile file,
@RequestParam(name = "type") String type) throws IOException {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "上传文件v2", description = "上传文件到服务器")
@Parameters(value = {
@Parameter(name = "file", description = "文件"),
@Parameter(name = "type", description = "文件类型(只能为keepFiles、imageFiles、recordFiles、logFiles、packageFiles)"),
})
@PostMapping("/v2")
public RespModel<String> uploadFilesV2(@RequestParam(name = "file") MultipartFile file,
@RequestParam(name = "type") String type) throws IOException {
String url = fileTool.uploadV2(type, file);
if (url != null) {
return new RespModel(RespEnum.UPLOAD_OK, url);
} else {
return new RespModel(RespEnum.UPLOAD_FAIL);
}
}
@WebAspect
@Operation(summary = "上传文件(录像分段上传)", description = "上传文件到服务器")
@Parameters(value = {
@Parameter(name = "file", description = "文件"),
@Parameter(name = "uuid", description = "文件uuid"),
@Parameter(name = "index", description = "当前index"),
@Parameter(name = "total", description = "index总数"),
})
@PostMapping(value = "/recordFiles")
public RespModel<String> uploadRecord(@RequestParam(name = "file") MultipartFile file,
@RequestParam(name = "uuid") String uuid,
@RequestParam(name = "index") int index,
@RequestParam(name = "total") int total) throws IOException {
//先创建对应uuid的文件夹
File uuidFolder = new File("recordFiles" + File.separator + uuid);
if (!uuidFolder.exists()) {
uuidFolder.mkdirs();
}
String fileName = file.getOriginalFilename();
String newName = fileName.substring(0, fileName.indexOf(".mp4")) + "-" + index + ".mp4";
File local = new File(uuidFolder.getPath() + File.separator + newName);
RespModel<String> responseModel;
try {
file.transferTo(local.getAbsoluteFile());
responseModel = new RespModel<>(RespEnum.UPLOAD_OK);
} catch (FileAlreadyExistsException e) {
responseModel = new RespModel<>(RespEnum.UPLOAD_FAIL);
}
//如果当前是最后一个,就开始合并录像文件
if (index == total - 1) {
responseModel.setData(fileTool.merge(uuid, file.getOriginalFilename(), total));
}
return responseModel;
}
}
|
String url = fileTool.upload(type, file);
if (url != null) {
return new RespModel(RespEnum.UPLOAD_OK, url);
} else {
return new RespModel(RespEnum.UPLOAD_FAIL);
}
| 860
| 72
| 932
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-folder/src/main/java/org/cloud/sonic/folder/tools/FileTool.java
|
FileTool
|
upload
|
class FileTool {
private final Logger logger = LoggerFactory.getLogger(FileTool.class);
@Value("${gateway.host}")
private String host;
/**
* @param folderName 文件夹
* @param file
* @return java.lang.String
* @author ZhouYiXun
* @des 上传
* @date 2021/8/18 20:41
*/
public String upload(String folderName, MultipartFile file) throws IOException {<FILL_FUNCTION_BODY>}
public String uploadV2(String folderName, MultipartFile file) throws IOException {
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
File folder = new File(folderName + File.separator
+ sf.format(Calendar.getInstance().getTimeInMillis()));
if (!folder.exists()) {
folder.mkdirs();
}
//防止文件重名
final String nombre = file.getOriginalFilename();
final int p = nombre.lastIndexOf(".");
File local = new File(folder.getPath() + File.separator +
UUID.randomUUID() + (p>=0 ? nombre.substring(p) : nombre));
try {
file.transferTo(local.getAbsoluteFile());
} catch (FileAlreadyExistsException e) {
logger.error(e.getMessage());
}
return local.getPath().replaceAll("\\\\", "/");
}
/**
* @param file
* @return void
* @author ZhouYiXun
* @des 删除文件
* @date 2021/8/18 23:27
*/
public void deleteDir(File file) {
if (!file.exists()) {
logger.info("文件不存在");
return;
}
File[] files = file.listFiles();
for (File f : files) {
if (f.isDirectory()) {
deleteDir(f);
} else {
f.delete();
}
}
file.delete();
}
/**
* @param uuid
* @param fileName
* @param totalCount
* @return java.io.File
* @author ZhouYiXun
* @des
* @date 2021/8/18 20:14
*/
public String merge(String uuid, String fileName, int totalCount) {
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
File files = new File("recordFiles" + File.separator
+ sf.format(Calendar.getInstance().getTimeInMillis()));
if (!files.exists()) {
files.mkdirs();
}
//结果file
File file = new File(files.getPath() + File.separator + fileName);
try {
RandomAccessFile target = new RandomAccessFile(file, "rw");
//获取碎片文件夹
File uuidFolder = new File("recordFiles" + File.separator + uuid);
int waitTime = 0;
int fileCount = uuidFolder.listFiles().length;
//如果碎片还没齐全,进行等待一段时间
while (fileCount < totalCount && waitTime < 20) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
waitTime++;
}
for (int i = 0; i < fileCount; i++) {
//开始读取碎片文件
String newName = fileName.substring(0, fileName.indexOf(".mp4")) + "-" + i + ".mp4";
File patchFile = new File(uuidFolder.getPath() + File.separator + newName);
if (!patchFile.exists()) {
continue;
}
RandomAccessFile readFile = new RandomAccessFile(patchFile, "r");
long readSize = readFile.length();
//每次读取字节数,不用设置太大,防止内存溢出
byte[] bytes = new byte[1024];
int len;
while ((len = readFile.read(bytes)) != -1) {
//如果文件长度大于本次读取,直接写入
if (readSize > len) {
target.write(bytes, 0, len);
//读完要减去本次读取len
readSize -= len;
} else {
//小于本次读取说明是余数,直接写入剩余的readSize即可
target.write(bytes, 0, (int) readSize);
}
}
readFile.close();
patchFile.delete();
}
target.close();
uuidFolder.delete();
} catch (FileNotFoundException e) {
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
}
host = host.replace(":80/", "/");
return host + "/api/folder/" + file.getPath();
}
}
|
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
File folder = new File(folderName + File.separator
+ sf.format(Calendar.getInstance().getTimeInMillis()));
if (!folder.exists()) {
folder.mkdirs();
}
//防止文件重名
final String nombre = file.getOriginalFilename();
final int p = nombre.lastIndexOf(".");
File local = new File(folder.getPath() + File.separator +
UUID.randomUUID() + (p>=0 ? nombre.substring(p) : nombre));
try {
file.transferTo(local.getAbsoluteFile());
} catch (FileAlreadyExistsException e) {
logger.error(e.getMessage());
}
host = host.replace(":80/", "/");
return host + "/api/folder/" + local.getPath().replaceAll("\\\\", "/");
| 1,288
| 233
| 1,521
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/config/AuthFilter.java
|
AuthFilter
|
filter
|
class AuthFilter implements GlobalFilter, Ordered {
@Value("${filter.white-list}")
private List<String> whiteList;
@Autowired
private JWTTokenTool jwtTokenTool;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return -100;
}
private DataBuffer sendResp(ServerHttpResponse response) {
JSONObject result = (JSONObject) JSONObject.toJSON(new RespModel(RespEnum.UNAUTHORIZED));
DataBuffer buffer = response.bufferFactory().wrap(result.toJSONString().getBytes(StandardCharsets.UTF_8));
return buffer;
}
}
|
for (String white : whiteList) {
if (exchange.getRequest().getURI().getPath().contains(white)) {
return chain.filter(exchange);
}
}
String token = exchange.getRequest().getHeaders().getFirst("SonicToken");
ServerHttpResponse response = exchange.getResponse();
response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
DataBuffer buffer = sendResp(response);
if (token == null) {
return response.writeWith(Mono.just(buffer));
}
// verify token
if (!jwtTokenTool.verify(token)) {
return response.writeWith(Mono.just(buffer));
}
return chain.filter(exchange);
| 207
| 195
| 402
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/config/CORSConfig.java
|
CORSConfig
|
corsWebFilter
|
class CORSConfig {
@Bean
public CorsWebFilter corsWebFilter() {<FILL_FUNCTION_BODY>}
}
|
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOriginPattern("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
| 37
| 109
| 146
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/config/UriWithBracketsFilter.java
|
UriWithBracketsFilter
|
filter
|
class UriWithBracketsFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return ReactiveLoadBalancerClientFilter.LOAD_BALANCER_CLIENT_FILTER_ORDER + 1;
}
}
|
String query = exchange.getRequest().getURI().getRawQuery();
if (query != null && query.contains("%") && (query.contains("[") || query.contains("]"))) {
try {
String badUrl = exchange.getAttributes().get(GATEWAY_REQUEST_URL_ATTR).toString();
String fineUrl = badUrl.substring(0, badUrl.indexOf('?') + 1) +
query.replace("[", "%5B").replace("]", "%5D");
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, new URI(fineUrl));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return chain.filter(exchange);
| 103
| 189
| 292
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/AbstractJasminClass.java
|
SafeVisibilityAnnotationTags
|
get
|
class SafeVisibilityAnnotationTags {
private static final Map<Integer, VisibilityAnnotationTag> safeVats = new HashMap<Integer, VisibilityAnnotationTag>();
static VisibilityAnnotationTag get(int kind) {<FILL_FUNCTION_BODY>}
private SafeVisibilityAnnotationTags() {
}
}
|
VisibilityAnnotationTag safeVat = safeVats.get(kind);
if (safeVat == null) {
safeVats.put(kind, safeVat = new VisibilityAnnotationTag(kind));
}
return safeVat;
| 82
| 64
| 146
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/AbstractSootFieldRef.java
|
FieldResolutionFailedException
|
resolve
|
class FieldResolutionFailedException extends ResolutionFailedException {
/**
*
*/
private static final long serialVersionUID = -4657113720516199499L;
public FieldResolutionFailedException() {
super("Class " + declaringClass + " doesn't have field " + name + " : " + type
+ "; failed to resolve in superclasses and interfaces");
}
@Override
public String toString() {
StringBuffer ret = new StringBuffer();
ret.append(super.toString());
resolve(ret);
return ret.toString();
}
}
@Override
public SootField resolve() {
return resolve(null);
}
private SootField checkStatic(SootField ret) {
if ((Options.v().wrong_staticness() == Options.wrong_staticness_fail
|| Options.v().wrong_staticness() == Options.wrong_staticness_fixstrict) && ret.isStatic() != isStatic()
&& !ret.isPhantom()) {
throw new ResolutionFailedException("Resolved " + this + " to " + ret + " which has wrong static-ness");
}
return ret;
}
private SootField resolve(StringBuffer trace) {<FILL_FUNCTION_BODY>
|
SootClass cl = declaringClass;
while (true) {
if (trace != null) {
trace.append("Looking in " + cl + " which has fields " + cl.getFields() + "\n");
}
// Check whether we have the field in the current class
SootField clField = cl.getFieldUnsafe(name, type);
if (clField != null) {
return checkStatic(clField);
}
// If we have a phantom class, we directly construct a phantom field
// in it and don't care about superclasses.
else if (Scene.v().allowsPhantomRefs() && cl.isPhantom()) {
synchronized (cl) {
// Check that no other thread has created the field in the
// meantime
clField = cl.getFieldUnsafe(name, type);
if (clField != null) {
return checkStatic(clField);
}
// Make sure that we don't have a conflicting field
SootField existingField = cl.getFieldByNameUnsafe(name);
if (existingField != null) {
return handleFieldTypeMismatch(clField);
}
// Create the phantom field
SootField f = Scene.v().makeSootField(name, type, isStatic() ? Modifier.STATIC : 0);
f.setPhantom(true);
cl.addField(f);
return f;
}
} else {
// Since this class is not phantom, we look at its interfaces
ArrayDeque<SootClass> queue = new ArrayDeque<SootClass>();
queue.addAll(cl.getInterfaces());
while (true) {
SootClass iface = queue.poll();
if (iface == null) {
break;
}
if (trace != null) {
trace.append("Looking in " + iface + " which has fields " + iface.getFields() + "\n");
}
SootField ifaceField = iface.getFieldUnsafe(name, type);
if (ifaceField != null) {
return checkStatic(ifaceField);
}
queue.addAll(iface.getInterfaces());
}
// If we have not found a suitable field in the current class,
// try the superclass
if (cl.hasSuperclass()) {
cl = cl.getSuperclass();
} else {
break;
}
}
}
// If we allow phantom refs, we construct phantom fields
if (Options.v().allow_phantom_refs()) {
SootField sf = Scene.v().makeSootField(name, type, isStatic ? Modifier.STATIC : 0);
sf.setPhantom(true);
synchronized (declaringClass) {
// Be careful: Another thread may have already created this
// field in the meantime, so better check twice.
SootField clField = declaringClass.getFieldByNameUnsafe(name);
if (clField != null) {
if (clField.getType().equals(type)) {
return checkStatic(clField);
} else {
return handleFieldTypeMismatch(clField);
}
} else {
// Add the new phantom field
declaringClass.addField(sf);
return sf;
}
}
}
if (trace == null) {
FieldResolutionFailedException e = new FieldResolutionFailedException();
if (Options.v().ignore_resolution_errors()) {
logger.debug("" + e.getMessage());
} else {
throw e;
}
}
return null;
| 336
| 952
| 1,288
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/AbstractUnit.java
|
AbstractUnit
|
getUseAndDefBoxes
|
class AbstractUnit extends AbstractHost implements Unit {
/**
* List of UnitBoxes pointing to this Unit.
*/
protected List<UnitBox> boxesPointingToThis = null;
/**
* Returns a deep clone of this object.
*/
@Override
public abstract Object clone();
/**
* Returns a list of Boxes containing Values used in this Unit. The list of boxes is dynamically updated as the structure
* changes. Note that they are returned in usual evaluation order. (this is important for aggregation)
*/
@Override
public List<ValueBox> getUseBoxes() {
return Collections.emptyList();
}
/**
* Returns a list of Boxes containing Values defined in this Unit. The list of boxes is dynamically updated as the
* structure changes.
*/
@Override
public List<ValueBox> getDefBoxes() {
return Collections.emptyList();
}
/**
* Returns a list of Boxes containing Units defined in this Unit; typically branch targets. The list of boxes is
* dynamically updated as the structure changes.
*/
@Override
public List<UnitBox> getUnitBoxes() {
return Collections.emptyList();
}
/**
* Returns a list of Boxes pointing to this Unit.
*/
@Override
public List<UnitBox> getBoxesPointingToThis() {
List<UnitBox> ref = boxesPointingToThis;
return (ref == null) ? Collections.emptyList() : Collections.unmodifiableList(ref);
}
@Override
public void addBoxPointingToThis(UnitBox b) {
List<UnitBox> ref = boxesPointingToThis;
if (ref == null) {
boxesPointingToThis = ref = new ArrayList<UnitBox>();
}
ref.add(b);
}
@Override
public void removeBoxPointingToThis(UnitBox b) {
List<UnitBox> ref = boxesPointingToThis;
if (ref != null) {
ref.remove(b);
}
}
@Override
public void clearUnitBoxes() {
for (UnitBox ub : getUnitBoxes()) {
ub.setUnit(null);
}
}
/**
* Returns a list of ValueBoxes, either used or defined in this Unit.
*/
@Override
public List<ValueBox> getUseAndDefBoxes() {<FILL_FUNCTION_BODY>}
/**
* Used to implement the Switchable construct.
*/
@Override
public void apply(Switch sw) {
}
@Override
public void redirectJumpsToThisTo(Unit newLocation) {
// important to make a copy to prevent concurrent modification
for (UnitBox box : new ArrayList<>(getBoxesPointingToThis())) {
if (box.getUnit() != this) {
throw new RuntimeException("Something weird's happening");
}
if (box.isBranchTarget()) {
box.setUnit(newLocation);
}
}
}
}
|
List<ValueBox> useBoxes = getUseBoxes();
List<ValueBox> defBoxes = getDefBoxes();
if (useBoxes.isEmpty()) {
return defBoxes;
} else if (defBoxes.isEmpty()) {
return useBoxes;
} else {
List<ValueBox> valueBoxes = new ArrayList<ValueBox>(defBoxes.size() + useBoxes.size());
valueBoxes.addAll(defBoxes);
valueBoxes.addAll(useBoxes);
return valueBoxes;
}
| 784
| 145
| 929
|
<methods>public non-sealed void <init>() ,public void addAllTagsOf(soot.tagkit.Host) ,public void addTag(soot.tagkit.Tag) ,public int getJavaSourceStartColumnNumber() ,public int getJavaSourceStartLineNumber() ,public soot.tagkit.Tag getTag(java.lang.String) ,public List<soot.tagkit.Tag> getTags() ,public boolean hasTag(java.lang.String) ,public void removeAllTags() ,public void removeTag(java.lang.String) <variables>protected int col,protected int line,protected List<soot.tagkit.Tag> mTagList
|
soot-oss_soot
|
soot/src/main/java/soot/AbstractUnitBox.java
|
AbstractUnitBox
|
setUnit
|
class AbstractUnitBox implements UnitBox {
protected Unit unit;
@Override
public boolean isBranchTarget() {
return true;
}
@Override
public void setUnit(Unit unit) {<FILL_FUNCTION_BODY>}
@Override
public Unit getUnit() {
return unit;
}
@Override
public void toString(UnitPrinter up) {
up.startUnitBox(this);
up.unitRef(unit, isBranchTarget());
up.endUnitBox(this);
}
}
|
if (!canContainUnit(unit)) {
throw new RuntimeException("attempting to put invalid unit in UnitBox");
}
// Remove this from set of back pointers.
if (this.unit != null) {
this.unit.removeBoxPointingToThis(this);
}
// Perform link
this.unit = unit;
// Add this to back pointers
if (this.unit != null) {
this.unit.addBoxPointingToThis(this);
}
| 145
| 136
| 281
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/AbstractValueBox.java
|
AbstractValueBox
|
setValue
|
class AbstractValueBox extends AbstractHost implements ValueBox {
protected Value value;
@Override
public void setValue(Value value) {<FILL_FUNCTION_BODY>}
@Override
public Value getValue() {
return value;
}
@Override
public void toString(UnitPrinter up) {
up.startValueBox(this);
value.toString(up);
up.endValueBox(this);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + value + ")";
}
}
|
if (value == null) {
throw new IllegalArgumentException("value may not be null");
}
if (canContainValue(value)) {
this.value = value;
} else {
throw new RuntimeException("Box " + this + " cannot contain value: " + value + "(" + value.getClass() + ")");
}
| 153
| 88
| 241
|
<methods>public non-sealed void <init>() ,public void addAllTagsOf(soot.tagkit.Host) ,public void addTag(soot.tagkit.Tag) ,public int getJavaSourceStartColumnNumber() ,public int getJavaSourceStartLineNumber() ,public soot.tagkit.Tag getTag(java.lang.String) ,public List<soot.tagkit.Tag> getTags() ,public boolean hasTag(java.lang.String) ,public void removeAllTags() ,public void removeTag(java.lang.String) <variables>protected int col,protected int line,protected List<soot.tagkit.Tag> mTagList
|
soot-oss_soot
|
soot/src/main/java/soot/ArrayType.java
|
ArrayType
|
v
|
class ArrayType extends RefLikeType {
/**
* baseType can be any type except for an array type, null and void
*
* What is the base type of the array? That is, for an array of type A[][][], how do I find out what the A is? The accepted
* way of doing this has always been to look at the public field baseType in ArrayType, ever since the very beginning of
* Soot.
*/
public final Type baseType;
/**
* dimension count for the array type
*/
public final int numDimensions;
private ArrayType(Type baseType, int numDimensions) {
if (!(baseType instanceof PrimType || baseType instanceof RefType || baseType instanceof NullType)) {
throw new RuntimeException("oops, base type must be PrimType or RefType but not '" + baseType + "'");
}
if (numDimensions < 1) {
throw new RuntimeException("attempt to create array with " + numDimensions + " dimensions");
}
this.baseType = baseType;
this.numDimensions = numDimensions;
}
/**
* Creates an ArrayType parameterized by a given Type and dimension count.
*
* @param baseType
* a Type to parameterize the ArrayType
* @param numDimensions
* the dimension count to parameterize the ArrayType.
* @return an ArrayType parameterized accordingly.
*/
public static ArrayType v(Type baseType, int numDimensions) {<FILL_FUNCTION_BODY>}
/**
* Two ArrayType are 'equal' if they are parameterized identically. (ie have same Type and dimension count.
*
* @param t
* object to test for equality
* @return true if t is an ArrayType and is parameterized identically to this.
*/
@Override
public boolean equals(Object t) {
return t == this;
}
public void toString(UnitPrinter up) {
up.type(baseType);
for (int i = 0; i < numDimensions; i++) {
up.literal("[]");
}
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(baseType.toString());
for (int i = 0; i < numDimensions; i++) {
buffer.append("[]");
}
return buffer.toString();
}
/**
* Returns a textual representation, quoted as needed, of this type for serialization, e.g. to .jimple format
*/
@Override
public String toQuotedString() {
StringBuilder buffer = new StringBuilder();
buffer.append(baseType.toQuotedString());
for (int i = 0; i < numDimensions; i++) {
buffer.append("[]");
}
return buffer.toString();
}
@Override
public int hashCode() {
return baseType.hashCode() + 0x432E0341 * numDimensions;
}
@Override
public void apply(Switch sw) {
((TypeSwitch) sw).caseArrayType(this);
}
/**
* If I have a variable x of declared type t, what is a good declared type for the expression ((Object[]) x)[i]? The
* getArrayElementType() method in RefLikeType was introduced to answer this question for all classes implementing
* RefLikeType. If t is an array, then the answer is the same as getElementType(). But t could also be Object,
* Serializable, or Cloneable, which can all hold any array, so then the answer is Object.
*/
@Override
public Type getArrayElementType() {
return getElementType();
}
/**
* If I get an element of the array, what will be its type? That is, if I have an array a of type A[][][], what is the type
* of a[] (it's A[][])? The getElementType() method in ArrayType was introduced to answer this question.
*/
public Type getElementType() {
if (numDimensions > 1) {
return ArrayType.v(baseType, numDimensions - 1);
} else {
return baseType;
}
}
@Override
public ArrayType makeArrayType() {
return ArrayType.v(baseType, numDimensions + 1);
}
@Override
public boolean isAllowedInFinalCode() {
return true;
}
}
|
if (numDimensions < 0) {
throw new RuntimeException("Invalid number of array dimensions: " + numDimensions);
}
final int orgDimensions = numDimensions;
Type elementType = baseType;
while (numDimensions > 0) {
ArrayType ret = elementType.getArrayType();
if (ret == null) {
ret = new ArrayType(baseType, orgDimensions - numDimensions + 1);
elementType.setArrayType(ret);
}
elementType = ret;
numDimensions--;
}
return (ArrayType) elementType;
| 1,137
| 154
| 1,291
|
<methods>public non-sealed void <init>() ,public abstract soot.Type getArrayElementType() <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/AttributesUnitPrinter.java
|
AttributesUnitPrinter
|
hasColorTag
|
class AttributesUnitPrinter {
private static final Logger logger = LoggerFactory.getLogger(AttributesUnitPrinter.class);
private Stack<Integer> startOffsets;
private int endOffset;
private int startStmtOffset;
private int startLn;
private int currentLn;
private int lastNewline;
private UnitPrinter printer;
public AttributesUnitPrinter(int currentLnNum) {
this.currentLn = currentLnNum;
}
public void startUnit(Unit u) {
startLn = currentLn;
startStmtOffset = outputLength() - lastNewline;
}
public void endUnit(Unit u) {
int endStmtOffset = outputLength() - lastNewline;
// logger.debug("u: "+u.toString());
if (hasTag(u)) {
// logger.debug("u: "+u.toString()+" has tag");
u.addTag(new JimpleLineNumberTag(startLn, currentLn));
}
if (hasColorTag(u)) {
u.addTag(new PositionTag(startStmtOffset, endStmtOffset));
}
}
public void startValueBox(ValueBox u) {
if (startOffsets == null) {
startOffsets = new Stack<Integer>();
}
startOffsets.push(outputLength() - lastNewline);
}
public void endValueBox(ValueBox u) {
endOffset = outputLength() - lastNewline;
if (hasColorTag(u)) {
u.addTag(new PositionTag(startOffsets.pop(), endOffset));
}
}
private boolean hasTag(Host h) {
if (h instanceof Unit) {
for (ValueBox box : ((Unit) h).getUseAndDefBoxes()) {
if (hasTag(box)) {
return true;
}
}
}
return !h.getTags().isEmpty();
}
private boolean hasColorTag(Host h) {<FILL_FUNCTION_BODY>}
public void setEndLn(int ln) {
currentLn = ln;
}
public int getEndLn() {
return currentLn;
}
public void newline() {
currentLn++;
lastNewline = outputLength();
}
private int outputLength() {
return printer.output().length();
}
public void setUnitPrinter(UnitPrinter up) {
printer = up;
}
}
|
for (Tag t : h.getTags()) {
if (t instanceof ColorTag) {
return true;
}
}
return false;
| 652
| 42
| 694
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/BodyPack.java
|
BodyPack
|
internalApply
|
class BodyPack extends Pack {
private static final Logger logger = LoggerFactory.getLogger(BodyPack.class);
public BodyPack(String name) {
super(name);
}
@Override
protected void internalApply(Body b) {<FILL_FUNCTION_BODY>}
}
|
final boolean interactive_mode = Options.v().interactive_mode();
for (Transform t : this) {
if (interactive_mode) {
// logger.debug("sending transform: "+t.getPhaseName()+" for body: "+b+" for body pack: "+this.getPhaseName());
InteractionHandler.v().handleNewAnalysis(t, b);
}
t.apply(b);
if (interactive_mode) {
InteractionHandler.v().handleTransformDone(t, b);
}
}
| 78
| 142
| 220
|
<methods>public void <init>(java.lang.String) ,public void add(soot.Transform) ,public final void apply() ,public final void apply(soot.Body) ,public soot.Transform get(java.lang.String) ,public java.lang.String getDeclaredOptions() ,public java.lang.String getDefaultOptions() ,public java.lang.String getPhaseName() ,public void insertAfter(soot.Transform, java.lang.String) ,public void insertBefore(soot.Transform, java.lang.String) ,public Iterator<soot.Transform> iterator() ,public boolean remove(java.lang.String) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String name,private final List<soot.Transform> opts
|
soot-oss_soot
|
soot/src/main/java/soot/BooleanType.java
|
BooleanType
|
getTypeAsString
|
class BooleanType extends PrimType implements IntegerType {
public static final int HASHCODE = 0x1C4585DA;
public BooleanType(Singletons.Global g) {
}
public static BooleanType v() {
return G.v().soot_BooleanType();
}
@Override
public boolean equals(Object t) {
return this == t;
}
@Override
public int hashCode() {
return HASHCODE;
}
@Override
public String toString() {
return "boolean";
}
@Override
public void apply(Switch sw) {
((TypeSwitch) sw).caseBooleanType(this);
}
@Override
public String getTypeAsString() {<FILL_FUNCTION_BODY>}
@Override
public Class<?> getJavaBoxedType() {
return Boolean.class;
}
@Override
public Class<?> getJavaPrimitiveType() {
return boolean.class;
}
}
|
if (Options.v().src_prec() == Options.src_prec_dotnet) {
return DotnetBasicTypes.SYSTEM_BOOLEAN;
}
return JavaBasicTypes.JAVA_LANG_BOOLEAN;
| 265
| 65
| 330
|
<methods>public non-sealed void <init>() ,public soot.RefType boxedType() ,public abstract Class<?> getJavaBoxedType() ,public abstract Class<?> getJavaPrimitiveType() ,public abstract java.lang.String getTypeAsString() ,public boolean isAllowedInFinalCode() <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/BriefUnitPrinter.java
|
BriefUnitPrinter
|
identityRef
|
class BriefUnitPrinter extends LabeledUnitPrinter {
private boolean baf;
public BriefUnitPrinter(Body body) {
super(body);
}
@Override
public void startUnit(Unit u) {
super.startUnit(u);
baf = !(u instanceof Stmt);
}
@Override
public void methodRef(SootMethodRef m) {
handleIndent();
if (!baf && m.resolve().isStatic()) {
output.append(m.getDeclaringClass().getName());
literal(".");
}
output.append(m.name());
}
@Override
public void fieldRef(SootFieldRef f) {
handleIndent();
if (baf || f.resolve().isStatic()) {
output.append(f.declaringClass().getName());
literal(".");
}
output.append(f.name());
}
@Override
public void identityRef(IdentityRef r) {<FILL_FUNCTION_BODY>}
private boolean eatSpace = false;
@Override
public void literal(String s) {
handleIndent();
if (eatSpace && " ".equals(s)) {
eatSpace = false;
return;
}
eatSpace = false;
if (!baf) {
switch (s) {
case Jimple.STATICINVOKE:
case Jimple.VIRTUALINVOKE:
case Jimple.INTERFACEINVOKE:
eatSpace = true;
return;
}
}
output.append(s);
}
@Override
public void type(Type t) {
handleIndent();
output.append(t.toString());
}
}
|
handleIndent();
if (r instanceof ThisRef) {
literal("@this");
} else if (r instanceof ParameterRef) {
ParameterRef pr = (ParameterRef) r;
literal("@parameter" + pr.getIndex());
} else if (r instanceof CaughtExceptionRef) {
literal("@caughtexception");
} else {
throw new RuntimeException();
}
| 451
| 103
| 554
|
<methods>public void <init>(soot.Body) ,public Map<soot.Unit,java.lang.String> labels() ,public Map<soot.Unit,java.lang.String> references() ,public void unitRef(soot.Unit, boolean) <variables>protected java.lang.String labelIndent,protected Map<soot.Unit,java.lang.String> labels,protected Map<soot.Unit,java.lang.String> references
|
soot-oss_soot
|
soot/src/main/java/soot/ByteType.java
|
ByteType
|
getTypeAsString
|
class ByteType extends PrimType implements IntegerType {
public static final int HASHCODE = 0x813D1329;
public ByteType(Singletons.Global g) {
}
public static ByteType v() {
return G.v().soot_ByteType();
}
@Override
public int hashCode() {
return HASHCODE;
}
@Override
public boolean equals(Object t) {
return this == t;
}
@Override
public String toString() {
return "byte";
}
@Override
public void apply(Switch sw) {
((TypeSwitch) sw).caseByteType(this);
}
@Override
public String getTypeAsString() {<FILL_FUNCTION_BODY>}
@Override
public Class<?> getJavaBoxedType() {
return Byte.class;
}
@Override
public Class<?> getJavaPrimitiveType() {
return byte.class;
}
}
|
if (Options.v().src_prec() == Options.src_prec_dotnet) {
return DotnetBasicTypes.SYSTEM_BYTE;
}
return JavaBasicTypes.JAVA_LANG_BYTE;
| 266
| 61
| 327
|
<methods>public non-sealed void <init>() ,public soot.RefType boxedType() ,public abstract Class<?> getJavaBoxedType() ,public abstract Class<?> getJavaPrimitiveType() ,public abstract java.lang.String getTypeAsString() ,public boolean isAllowedInFinalCode() <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/ConflictingFieldRefException.java
|
ConflictingFieldRefException
|
toString
|
class ConflictingFieldRefException extends RuntimeException {
private static final long serialVersionUID = -2351763146637880592L;
private final SootField existingField;
private final Type requestedType;
public ConflictingFieldRefException(SootField existingField, Type requestedType) {
this.existingField = existingField;
this.requestedType = requestedType;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return String.format("Existing field %s does not match expected field type %s", existingField.toString(),
requestedType.toString());
| 138
| 36
| 174
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
|
soot-oss_soot
|
soot/src/main/java/soot/DexClassProvider.java
|
DexClassProvider
|
find
|
class DexClassProvider implements ClassProvider {
private static final Logger logger = LoggerFactory.getLogger(DexClassProvider.class);
public static Set<String> classesOfDex(DexFile dexFile) {
Set<String> classes = new HashSet<String>();
for (ClassDef c : dexFile.getClasses()) {
classes.add(Util.dottedClassName(c.getType()));
}
return classes;
}
/**
* Provides the DexClassSource for the class.
*
* @param className
* class to provide.
* @return a DexClassSource that defines the className named class.
*/
@Override
public ClassSource find(String className) {<FILL_FUNCTION_BODY>}
/**
* Checks whether the dex class index needs to be (re)built and triggers the build if necessary
*/
protected void ensureDexIndex() {
final SourceLocator loc = SourceLocator.v();
Map<String, File> index = loc.dexClassIndex();
if (index == null) {
index = new HashMap<String, File>();
buildDexIndex(index, loc.classPath());
loc.setDexClassIndex(index);
}
// Process the classpath extensions
Set<String> extensions = loc.getDexClassPathExtensions();
if (extensions != null) {
buildDexIndex(index, new ArrayList<>(extensions));
loc.clearDexClassPathExtensions();
}
}
/**
* Build index of ClassName-to-File mappings.
*
* @param index
* map to insert mappings into
* @param classPath
* paths to index
*/
private void buildDexIndex(Map<String, File> index, List<String> classPath) {
for (String path : classPath) {
try {
File dexFile = new File(path);
if (dexFile.exists()) {
for (DexFileProvider.DexContainer<? extends DexFile> container : DexFileProvider.v().getDexFromSource(dexFile)) {
for (String className : classesOfDex(container.getBase().getDexFile())) {
if (!index.containsKey(className)) {
index.put(className, container.getFilePath());
} else if (Options.v().verbose()) {
logger.debug(String.format(
"Warning: Duplicate of class '%s' found in dex file '%s' from source '%s'. Omitting class.", className,
container.getDexName(), container.getFilePath().getCanonicalPath()));
}
}
}
}
} catch (IOException e) {
logger.warn("IO error while processing dex file '" + path + "'");
logger.debug("Exception: " + e);
} catch (Exception e) {
logger.warn("exception while processing dex file '" + path + "'");
logger.debug("Exception: " + e);
}
}
}
}
|
ensureDexIndex();
File file = SourceLocator.v().dexClassIndex().get(className);
return (file == null) ? null : new DexClassSource(className, file);
| 773
| 52
| 825
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/DexClassSource.java
|
DexClassSource
|
resolve
|
class DexClassSource extends ClassSource {
private static final Logger logger = LoggerFactory.getLogger(DexClassSource.class);
protected final File path;
/**
* @param className
* the class which dependencies are to be resolved.
* @param path
* to the file that defines the class.
*/
public DexClassSource(String className, File path) {
super(className);
this.path = path;
}
/**
* Resolve dependencies of class.
*
* @param sc
* The SootClass to resolve into.
* @return Dependencies of class (Strings or Types referenced).
*/
@Override
public Dependencies resolve(SootClass sc) {<FILL_FUNCTION_BODY>}
}
|
if (Options.v().verbose()) {
logger.debug("resolving " + className + " from file " + path.getPath());
}
return DexResolver.v().resolveFromFile(path, className, sc);
| 205
| 59
| 264
|
<methods>public void <init>(java.lang.String) ,public void close() ,public abstract soot.javaToJimple.IInitialResolver.Dependencies resolve(soot.SootClass) <variables>protected final non-sealed java.lang.String className
|
soot-oss_soot
|
soot/src/main/java/soot/DoubleType.java
|
DoubleType
|
getTypeAsString
|
class DoubleType extends PrimType {
public static final int HASHCODE = 0x4B9D7242;
public DoubleType(Singletons.Global g) {
}
public static DoubleType v() {
return G.v().soot_DoubleType();
}
@Override
public boolean equals(Object t) {
return this == t;
}
@Override
public int hashCode() {
return HASHCODE;
}
@Override
public String toString() {
return "double";
}
@Override
public void apply(Switch sw) {
((TypeSwitch) sw).caseDoubleType(this);
}
@Override
public String getTypeAsString() {<FILL_FUNCTION_BODY>}
@Override
public Class<?> getJavaBoxedType() {
return Double.class;
}
@Override
public Class<?> getJavaPrimitiveType() {
return double.class;
}
}
|
if (Options.v().src_prec() == Options.src_prec_dotnet) {
return DotnetBasicTypes.SYSTEM_DOUBLE;
}
return JavaBasicTypes.JAVA_LANG_DOUBLE;
| 263
| 63
| 326
|
<methods>public non-sealed void <init>() ,public soot.RefType boxedType() ,public abstract Class<?> getJavaBoxedType() ,public abstract Class<?> getJavaPrimitiveType() ,public abstract java.lang.String getTypeAsString() ,public boolean isAllowedInFinalCode() <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/EquivalentValue.java
|
EquivalentValue
|
equals
|
class EquivalentValue implements Value {
private final Value e;
public EquivalentValue(Value v) {
this.e = (v instanceof EquivalentValue) ? ((EquivalentValue) v).e : v;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/**
* compares the encapsulated value with <code>v</code>, using <code>equivTo</code>
*/
public boolean equivToValue(Value v) {
return e.equivTo(v);
}
/**
* compares the encapsulated value with <code>v</code>, using <code>equals</code>
*/
public boolean equalsToValue(Value v) {
return e.equals(v);
}
/**
* @deprecated
* @see #getValue()
*/
@Deprecated
public Value getDeepestValue() {
return getValue();
}
@Override
public int hashCode() {
return e.equivHashCode();
}
@Override
public String toString() {
return e.toString();
}
public Value getValue() {
return e;
}
/*********************************/
/* implement the Value-interface */
/*********************************/
@Override
public List<ValueBox> getUseBoxes() {
return e.getUseBoxes();
}
@Override
public Type getType() {
return e.getType();
}
@Override
public Object clone() {
return new EquivalentValue((Value) e.clone());
}
@Override
public boolean equivTo(Object o) {
return e.equivTo(o);
}
@Override
public int equivHashCode() {
return e.equivHashCode();
}
@Override
public void apply(Switch sw) {
e.apply(sw);
}
@Override
public void toString(UnitPrinter up) {
e.toString(up);
}
}
|
return e.equivTo((o instanceof EquivalentValue) ? ((EquivalentValue) o).e : o);
| 534
| 29
| 563
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/FloatType.java
|
FloatType
|
getTypeAsString
|
class FloatType extends PrimType {
public static final int HASHCODE = 0xA84373FA;
public FloatType(Singletons.Global g) {
}
public static FloatType v() {
return G.v().soot_FloatType();
}
@Override
public boolean equals(Object t) {
return this == t;
}
@Override
public int hashCode() {
return HASHCODE;
}
@Override
public String toString() {
return "float";
}
@Override
public void apply(Switch sw) {
((TypeSwitch) sw).caseFloatType(this);
}
@Override
public String getTypeAsString() {<FILL_FUNCTION_BODY>}
@Override
public Class<?> getJavaBoxedType() {
return Float.class;
}
@Override
public Class<?> getJavaPrimitiveType() {
return float.class;
}
}
|
if (Options.v().src_prec() == Options.src_prec_dotnet) {
return DotnetBasicTypes.SYSTEM_SINGLE;
}
return JavaBasicTypes.JAVA_LANG_FLOAT;
| 266
| 63
| 329
|
<methods>public non-sealed void <init>() ,public soot.RefType boxedType() ,public abstract Class<?> getJavaBoxedType() ,public abstract Class<?> getJavaPrimitiveType() ,public abstract java.lang.String getTypeAsString() ,public boolean isAllowedInFinalCode() <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/FoundFile.java
|
FoundFile
|
inputStream
|
class FoundFile implements IFoundFile {
private static final Logger logger = LoggerFactory.getLogger(FoundFile.class);
protected final List<InputStream> openedInputStreams = new ArrayList<InputStream>();
protected Path path;
protected File file;
protected String entryName;
protected SharedCloseable<ZipFile> zipFile;
protected ZipEntry zipEntry;
public FoundFile(String archivePath, String entryName) {
if (archivePath == null || entryName == null) {
throw new IllegalArgumentException("Error: The archive path and entry name cannot be null.");
}
this.file = new File(archivePath);
this.entryName = entryName;
}
public FoundFile(File file) {
if (file == null) {
throw new IllegalArgumentException("Error: The file cannot be null.");
}
this.file = file;
this.entryName = null;
}
public FoundFile(Path path) {
this.path = path;
}
@Override
public String getFilePath() {
if (file == null) {
if (path != null) {
File f = path.toFile();
if (f != null) {
return f.getPath();
}
}
return null;
}
return file.getPath();
}
@Override
public boolean isZipFile() {
return entryName != null;
}
@Override
public ZipFile getZipFile() {
return zipFile != null ? zipFile.get() : null;
}
@Override
public File getFile() {
return file;
}
@Override
public String getAbsolutePath() {
try {
return file != null ? file.getCanonicalPath() : path.toRealPath().toString();
} catch (IOException ex) {
return file != null ? file.getAbsolutePath() : path.toAbsolutePath().toString();
}
}
@Override
public InputStream inputStream() {<FILL_FUNCTION_BODY>}
@Override
public void close() {
// Try to close all opened input streams
List<Exception> errs = new ArrayList<Exception>(0);
for (InputStream is : openedInputStreams) {
try {
is.close();
} catch (Exception e) {
errs.add(e);// record errors for later
}
}
openedInputStreams.clear();
closeZipFile(errs);
// Throw single exception combining all errors
if (!errs.isEmpty()) {
String msg = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (PrintStream ps = new PrintStream(baos, true, "utf-8")) {
ps.println("Error: Failed to close all opened resources. The following exceptions were thrown in the process: ");
int i = 0;
for (Throwable t : errs) {
ps.print("Exception ");
ps.print(i++);
ps.print(": ");
logger.error(t.getMessage(), t);
}
msg = new String(baos.toByteArray(), StandardCharsets.UTF_8);
} catch (Exception e) {
// Do nothing as this will never occur
}
throw new RuntimeException(msg);
}
}
protected void closeZipFile(List<Exception> errs) {
// Try to close the opened zip file if it exists
if (zipFile != null) {
try {
zipFile.close();
errs.clear();// Successfully closed the archive so all input
// streams were closed successfully also
} catch (Exception e) {
errs.add(e);
}
zipFile = null;// set to null no matter what
zipEntry = null;// set to null no matter what
}
}
private static InputStream doJDKBugWorkaround(InputStream is, long size) throws IOException {
int sz = (int) size;
final byte[] buf = new byte[sz];
final int N = 1024;
for (int ln = 0, count = 0; sz > 0 && (ln = is.read(buf, count, Math.min(N, sz))) != -1;) {
count += ln;
sz -= ln;
}
return new ByteArrayInputStream(buf);
}
}
|
InputStream ret = null;
if (path != null) {
try {
ret = Files.newInputStream(path);
} catch (IOException e) {
throw new RuntimeException(
"Error: Failed to open a InputStream for the file at path '" + path.toAbsolutePath().toString() + "'.", e);
}
} else if (!isZipFile()) {
try {
ret = new FileInputStream(file);
} catch (Exception e) {
throw new RuntimeException("Error: Failed to open a InputStream for the file at path '" + file.getPath() + "'.", e);
}
} else {
if (zipFile == null) {
try {
zipFile = SourceLocator.v().archivePathToZip.getRef(file.getPath());
zipEntry = zipFile.get().getEntry(entryName);
if (zipEntry == null) {
silentClose();
throw new RuntimeException(
"Error: Failed to find entry '" + entryName + "' in the archive file at path '" + file.getPath() + "'.");
}
} catch (Exception e) {
silentClose();
throw new RuntimeException(
"Error: Failed to open the archive file at path '" + file.getPath() + "' for entry '" + entryName + "'.", e);
}
}
try (InputStream stream = zipFile.get().getInputStream(zipEntry)) {
ret = doJDKBugWorkaround(stream, zipEntry.getSize());
} catch (Exception e) {
throw new RuntimeException("Error: Failed to open a InputStream for the entry '" + zipEntry.getName()
+ "' of the archive at path '" + zipFile.get().getName() + "'.", e);
}
}
ret = new BufferedInputStream(ret);
openedInputStreams.add(ret);
return ret;
| 1,118
| 462
| 1,580
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/G.java
|
Global
|
resetSpark
|
class Global {
}
public int SETNodeLabel_uniqueId = 0;
public HashMap<SETNode, SETBasicBlock> SETBasicBlock_binding = new HashMap<SETNode, SETBasicBlock>();
public boolean ASTAnalysis_modified;
public NativeHelper NativeHelper_helper = null;
public P2SetFactory newSetFactory;
public P2SetFactory oldSetFactory;
public Map<Pair<SootMethod, Integer>, Parm> Parm_pairToElement = new HashMap<Pair<SootMethod, Integer>, Parm>();
public int SparkNativeHelper_tempVar = 0;
public int PaddleNativeHelper_tempVar = 0;
public boolean PointsToSetInternal_warnedAlready = false;
public HashMap<SootMethod, MethodPAG> MethodPAG_methodToPag = new HashMap<SootMethod, MethodPAG>();
public Set MethodRWSet_allGlobals = new HashSet();
public Set MethodRWSet_allFields = new HashSet();
public int GeneralConstObject_counter = 0;
public UnionFactory Union_factory = null;
public HashMap<Object, Array2ndDimensionSymbol> Array2ndDimensionSymbol_pool
= new HashMap<Object, Array2ndDimensionSymbol>();
public List<Timer> Timer_outstandingTimers = new ArrayList<Timer>();
public boolean Timer_isGarbageCollecting;
public Timer Timer_forcedGarbageCollectionTimer = new Timer("gc");
public int Timer_count;
public final Map<Scene, ClassHierarchy> ClassHierarchy_classHierarchyMap = new HashMap<Scene, ClassHierarchy>();
public final Map<MethodContext, MethodContext> MethodContext_map = new HashMap<MethodContext, MethodContext>();
public DalvikThrowAnalysis interproceduralDalvikThrowAnalysis = null;
public DalvikThrowAnalysis interproceduralDalvikThrowAnalysis() {
if (this.interproceduralDalvikThrowAnalysis == null) {
this.interproceduralDalvikThrowAnalysis = new DalvikThrowAnalysis(g, true);
}
return this.interproceduralDalvikThrowAnalysis;
}
public boolean ASTTransformations_modified;
/*
* 16th Feb 2006 Nomair The AST transformations are unfortunately non-monotonic. Infact one transformation on each
* iteration simply reverses the bodies of an if-else To make the remaining transformations monotonic this transformation
* is handled with a separate flag...clumsy but works
*/
public boolean ASTIfElseFlipped;
/*
* Nomair A. Naeem January 15th 2006 Added For Dava.toolkits.AST.transformations.SuperFirstStmtHandler
*
* The SootMethodAddedByDava is checked by the PackManager after decompiling methods for a class. If any additional methods
* were added by the decompiler (refer to filer SuperFirstStmtHandler) SootMethodsAdded ArrayList contains these method.
* These methods are then added to the SootClass
*
* Some of these newly added methods make use of an object of a static inner class DavaSuperHandler which is to be output
* in the decompilers output. The class is marked to need a DavaSuperHandlerClass by adding it into the
* SootClassNeedsDavaSuperHandlerClass list. The DavaPrinter when printing out the class checks this list and if this
* class's name exists in the list prints out an implementation of DavSuperHandler
*/
public boolean SootMethodAddedByDava;
public ArrayList<SootClass> SootClassNeedsDavaSuperHandlerClass = new ArrayList<SootClass>();
public ArrayList<SootMethod> SootMethodsAdded = new ArrayList<SootMethod>();
// ASTMetrics Data
public ArrayList<ClassData> ASTMetricsData = new ArrayList<ClassData>();
public void resetSpark() {<FILL_FUNCTION_BODY>
|
// We reset SPARK the hard way.
for (Method m : getClass().getSuperclass().getDeclaredMethods()) {
if (m.getName().startsWith("release_soot_jimple_spark_")) {
try {
m.invoke(this);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
// Reset some other stuff directly in this class
MethodPAG_methodToPag.clear();
MethodRWSet_allFields.clear();
MethodRWSet_allGlobals.clear();
newSetFactory = null;
oldSetFactory = null;
Parm_pairToElement.clear();
// We need to reset the virtual call resolution table
release_soot_jimple_toolkits_callgraph_VirtualCalls();
| 1,004
| 258
| 1,262
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/IntType.java
|
IntType
|
getTypeAsString
|
class IntType extends PrimType implements IntegerType {
public static final int HASHCODE = 0xB747239F;
public IntType(Singletons.Global g) {
}
public static IntType v() {
return G.v().soot_IntType();
}
@Override
public boolean equals(Object t) {
return this == t;
}
@Override
public int hashCode() {
return HASHCODE;
}
@Override
public String toString() {
return "int";
}
@Override
public void apply(Switch sw) {
((TypeSwitch) sw).caseIntType(this);
}
@Override
public String getTypeAsString() {<FILL_FUNCTION_BODY>}
@Override
public Class<?> getJavaBoxedType() {
return Integer.class;
}
@Override
public Class<?> getJavaPrimitiveType() {
return int.class;
}
}
|
if (Options.v().src_prec() == Options.src_prec_dotnet) {
return DotnetBasicTypes.SYSTEM_INT32;
}
return JavaBasicTypes.JAVA_LANG_INTEGER;
| 267
| 63
| 330
|
<methods>public non-sealed void <init>() ,public soot.RefType boxedType() ,public abstract Class<?> getJavaBoxedType() ,public abstract Class<?> getJavaPrimitiveType() ,public abstract java.lang.String getTypeAsString() ,public boolean isAllowedInFinalCode() <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/JastAddInitialResolver.java
|
JastAddInitialResolver
|
getBody
|
class JastAddInitialResolver implements IInitialResolver {
private static final Logger logger = LoggerFactory.getLogger(JastAddInitialResolver.class);
public JastAddInitialResolver(soot.Singletons.Global g) {
}
public static JastAddInitialResolver v() {
return soot.G.v().soot_JastAddInitialResolver();
}
protected Map<String, CompilationUnit> classNameToCU = new HashMap<String, CompilationUnit>();
public void formAst(String fullPath, List<String> locations, String className) {
Program program = SootResolver.v().getProgram();
CompilationUnit u = program.getCachedOrLoadCompilationUnit(fullPath);
if (u != null && !u.isResolved) {
u.isResolved = true;
java.util.ArrayList<soot.JastAddJ.Problem> errors = new java.util.ArrayList<soot.JastAddJ.Problem>();
u.errorCheck(errors);
if (!errors.isEmpty()) {
for (soot.JastAddJ.Problem p : errors) {
logger.debug("" + p);
}
// die
throw new CompilationDeathException(CompilationDeathException.COMPILATION_ABORTED,
"there were errors during parsing and/or type checking (JastAdd frontend)");
}
u.transformation();
u.jimplify1phase1();
u.jimplify1phase2();
HashSet<SootClass> types = new HashSet<SootClass>();
for (TypeDecl typeDecl : u.getTypeDecls()) {
collectTypeDecl(typeDecl, types);
}
if (types.isEmpty()) {
classNameToCU.put(className, u);
} else {
for (SootClass sc : types) {
classNameToCU.put(sc.getName(), u);
}
}
}
}
@SuppressWarnings("unchecked")
private void collectTypeDecl(TypeDecl typeDecl, HashSet<SootClass> types) {
types.add(typeDecl.getSootClassDecl());
for (TypeDecl nestedType : (Collection<TypeDecl>) typeDecl.nestedTypes()) {
collectTypeDecl(nestedType, types);
}
}
@SuppressWarnings("unchecked")
private TypeDecl findNestedTypeDecl(TypeDecl typeDecl, SootClass sc) {
if (typeDecl.sootClass() == sc) {
return typeDecl;
}
for (TypeDecl nestedType : (Collection<TypeDecl>) typeDecl.nestedTypes()) {
TypeDecl t = findNestedTypeDecl(nestedType, sc);
if (t != null) {
return t;
}
}
return null;
}
public Dependencies resolveFromJavaFile(SootClass sootclass) {
CompilationUnit u = classNameToCU.get(sootclass.getName());
if (u == null) {
throw new RuntimeException("Error: couldn't find class: " + sootclass.getName() + " are the packages set properly?");
}
HashSet<SootClass> types = new HashSet<SootClass>();
for (TypeDecl typeDecl : u.getTypeDecls()) {
collectTypeDecl(typeDecl, types);
}
Dependencies deps = new Dependencies();
u.collectTypesToHierarchy(deps.typesToHierarchy);
u.collectTypesToSignatures(deps.typesToSignature);
for (SootClass sc : types) {
for (SootMethod m : sc.getMethods()) {
m.setSource(new MethodSource() {
public Body getBody(SootMethod m, String phaseName) {<FILL_FUNCTION_BODY>}
});
}
}
return deps;
}
}
|
SootClass sc = m.getDeclaringClass();
CompilationUnit u = classNameToCU.get(sc.getName());
for (TypeDecl typeDecl : u.getTypeDecls()) {
typeDecl = findNestedTypeDecl(typeDecl, sc);
if (typeDecl != null) {
if (typeDecl.clinit == m) {
typeDecl.jimplify2clinit();
return m.getActiveBody();
}
for (BodyDecl bodyDecl : typeDecl.getBodyDecls()) {
if (bodyDecl instanceof MethodDecl) {
MethodDecl methodDecl = (MethodDecl) bodyDecl;
if (m.equals(methodDecl.sootMethod)) {
methodDecl.jimplify2();
return m.getActiveBody();
}
} else if (bodyDecl instanceof ConstructorDecl) {
ConstructorDecl constrDecl = (ConstructorDecl) bodyDecl;
if (m.equals(constrDecl.sootMethod)) {
constrDecl.jimplify2();
return m.getActiveBody();
}
}
}
}
}
throw new RuntimeException(
"Could not find body for " + m.getSignature() + " in " + m.getDeclaringClass().getName());
| 997
| 316
| 1,313
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/JavaClassProvider.java
|
JarException
|
find
|
class JarException extends RuntimeException {
private static final long serialVersionUID = 1L;
public JarException(String className) {
super("Class " + className
+ " was found in an archive, but Soot doesn't support reading source files out of an archive");
}
}
/**
* Look for the specified class. Return a ClassSource for it if found, or null if it was not found.
*/
@Override
public ClassSource find(String className) {<FILL_FUNCTION_BODY>
|
if (Options.v().polyglot() && soot.javaToJimple.InitialResolver.v().hasASTForSootName(className)) {
soot.javaToJimple.InitialResolver.v().setASTForSootName(className);
return new JavaClassSource(className);
} else { // jastAdd; or polyglot AST not yet produced
/*
* 04.04.2006 mbatch if there is a $ in the name, we need to check if it's a real file, not just inner class
*/
boolean checkAgain = className.indexOf('$') >= 0;
IFoundFile file = null;
try {
final SourceLocator loc = SourceLocator.v();
String javaClassName = loc.getSourceForClass(className);
file = loc.lookupInClassPath(javaClassName.replace('.', '/') + ".java");
/*
* 04.04.2006 mbatch if inner class not found, check if it's a real file
*/
if (file == null && checkAgain) {
file = loc.lookupInClassPath(className.replace('.', '/') + ".java");
}
/* 04.04.2006 mbatch end */
if (file == null) {
return null;
}
if (file.isZipFile()) {
throw new JarException(className);
}
return new JavaClassSource(className, file.getFile());
} finally {
if (file != null) {
file.close();
}
}
}
| 130
| 406
| 536
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/JavaClassSource.java
|
JavaClassSource
|
resolve
|
class JavaClassSource extends ClassSource {
private static final Logger logger = LoggerFactory.getLogger(JavaClassSource.class);
private final File fullPath;
public JavaClassSource(String className, File fullPath) {
super(className);
this.fullPath = fullPath;
}
public JavaClassSource(String className) {
this(className, null);
}
@Override
public Dependencies resolve(SootClass sc) {<FILL_FUNCTION_BODY>}
}
|
if (Options.v().verbose()) {
logger.debug("resolving [from .java]: " + className);
}
IInitialResolver resolver = Options.v().polyglot() ? InitialResolver.v() : JastAddInitialResolver.v();
if (fullPath != null) {
resolver.formAst(fullPath.getPath(), SourceLocator.v().sourcePath(), className);
}
// System.out.println("about to call initial resolver in j2j: "+sc.getName());
Dependencies references = resolver.resolveFromJavaFile(sc);
/*
* 1st March 2006 Nomair This seems to be a good place to calculate all the AST Metrics needed from Java's AST
*/
if (Options.v().ast_metrics()) {
// System.out.println("CALLING COMPUTEASTMETRICS!!!!!!!");
Node ast = InitialResolver.v().getAst();
if (ast == null) {
logger.debug("No compatible AST available for AST metrics. Skipping. Try -polyglot option.");
} else {
ComputeASTMetrics metrics = new ComputeASTMetrics(ast);
metrics.apply();
}
}
return references;
| 131
| 317
| 448
|
<methods>public void <init>(java.lang.String) ,public void close() ,public abstract soot.javaToJimple.IInitialResolver.Dependencies resolve(soot.SootClass) <variables>protected final non-sealed java.lang.String className
|
soot-oss_soot
|
soot/src/main/java/soot/JavaToJimpleBodyPack.java
|
JavaToJimpleBodyPack
|
applyPhaseOptions
|
class JavaToJimpleBodyPack extends BodyPack {
public JavaToJimpleBodyPack() {
super("jj");
}
/**
* Applies the transformations corresponding to the given options.
*/
private void applyPhaseOptions(JimpleBody b, Map<String, String> opts) {<FILL_FUNCTION_BODY>}
@Override
protected void internalApply(Body b) {
applyPhaseOptions((JimpleBody) b, PhaseOptions.v().getPhaseOptions(getPhaseName()));
}
}
|
JJOptions options = new JJOptions(opts);
if (options.use_original_names()) {
PhaseOptions.v().setPhaseOptionIfUnset("jj.lns", "only-stack-locals");
}
final PackManager pacman = PackManager.v();
final boolean time = Options.v().time();
if (time) {
Timers.v().splitTimer.start();
}
pacman.getTransform("jj.ls").apply(b);
if (time) {
Timers.v().splitTimer.end();
}
pacman.getTransform("jj.a").apply(b);
pacman.getTransform("jj.ule").apply(b);
pacman.getTransform("jj.ne").apply(b);
if (time) {
Timers.v().assignTimer.start();
}
pacman.getTransform("jj.tr").apply(b);
if (time) {
Timers.v().assignTimer.end();
}
if (options.use_original_names()) {
pacman.getTransform("jj.ulp").apply(b);
}
pacman.getTransform("jj.lns").apply(b);
pacman.getTransform("jj.cp").apply(b);
pacman.getTransform("jj.dae").apply(b);
pacman.getTransform("jj.cp-ule").apply(b);
pacman.getTransform("jj.lp").apply(b);
// pacman.getTransform( "jj.ct" ).apply( b );
pacman.getTransform("jj.uce").apply(b);
if (time) {
Timers.v().stmtCount += b.getUnits().size();
}
| 143
| 459
| 602
|
<methods>public void <init>(java.lang.String) <variables>private static final org.slf4j.Logger logger
|
soot-oss_soot
|
soot/src/main/java/soot/JimpleBodyPack.java
|
JimpleBodyPack
|
applyPhaseOptions
|
class JimpleBodyPack extends BodyPack {
public JimpleBodyPack() {
super("jb");
}
/**
* Applies the transformations corresponding to the given options.
*/
private void applyPhaseOptions(JimpleBody b, Map<String, String> opts) {<FILL_FUNCTION_BODY>}
@Override
protected void internalApply(Body b) {
applyPhaseOptions((JimpleBody) b, PhaseOptions.v().getPhaseOptions(getPhaseName()));
}
}
|
JBOptions options = new JBOptions(opts);
if (options.use_original_names()) {
PhaseOptions.v().setPhaseOptionIfUnset("jb.lns", "only-stack-locals");
}
final PackManager pacman = PackManager.v();
final boolean time = Options.v().time();
if (time) {
Timers.v().splitTimer.start();
}
pacman.getTransform("jb.tt").apply(b); // TrapTigthener
pacman.getTransform("jb.dtr").apply(b); // DuplicateCatchAllTrapRemover
// UnreachableCodeEliminator: We need to do this before splitting
// locals for not creating disconnected islands of useless assignments
// that afterwards mess up type assignment.
pacman.getTransform("jb.uce").apply(b);
pacman.getTransform("jb.ls").apply(b);
pacman.getTransform("jb.sils").apply(b);
if (time) {
Timers.v().splitTimer.end();
}
pacman.getTransform("jb.a").apply(b);
pacman.getTransform("jb.ule").apply(b);
if (time) {
Timers.v().assignTimer.start();
}
pacman.getTransform("jb.tr").apply(b);
if (time) {
Timers.v().assignTimer.end();
}
if (options.use_original_names()) {
pacman.getTransform("jb.ulp").apply(b);
}
pacman.getTransform("jb.lns").apply(b); // LocalNameStandardizer
pacman.getTransform("jb.cp").apply(b); // CopyPropagator
pacman.getTransform("jb.dae").apply(b); // DeadAssignmentElimintaor
pacman.getTransform("jb.cp-ule").apply(b); // UnusedLocalEliminator
pacman.getTransform("jb.lp").apply(b); // LocalPacker
pacman.getTransform("jb.ne").apply(b); // NopEliminator
pacman.getTransform("jb.uce").apply(b); // UnreachableCodeEliminator: Again, we might have new dead code
// LocalNameStandardizer: After all these changes, some locals
// may end up being eliminated. If we want a stable local iteration
// order between soot instances, running LocalNameStandardizer
// again after all other changes is required.
if (options.stabilize_local_names()) {
PhaseOptions.v().setPhaseOption("jb.lns", "sort-locals:true");
pacman.getTransform("jb.lns").apply(b);
}
if (time) {
Timers.v().stmtCount += b.getUnits().size();
}
| 137
| 740
| 877
|
<methods>public void <init>(java.lang.String) <variables>private static final org.slf4j.Logger logger
|
soot-oss_soot
|
soot/src/main/java/soot/JimpleClassProvider.java
|
JimpleClassProvider
|
find
|
class JimpleClassProvider implements ClassProvider {
/**
* Look for the specified class. Return a ClassSource for it if found, or null if it was not found.
*/
@Override
public ClassSource find(String className) {<FILL_FUNCTION_BODY>}
}
|
IFoundFile file = SourceLocator.v().lookupInClassPath(className + ".jimple");
if (file == null) {
if (Options.v().permissive_resolving()) {
file = SourceLocator.v().lookupInClassPath(className.replace('.', '/') + ".jimple");
}
if (file == null) {
return null;
}
}
return new JimpleClassSource(className, file);
| 72
| 119
| 191
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/Kind.java
|
Kind
|
isFake
|
class Kind implements Numberable {
public static final Kind INVALID = new Kind("INVALID");
/**
* Due to explicit invokestatic instruction.
*/
public static final Kind STATIC = new Kind("STATIC");
/**
* Due to explicit invokevirtual instruction.
*/
public static final Kind VIRTUAL = new Kind("VIRTUAL");
/**
* Due to explicit invokeinterface instruction.
*/
public static final Kind INTERFACE = new Kind("INTERFACE");
/**
* Due to explicit invokespecial instruction.
*/
public static final Kind SPECIAL = new Kind("SPECIAL");
/**
* Implicit call to static initializer.
*/
public static final Kind CLINIT = new Kind("CLINIT");
/**
* Fake edges from our generic callback model.
*/
public static final Kind GENERIC_FAKE = new Kind("GENERIC_FAKE");
/**
* Implicit call to Thread.run() due to Thread.start() call.
*/
public static final Kind THREAD = new Kind("THREAD");
/**
* Implicit call to java.lang.Runnable.run() due to Executor.execute() call.
*/
public static final Kind EXECUTOR = new Kind("EXECUTOR");
/**
* Implicit call to AsyncTask.doInBackground() due to AsyncTask.execute() call.
*/
public static final Kind ASYNCTASK = new Kind("ASYNCTASK");
/**
* Implicit call to java.lang.ref.Finalizer.register from new bytecode.
*/
public static final Kind FINALIZE = new Kind("FINALIZE");
/**
* Implicit call to Handler.handleMessage(android.os.Message) due to Handler.sendxxxxMessagexxxx() call.
*/
public static final Kind HANDLER = new Kind("HANDLER");
/**
* Implicit call to finalize() from java.lang.ref.Finalizer.invokeFinalizeMethod().
*/
public static final Kind INVOKE_FINALIZE = new Kind("INVOKE_FINALIZE");
/**
* Implicit call to run() through AccessController.doPrivileged().
*/
public static final Kind PRIVILEGED = new Kind("PRIVILEGED");
/**
* Implicit call to constructor from java.lang.Class.newInstance().
*/
public static final Kind NEWINSTANCE = new Kind("NEWINSTANCE");
/**
* Due to call to Method.invoke(..).
*/
public static final Kind REFL_INVOKE = new Kind("REFL_METHOD_INVOKE");
/**
* Due to call to Constructor.newInstance(..).
*/
public static final Kind REFL_CONSTR_NEWINSTANCE = new Kind("REFL_CONSTRUCTOR_NEWINSTANCE");
/**
* Due to call to Class.newInstance(..) when reflection log is enabled.
*/
public static final Kind REFL_CLASS_NEWINSTANCE = new Kind("REFL_CLASS_NEWINSTANCE");
private final String name;
private int num;
private Kind(String name) {
this.name = name;
}
public String name() {
return name;
}
@Override
public int getNumber() {
return num;
}
@Override
public void setNumber(int num) {
this.num = num;
}
@Override
public String toString() {
return name();
}
public boolean passesParameters() {
return passesParameters(this);
}
public boolean isFake() {
return isFake(this);
}
/**
* Returns true if the call is due to an explicit invoke statement.
*/
public boolean isExplicit() {
return isExplicit(this);
}
/**
* Returns true if the call is due to an explicit instance invoke statement.
*/
public boolean isInstance() {
return isInstance(this);
}
/**
* Returns true if the call is due to an explicit virtual invoke statement.
*/
public boolean isVirtual() {
return isVirtual(this);
}
public boolean isSpecial() {
return isSpecial(this);
}
/**
* Returns true if the call is to static initializer.
*/
public boolean isClinit() {
return isClinit(this);
}
/**
* Returns true if the call is due to an explicit static invoke statement.
*/
public boolean isStatic() {
return isStatic(this);
}
public boolean isThread() {
return isThread(this);
}
public boolean isExecutor() {
return isExecutor(this);
}
public boolean isAsyncTask() {
return isAsyncTask(this);
}
public boolean isPrivileged() {
return isPrivileged(this);
}
public boolean isReflection() {
return isReflection(this);
}
public boolean isReflInvoke() {
return isReflInvoke(this);
}
public boolean isHandler() {
return isHandler(this);
}
public static boolean passesParameters(Kind k) {
return isExplicit(k) || k == THREAD || k == EXECUTOR || k == ASYNCTASK || k == FINALIZE || k == PRIVILEGED
|| k == NEWINSTANCE || k == INVOKE_FINALIZE || k == REFL_INVOKE || k == REFL_CONSTR_NEWINSTANCE
|| k == REFL_CLASS_NEWINSTANCE || k == GENERIC_FAKE;
}
public static boolean isFake(Kind k) {<FILL_FUNCTION_BODY>}
/**
* Returns true if the call is due to an explicit invoke statement.
*/
public static boolean isExplicit(Kind k) {
return isInstance(k) || isStatic(k);
}
/**
* Returns true if the call is due to an explicit instance invoke statement.
*/
public static boolean isInstance(Kind k) {
return k == VIRTUAL || k == INTERFACE || k == SPECIAL;
}
/**
* Returns true if the call is due to an explicit virtual invoke statement.
*/
public static boolean isVirtual(Kind k) {
return k == VIRTUAL;
}
public static boolean isSpecial(Kind k) {
return k == SPECIAL;
}
/**
* Returns true if the call is to static initializer.
*/
public static boolean isClinit(Kind k) {
return k == CLINIT;
}
/**
* Returns true if the call is due to an explicit static invoke statement.
*/
public static boolean isStatic(Kind k) {
return k == STATIC;
}
public static boolean isThread(Kind k) {
return k == THREAD;
}
public static boolean isExecutor(Kind k) {
return k == EXECUTOR;
}
public static boolean isAsyncTask(Kind k) {
return k == ASYNCTASK;
}
public static boolean isPrivileged(Kind k) {
return k == PRIVILEGED;
}
public static boolean isReflection(Kind k) {
return k == REFL_CLASS_NEWINSTANCE || k == REFL_CONSTR_NEWINSTANCE || k == REFL_INVOKE;
}
public static boolean isReflInvoke(Kind k) {
return k == REFL_INVOKE;
}
public static boolean isHandler(Kind k) {
return k == HANDLER;
}
}
|
return k == THREAD || k == EXECUTOR || k == ASYNCTASK || k == PRIVILEGED || k == HANDLER || k == GENERIC_FAKE;
| 1,994
| 51
| 2,045
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/MethodContext.java
|
MethodContext
|
v
|
class MethodContext implements MethodOrMethodContext {
private SootMethod method;
public SootMethod method() {
return method;
}
private Context context;
public Context context() {
return context;
}
private MethodContext(SootMethod method, Context context) {
this.method = method;
this.context = context;
}
public int hashCode() {
return method.hashCode() + context.hashCode();
}
public boolean equals(Object o) {
if (o instanceof MethodContext) {
MethodContext other = (MethodContext) o;
return method.equals(other.method) && context.equals(other.context);
}
return false;
}
public static MethodOrMethodContext v(SootMethod method, Context context) {<FILL_FUNCTION_BODY>}
public String toString() {
return "Method " + method + " in context " + context;
}
}
|
if (context == null) {
return method;
}
MethodContext probe = new MethodContext(method, context);
Map<MethodContext, MethodContext> map = G.v().MethodContext_map;
MethodContext ret = map.get(probe);
if (ret == null) {
map.put(probe, probe);
return probe;
}
return ret;
| 246
| 99
| 345
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/MethodSubSignature.java
|
MethodSubSignature
|
equals
|
class MethodSubSignature {
public final String methodName;
public final Type returnType;
public final List<Type> parameterTypes;
public final NumberedString numberedSubSig;
private static final Pattern PATTERN_METHOD_SUBSIG
= Pattern.compile("(?<returnType>.*?) (?<methodName>.*?)\\((?<parameters>.*?)\\)");
public MethodSubSignature(SootMethodRef r) {
methodName = r.getName();
returnType = r.getReturnType();
parameterTypes = r.getParameterTypes();
numberedSubSig = r.getSubSignature();
}
public MethodSubSignature(NumberedString subsig) {
this.numberedSubSig = subsig;
Matcher m = PATTERN_METHOD_SUBSIG.matcher(subsig.toString());
if (!m.matches()) {
throw new IllegalArgumentException("Not a valid subsignature: " + subsig);
}
Scene sc = Scene.v();
methodName = m.group(2);
returnType = sc.getTypeUnsafe(m.group(1));
String parameters = m.group(3);
String[] spl = parameters.split(",");
parameterTypes = new ArrayList<>(spl.length);
if (parameters != null && !parameters.isEmpty()) {
for (String p : spl) {
parameterTypes.add(sc.getTypeUnsafe(p.trim()));
}
}
}
public MethodSubSignature(String methodName, Type returnType, List<Type> parameterTypes) {
this.methodName = methodName;
this.returnType = returnType;
this.parameterTypes = parameterTypes;
this.numberedSubSig = Scene.v().getSubSigNumberer()
.findOrAdd(returnType + " " + methodName + "(" + Joiner.on(',').join(parameterTypes) + ")");
}
/**
* Creates a new instance of the {@link MethodSubSignature} class based on a call site. The subsignature of the callee will
* be taken from the method referenced at the call site.
*
* @param callSite
* The call site
*/
public MethodSubSignature(Stmt callSite) {
this(callSite.getInvokeExpr().getMethodRef().getSubSignature());
}
public String getMethodName() {
return methodName;
}
public Type getReturnType() {
return returnType;
}
public List<Type> getParameterTypes() {
return parameterTypes;
}
public NumberedString getNumberedSubSig() {
return numberedSubSig;
}
/**
* Tries to find the exact method in a class. Returns null if cannot be found
*
* @param c
* the class
* @return the method (or null)
*/
public SootMethod getInClassUnsafe(SootClass c) {
return c.getMethodUnsafe(numberedSubSig);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((numberedSubSig == null) ? 0 : numberedSubSig.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return numberedSubSig.toString();
}
}
|
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
return false;
}
MethodSubSignature other = (MethodSubSignature) obj;
if (numberedSubSig == null) {
if (other.numberedSubSig != null) {
return false;
}
} else if (!numberedSubSig.equals(other.numberedSubSig)) {
return false;
}
return true;
| 893
| 136
| 1,029
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/Modifier.java
|
Modifier
|
toString
|
class Modifier {
public static final int ABSTRACT = 0x0400;
public static final int FINAL = 0x0010;
public static final int INTERFACE = 0x0200;
public static final int NATIVE = 0x0100;
public static final int PRIVATE = 0x0002;
public static final int PROTECTED = 0x0004;
public static final int PUBLIC = 0x0001;
public static final int STATIC = 0x0008;
public static final int SYNCHRONIZED = 0x0020;
public static final int TRANSIENT = 0x0080; /* VARARGS for methods */
public static final int VOLATILE = 0x0040; /* BRIDGE for methods */
public static final int STRICTFP = 0x0800;
public static final int ANNOTATION = 0x2000;
public static final int ENUM = 0x4000;
// dex specifific modifiers
public static final int SYNTHETIC = 0x1000;
public static final int CONSTRUCTOR = 0x10000;
public static final int DECLARED_SYNCHRONIZED = 0x20000;
// add
// modifier for java 9 modules
public static final int REQUIRES_TRANSITIVE = 0x0020;
public static final int REQUIRES_STATIC = 0x0040;
public static final int REQUIRES_SYNTHETIC = 0x1000;
public static final int REQUIRES_MANDATED = 0x8000;
private Modifier() {
}
public static boolean isAbstract(int m) {
return (m & ABSTRACT) != 0;
}
public static boolean isFinal(int m) {
return (m & FINAL) != 0;
}
public static boolean isInterface(int m) {
return (m & INTERFACE) != 0;
}
public static boolean isNative(int m) {
return (m & NATIVE) != 0;
}
public static boolean isPrivate(int m) {
return (m & PRIVATE) != 0;
}
public static boolean isProtected(int m) {
return (m & PROTECTED) != 0;
}
public static boolean isPublic(int m) {
return (m & PUBLIC) != 0;
}
public static boolean isStatic(int m) {
return (m & STATIC) != 0;
}
public static boolean isSynchronized(int m) {
return (m & SYNCHRONIZED) != 0;
}
public static boolean isTransient(int m) {
return (m & TRANSIENT) != 0;
}
public static boolean isVolatile(int m) {
return (m & VOLATILE) != 0;
}
public static boolean isStrictFP(int m) {
return (m & STRICTFP) != 0;
}
public static boolean isAnnotation(int m) {
return (m & ANNOTATION) != 0;
}
public static boolean isEnum(int m) {
return (m & ENUM) != 0;
}
public static boolean isSynthetic(int m) {
return (m & SYNTHETIC) != 0;
}
public static boolean isConstructor(int m) {
return (m & CONSTRUCTOR) != 0;
}
public static boolean isDeclaredSynchronized(int m) {
return (m & DECLARED_SYNCHRONIZED) != 0;
}
/**
* Converts the given modifiers to their string representation, in canonical form.
*
* @param m
* a modifier set
* @return a textual representation of the modifiers.
*/
public static String toString(int m) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder buffer = new StringBuilder();
if (isPublic(m)) {
buffer.append("public ");
} else if (isPrivate(m)) {
buffer.append("private ");
} else if (isProtected(m)) {
buffer.append("protected ");
}
if (isAbstract(m)) {
buffer.append("abstract ");
}
if (isStatic(m)) {
buffer.append("static ");
}
if (isFinal(m)) {
buffer.append("final ");
}
if (isSynchronized(m)) {
buffer.append("synchronized ");
}
if (isNative(m)) {
buffer.append("native ");
}
if (isTransient(m)) {
buffer.append("transient ");
}
if (isVolatile(m)) {
buffer.append("volatile ");
}
if (isStrictFP(m)) {
buffer.append("strictfp ");
}
if (isAnnotation(m)) {
buffer.append("annotation ");
}
if (isEnum(m)) {
buffer.append("enum ");
}
if (isInterface(m)) {
buffer.append("interface ");
}
return buffer.toString().trim();
| 1,078
| 341
| 1,419
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/NormalUnitPrinter.java
|
NormalUnitPrinter
|
identityRef
|
class NormalUnitPrinter extends LabeledUnitPrinter {
public NormalUnitPrinter(Body body) {
super(body);
}
@Override
public void type(Type t) {
handleIndent();
output.append(t == null ? "<null>" : t.toQuotedString());
}
@Override
public void methodRef(SootMethodRef m) {
handleIndent();
output.append(m.getSignature());
}
@Override
public void fieldRef(SootFieldRef f) {
handleIndent();
output.append(f.getSignature());
}
@Override
public void identityRef(IdentityRef r) {<FILL_FUNCTION_BODY>}
@Override
public void literal(String s) {
handleIndent();
output.append(s);
}
}
|
handleIndent();
if (r instanceof ThisRef) {
literal("@this: ");
type(r.getType());
} else if (r instanceof ParameterRef) {
ParameterRef pr = (ParameterRef) r;
literal("@parameter" + pr.getIndex() + ": ");
type(r.getType());
} else if (r instanceof CaughtExceptionRef) {
literal("@caughtexception");
} else {
throw new RuntimeException();
}
| 223
| 126
| 349
|
<methods>public void <init>(soot.Body) ,public Map<soot.Unit,java.lang.String> labels() ,public Map<soot.Unit,java.lang.String> references() ,public void unitRef(soot.Unit, boolean) <variables>protected java.lang.String labelIndent,protected Map<soot.Unit,java.lang.String> labels,protected Map<soot.Unit,java.lang.String> references
|
soot-oss_soot
|
soot/src/main/java/soot/Pack.java
|
Pack
|
insertAfter
|
class Pack implements HasPhaseOptions, Iterable<Transform> {
private final List<Transform> opts = new ArrayList<Transform>();
private final String name;
@Override
public String getPhaseName() {
return name;
}
public Pack(String name) {
this.name = name;
}
@Override
public Iterator<Transform> iterator() {
return opts.iterator();
}
public void add(Transform t) {
if (!t.getPhaseName().startsWith(getPhaseName() + ".")) {
throw new RuntimeException(
"Transforms in pack '" + getPhaseName() + "' must have a phase name that starts with '" + getPhaseName() + ".'.");
}
PhaseOptions.v().getPM().notifyAddPack();
if (get(t.getPhaseName()) != null) {
throw new RuntimeException("Phase " + t.getPhaseName() + " already in pack");
}
opts.add(t);
}
public void insertAfter(Transform t, String phaseName) {<FILL_FUNCTION_BODY>}
public void insertBefore(Transform t, String phaseName) {
PhaseOptions.v().getPM().notifyAddPack();
for (Transform tr : opts) {
if (tr.getPhaseName().equals(phaseName)) {
opts.add(opts.indexOf(tr), t);
return;
}
}
throw new RuntimeException("phase " + phaseName + " not found!");
}
public Transform get(String phaseName) {
for (Transform tr : opts) {
if (tr.getPhaseName().equals(phaseName)) {
return tr;
}
}
return null;
}
public boolean remove(String phaseName) {
for (Transform tr : opts) {
if (tr.getPhaseName().equals(phaseName)) {
opts.remove(tr);
return true;
}
}
return false;
}
protected void internalApply() {
throw new RuntimeException("wrong type of pack");
}
protected void internalApply(Body b) {
throw new RuntimeException("wrong type of pack");
}
public final void apply() {
Map<String, String> options = PhaseOptions.v().getPhaseOptions(this);
if (!PhaseOptions.getBoolean(options, "enabled")) {
return;
}
internalApply();
}
public final void apply(Body b) {
Map<String, String> options = PhaseOptions.v().getPhaseOptions(this);
if (!PhaseOptions.getBoolean(options, "enabled")) {
return;
}
internalApply(b);
}
@Override
public String getDeclaredOptions() {
return soot.options.Options.getDeclaredOptionsForPhase(getPhaseName());
}
@Override
public String getDefaultOptions() {
return soot.options.Options.getDefaultOptionsForPhase(getPhaseName());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append(" { ");
for (int i = 0; i < opts.size(); i++) {
sb.append(opts.get(i).getPhaseName());
if (i < opts.size() - 1) {
sb.append(",");
}
sb.append(" ");
}
sb.append(" }");
return sb.toString();
}
}
|
PhaseOptions.v().getPM().notifyAddPack();
for (Transform tr : opts) {
if (tr.getPhaseName().equals(phaseName)) {
opts.add(opts.indexOf(tr) + 1, t);
return;
}
}
throw new RuntimeException("phase " + phaseName + " not found!");
| 915
| 90
| 1,005
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/PolymorphicMethodRef.java
|
PolymorphicMethodRef
|
resolve
|
class PolymorphicMethodRef extends SootMethodRefImpl {
public static final String METHODHANDLE_SIGNATURE = "java.lang.invoke.MethodHandle";
public static final String VARHANDLE_SIGNATURE = "java.lang.invoke.VarHandle";
public static final String POLYMORPHIC_SIGNATURE = "java/lang/invoke/MethodHandle$PolymorphicSignature";
/**
* Check if the declaring class "has the rights" to declare polymorphic methods
* {@see http://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.4.4}
*
* @param declaringClass
* the class to check
* @return if the class is allowed according to the JVM Spec
*/
public static boolean handlesClass(SootClass declaringClass) {
return handlesClass(declaringClass.getName());
}
public static boolean handlesClass(String declaringClassName) {
return PolymorphicMethodRef.METHODHANDLE_SIGNATURE.equals(declaringClassName)
|| PolymorphicMethodRef.VARHANDLE_SIGNATURE.equals(declaringClassName);
}
/**
* Constructor.
*
* @param declaringClass
* the declaring class. Must not be {@code null}
* @param name
* the method name. Must not be {@code null}
* @param parameterTypes
* the types of parameters. May be {@code null}
* @param returnType
* the type of return value. Must not be {@code null}
* @param isStatic
* the static modifier value
* @throws IllegalArgumentException
* is thrown when {@code declaringClass}, or {@code name}, or {@code returnType} is null
*/
public PolymorphicMethodRef(SootClass declaringClass, String name, List<Type> parameterTypes, Type returnType,
boolean isStatic) {
super(declaringClass, name, parameterTypes, returnType, isStatic);
}
@Override
public SootMethod resolve() {<FILL_FUNCTION_BODY>}
private SootMethod addPolyMorphicMethod(SootMethod originalPolyMorphicMethod) {
SootMethod newMethod
= new SootMethod(getName(), getParameterTypes(), getReturnType(), originalPolyMorphicMethod.modifiers);
getDeclaringClass().addMethod(newMethod);
return newMethod;
}
}
|
SootMethod method = getDeclaringClass().getMethodUnsafe(getName(), getParameterTypes(), getReturnType());
if (method != null) {
return method;
}
// No method with matching parameter types or return types found for polymorphic methods,
// we don't care about the return or parameter types. We just check if a method with the
// name exists and has a polymorphic type signature.
// Note(MB): We cannot use getMethodByName here since the method name is ambiguous after
// adding the first method with same name and refined signature.
for (SootMethod candidateMethod : getDeclaringClass().getMethods()) {
if (candidateMethod.getName().equals(getName())) {
Tag annotationsTag = candidateMethod.getTag(VisibilityAnnotationTag.NAME);
if (annotationsTag != null) {
for (AnnotationTag annotation : ((VisibilityAnnotationTag) annotationsTag).getAnnotations()) {
// check the annotation's type
if (('L' + POLYMORPHIC_SIGNATURE + ';').equals(annotation.getType())) {
// The method is polymorphic, add a fitting method to the MethodHandle
// or VarHandle class, as the JVM does on runtime.
return addPolyMorphicMethod(candidateMethod);
}
}
}
}
}
return super.resolve();
| 647
| 347
| 994
|
<methods>public void <init>(soot.SootClass, java.lang.String, List<soot.Type>, soot.Type, boolean) ,public soot.SootClass declaringClass() ,public boolean equals(java.lang.Object) ,public soot.SootClass getDeclaringClass() ,public java.lang.String getName() ,public soot.Type getParameterType(int) ,public List<soot.Type> getParameterTypes() ,public soot.Type getReturnType() ,public java.lang.String getSignature() ,public soot.util.NumberedString getSubSignature() ,public int hashCode() ,public boolean isStatic() ,public java.lang.String name() ,public soot.Type parameterType(int) ,public List<soot.Type> parameterTypes() ,public soot.SootMethod resolve() ,public soot.Type returnType() ,public java.lang.String toString() ,public soot.SootMethod tryResolve() <variables>private final non-sealed soot.SootClass declaringClass,private final non-sealed boolean isStatic,private static final org.slf4j.Logger logger,private final non-sealed java.lang.String name,private final non-sealed List<soot.Type> parameterTypes,private soot.SootMethod resolveCache,private final non-sealed soot.Type returnType,private soot.util.NumberedString subsig
|
soot-oss_soot
|
soot/src/main/java/soot/RadioScenePack.java
|
RadioScenePack
|
internalApply
|
class RadioScenePack extends ScenePack {
private static final Logger logger = LoggerFactory.getLogger(RadioScenePack.class);
public RadioScenePack(String name) {
super(name);
}
@Override
protected void internalApply() {<FILL_FUNCTION_BODY>}
@Override
public void add(Transform t) {
super.add(t);
checkEnabled(t);
}
@Override
public void insertAfter(Transform t, String phaseName) {
super.insertAfter(t, phaseName);
checkEnabled(t);
}
@Override
public void insertBefore(Transform t, String phaseName) {
super.insertBefore(t, phaseName);
checkEnabled(t);
}
private void checkEnabled(Transform t) {
Map<String, String> options = PhaseOptions.v().getPhaseOptions(t);
if (PhaseOptions.getBoolean(options, "enabled")) {
// Enabling this one will disable all the others
PhaseOptions.v().setPhaseOption(t, "enabled:true");
}
}
}
|
LinkedList<Transform> enabled = new LinkedList<Transform>();
for (Transform t : this) {
Map<String, String> opts = PhaseOptions.v().getPhaseOptions(t);
if (PhaseOptions.getBoolean(opts, "enabled")) {
enabled.add(t);
}
}
if (enabled.isEmpty()) {
logger.debug("Exactly one phase in the pack " + getPhaseName() + " must be enabled. Currently, none of them are.");
throw new CompilationDeathException(CompilationDeathException.COMPILATION_ABORTED);
}
if (enabled.size() > 1) {
logger
.debug("Only one phase in the pack " + getPhaseName() + " may be enabled. The following are enabled currently: ");
for (Transform t : enabled) {
logger.debug(" " + t.getPhaseName());
}
throw new CompilationDeathException(CompilationDeathException.COMPILATION_ABORTED);
}
for (Transform t : enabled) {
t.apply();
}
| 291
| 277
| 568
|
<methods>public void <init>(java.lang.String) <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/RefType.java
|
RefType
|
merge
|
class RefType extends RefLikeType implements Comparable<RefType> {
/**
* the class name that parameterizes this RefType
*/
private String className;
private AnySubType anySubType;
protected volatile SootClass sootClass;
public RefType(Singletons.Global g) {
this.className = "";
}
protected RefType(String className) {
if (!className.isEmpty()) {
if (className.charAt(0) == '[') {
throw new RuntimeException("Attempt to create RefType whose name starts with [ --> " + className);
}
if (className.indexOf('/') >= 0) {
throw new RuntimeException("Attempt to create RefType containing a / --> " + className);
}
if (className.indexOf(';') >= 0) {
throw new RuntimeException("Attempt to create RefType containing a ; --> " + className);
}
}
this.className = className;
}
public static RefType v() {
G g = G.v();
if (g.soot_ModuleUtil().isInModuleMode()) {
return g.soot_ModuleRefType();
} else {
return g.soot_RefType();
}
}
/**
* Create a RefType for a class.
*
* @param className
* The name of the class used to parameterize the created RefType.
* @return a RefType for the given class name.
*/
public static RefType v(String className) {
if (ModuleUtil.module_mode()) {
return ModuleRefType.v(className);
} else {
return Scene.v().getOrAddRefType(className);
}
}
/**
* Create a RefType for a class.
*
* @param c
* A SootClass for which to create a RefType.
* @return a RefType for the given SootClass..
*/
public static RefType v(SootClass c) {
if (ModuleUtil.module_mode()) {
return ModuleRefType.v(c.getName(), Optional.fromNullable(c.moduleName));
} else {
return v(c.getName());
}
}
public String getClassName() {
return className;
}
@Override
public int compareTo(RefType t) {
return this.toString().compareTo(t.toString());
}
/**
* Get the SootClass object corresponding to this RefType.
*
* @return the corresponding SootClass
*/
public SootClass getSootClass() {
if (sootClass == null) {
// System.out.println( "wrning: "+this+" has no sootclass" );
sootClass = SootResolver.v().makeClassRef(className);
}
return sootClass;
}
public boolean hasSootClass() {
return sootClass != null;
}
public void setClassName(String className) {
this.className = className;
}
/**
* Set the SootClass object corresponding to this RefType.
*
* @param sootClass
* The SootClass corresponding to this RefType.
*/
public void setSootClass(SootClass sootClass) {
this.sootClass = sootClass;
}
/**
* Two RefTypes are considered equal if they are parameterized by the same class name String.
*
* @param t
* an object to test for equality. @ return true if t is a RefType parameterized by the same name as this.
*/
@Override
public boolean equals(Object t) {
return ((t instanceof RefType) && className.equals(((RefType) t).className));
}
@Override
public String toString() {
return className;
}
/**
* Returns a textual representation, quoted as needed, of this type for serialization, e.g. to .jimple format
*/
@Override
public String toQuotedString() {
return Scene.v().quotedNameOf(className);
}
@Override
public int hashCode() {
return className.hashCode();
}
@Override
public void apply(Switch sw) {
((TypeSwitch) sw).caseRefType(this);
}
/**
* Returns the least common superclass of this type and other.
*/
@Override
public Type merge(Type other, Scene cm) {<FILL_FUNCTION_BODY>}
@Override
public Type getArrayElementType() {
if (Options.v().src_prec() == Options.src_prec_dotnet) {
if (DotnetBasicTypes.SYSTEM_OBJECT.equals(className) || DotnetBasicTypes.SYSTEM_ICLONEABLE.equals(className)) {
return Scene.v().getObjectType();
}
}
if (JavaBasicTypes.JAVA_LANG_OBJECT.equals(className) || JavaBasicTypes.JAVA_IO_SERIALIZABLE.equals(className)
|| JavaBasicTypes.JAVA_LANG_CLONABLE.equals(className)) {
return Scene.v().getObjectType();
}
throw new RuntimeException("Attempt to get array base type of a non-array");
}
public AnySubType getAnySubType() {
return anySubType;
}
public void setAnySubType(AnySubType anySubType) {
this.anySubType = anySubType;
}
@Override
public boolean isAllowedInFinalCode() {
return true;
}
}
|
if (other.equals(UnknownType.v()) || this.equals(other)) {
return this;
}
if (!(other instanceof RefType)) {
throw new RuntimeException("illegal type merge: " + this + " and " + other);
}
{
// Return least common superclass
final SootClass javalangObject = cm.getObjectType().getSootClass();
ArrayDeque<SootClass> thisHierarchy = new ArrayDeque<>();
ArrayDeque<SootClass> otherHierarchy = new ArrayDeque<>();
// Build thisHierarchy
// This should never be null, so we could also use "while
// (true)"; but better be safe than sorry.
for (SootClass sc = cm.getSootClass(this.className); sc != null;) {
thisHierarchy.addFirst(sc);
if (sc == javalangObject) {
break;
}
sc = sc.getSuperclassUnsafe();
if (sc == null) {
sc = javalangObject;
}
}
// Build otherHierarchy
// This should never be null, so we could also use "while
// (true)"; but better be safe than sorry.
for (SootClass sc = cm.getSootClass(((RefType) other).className); sc != null;) {
otherHierarchy.addFirst(sc);
if (sc == javalangObject) {
break;
}
sc = sc.getSuperclassUnsafe();
if (sc == null) {
sc = javalangObject;
}
}
// Find least common superclass
{
SootClass commonClass = null;
while (!otherHierarchy.isEmpty() && !thisHierarchy.isEmpty()
&& otherHierarchy.getFirst() == thisHierarchy.getFirst()) {
commonClass = otherHierarchy.removeFirst();
thisHierarchy.removeFirst();
}
if (commonClass == null) {
throw new RuntimeException("Could not find a common superclass for " + this + " and " + other);
}
return commonClass.getType();
}
}
| 1,440
| 561
| 2,001
|
<methods>public non-sealed void <init>() ,public abstract soot.Type getArrayElementType() <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/ShortType.java
|
ShortType
|
getTypeAsString
|
class ShortType extends PrimType implements IntegerType {
public static final int HASHCODE = 0x8B817DD3;
public ShortType(Singletons.Global g) {
}
public static ShortType v() {
return G.v().soot_ShortType();
}
@Override
public int hashCode() {
return HASHCODE;
}
@Override
public boolean equals(Object t) {
return this == t;
}
@Override
public String toString() {
return "short";
}
@Override
public void apply(Switch sw) {
((TypeSwitch) sw).caseShortType(this);
}
@Override
public String getTypeAsString() {<FILL_FUNCTION_BODY>}
@Override
public Class<?> getJavaBoxedType() {
return Short.class;
}
@Override
public Class<?> getJavaPrimitiveType() {
return short.class;
}
}
|
if (Options.v().src_prec() == Options.src_prec_dotnet) {
return DotnetBasicTypes.SYSTEM_INT16;
}
return JavaBasicTypes.JAVA_LANG_SHORT;
| 266
| 62
| 328
|
<methods>public non-sealed void <init>() ,public soot.RefType boxedType() ,public abstract Class<?> getJavaBoxedType() ,public abstract Class<?> getJavaPrimitiveType() ,public abstract java.lang.String getTypeAsString() ,public boolean isAllowedInFinalCode() <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/SootMethodRefImpl.java
|
ClassResolutionFailedException
|
createUnresolvedErrorMethod
|
class ClassResolutionFailedException extends ResolutionFailedException {
/** */
private static final long serialVersionUID = 5430199603403917938L;
public ClassResolutionFailedException() {
super("Class " + declaringClass + " doesn't have method " + name + "(" + (parameterTypes == null ? "" : parameterTypes)
+ ")" + " : " + returnType + "; failed to resolve in superclasses and interfaces");
}
@Override
public String toString() {
final StringBuilder ret = new StringBuilder(super.toString());
resolve(ret);
return ret.toString();
}
}
@Override
public SootMethod resolve() {
SootMethod cached = this.resolveCache;
// Use the cached SootMethod if available and still valid
if (cached == null || !cached.isValidResolve(this)) {
cached = resolve(null);
this.resolveCache = cached;
}
return cached;
}
@Override
public SootMethod tryResolve() {
return tryResolve(null);
}
private void checkStatic(SootMethod method) {
final int opt = Options.v().wrong_staticness();
if ((opt == Options.wrong_staticness_fail || opt == Options.wrong_staticness_fixstrict)
&& method.isStatic() != isStatic() && !method.isPhantom()) {
throw new ResolutionFailedException("Resolved " + this + " to " + method + " which has wrong static-ness");
}
}
protected SootMethod tryResolve(final StringBuilder trace) {
// let's do a dispatch and allow abstract method for resolution
// we do not have a base object for call so we just take the type of the declaring class
SootMethod resolved = Scene.v().getOrMakeFastHierarchy().resolveMethod(declaringClass, declaringClass, name,
parameterTypes, returnType, true, this.getSubSignature());
if (resolved != null) {
checkStatic(resolved);
return resolved;
} else if (Scene.v().allowsPhantomRefs()) {
// Try to resolve in the current class and the interface,
// if not found check for phantom class in the superclass.
for (SootClass selectedClass = declaringClass; selectedClass != null;) {
if (selectedClass.isPhantom()) {
SootMethod phantomMethod
= Scene.v().makeSootMethod(name, parameterTypes, returnType, isStatic() ? Modifier.STATIC : 0);
phantomMethod.setPhantom(true);
phantomMethod = selectedClass.getOrAddMethod(phantomMethod);
checkStatic(phantomMethod);
return phantomMethod;
}
selectedClass = selectedClass.getSuperclassUnsafe();
}
}
// If we don't have a method yet, we try to fix it on the fly
if (Scene.v().allowsPhantomRefs() && Options.v().ignore_resolution_errors()) {
// if we have a phantom class in the hierarchy, we add the method to it.
SootClass classToAddTo = declaringClass;
while (classToAddTo != null && !classToAddTo.isPhantom()) {
classToAddTo = classToAddTo.getSuperclassUnsafe();
}
// We just take the declared class, otherwise.
if (classToAddTo == null) {
classToAddTo = declaringClass;
}
SootMethod method = Scene.v().makeSootMethod(name, parameterTypes, returnType, isStatic() ? Modifier.STATIC : 0);
method.setPhantom(true);
method = classToAddTo.getOrAddMethod(method);
checkStatic(method);
return method;
}
return null;
}
private SootMethod resolve(final StringBuilder trace) {
SootMethod resolved = tryResolve(trace);
if (resolved != null) {
return resolved;
}
// When allowing phantom refs we also allow for references to non-existing
// methods. We simply create the methods on the fly. The method body will
// throw an appropriate error just in case the code *is* actually reached
// at runtime. Furthermore, the declaring class of dynamic invocations is
// not known at compile time, treat as phantom class regardless if phantom
// classes are enabled or not.
if (Options.v().allow_phantom_refs() || SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME.equals(declaringClass.getName())) {
return createUnresolvedErrorMethod(declaringClass);
}
if (trace == null) {
ClassResolutionFailedException e = new ClassResolutionFailedException();
if (Options.v().ignore_resolution_errors()) {
logger.debug(e.getMessage());
} else {
throw e;
}
}
return null;
}
/**
* Creates a method body that throws an "unresolved compilation error" message
*
* @param declaringClass
* The class that was supposed to contain the method
* @return The created SootMethod
*/
private SootMethod createUnresolvedErrorMethod(SootClass declaringClass) {<FILL_FUNCTION_BODY>
|
final Jimple jimp = Jimple.v();
SootMethod m = Scene.v().makeSootMethod(name, parameterTypes, returnType, isStatic() ? Modifier.STATIC : 0);
int modifiers = Modifier.PUBLIC; // we don't know who will be calling us
if (isStatic()) {
modifiers |= Modifier.STATIC;
}
m.setModifiers(modifiers);
JimpleBody body = jimp.newBody(m);
m.setActiveBody(body);
final LocalGenerator lg = Scene.v().createLocalGenerator(body);
// For producing valid Jimple code, we need to access all parameters.
// Otherwise, methods like "getThisLocal()" will fail.
body.insertIdentityStmts(declaringClass);
// exc = new Error
RefType runtimeExceptionType = RefType.v("java.lang.Error");
if (Options.v().src_prec() == Options.src_prec_dotnet) {
runtimeExceptionType = RefType.v(DotnetBasicTypes.SYSTEM_EXCEPTION);
}
Local exceptionLocal = lg.generateLocal(runtimeExceptionType);
AssignStmt assignStmt = jimp.newAssignStmt(exceptionLocal, jimp.newNewExpr(runtimeExceptionType));
body.getUnits().add(assignStmt);
// exc.<init>(message)
SootMethodRef cref = Scene.v().makeConstructorRef(runtimeExceptionType.getSootClass(),
Collections.<Type>singletonList(RefType.v("java.lang.String")));
if (Options.v().src_prec() == Options.src_prec_dotnet) {
cref = Scene.v().makeConstructorRef(runtimeExceptionType.getSootClass(),
Collections.<Type>singletonList(RefType.v(DotnetBasicTypes.SYSTEM_STRING)));
}
SpecialInvokeExpr constructorInvokeExpr = jimp.newSpecialInvokeExpr(exceptionLocal, cref,
StringConstant.v("Unresolved compilation error: Method " + getSignature() + " does not exist!"));
InvokeStmt initStmt = jimp.newInvokeStmt(constructorInvokeExpr);
body.getUnits().insertAfter(initStmt, assignStmt);
// throw exc
body.getUnits().insertAfter(jimp.newThrowStmt(exceptionLocal), initStmt);
return declaringClass.getOrAddMethod(m);
| 1,366
| 623
| 1,989
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/SootModuleResolver.java
|
SootModuleResolver
|
resolveClass
|
class SootModuleResolver extends SootResolver {
public SootModuleResolver(Singletons.Global g) {
super(g);
}
public static SootModuleResolver v() {
return G.v().soot_SootModuleResolver();
}
public SootClass makeClassRef(String className, Optional<String> moduleName) {
// If this class name is escaped, we need to un-escape it
className = Scene.unescapeName(className);
String module = null;
if (moduleName.isPresent()) {
module = ModuleUtil.v().declaringModule(className, moduleName.get());
}
// if no module return first one found
final ModuleScene modScene = ModuleScene.v();
if (modScene.containsClass(className, Optional.fromNullable(module))) {
return modScene.getSootClass(className, Optional.fromNullable(module));
}
SootClass newClass;
if (className.endsWith(SootModuleInfo.MODULE_INFO)) {
newClass = new SootModuleInfo(className, module);
} else {
newClass = modScene.makeSootClass(className, module);
}
newClass.setResolvingLevel(SootClass.DANGLING);
modScene.addClass(newClass);
return newClass;
}
@Override
public SootClass makeClassRef(String className) {
ModuleUtil.ModuleClassNameWrapper wrapper = ModuleUtil.v().makeWrapper(className);
return makeClassRef(wrapper.getClassName(), wrapper.getModuleNameOptional());
}
/**
* Resolves the given class. Depending on the resolver settings, may decide to resolve other classes as well. If the class
* has already been resolved, just returns the class that was already resolved.
*/
public SootClass resolveClass(String className, int desiredLevel, Optional<String> moduleName) {<FILL_FUNCTION_BODY>}
@Override
public SootClass resolveClass(String className, int desiredLevel) {
ModuleUtil.ModuleClassNameWrapper wrapper = ModuleUtil.v().makeWrapper(className);
return resolveClass(wrapper.getClassName(), desiredLevel, wrapper.getModuleNameOptional());
}
}
|
SootClass resolvedClass = null;
try {
resolvedClass = makeClassRef(className, moduleName);
addToResolveWorklist(resolvedClass, desiredLevel);
processResolveWorklist();
return resolvedClass;
} catch (SootClassNotFoundException e) {
// remove unresolved class and rethrow
if (resolvedClass != null) {
assert (resolvedClass.resolvingLevel() == SootClass.DANGLING);
ModuleScene.v().removeClass(resolvedClass);
}
throw e;
}
| 564
| 140
| 704
|
<methods>public void <init>(Singletons.Global) ,public Program getProgram() ,public soot.SootClass makeClassRef(java.lang.String) ,public void reResolve(soot.SootClass, int) ,public void reResolve(soot.SootClass) ,public void reResolveHierarchy(soot.SootClass, int) ,public soot.SootClass resolveClass(java.lang.String, int) ,public static soot.SootResolver v() <variables>protected MultiMap<soot.SootClass,soot.Type> classToTypesHierarchy,protected MultiMap<soot.SootClass,soot.Type> classToTypesSignature,private static final org.slf4j.Logger logger,private Program program,private final Deque<soot.SootClass>[] worklist
|
soot-oss_soot
|
soot/src/main/java/soot/TrapManager.java
|
TrapManager
|
getExceptionTypesOf
|
class TrapManager {
/**
* If exception e is caught at unit u in body b, return true; otherwise, return false.
*/
public static boolean isExceptionCaughtAt(SootClass e, Unit u, Body b) {
// Look through the traps t of b, checking to see if (1) caught exception is
// e and, (2) unit lies between t.beginUnit and t.endUnit.
final Hierarchy h = Scene.v().getActiveHierarchy();
final Chain<Unit> units = b.getUnits();
for (Trap t : b.getTraps()) {
/* Ah ha, we might win. */
if (h.isClassSubclassOfIncluding(e, t.getException())) {
for (Iterator<Unit> it = units.iterator(t.getBeginUnit(), units.getPredOf(t.getEndUnit())); it.hasNext();) {
if (u.equals(it.next())) {
return true;
}
}
}
}
return false;
}
/** Returns the list of traps caught at Unit u in Body b. */
public static List<Trap> getTrapsAt(Unit unit, Body b) {
final Chain<Unit> units = b.getUnits();
List<Trap> trapsList = new ArrayList<Trap>();
for (Trap t : b.getTraps()) {
for (Iterator<Unit> it = units.iterator(t.getBeginUnit(), units.getPredOf(t.getEndUnit())); it.hasNext();) {
if (unit.equals(it.next())) {
trapsList.add(t);
}
}
}
return trapsList;
}
/** Returns a set of units which lie inside the range of any trap. */
public static Set<Unit> getTrappedUnitsOf(Body b) {
final Chain<Unit> units = b.getUnits();
Set<Unit> trapsSet = new HashSet<Unit>();
for (Trap t : b.getTraps()) {
for (Iterator<Unit> it = units.iterator(t.getBeginUnit(), units.getPredOf(t.getEndUnit())); it.hasNext();) {
trapsSet.add(it.next());
}
}
return trapsSet;
}
/**
* Splits all traps so that they do not cross the range rangeStart - rangeEnd. Note that rangeStart is inclusive, rangeEnd
* is exclusive.
*/
public static void splitTrapsAgainst(Body b, Unit rangeStart, Unit rangeEnd) {
final Chain<Trap> traps = b.getTraps();
final Chain<Unit> units = b.getUnits();
for (Iterator<Trap> trapsIt = traps.snapshotIterator(); trapsIt.hasNext();) {
Trap t = trapsIt.next();
boolean insideRange = false;
for (Iterator<Unit> unitIt = units.iterator(t.getBeginUnit(), t.getEndUnit()); unitIt.hasNext();) {
Unit u = unitIt.next();
if (rangeStart.equals(u)) {
insideRange = true;
}
if (!unitIt.hasNext()) { // i.e. u.equals(t.getEndUnit())
if (insideRange) {
Trap newTrap = (Trap) t.clone();
t.setBeginUnit(rangeStart);
newTrap.setEndUnit(rangeStart);
traps.insertAfter(newTrap, t);
} else {
break;
}
}
if (rangeEnd.equals(u)) {
// insideRange had better be true now.
if (!insideRange) {
throw new RuntimeException("inversed range?");
}
Trap firstTrap = (Trap) t.clone();
Trap secondTrap = (Trap) t.clone();
firstTrap.setEndUnit(rangeStart);
secondTrap.setBeginUnit(rangeStart);
secondTrap.setEndUnit(rangeEnd);
t.setBeginUnit(rangeEnd);
traps.insertAfter(firstTrap, t);
traps.insertAfter(secondTrap, t);
}
}
}
}
/**
* Given a body and a unit handling an exception, returns the list of exception types possibly caught by the handler.
*/
public static List<RefType> getExceptionTypesOf(Unit u, Body body) {<FILL_FUNCTION_BODY>}
}
|
final boolean module_mode = ModuleUtil.module_mode();
List<RefType> possibleTypes = new ArrayList<RefType>();
for (Trap trap : body.getTraps()) {
if (trap.getHandlerUnit() == u) {
RefType type;
if (module_mode) {
type = ModuleRefType.v(trap.getException().getName(), Optional.fromNullable(trap.getException().moduleName));
} else {
type = RefType.v(trap.getException().getName());
}
possibleTypes.add(type);
}
}
return possibleTypes;
| 1,155
| 161
| 1,316
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.