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
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/scheduler/netty/process/CollectCyclicDataResponseProcessor.java
CollectCyclicDataResponseProcessor
handle
class CollectCyclicDataResponseProcessor implements NettyRemotingProcessor { @Override public ClusterMsg.Message handle(ChannelHandlerContext ctx, ClusterMsg.Message message) {<FILL_FUNCTION_BODY>} }
CommonDataQueue dataQueue = SpringContextHolder.getBean(CommonDataQueue.class); CollectRep.MetricsData metricsData = (CollectRep.MetricsData) ProtoJsonUtil.toProtobuf(message.getMsg(), CollectRep.MetricsData.newBuilder()); if (metricsData != null) { dataQueue.sendMetricsData(metricsData); } return null;
57
99
156
<no_super_class>
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/scheduler/netty/process/CollectOneTimeDataResponseProcessor.java
CollectOneTimeDataResponseProcessor
handle
class CollectOneTimeDataResponseProcessor implements NettyRemotingProcessor { private final ManageServer manageServer; public CollectOneTimeDataResponseProcessor(ManageServer manageServer) { this.manageServer = manageServer; } @Override public ClusterMsg.Message handle(ChannelHandlerContext ctx, ClusterMsg.Message message) {<FILL_FUNCTION_BODY>} }
TypeReference<List<String>> typeReference = new TypeReference<>() { }; List<String> jsonArr = JsonUtil.fromJson(message.getMsg(), typeReference); if (jsonArr == null) { log.error("netty receive response one time task data parse null error"); return null; } List<CollectRep.MetricsData> metricsDataList = new ArrayList<>(jsonArr.size()); for (String str : jsonArr) { CollectRep.MetricsData metricsData = (CollectRep.MetricsData) ProtoJsonUtil.toProtobuf(str, CollectRep.MetricsData.newBuilder()); if (metricsData != null) { metricsDataList.add(metricsData); } } this.manageServer.getCollectorAndJobScheduler().collectSyncJobResponse(metricsDataList); return null;
100
221
321
<no_super_class>
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/scheduler/netty/process/CollectorOfflineProcessor.java
CollectorOfflineProcessor
handle
class CollectorOfflineProcessor implements NettyRemotingProcessor { private final ManageServer manageServer; public CollectorOfflineProcessor(final ManageServer manageServer) { this.manageServer = manageServer; } @Override public ClusterMsg.Message handle(ChannelHandlerContext ctx, ClusterMsg.Message message) {<FILL_FUNCTION_BODY>} }
String collector = message.getIdentity(); log.info("the collector {} actively requests to go offline.", collector); this.manageServer.getCollectorAndJobScheduler().collectorGoOffline(collector); return null;
99
60
159
<no_super_class>
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/scheduler/netty/process/CollectorOnlineProcessor.java
CollectorOnlineProcessor
handle
class CollectorOnlineProcessor implements NettyRemotingProcessor { private final ManageServer manageServer; public CollectorOnlineProcessor(final ManageServer manageServer) { this.manageServer = manageServer; } @Override public ClusterMsg.Message handle(ChannelHandlerContext ctx, ClusterMsg.Message message) {<FILL_FUNCTION_BODY>} }
String collector = message.getIdentity(); log.info("the collector {} actively requests to go online.", collector); CollectorInfo collectorInfo = JsonUtil.fromJson(message.getMsg(), CollectorInfo.class); this.manageServer.addChannel(collector, ctx.channel()); this.manageServer.getCollectorAndJobScheduler().collectorGoOnline(collector, collectorInfo); return null;
96
105
201
<no_super_class>
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/scheduler/netty/process/HeartbeatProcessor.java
HeartbeatProcessor
handle
class HeartbeatProcessor implements NettyRemotingProcessor { private final ManageServer manageServer; public HeartbeatProcessor(final ManageServer manageServer) { this.manageServer = manageServer; } @Override public ClusterMsg.Message handle(ChannelHandlerContext ctx, ClusterMsg.Message message) {<FILL_FUNCTION_BODY>} }
String identity = message.getIdentity(); boolean isChannelExist = this.manageServer.isChannelExist(identity); if (!isChannelExist) { log.info("the collector {} is not online.", identity); } if (log.isDebugEnabled()) { log.debug("server receive collector {} heartbeat", message.getIdentity()); } return ClusterMsg.Message.newBuilder() .setType(ClusterMsg.MessageType.HEARTBEAT) .build();
95
128
223
<no_super_class>
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/service/AvailableAlertDefineInit.java
AvailableAlertDefineInit
run
class AvailableAlertDefineInit implements CommandLineRunner { @Autowired private AlertDefineDao alertDefineDao; @Autowired private AppService appService; @Override public void run(String... args) throws Exception {<FILL_FUNCTION_BODY>} }
Set<String> apps = appService.getAllAppDefines().keySet(); for (String app : apps) { try { List<AlertDefine> defines = alertDefineDao.queryAlertDefineByAppAndMetric(app, CommonConstants.AVAILABILITY); if (defines.isEmpty()) { AlertDefine alertDefine = AlertDefine.builder() .app(app) .metric(CommonConstants.AVAILABILITY) .preset(true) .times(2) .enable(true) .recoverNotice(false) .priority(CommonConstants.ALERT_PRIORITY_CODE_EMERGENCY) .template("${app} monitoring availability alert, code is ${code}") .build(); alertDefineDao.save(alertDefine); } } catch (Exception e) { log.error(e.getMessage(), e); } }
82
249
331
<no_super_class>
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/AbstractGeneralConfigServiceImpl.java
AbstractGeneralConfigServiceImpl
saveConfig
class AbstractGeneralConfigServiceImpl<T> implements GeneralConfigService<T> { protected final GeneralConfigDao generalConfigDao; protected final ObjectMapper objectMapper; /** * 构造方法,传入GeneralConfigDao、ObjectMapper和type。 * <p>Constructor, passing in GeneralConfigDao, ObjectMapper and type.</p> * @param generalConfigDao 配置Dao对象 * @param objectMapper JSON工具类对象 */ protected AbstractGeneralConfigServiceImpl(GeneralConfigDao generalConfigDao, ObjectMapper objectMapper) { this.generalConfigDao = generalConfigDao; this.objectMapper = objectMapper; } /** * 保存配置。 * <p>Save a configuration.</p> * @param config 需要保存的配置对象 */ @Transactional(rollbackFor = Exception.class) @Override public void saveConfig(T config) {<FILL_FUNCTION_BODY>} /** * 获取配置。 * <p>Get a configuration.</p> * @return 查询到的配置对象 */ @Override public T getConfig() { GeneralConfig generalConfig = generalConfigDao.findByType(type()); if (generalConfig == null) { return null; } try { return objectMapper.readValue(generalConfig.getContent(), getTypeReference()); } catch (JsonProcessingException e) { throw new IllegalArgumentException("Get configuration failed: " + e.getMessage()); } } /** * 获取配置类型的TypeReference对象。 * <p>Get TypeReference object of configuration type.</p> * @return 配置类型的TypeReference对象 */ protected abstract TypeReference<T> getTypeReference(); }
try { String contentJson = objectMapper.writeValueAsString(config); GeneralConfig generalConfig2Save = GeneralConfig.builder() .type(type()) .content(contentJson) .build(); generalConfigDao.save(generalConfig2Save); log.info("配置保存成功|Configuration saved successfully"); handler(getConfig()); } catch (JsonProcessingException e) { throw new IllegalArgumentException("Configuration saved failed: " + e.getMessage()); }
461
126
587
<no_super_class>
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/AbstractImExportServiceImpl.java
AbstractImExportServiceImpl
convert
class AbstractImExportServiceImpl implements ImExportService { @Resource @Lazy private MonitorService monitorService; @Resource private TagService tagService; @Override public void importConfig(InputStream is) { var formList = parseImport(is) .stream() .map(this::convert) .collect(Collectors.toUnmodifiableList()); if (!CollectionUtils.isEmpty(formList)) { formList.forEach(monitorDto -> { monitorService.validate(monitorDto, false); if (monitorDto.isDetected()) { monitorService.detectMonitor(monitorDto.getMonitor(), monitorDto.getParams(), monitorDto.getCollector()); } monitorService.addMonitor(monitorDto.getMonitor(), monitorDto.getParams(), monitorDto.getCollector()); }); } } @Override public void exportConfig(OutputStream os, List<Long> configList) { var monitorList = configList.stream() .map(it -> monitorService.getMonitorDto(it)) .filter(Objects::nonNull) .map(this::convert) .collect(Collectors.toUnmodifiableList()); writeOs(monitorList, os); } /** * Parsing an input stream into a form * 将输入流解析为表单 * * @param is 输入流 * @return 表单 */ abstract List<ExportMonitorDTO> parseImport(InputStream is); /** * Export Configuration to Output Stream * 导出配置到输出流 * * @param monitorList 配置列表 * @param os 输出流 */ abstract void writeOs(List<ExportMonitorDTO> monitorList, OutputStream os); private ExportMonitorDTO convert(MonitorDto dto) { var exportMonitor = new ExportMonitorDTO(); var monitor = new MonitorDTO(); BeanUtils.copyProperties(dto.getMonitor(), monitor); if (!CollectionUtils.isEmpty(dto.getMonitor().getTags())) { monitor.setTags(dto.getMonitor().getTags().stream() .map(Tag::getId).collect(Collectors.toUnmodifiableList())); } exportMonitor.setMonitor(monitor); exportMonitor.setParams(dto.getParams().stream() .map(it -> { var param = new ParamDTO(); BeanUtils.copyProperties(it, param); return param; }) .collect(Collectors.toUnmodifiableList())); exportMonitor.setMetrics(dto.getMetrics()); exportMonitor.setDetected(false); exportMonitor.getMonitor().setCollector(dto.getCollector()); return exportMonitor; } private MonitorDto convert(ExportMonitorDTO exportMonitor) {<FILL_FUNCTION_BODY>} protected String fileNamePrefix() { return "hertzbeat_monitor_" + LocalDate.now(); } @Data @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @ExcelTarget(value = "ExportMonitorDTO") protected static class ExportMonitorDTO { @ExcelEntity(name = "Monitor") private MonitorDTO monitor; @ExcelCollection(name = "Params") private List<ParamDTO> params; @ExcelCollection(name = "Metrics") private List<String> metrics; @ExcelCollection(name = "detected") private Boolean detected; } @Data @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @ExcelTarget(value = "MonitorDTO") protected static class MonitorDTO { @Excel(name = "Name") private String name; @Excel(name = "App") private String app; @Excel(name = "Host") private String host; @Excel(name = "Intervals") private Integer intervals; @Excel(name = "Status") private Byte status; @Excel(name = "Description") private String description; @Excel(name = "Tags") private List<Long> tags; @Excel(name = "Collector") private String collector; } @Data @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @ExcelTarget(value = "ParamDTO") protected static class ParamDTO { @Excel(name = "Field") private String field; @Excel(name = "Type") private Byte type; @Excel(name = "Value") private String value; } }
if (exportMonitor == null || exportMonitor.monitor == null) { throw new IllegalArgumentException("exportMonitor and exportMonitor.monitor must not be null"); } var monitorDto = new MonitorDto(); monitorDto.setDetected(exportMonitor.getDetected()); var monitor = new Monitor(); log.debug("exportMonitor.monitor{}", exportMonitor.monitor); if (exportMonitor.monitor != null) { //多增加一个null检测 BeanUtils.copyProperties(exportMonitor.monitor, monitor); if (exportMonitor.monitor.tags != null) { monitor.setTags(tagService.listTag(new HashSet<>(exportMonitor.monitor.tags)) .stream() .filter(tag -> !(tag.getName().equals(CommonConstants.TAG_MONITOR_ID) || tag.getName().equals(CommonConstants.TAG_MONITOR_NAME))) .collect(Collectors.toList())); } else { monitor.setTags(Collections.emptyList()); } } monitorDto.setMonitor(monitor); if (exportMonitor.getMonitor() != null) { monitorDto.setCollector(exportMonitor.getMonitor().getCollector()); } monitorDto.setMetrics(exportMonitor.metrics); if (exportMonitor.params != null) { monitorDto.setParams(exportMonitor.params.stream() .map(it -> { var param = new Param(); BeanUtils.copyProperties(it, param); return param; }) .collect(Collectors.toUnmodifiableList())); } else { monitorDto.setParams(Collections.emptyList()); } return monitorDto;
1,240
431
1,671
<no_super_class>
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/CollectorServiceImpl.java
CollectorServiceImpl
deleteRegisteredCollector
class CollectorServiceImpl implements CollectorService { @Autowired private CollectorDao collectorDao; @Autowired private CollectorMonitorBindDao collectorMonitorBindDao; @Autowired private ConsistentHash consistentHash; @Autowired(required = false) private ManageServer manageServer; @Override @Transactional(readOnly = true) public Page<CollectorSummary> getCollectors(Specification<Collector> specification, PageRequest pageRequest) { Page<Collector> collectors = collectorDao.findAll(specification, pageRequest); List<CollectorSummary> collectorSummaryList = new LinkedList<>(); for (Collector collector : collectors.getContent()) { CollectorSummary.CollectorSummaryBuilder summaryBuilder = CollectorSummary.builder().collector(collector); ConsistentHash.Node node = consistentHash.getNode(collector.getName()); if (node != null && node.getAssignJobs() != null) { AssignJobs assignJobs = node.getAssignJobs(); summaryBuilder.pinMonitorNum(assignJobs.getPinnedJobs().size()); summaryBuilder.dispatchMonitorNum(assignJobs.getJobs().size()); } collectorSummaryList.add(summaryBuilder.build()); } return new PageImpl<>(collectorSummaryList, pageRequest, collectors.getTotalElements()); } @Override @Transactional(rollbackFor = Exception.class) public void deleteRegisteredCollector(List<String> collectors) {<FILL_FUNCTION_BODY>} @Override public boolean hasCollector(String collector) { return this.collectorDao.findCollectorByName(collector).isPresent(); } }
if (collectors == null || collectors.isEmpty()) { return; } // Determine whether there are fixed tasks on the collector collectors.forEach(collector -> { List<CollectorMonitorBind> binds = this.collectorMonitorBindDao.findCollectorMonitorBindsByCollector(collector); if (!binds.isEmpty()) { throw new CommonException("The collector " + collector + " has pinned tasks that cannot be deleted."); } }); collectors.forEach(collector -> { this.manageServer.closeChannel(collector); this.collectorDao.deleteCollectorByName(collector); });
454
170
624
<no_super_class>
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/JsonImExportServiceImpl.java
JsonImExportServiceImpl
parseImport
class JsonImExportServiceImpl extends AbstractImExportServiceImpl { public static final String TYPE = "JSON"; public static final String FILE_SUFFIX = ".json"; private final ObjectMapper objectMapper; @Override List<ExportMonitorDTO> parseImport(InputStream is) {<FILL_FUNCTION_BODY>} @Override void writeOs(List<ExportMonitorDTO> monitorList, OutputStream os) { try { objectMapper.writeValue(os, monitorList); } catch (IOException ex) { log.error("export monitor failed.", ex); throw new RuntimeException("export monitor failed"); } } @Override public String type() { return TYPE; } @Override public String getFileName() { return fileNamePrefix() + FILE_SUFFIX; } }
try { return objectMapper.readValue(is, new TypeReference<>() { }); } catch (IOException ex) { log.error("import monitor failed.", ex); throw new RuntimeException("import monitor failed"); }
217
62
279
<methods>public void exportConfig(java.io.OutputStream, List<java.lang.Long>) ,public void importConfig(java.io.InputStream) <variables>private org.apache.hertzbeat.manager.service.MonitorService monitorService,private org.apache.hertzbeat.manager.service.TagService tagService
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/MailGeneralConfigServiceImpl.java
MailGeneralConfigServiceImpl
getTypeReference
class MailGeneralConfigServiceImpl extends AbstractGeneralConfigServiceImpl<EmailNoticeSender> { /** * MailGeneralConfigServiceImpl的构造函数,通过默认构造函数或者反序列化构造(setBeanProps)来创建该类实例。 * 参数generalConfigDao用于操作数据的dao层,参数objectMapper用于进行对象映射。 * MailGeneralConfigServiceImpl's constructor creates an instance of this class * through the default constructor or deserialization construction (setBeanProps). * The parameter generalConfigDao is used for dao layer operation data, * and objectMapper is used for object mapping. * @param generalConfigDao 数据操作的dao层,供创建该类实例所需 * dao layer operation data, needed to create an instance of this class * @param objectMapper 对象映射,供创建该类实例所需 * object mapping , needed to create an instance of this class */ public MailGeneralConfigServiceImpl(GeneralConfigDao generalConfigDao, ObjectMapper objectMapper) { super(generalConfigDao, objectMapper); } @Override public String type() { return "email"; } /** * 该方法用于获取NoticeSender类型的TypeReference,以供后续处理。 * This method is used to get the TypeReference of NoticeSender type for subsequent processing. * @return NoticeSender类型的TypeReference * a TypeReference of NoticeSender type */ @Override protected TypeReference<EmailNoticeSender> getTypeReference() {<FILL_FUNCTION_BODY>} }
return new TypeReference<>() { @Override public Type getType() { return EmailNoticeSender.class; } };
407
40
447
<methods>public org.apache.hertzbeat.manager.pojo.dto.EmailNoticeSender getConfig() ,public void saveConfig(org.apache.hertzbeat.manager.pojo.dto.EmailNoticeSender) <variables>protected final non-sealed org.apache.hertzbeat.manager.dao.GeneralConfigDao generalConfigDao,protected final non-sealed ObjectMapper objectMapper
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/MailServiceImpl.java
MailServiceImpl
buildAlertHtmlTemplate
class MailServiceImpl implements MailService { @Resource private AlerterProperties alerterProperties; @Resource protected NoticeConfigService noticeConfigService; private ResourceBundle bundle = ResourceBundleUtil.getBundle("alerter"); private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public String buildAlertHtmlTemplate(final Alert alert, NoticeTemplate noticeTemplate) throws IOException, TemplateException {<FILL_FUNCTION_BODY>} @EventListener(SystemConfigChangeEvent.class) public void onEvent(SystemConfigChangeEvent event) { log.info("{} receive system config change event: {}.", this.getClass().getName(), event.getSource()); this.bundle = ResourceBundleUtil.getBundle("alerter"); } }
freemarker.template.Template templateMail = null; Configuration cfg = new Configuration(Configuration.VERSION_2_3_0); String monitorId = null; String monitorName = null; String monitorHost = null; if (alert.getTags() != null) { monitorId = alert.getTags().get(CommonConstants.TAG_MONITOR_ID); monitorName = alert.getTags().get(CommonConstants.TAG_MONITOR_NAME); monitorHost = alert.getTags().get(CommonConstants.TAG_MONITOR_HOST); } monitorId = monitorId == null ? "External Alarm, No ID" : monitorId; monitorName = monitorName == null ? "External Alarm, No Name" : monitorName; monitorHost = monitorHost == null ? "External Alarm, No Host" : monitorHost; // Introduce context parameters to render pages Map<String, String> model = new HashMap<>(16); model.put("nameTitle", bundle.getString("alerter.notify.title")); model.put("nameMonitorId", bundle.getString("alerter.notify.monitorId")); model.put("nameMonitorName", bundle.getString("alerter.notify.monitorName")); model.put("nameMonitorHost", bundle.getString("alerter.notify.monitorHost")); model.put("target", alert.getTarget()); model.put("monitorId", monitorId); model.put("monitorName", monitorName); model.put("monitorHost", monitorHost); model.put("nameTarget", bundle.getString("alerter.notify.target")); model.put("nameConsole", bundle.getString("alerter.notify.console")); model.put("namePriority", bundle.getString("alerter.notify.priority")); model.put("priority", bundle.getString("alerter.priority." + alert.getPriority())); model.put("nameTriggerTime", bundle.getString("alerter.notify.triggerTime")); model.put("lastTriggerTime", simpleDateFormat.format(new Date(alert.getLastAlarmTime()))); if (CommonConstants.ALERT_STATUS_CODE_RESTORED == alert.getStatus()) { model.put("nameRestoreTime", bundle.getString("alerter.notify.restoreTime")); model.put("restoreTime", simpleDateFormat.format(new Date(alert.getFirstAlarmTime()))); } model.put("consoleUrl", alerterProperties.getConsoleUrl()); model.put("nameContent", bundle.getString("alerter.notify.content")); model.put("content", alert.getContent()); if (noticeTemplate == null) { noticeTemplate = noticeConfigService.getDefaultNoticeTemplateByType((byte) 1); } if (noticeTemplate == null) { throw new NullPointerException("email does not have mapping default notice template"); } StringTemplateLoader stringLoader = new StringTemplateLoader(); String templateName = "mailTemplate"; stringLoader.putTemplate(templateName, noticeTemplate.getContent()); cfg.setTemplateLoader(stringLoader); templateMail = cfg.getTemplate(templateName, Locale.CHINESE); return FreeMarkerTemplateUtils.processTemplateIntoString(templateMail, model);
208
816
1,024
<no_super_class>
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/ObjectStoreConfigServiceImpl.java
ObjectStoreConfigServiceImpl
handler
class ObjectStoreConfigServiceImpl extends AbstractGeneralConfigServiceImpl<ObjectStoreDTO<T>> implements InitializingBean { @Resource private DefaultListableBeanFactory beanFactory; @Resource private ApplicationContext ctx; private static final String BEAN_NAME = "ObjectStoreService"; /** * 构造方法,传入GeneralConfigDao、ObjectMapper和type。 * * <p>Constructor, passing in GeneralConfigDao, ObjectMapper and type.</p> * * @param generalConfigDao 配置Dao对象 * @param objectMapper JSON工具类对象 */ protected ObjectStoreConfigServiceImpl(GeneralConfigDao generalConfigDao, ObjectMapper objectMapper) { super(generalConfigDao, objectMapper); } @Override public String type() { return "oss"; } @Override protected TypeReference<ObjectStoreDTO<T>> getTypeReference() { return new TypeReference<>() { @Override public Type getType() { return ObjectStoreDTO.class; } }; } @Override public void handler(ObjectStoreDTO<T> config) {<FILL_FUNCTION_BODY>} /** * 初始化华为云OBS */ private void initObs(ObjectStoreDTO<T> config) { var obsConfig = objectMapper.convertValue(config.getConfig(), ObjectStoreDTO.ObsConfig.class); Assert.hasText(obsConfig.getAccessKey(), "cannot find obs accessKey"); Assert.hasText(obsConfig.getSecretKey(), "cannot find obs secretKey"); Assert.hasText(obsConfig.getEndpoint(), "cannot find obs endpoint"); Assert.hasText(obsConfig.getBucketName(), "cannot find obs bucket name"); var obsClient = new ObsClient(obsConfig.getAccessKey(), obsConfig.getSecretKey(), obsConfig.getEndpoint()); beanFactory.destroySingleton(BEAN_NAME); beanFactory.registerSingleton(BEAN_NAME, new ObsObjectStoreServiceImpl(obsClient, obsConfig.getBucketName(), obsConfig.getSavePath())); log.info("obs store service init success."); } @Override public void afterPropertiesSet() throws Exception { // 初始化文件存储 handler(getConfig()); } }
// 初始化文件存储服务 if (config != null) { switch (config.getType()) { case OBS: initObs(config); break; // case other object store service default: } ctx.publishEvent(new ObjectStoreConfigChangeEvent(config)); }
595
86
681
<methods>public ObjectStoreDTO<T> getConfig() ,public void saveConfig(ObjectStoreDTO<T>) <variables>protected final non-sealed org.apache.hertzbeat.manager.dao.GeneralConfigDao generalConfigDao,protected final non-sealed ObjectMapper objectMapper
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/ObsObjectStoreServiceImpl.java
ObsObjectStoreServiceImpl
download
class ObsObjectStoreServiceImpl implements ObjectStoreService { private final ObsClient obsClient; private final String bucketName; private final String rootPath; public ObsObjectStoreServiceImpl(ObsClient obsClient, String bucketName, String rootPath) { this.obsClient = obsClient; this.bucketName = bucketName; if (rootPath.startsWith(SignConstants.RIGHT_DASH)) { this.rootPath = rootPath.substring(1); } else { this.rootPath = rootPath; } } @Override public boolean upload(String filePath, InputStream is) { var objectKey = getObjectKey(filePath); var response = obsClient.putObject(bucketName, objectKey, is); return Objects.equals(response.getStatusCode(), 200); } @Override public FileDTO download(String filePath) {<FILL_FUNCTION_BODY>} @Override public List<FileDTO> list(String dir) { var request = new ListObjectsRequest(bucketName); request.setPrefix(getObjectKey(dir)); return obsClient.listObjects(request).getObjects() .stream() .map(it -> new FileDTO(it.getObjectKey(), it.getObjectContent())) .collect(Collectors.toUnmodifiableList()); } @Override public ObjectStoreDTO.Type type() { return ObjectStoreDTO.Type.OBS; } private String getObjectKey(String filePath) { return rootPath + SignConstants.RIGHT_DASH + filePath; } }
var objectKey = getObjectKey(filePath); try { var obsObject = obsClient.getObject(bucketName, objectKey); return new FileDTO(filePath, obsObject.getObjectContent()); } catch (Exception ex) { log.warn("download file from obs error {}", objectKey); return null; }
426
90
516
<no_super_class>
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/SystemGeneralConfigServiceImpl.java
SystemGeneralConfigServiceImpl
getTypeReference
class SystemGeneralConfigServiceImpl extends AbstractGeneralConfigServiceImpl<SystemConfig> { private static final Integer LANG_REGION_LENGTH = 2; @Resource private ApplicationContext applicationContext; /** * 构造方法,传入GeneralConfigDao、ObjectMapper和type。 * * <p>Constructor, passing in GeneralConfigDao, ObjectMapper and type.</p> * * @param generalConfigDao 配置Dao对象 * @param objectMapper JSON工具类对象 */ protected SystemGeneralConfigServiceImpl(GeneralConfigDao generalConfigDao, ObjectMapper objectMapper) { super(generalConfigDao, objectMapper); } @Override public void handler(SystemConfig systemConfig) { if (systemConfig != null) { if (systemConfig.getTimeZoneId() != null) { TimeZone.setDefault(TimeZone.getTimeZone(systemConfig.getTimeZoneId())); } if (systemConfig.getLocale() != null) { String[] arr = systemConfig.getLocale().split(CommonConstants.LOCALE_SEPARATOR); if (arr.length == LANG_REGION_LENGTH) { String language = arr[0]; String country = arr[1]; Locale.setDefault(new Locale(language, country)); } } applicationContext.publishEvent(new SystemConfigChangeEvent(applicationContext)); } } @Override public String type() { return "system"; } @Override protected TypeReference<SystemConfig> getTypeReference() {<FILL_FUNCTION_BODY>} }
return new TypeReference<>() { @Override public Type getType() { return SystemConfig.class; } };
426
38
464
<methods>public org.apache.hertzbeat.manager.pojo.dto.SystemConfig getConfig() ,public void saveConfig(org.apache.hertzbeat.manager.pojo.dto.SystemConfig) <variables>protected final non-sealed org.apache.hertzbeat.manager.dao.GeneralConfigDao generalConfigDao,protected final non-sealed ObjectMapper objectMapper
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/TagServiceImpl.java
TagServiceImpl
deleteMonitorSystemTags
class TagServiceImpl implements TagService { @Autowired private TagDao tagDao; @Override public void addTags(List<Tag> tags) { tagDao.saveAll(tags); } @Override public void modifyTag(Tag tag) { Optional<Tag> tagOptional = tagDao.findById(tag.getId()); if (tagOptional.isPresent()) { tagDao.save(tag); } else { throw new IllegalArgumentException("The tag is not existed"); } } @Override public Page<Tag> getTags(Specification<Tag> specification, PageRequest pageRequest) { return tagDao.findAll(specification, pageRequest); } @Override public void deleteTags(HashSet<Long> ids) { tagDao.deleteTagsByIdIn(ids); } @Override public List<Tag> listTag(Set<Long> ids) { return tagDao.findByIdIn(ids); } @Override public void deleteMonitorSystemTags(Monitor monitor) {<FILL_FUNCTION_BODY>} }
if (CollectionUtils.isNotEmpty(monitor.getTags())) { List<Tag> tags = monitor.getTags().stream().filter(tag -> tag.getType() == (byte) 0).collect(Collectors.toList()); tagDao.deleteAll(tags); }
296
74
370
<no_super_class>
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/TemplateConfigServiceImpl.java
TemplateConfigServiceImpl
getTypeReference
class TemplateConfigServiceImpl extends AbstractGeneralConfigServiceImpl<TemplateConfig> { @Resource private AppService appService; /** * 构造方法,传入GeneralConfigDao、ObjectMapper和type。 * * <p>Constructor, passing in GeneralConfigDao, ObjectMapper and type.</p> * * @param generalConfigDao 配置Dao对象 * @param objectMapper JSON工具类对象 */ protected TemplateConfigServiceImpl(GeneralConfigDao generalConfigDao, ObjectMapper objectMapper) { super(generalConfigDao, objectMapper); } @Override public void handler(TemplateConfig templateConfig) { if (templateConfig != null) { appService.updateCustomTemplateConfig(templateConfig); } } @Override public String type() { return "template"; } @Override protected TypeReference<TemplateConfig> getTypeReference() {<FILL_FUNCTION_BODY>} }
return new TypeReference<>() { @Override public Type getType() { return TemplateConfig.class; } };
261
38
299
<methods>public org.apache.hertzbeat.manager.pojo.dto.TemplateConfig getConfig() ,public void saveConfig(org.apache.hertzbeat.manager.pojo.dto.TemplateConfig) <variables>protected final non-sealed org.apache.hertzbeat.manager.dao.GeneralConfigDao generalConfigDao,protected final non-sealed ObjectMapper objectMapper
apache_hertzbeat
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/YamlImExportServiceImpl.java
YamlImExportServiceImpl
parseImport
class YamlImExportServiceImpl extends AbstractImExportServiceImpl{ public static final String TYPE = "YAML"; public static final String FILE_SUFFIX = ".yaml"; /** * Export file type * 导出文件类型 * @return 文件类型 */ @Override public String type() { return TYPE; } /** * Get Export File Name * 获取导出文件名 * @return 文件名 */ @Override public String getFileName() { return fileNamePrefix() + FILE_SUFFIX; } /** * Parsing an input stream into a form * 将输入流解析为表单 * @param is 输入流 * @return 表单 */ @Override List<ExportMonitorDTO> parseImport(InputStream is) {<FILL_FUNCTION_BODY>} /** * Export Configuration to Output Stream * 导出配置到输出流 * @param monitorList 配置列表 * @param os 输出流 */ @Override void writeOs(List<ExportMonitorDTO> monitorList, OutputStream os) { DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); options.setIndent(2); options.setPrettyFlow(true); Yaml yaml = new Yaml(options); yaml.dump(monitorList, new OutputStreamWriter(os, StandardCharsets.UTF_8)); } }
// todo now disable this, will enable it in the future. // upgrade to snakeyaml 2.2 and springboot3.x to fix the issue Yaml yaml = new Yaml(); return yaml.load(is);
402
62
464
<methods>public void exportConfig(java.io.OutputStream, List<java.lang.Long>) ,public void importConfig(java.io.InputStream) <variables>private org.apache.hertzbeat.manager.service.MonitorService monitorService,private org.apache.hertzbeat.manager.service.TagService tagService
apache_hertzbeat
hertzbeat/push/src/main/java/org/apache/hertzbeat/push/controller/PushGatewayController.java
PushGatewayController
pushMetrics
class PushGatewayController { @Autowired private PushGatewayService pushGatewayService; @PostMapping() @Operation(summary = "Push metric data to hertzbeat pushgateway", description = "Push metric data to hertzbeat pushgateway") public ResponseEntity<Message<Void>> pushMetrics(HttpServletRequest request) throws IOException {<FILL_FUNCTION_BODY>} }
InputStream inputStream = request.getInputStream(); boolean result = pushGatewayService.pushMetricsData(inputStream); if (result) { return ResponseEntity.ok(Message.success("Push success")); } else { return ResponseEntity.ok(Message.success("Push failed")); }
110
82
192
<no_super_class>
apache_hertzbeat
hertzbeat/push/src/main/java/org/apache/hertzbeat/push/service/impl/PushServiceImpl.java
PushServiceImpl
getPushMetricData
class PushServiceImpl implements PushService { @Autowired private PushMonitorDao monitorDao; @Autowired private PushMetricsDao metricsDao; private final Map<Long, Long> monitorIdCache; // key: monitorId, value: time stamp of last query private static final long cacheTimeout = 5000; // ms private final Map<Long, PushMetricsDto.Metrics> lastPushMetrics; private static final long deleteMetricsPeriod = 1000 * 60 * 60 * 12; private static final long deleteBeforeTime = deleteMetricsPeriod / 2; PushServiceImpl(){ monitorIdCache = new HashMap<>(); lastPushMetrics = new HashMap<>(); new Timer().schedule(new TimerTask() { @Override public void run() { try{ deletePeriodically(); }catch (Exception e) { log.error("periodical deletion failed. {}", e.getMessage()); } } }, 1000, deleteMetricsPeriod); } public void deletePeriodically(){ metricsDao.deleteAllByTimeBefore(System.currentTimeMillis() - deleteBeforeTime); } @Override public void pushMetricsData(PushMetricsDto pushMetricsDto) throws RuntimeException { List<PushMetrics> pushMetricsList = new ArrayList<>(); long curTime = System.currentTimeMillis(); for (PushMetricsDto.Metrics metrics : pushMetricsDto.getMetricsList()) { long monitorId = metrics.getMonitorId(); metrics.setTime(curTime); if (!monitorIdCache.containsKey(monitorId) || (monitorIdCache.containsKey(monitorId) && curTime > monitorIdCache.get(monitorId) + cacheTimeout)) { Optional<Monitor> queryOption = monitorDao.findById(monitorId); if (queryOption.isEmpty()) { monitorIdCache.remove(monitorId); continue; } monitorIdCache.put(monitorId, curTime); } PushMetrics pushMetrics = PushMetrics.builder() .monitorId(metrics.getMonitorId()) .time(curTime) .metrics(JsonUtil.toJson(metrics.getMetrics())).build(); lastPushMetrics.put(monitorId, metrics); pushMetricsList.add(pushMetrics); } metricsDao.saveAll(pushMetricsList); } @Override public PushMetricsDto getPushMetricData(final Long monitorId, final Long time) {<FILL_FUNCTION_BODY>} }
PushMetricsDto.Metrics metrics; PushMetricsDto pushMetricsDto = new PushMetricsDto(); if (lastPushMetrics.containsKey(monitorId)) { metrics = lastPushMetrics.get(monitorId); } else { try { PushMetrics pushMetrics = metricsDao.findFirstByMonitorIdOrderByTimeDesc(monitorId); if (pushMetrics == null || pushMetrics.getMetrics() == null) { return pushMetricsDto; } List<Map<String, String>> jsonMap = JsonUtil.fromJson(pushMetrics.getMetrics(), new TypeReference<List<Map<String, String>>>() { }); metrics = PushMetricsDto.Metrics.builder().monitorId(monitorId).metrics(jsonMap).time(pushMetrics.getTime()).build(); lastPushMetrics.put(monitorId, metrics); } catch (Exception e) { log.error("no metrics found, monitor id: {}, {}, {}", monitorId, e.getMessage(), e); return pushMetricsDto; } } if (time > metrics.getTime()) { // return void because time param is invalid return pushMetricsDto; } pushMetricsDto.getMetricsList().add(metrics); return pushMetricsDto;
673
329
1,002
<no_super_class>
apache_hertzbeat
hertzbeat/remoting/src/main/java/org/apache/hertzbeat/remoting/netty/NettyRemotingAbstract.java
NettyRemotingAbstract
channelIdle
class NettyRemotingAbstract implements RemotingService { protected ConcurrentHashMap<ClusterMsg.MessageType, NettyRemotingProcessor> processorTable = new ConcurrentHashMap<>(); protected ConcurrentHashMap<String, ResponseFuture> responseTable = new ConcurrentHashMap<>(); protected List<NettyHook> nettyHookList = new ArrayList<>(); protected NettyEventListener nettyEventListener; protected NettyRemotingAbstract(NettyEventListener nettyEventListener) { this.nettyEventListener = nettyEventListener; } public void registerProcessor(final ClusterMsg.MessageType messageType, final NettyRemotingProcessor processor) { this.processorTable.put(messageType, processor); } protected void processReceiveMsg(ChannelHandlerContext ctx, ClusterMsg.Message message) { if (ClusterMsg.Direction.REQUEST.equals(message.getDirection())) { this.processRequestMsg(ctx, message); } else { this.processResponseMsg(message); } } protected void processRequestMsg(ChannelHandlerContext ctx, ClusterMsg.Message request) { this.doBeforeRequest(ctx, request); NettyRemotingProcessor processor = this.processorTable.get(request.getType()); if (processor == null) { log.info("request type {} not supported", request.getType()); return; } ClusterMsg.Message response = processor.handle(ctx, request); if (response != null) { ctx.writeAndFlush(response); } } private void doBeforeRequest(ChannelHandlerContext ctx, ClusterMsg.Message request) { if (this.nettyHookList == null || this.nettyHookList.isEmpty()) { return; } for (NettyHook nettyHook : this.nettyHookList) { nettyHook.doBeforeRequest(ctx, request); } } protected void processResponseMsg(ClusterMsg.Message response) { if (this.responseTable.containsKey(response.getIdentity())) { ResponseFuture responseFuture = this.responseTable.get(response.getIdentity()); responseFuture.putResponse(response); } else { log.warn("receive response not in responseTable, identity: {}", response.getIdentity()); } } protected void sendMsgImpl(final Channel channel, final ClusterMsg.Message request) { channel.writeAndFlush(request).addListener(future -> { if (!future.isSuccess()) { log.warn("send request message failed. address: {}, ", channel.remoteAddress(), future.cause()); } }); } protected ClusterMsg.Message sendMsgSyncImpl(final Channel channel, final ClusterMsg.Message request, final int timeoutMillis) { final String identity = request.getIdentity(); try { ResponseFuture responseFuture = new ResponseFuture(); this.responseTable.put(identity, responseFuture); channel.writeAndFlush(request).addListener(future -> { if (!future.isSuccess()) { responseTable.remove(identity); log.warn("send request message failed. request: {}, address: {}, ", request, channel.remoteAddress(), future.cause()); } }); ClusterMsg.Message response = responseFuture.waitResponse(timeoutMillis); if (response == null) { log.warn("get response message failed, message is null"); } return response; } catch (InterruptedException e) { log.warn("get response message failed, ", e); } finally { responseTable.remove(identity); } return null; } protected void channelActive(ChannelHandlerContext ctx) throws Exception { if (this.nettyEventListener != null && ctx.channel().isActive()) { this.nettyEventListener.onChannelActive(ctx.channel()); } } protected void channelIdle(ChannelHandlerContext ctx, Object evt) throws Exception {<FILL_FUNCTION_BODY>} protected boolean useEpoll() { return NetworkUtil.isLinuxPlatform() && Epoll.isAvailable(); } }
IdleStateEvent event = (IdleStateEvent) evt; if (this.nettyEventListener != null && event.state() == IdleState.ALL_IDLE) { ctx.channel().closeFuture(); this.nettyEventListener.onChannelIdle(ctx.channel()); }
1,026
77
1,103
<no_super_class>
apache_hertzbeat
hertzbeat/remoting/src/main/java/org/apache/hertzbeat/remoting/netty/NettyRemotingClient.java
NettyRemotingClient
start
class NettyRemotingClient extends NettyRemotingAbstract implements RemotingClient { private final NettyClientConfig nettyClientConfig; private final CommonThreadPool threadPool; private final Bootstrap bootstrap = new Bootstrap(); private EventLoopGroup workerGroup; private Channel channel; public NettyRemotingClient(final NettyClientConfig nettyClientConfig, final NettyEventListener nettyEventListener, final CommonThreadPool threadPool) { super(nettyEventListener); this.nettyClientConfig = nettyClientConfig; this.threadPool = threadPool; } @Override public void start() {<FILL_FUNCTION_BODY>} private void initChannel(final SocketChannel channel) { ChannelPipeline pipeline = channel.pipeline(); // zip pipeline.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP)); pipeline.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP)); // protocol buf encode decode pipeline.addLast(new ProtobufVarint32FrameDecoder()); pipeline.addLast(new ProtobufDecoder(ClusterMsg.Message.getDefaultInstance())); pipeline.addLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.addLast(new ProtobufEncoder()); pipeline.addLast(new NettyClientHandler()); } @Override public void shutdown() { try { if (this.channel != null) { this.channel.close(); } this.workerGroup.shutdownGracefully(); this.threadPool.destroy(); } catch (Exception e) { log.error("netty client shutdown exception, ", e); } } @Override public boolean isStart() { return this.channel != null && this.channel.isActive(); } @Override public void sendMsg(final ClusterMsg.Message request) { this.sendMsgImpl(this.channel, request); } @Override public ClusterMsg.Message sendMsgSync(ClusterMsg.Message request, int timeoutMillis) { return this.sendMsgSyncImpl(this.channel, request, timeoutMillis); } class NettyClientHandler extends SimpleChannelInboundHandler<ClusterMsg.Message> { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { NettyRemotingClient.this.channelActive(ctx); } @Override protected void channelRead0(ChannelHandlerContext ctx, ClusterMsg.Message msg) throws Exception { NettyRemotingClient.this.processReceiveMsg(ctx, msg); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { NettyRemotingClient.this.channelIdle(ctx, evt); } } }
this.threadPool.execute(() -> { ThreadFactory threadFactory = new ThreadFactoryBuilder() .setUncaughtExceptionHandler((thread, throwable) -> { log.error("NettyClientWorker has uncaughtException."); log.error(throwable.getMessage(), throwable); }) .setDaemon(true) .setNameFormat("netty-client-worker-%d") .build(); this.workerGroup = new NioEventLoopGroup(threadFactory); this.bootstrap.group(workerGroup) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, this.nettyClientConfig.getConnectTimeoutMillis()) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel channel) throws Exception { NettyRemotingClient.this.initChannel(channel); } }); this.channel = null; boolean first = true; while (!Thread.currentThread().isInterrupted() && (first || this.channel == null || !this.channel.isActive())) { first = false; try { this.channel = this.bootstrap .connect(this.nettyClientConfig.getServerHost(), this.nettyClientConfig.getServerPort()) .sync().channel(); this.channel.closeFuture().sync(); } catch (InterruptedException ignored) { log.info("client shutdown now!"); Thread.currentThread().interrupt(); } catch (Exception e2) { log.error("client connect to server error: {}. try after 10s.", e2.getMessage()); try { Thread.sleep(10000); } catch (InterruptedException ignored) { } } } workerGroup.shutdownGracefully(); });
740
469
1,209
<methods>public void registerProcessor(org.apache.hertzbeat.common.entity.message.ClusterMsg.MessageType, org.apache.hertzbeat.remoting.netty.NettyRemotingProcessor) <variables>protected org.apache.hertzbeat.remoting.event.NettyEventListener nettyEventListener,protected List<org.apache.hertzbeat.remoting.netty.NettyHook> nettyHookList,protected ConcurrentHashMap<org.apache.hertzbeat.common.entity.message.ClusterMsg.MessageType,org.apache.hertzbeat.remoting.netty.NettyRemotingProcessor> processorTable,protected ConcurrentHashMap<java.lang.String,org.apache.hertzbeat.remoting.netty.ResponseFuture> responseTable
apache_hertzbeat
hertzbeat/remoting/src/main/java/org/apache/hertzbeat/remoting/netty/NettyRemotingServer.java
NettyRemotingServer
initChannel
class NettyRemotingServer extends NettyRemotingAbstract implements RemotingServer { private final NettyServerConfig nettyServerConfig; private final CommonThreadPool threadPool; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; private Channel channel = null; public NettyRemotingServer(final NettyServerConfig nettyServerConfig, final NettyEventListener nettyEventListener, final CommonThreadPool threadPool) { super(nettyEventListener); this.nettyServerConfig = nettyServerConfig; this.threadPool = threadPool; } @Override public void start() { this.threadPool.execute(() -> { int port = this.nettyServerConfig.getPort(); ThreadFactory bossThreadFactory = new ThreadFactoryBuilder() .setUncaughtExceptionHandler((thread, throwable) -> { log.error("NettyServerBoss has uncaughtException."); log.error(throwable.getMessage(), throwable); }) .setDaemon(true) .setNameFormat("netty-server-boss-%d") .build(); ThreadFactory workerThreadFactory = new ThreadFactoryBuilder() .setUncaughtExceptionHandler((thread, throwable) -> { log.error("NettyServerWorker has uncaughtException."); log.error(throwable.getMessage(), throwable); }) .setDaemon(true) .setNameFormat("netty-server-worker-%d") .build(); if (this.useEpoll()) { bossGroup = new EpollEventLoopGroup(bossThreadFactory); workerGroup = new EpollEventLoopGroup(workerThreadFactory); } else { bossGroup = new NioEventLoopGroup(bossThreadFactory); workerGroup = new NioEventLoopGroup(workerThreadFactory); } try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(this.useEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_KEEPALIVE, false) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel channel) throws Exception { NettyRemotingServer.this.initChannel(channel); } }); channel = b.bind(port).sync().channel(); channel.closeFuture().sync(); } catch (InterruptedException ignored) { log.info("server shutdown now!"); } catch (Exception e) { log.error("Netty Server start exception, {}", e.getMessage()); throw new RuntimeException(e); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }); } @Override public boolean isStart() { return this.channel != null && this.channel.isActive(); } private void initChannel(final SocketChannel channel) {<FILL_FUNCTION_BODY>} @Override public void shutdown() { try { this.bossGroup.shutdownGracefully(); this.workerGroup.shutdownGracefully(); this.threadPool.destroy(); } catch (Exception e) { log.error("Netty Server shutdown exception, ", e); } } @Override public void sendMsg(final Channel channel, final ClusterMsg.Message request) { this.sendMsgImpl(channel, request); } @Override public ClusterMsg.Message sendMsgSync(final Channel channel, final ClusterMsg.Message request, final int timeoutMillis) { return this.sendMsgSyncImpl(channel, request, timeoutMillis); } @Override public void registerHook(List<NettyHook> nettyHookList) { this.nettyHookList.addAll(nettyHookList); } /** * netty server handler */ @ChannelHandler.Sharable public class NettyServerHandler extends SimpleChannelInboundHandler<ClusterMsg.Message> { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { NettyRemotingServer.this.channelActive(ctx); } @Override protected void channelRead0(ChannelHandlerContext ctx, ClusterMsg.Message msg) throws Exception { NettyRemotingServer.this.processReceiveMsg(ctx, msg); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { NettyRemotingServer.this.channelIdle(ctx, evt); } } }
ChannelPipeline pipeline = channel.pipeline(); // zip pipeline.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP)); pipeline.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP)); // protocol buf encode decode pipeline.addLast(new ProtobufVarint32FrameDecoder()); pipeline.addLast(new ProtobufDecoder(ClusterMsg.Message.getDefaultInstance())); pipeline.addLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.addLast(new ProtobufEncoder()); // idle state pipeline.addLast(new IdleStateHandler(0, 0, nettyServerConfig.getIdleStateEventTriggerTime())); pipeline.addLast(new NettyServerHandler());
1,213
207
1,420
<methods>public void registerProcessor(org.apache.hertzbeat.common.entity.message.ClusterMsg.MessageType, org.apache.hertzbeat.remoting.netty.NettyRemotingProcessor) <variables>protected org.apache.hertzbeat.remoting.event.NettyEventListener nettyEventListener,protected List<org.apache.hertzbeat.remoting.netty.NettyHook> nettyHookList,protected ConcurrentHashMap<org.apache.hertzbeat.common.entity.message.ClusterMsg.MessageType,org.apache.hertzbeat.remoting.netty.NettyRemotingProcessor> processorTable,protected ConcurrentHashMap<java.lang.String,org.apache.hertzbeat.remoting.netty.ResponseFuture> responseTable
apache_hertzbeat
hertzbeat/warehouse/src/main/java/org/apache/hertzbeat/warehouse/WarehouseWorkerPool.java
WarehouseWorkerPool
initWorkExecutor
class WarehouseWorkerPool { private ThreadPoolExecutor workerExecutor; public WarehouseWorkerPool() { initWorkExecutor(); } private void initWorkExecutor() {<FILL_FUNCTION_BODY>} /** * Run warehouse task * @param runnable task * @throws RejectedExecutionException when THREAD POOL FULL */ public void executeJob(Runnable runnable) throws RejectedExecutionException { workerExecutor.execute(runnable); } }
// Thread factory ThreadFactory threadFactory = new ThreadFactoryBuilder() .setUncaughtExceptionHandler((thread, throwable) -> { log.error("workerExecutor has uncaughtException."); log.error(throwable.getMessage(), throwable); }) .setDaemon(true) .setNameFormat("warehouse-worker-%d") .build(); workerExecutor = new ThreadPoolExecutor(6, 10, 10, TimeUnit.SECONDS, new SynchronousQueue<>(), threadFactory, new ThreadPoolExecutor.AbortPolicy());
137
151
288
<no_super_class>
apache_hertzbeat
hertzbeat/warehouse/src/main/java/org/apache/hertzbeat/warehouse/controller/MetricsDataController.java
MetricsDataController
getMetricHistoryData
class MetricsDataController { private static final Integer METRIC_FULL_LENGTH = 3; private final List<AbstractRealTimeDataStorage> realTimeDataStorages; private final List<AbstractHistoryDataStorage> historyDataStorages; public MetricsDataController(List<AbstractRealTimeDataStorage> realTimeDataStorages, List<AbstractHistoryDataStorage> historyDataStorages) { this.realTimeDataStorages = realTimeDataStorages; this.historyDataStorages = historyDataStorages; } @GetMapping("/api/warehouse/storage/status") @Operation(summary = "Query Warehouse Storage Server Status", description = "Query the availability status of the storage service under the warehouse") public ResponseEntity<Message<Void>> getWarehouseStorageServerStatus() { boolean available = false; if (historyDataStorages != null) { available = historyDataStorages.stream().anyMatch(AbstractHistoryDataStorage::isServerAvailable); } if (available) { return ResponseEntity.ok(Message.success()); } else { return ResponseEntity.ok(Message.fail(FAIL_CODE, "Service not available!")); } } @GetMapping("/api/monitor/{monitorId}/metrics/{metrics}") @Operation(summary = "Query Real Time Metrics Data", description = "Query real-time metrics data of monitoring indicators") public ResponseEntity<Message<MetricsData>> getMetricsData( @Parameter(description = "Monitor Id", example = "343254354") @PathVariable Long monitorId, @Parameter(description = "Metrics Name", example = "cpu") @PathVariable String metrics) { AbstractRealTimeDataStorage realTimeDataStorage = realTimeDataStorages.stream() .filter(AbstractRealTimeDataStorage::isServerAvailable) .max((o1, o2) -> { if (o1 instanceof RealTimeMemoryDataStorage) { return -1; } else if (o2 instanceof RealTimeMemoryDataStorage) { return 1; } else { return 0; } }).orElse(null); if (realTimeDataStorage == null) { return ResponseEntity.ok(Message.fail(FAIL_CODE, "real time store not available")); } CollectRep.MetricsData storageData = realTimeDataStorage.getCurrentMetricsData(monitorId, metrics); if (storageData == null) { return ResponseEntity.ok(Message.success("query metrics data is empty")); } { MetricsData.MetricsDataBuilder dataBuilder = MetricsData.builder(); dataBuilder.id(storageData.getId()).app(storageData.getApp()).metrics(storageData.getMetrics()) .time(storageData.getTime()); List<Field> fields = storageData.getFieldsList().stream().map(tmpField -> Field.builder().name(tmpField.getName()) .type(Integer.valueOf(tmpField.getType()).byteValue()) .label(tmpField.getLabel()) .unit(tmpField.getUnit()) .build()) .collect(Collectors.toList()); dataBuilder.fields(fields); List<ValueRow> valueRows = new LinkedList<>(); for (CollectRep.ValueRow valueRow : storageData.getValuesList()) { Map<String, String> labels = new HashMap<>(8); List<Value> values = new LinkedList<>(); for (int i = 0; i < fields.size(); i++) { Field field = fields.get(i); String origin = valueRow.getColumns(i); if (CommonConstants.NULL_VALUE.equals(origin)) { values.add(new Value()); } else { values.add(new Value(origin)); if (field.getLabel()) { labels.put(field.getName(), origin); } } } valueRows.add(ValueRow.builder().labels(labels).values(values).build()); } dataBuilder.valueRows(valueRows); return ResponseEntity.ok(Message.success(dataBuilder.build())); } } @GetMapping("/api/monitor/{monitorId}/metric/{metricFull}") @Operation(summary = "Queries historical data for a specified metric for monitoring", description = "Queries historical data for a specified metric under monitoring") public ResponseEntity<Message<MetricsHistoryData>> getMetricHistoryData( @Parameter(description = "monitor the task ID", example = "343254354") @PathVariable Long monitorId, @Parameter(description = "monitor metric full path", example = "linux.cpu.usage") @PathVariable() String metricFull, @Parameter(description = "label filter, empty by default", example = "disk2") @RequestParam(required = false) String label, @Parameter(description = "query historical time period, default 6h-6 hours: s-seconds, M-minutes, h-hours, d-days, w-weeks", example = "6h") @RequestParam(required = false) String history, @Parameter(description = "aggregate data calc. off by default; 4-hour window, query limit >1 week", example = "false") @RequestParam(required = false) Boolean interval ) {<FILL_FUNCTION_BODY>} }
AbstractHistoryDataStorage historyDataStorage = historyDataStorages.stream() .filter(AbstractHistoryDataStorage::isServerAvailable).max((o1, o2) -> { if (o1 instanceof HistoryJpaDatabaseDataStorage) { return -1; } else if (o2 instanceof HistoryJpaDatabaseDataStorage) { return 1; } else { return 0; } }).orElse(null); if (historyDataStorage == null) { return ResponseEntity.ok(Message.fail(FAIL_CODE, "time series database not available")); } String[] names = metricFull.split("\\."); if (names.length != METRIC_FULL_LENGTH) { throw new IllegalArgumentException("metrics full name: " + metricFull + " is illegal."); } String app = names[0]; String metrics = names[1]; String metric = names[2]; if (history == null) { history = "6h"; } Map<String, List<Value>> instanceValuesMap; if (interval == null || !interval) { instanceValuesMap = historyDataStorage.getHistoryMetricData(monitorId, app, metrics, metric, label, history); } else { instanceValuesMap = historyDataStorage.getHistoryIntervalMetricData(monitorId, app, metrics, metric, label, history); } MetricsHistoryData historyData = MetricsHistoryData.builder() .id(monitorId).metrics(metrics).values(instanceValuesMap) .field(Field.builder().name(metric).type(CommonConstants.TYPE_NUMBER).build()) .build(); return ResponseEntity.ok(Message.success(historyData));
1,346
431
1,777
<no_super_class>
apache_hertzbeat
hertzbeat/warehouse/src/main/java/org/apache/hertzbeat/warehouse/service/WarehouseServiceImpl.java
WarehouseServiceImpl
queryMonitorMetricsData
class WarehouseServiceImpl implements WarehouseService { private final List<AbstractRealTimeDataStorage> realTimeDataStorages; public WarehouseServiceImpl(List<AbstractRealTimeDataStorage> realTimeDataStorages) { this.realTimeDataStorages = realTimeDataStorages; } @Override public List<CollectRep.MetricsData> queryMonitorMetricsData(Long monitorId) {<FILL_FUNCTION_BODY>} }
AbstractRealTimeDataStorage realTimeDataStorage = realTimeDataStorages.stream() .filter(AbstractRealTimeDataStorage::isServerAvailable) .max((o1, o2) -> { if (o1 instanceof RealTimeMemoryDataStorage) { return -1; } else if (o2 instanceof RealTimeMemoryDataStorage) { return 1; } else { return 0; } }).orElse(null); if (realTimeDataStorage == null) { log.error("real time store not available"); return Collections.emptyList(); } return realTimeDataStorage.getCurrentMetricsData(monitorId);
120
171
291
<no_super_class>
apache_hertzbeat
hertzbeat/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/DataStorageDispatch.java
DataStorageDispatch
startStorageRealTimeData
class DataStorageDispatch { private final CommonDataQueue commonDataQueue; private final WarehouseWorkerPool workerPool; private final List<AbstractHistoryDataStorage> historyDataStorages; private final List<AbstractRealTimeDataStorage> realTimeDataStorages; public DataStorageDispatch(CommonDataQueue commonDataQueue, WarehouseWorkerPool workerPool, List<AbstractHistoryDataStorage> historyDataStorages, List<AbstractRealTimeDataStorage> realTimeDataStorages) { this.commonDataQueue = commonDataQueue; this.workerPool = workerPool; this.historyDataStorages = historyDataStorages; this.realTimeDataStorages = realTimeDataStorages; startStoragePersistentData(); startStorageRealTimeData(); } private void startStorageRealTimeData() {<FILL_FUNCTION_BODY>} protected void startStoragePersistentData() { Runnable runnable = () -> { Thread.currentThread().setName("warehouse-persistent-data-storage"); if (historyDataStorages != null && historyDataStorages.size() > 1) { historyDataStorages.removeIf(item -> item instanceof HistoryJpaDatabaseDataStorage); } while (!Thread.currentThread().isInterrupted()) { try { CollectRep.MetricsData metricsData = commonDataQueue.pollMetricsDataToPersistentStorage(); if (metricsData != null && historyDataStorages != null) { for (AbstractHistoryDataStorage historyDataStorage : historyDataStorages) { historyDataStorage.saveData(metricsData); } } } catch (Exception e) { log.error(e.getMessage(), e); } } }; workerPool.executeJob(runnable); } }
Runnable runnable = () -> { Thread.currentThread().setName("warehouse-realtime-data-storage"); if (realTimeDataStorages != null && realTimeDataStorages.size() > 1) { realTimeDataStorages.removeIf(item -> item instanceof RealTimeMemoryDataStorage); } while (!Thread.currentThread().isInterrupted()) { try { CollectRep.MetricsData metricsData = commonDataQueue.pollMetricsDataToRealTimeStorage(); if (metricsData != null && realTimeDataStorages != null) { for (AbstractRealTimeDataStorage realTimeDataStorage : realTimeDataStorages) { realTimeDataStorage.saveData(metricsData); } } } catch (Exception e) { log.error(e.getMessage(), e); } } }; workerPool.executeJob(runnable);
472
237
709
<no_super_class>
apache_hertzbeat
hertzbeat/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/MetricsDataRedisCodec.java
MetricsDataRedisCodec
decodeValue
class MetricsDataRedisCodec implements RedisCodec<String, CollectRep.MetricsData> { @Override public String decodeKey(ByteBuffer byteBuffer) { return StandardCharsets.UTF_8.decode(byteBuffer).toString(); } @Override public CollectRep.MetricsData decodeValue(ByteBuffer byteBuffer) {<FILL_FUNCTION_BODY>} @Override public ByteBuffer encodeKey(String s) { return ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8)); } @Override public ByteBuffer encodeValue(CollectRep.MetricsData metricsData) { return ByteBuffer.wrap(metricsData.toByteArray()); } }
try { return CollectRep.MetricsData.parseFrom(byteBuffer); } catch (Exception e) { log.error(e.getMessage()); return null; }
183
49
232
<no_super_class>
apache_hertzbeat
hertzbeat/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/RealTimeRedisDataStorage.java
RealTimeRedisDataStorage
initRedisClient
class RealTimeRedisDataStorage extends AbstractRealTimeDataStorage { private RedisClient redisClient; private final Integer db; private StatefulRedisConnection<String, CollectRep.MetricsData> connection; public RealTimeRedisDataStorage(WarehouseProperties properties) { this.serverAvailable = initRedisClient(properties); this.db = getRedisSelectDb(properties); } private Integer getRedisSelectDb(WarehouseProperties properties){ return properties.getStore().getRedis().db(); } @Override public CollectRep.MetricsData getCurrentMetricsData(@NonNull Long monitorId, @NonNull String metric) { RedisCommands<String, CollectRep.MetricsData> commands = connection.sync(); commands.select(db); return commands.hget(String.valueOf(monitorId), metric); } @Override public List<CollectRep.MetricsData> getCurrentMetricsData(@NonNull Long monitorId) { RedisCommands<String, CollectRep.MetricsData> commands = connection.sync(); commands.select(db); Map<String, CollectRep.MetricsData> metricsDataMap = commands.hgetall(String.valueOf(monitorId)); return new ArrayList<>(metricsDataMap.values()); } @Override public void saveData(CollectRep.MetricsData metricsData) { String key = String.valueOf(metricsData.getId()); String hashKey = metricsData.getMetrics(); if (metricsData.getCode() != CollectRep.Code.SUCCESS || !isServerAvailable()) { return; } if (metricsData.getValuesList().isEmpty()) { log.info("[warehouse redis] redis flush metrics data {} - {} is null, ignore.", key, hashKey); return; } RedisAsyncCommands<String, CollectRep.MetricsData> commands = connection.async(); commands.select(db); commands.hset(key, hashKey, metricsData).thenAccept(response -> { if (response) { log.debug("[warehouse] redis add new data {}:{}.", key, hashKey); } else { log.debug("[warehouse] redis replace data {}:{}.", key, hashKey); } }); } private boolean initRedisClient(WarehouseProperties properties) {<FILL_FUNCTION_BODY>} @Override public void destroy() { if (connection != null) { connection.close(); } if (redisClient != null) { redisClient.shutdown(); } } }
if (properties == null || properties.getStore() == null || properties.getStore().getRedis() == null) { log.error("init error, please config Warehouse redis props in application.yml"); return false; } WarehouseProperties.StoreProperties.RedisProperties redisProp = properties.getStore().getRedis(); RedisURI.Builder uriBuilder = RedisURI.builder() .withHost(redisProp.host()) .withPort(redisProp.port()) .withTimeout(Duration.of(10, ChronoUnit.SECONDS)); if (redisProp.password() != null && !"".equals(redisProp.password())) { uriBuilder.withPassword(redisProp.password().toCharArray()); } try { redisClient = RedisClient.create(uriBuilder.build()); connection = redisClient.connect(new MetricsDataRedisCodec()); return true; } catch (Exception e) { log.error("init redis error {}", e.getMessage(), e); } return false;
665
277
942
<methods>public non-sealed void <init>() ,public abstract org.apache.hertzbeat.common.entity.message.CollectRep.MetricsData getCurrentMetricsData(java.lang.Long, java.lang.String) ,public abstract List<org.apache.hertzbeat.common.entity.message.CollectRep.MetricsData> getCurrentMetricsData(java.lang.Long) ,public boolean isServerAvailable() <variables>protected boolean serverAvailable
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationHolder.java
AuthenticationHolder
addSupplier
class AuthenticationHolder { private static final List<AuthenticationSupplier> suppliers = new ArrayList<>(); private static final ReadWriteLock lock = new ReentrantReadWriteLock(); private static Optional<Authentication> get(Function<AuthenticationSupplier, Optional<Authentication>> function) { int size = suppliers.size(); if (size == 0) { return Optional.empty(); } if (size == 1) { return function.apply(suppliers.get(0)); } SimpleAuthentication merge = new SimpleAuthentication(); for (AuthenticationSupplier supplier : suppliers) { function.apply(supplier).ifPresent(merge::merge); } if (merge.getUser() == null) { return Optional.empty(); } return Optional.of(merge); } /** * @return 当前登录的用户权限信息 */ public static Optional<Authentication> get() { return get(AuthenticationSupplier::get); } /** * 获取指定用户的权限信息 * * @param userId 用户ID * @return 权限信息 */ public static Optional<Authentication> get(String userId) { return get(supplier -> supplier.get(userId)); } /** * 初始化 {@link AuthenticationSupplier} * * @param supplier */ public static void addSupplier(AuthenticationSupplier supplier) {<FILL_FUNCTION_BODY>} }
lock.writeLock().lock(); try { suppliers.add(supplier); } finally { lock.writeLock().unlock(); }
379
42
421
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationUtils.java
AuthenticationUtils
createPredicate
class AuthenticationUtils { public static AuthenticationPredicate createPredicate(String expression) {<FILL_FUNCTION_BODY>} }
if (StringUtils.isEmpty(expression)) { return (authentication -> false); } AuthenticationPredicate main = null; // resource:user:add or update AuthenticationPredicate temp = null; boolean lastAnd = true; for (String conf : expression.split("[ ]")) { if (conf.startsWith("resource:")||conf.startsWith("permission:")) { String[] permissionAndActions = conf.split("[:]", 2); if (permissionAndActions.length < 2) { temp = authentication -> !authentication.getPermissions().isEmpty(); } else { String[] real = permissionAndActions[1].split("[:]"); temp = real.length > 1 ? AuthenticationPredicate.permission(real[0], real[1].split("[,]")) : AuthenticationPredicate.permission(real[0]); } } else if (main != null && conf.equalsIgnoreCase("and")) { lastAnd = true; main = main.and(temp); } else if (main != null && conf.equalsIgnoreCase("or")) { main = main.or(temp); lastAnd = false; } else { String[] real = conf.split("[:]", 2); if (real.length < 2) { temp = AuthenticationPredicate.dimension(real[0]); } else { temp = AuthenticationPredicate.dimension(real[0], real[1].split(",")); } } if (main == null) { main = temp; } } return main == null ? a -> false : (lastAnd ? main.and(temp) : main.or(temp));
37
432
469
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/ReactiveAuthenticationHolder.java
ReactiveAuthenticationHolder
get
class ReactiveAuthenticationHolder { private static final List<ReactiveAuthenticationSupplier> suppliers = new CopyOnWriteArrayList<>(); private static Mono<Authentication> get(Function<ReactiveAuthenticationSupplier, Mono<Authentication>> function) {<FILL_FUNCTION_BODY>} /** * @return 当前登录的用户权限信息 */ public static Mono<Authentication> get() { return get(ReactiveAuthenticationSupplier::get); } /** * 获取指定用户的权限信息 * * @param userId 用户ID * @return 权限信息 */ public static Mono<Authentication> get(String userId) { return get(supplier -> supplier.get(userId)); } /** * 初始化 {@link ReactiveAuthenticationSupplier} * * @param supplier */ public static void addSupplier(ReactiveAuthenticationSupplier supplier) { suppliers.add(supplier); } public static void setSupplier(ReactiveAuthenticationSupplier supplier) { suppliers.clear(); suppliers.add(supplier); } }
return Flux .merge(suppliers .stream() .map(function) .collect(Collectors.toList())) .collectList() .filter(CollectionUtils::isNotEmpty) .map(all -> { if (all.size() == 1) { return all.get(0); } SimpleAuthentication authentication = new SimpleAuthentication(); for (Authentication auth : all) { authentication.merge(auth); } return authentication; });
294
130
424
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/DimensionHelper.java
DimensionHelper
getDimensionDataAccessScope
class DimensionHelper { public static Set<Object> getDimensionDataAccessScope(Authentication atz, Permission permission, String action, String dimensionType) { return permission .getDataAccesses(action) .stream() .filter(DimensionDataAccessConfig.class::isInstance) .map(DimensionDataAccessConfig.class::cast) .filter(conf -> dimensionType.equals(conf.getScopeType())) .flatMap(conf -> { if (CollectionUtils.isEmpty(conf.getScope())) { return atz.getDimensions(dimensionType) .stream() .map(Dimension::getId); } return conf.getScope().stream(); }).collect(Collectors.toSet()); } public static Set<Object> getDimensionDataAccessScope(Authentication atz, Permission permission, String action, DimensionType dimensionType) { return getDimensionDataAccessScope(atz, permission, action, dimensionType.getId()); } public static Set<Object> getDimensionDataAccessScope(Authentication atz, String permission, String action, String dimensionType) {<FILL_FUNCTION_BODY>} public static Set<Object> getDimensionDataAccessScope(Authentication atz, String permission, String action, DimensionType dimensionType) { return atz .getPermission(permission) .map(per -> getDimensionDataAccessScope(atz, per, action, dimensionType)) .orElseGet(Collections::emptySet); } }
return atz .getPermission(permission) .map(per -> getDimensionDataAccessScope(atz, per, action, dimensionType)).orElseGet(Collections::emptySet);
417
50
467
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/define/DataAccessDefinition.java
DataAccessDefinition
getType
class DataAccessDefinition { Set<DataAccessTypeDefinition> dataAccessTypes = new HashSet<>(); public Optional<DataAccessTypeDefinition> getType(String typeId) {<FILL_FUNCTION_BODY>} }
return dataAccessTypes .stream() .filter(type -> type.getId() != null && type.getId().equalsIgnoreCase(typeId)) .findAny();
58
47
105
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/define/DimensionsDefinition.java
DimensionsDefinition
hasDimension
class DimensionsDefinition { private Set<DimensionDefinition> dimensions = new HashSet<>(); private Logical logical = Logical.DEFAULT; public void addDimension(DimensionDefinition definition) { dimensions.add(definition); } public boolean isEmpty(){ return CollectionUtils.isEmpty(this.dimensions); } public boolean hasDimension(Dimension dimension) { return dimensions .stream() .anyMatch(def -> def.getTypeId().equals(dimension.getType().getId()) && def.hasDimension(dimension.getId())); } public boolean hasDimension(List<Dimension> dimensions) {<FILL_FUNCTION_BODY>} }
if (logical == Logical.AND) { return dimensions.stream().allMatch(this::hasDimension); } return dimensions.stream().anyMatch(this::hasDimension);
184
53
237
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/define/MergedAuthorizeDefinition.java
MergedAuthorizeDefinition
merge
class MergedAuthorizeDefinition implements AuthorizeDefinitionContext { private final ResourcesDefinition resources = new ResourcesDefinition(); private final DimensionsDefinition dimensions = new DimensionsDefinition(); public Set<ResourceDefinition> getResources() { return resources.getResources(); } public Set<DimensionDefinition> getDimensions() { return dimensions.getDimensions(); } public void addResource(ResourceDefinition resource) { resources.addResource(resource, true); } public void addDimension(DimensionDefinition resource) { dimensions.addDimension(resource); } public void merge(List<AuthorizeDefinition> definitions) {<FILL_FUNCTION_BODY>} }
for (AuthorizeDefinition definition : definitions) { definition.getResources().getResources().forEach(this::addResource); definition.getDimensions().getDimensions().forEach(this::addDimension); }
178
55
233
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/define/ResourceDefinition.java
ResourceDefinition
of
class ResourceDefinition { private String id; private String name; private String description; private Set<ResourceActionDefinition> actions = new HashSet<>(); private List<String> group; @Setter(value = AccessLevel.PRIVATE) @JsonIgnore private volatile Set<String> actionIds; private Logical logical = Logical.DEFAULT; private Phased phased = Phased.before; public static ResourceDefinition of(String id, String name) {<FILL_FUNCTION_BODY>} public ResourceDefinition copy() { ResourceDefinition definition = FastBeanCopier.copy(this, ResourceDefinition::new); definition.setActions(actions.stream().map(ResourceActionDefinition::copy).collect(Collectors.toSet())); return definition; } public ResourceDefinition addAction(String id, String name) { ResourceActionDefinition action = new ResourceActionDefinition(); action.setId(id); action.setName(name); return addAction(action); } public synchronized ResourceDefinition addAction(ResourceActionDefinition action) { actionIds = null; ResourceActionDefinition old = getAction(action.getId()).orElse(null); if (old != null) { old.getDataAccess().getDataAccessTypes() .addAll(action.getDataAccess().getDataAccessTypes()); } actions.add(action); return this; } public Optional<ResourceActionDefinition> getAction(String action) { return actions.stream() .filter(act -> act.getId().equalsIgnoreCase(action)) .findAny(); } public Set<String> getActionIds() { if (actionIds == null) { actionIds = this.actions .stream() .map(ResourceActionDefinition::getId) .collect(Collectors.toSet()); } return actionIds; } @JsonIgnore public List<ResourceActionDefinition> getDataAccessAction() { return actions.stream() .filter(act -> CollectionUtils.isNotEmpty(act.getDataAccess().getDataAccessTypes())) .collect(Collectors.toList()); } public boolean hasDataAccessAction() { return actions.stream() .anyMatch(act -> CollectionUtils.isNotEmpty(act.getDataAccess().getDataAccessTypes())); } public boolean hasAction(Collection<String> actions) { if (CollectionUtils.isEmpty(this.actions)) { return true; } if (CollectionUtils.isEmpty(actions)) { return false; } if (logical == Logical.AND) { return getActionIds().containsAll(actions); } return getActionIds().stream().anyMatch(actions::contains); } }
ResourceDefinition definition = new ResourceDefinition(); definition.setId(id); definition.setName(name); return definition;
709
36
745
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/define/ResourcesDefinition.java
ResourcesDefinition
addResource
class ResourcesDefinition { private Set<ResourceDefinition> resources = new HashSet<>(); private Logical logical = Logical.DEFAULT; private Phased phased = Phased.before; public void addResource(ResourceDefinition resource, boolean merge) {<FILL_FUNCTION_BODY>} public Optional<ResourceDefinition> getResource(String id) { return resources .stream() .filter(resource -> resource.getId().equals(id)) .findAny(); } @JsonIgnore public List<ResourceDefinition> getDataAccessResources() { return resources .stream() .filter(ResourceDefinition::hasDataAccessAction) .collect(Collectors.toList()); } public boolean hasPermission(Permission permission) { if (CollectionUtils.isEmpty(resources)) { return true; } return getResource(permission.getId()) .filter(resource -> resource.hasAction(permission.getActions())) .isPresent(); } public boolean isEmpty() { return resources.isEmpty(); } public boolean hasPermission(Authentication authentication) { if (CollectionUtils.isEmpty(resources)) { return true; } if (logical == Logical.AND) { return resources .stream() .allMatch(resource -> authentication.hasPermission(resource.getId(), resource.getActionIds())); } return resources .stream() .anyMatch(resource -> authentication.hasPermission(resource.getId(), resource.getActionIds())); } }
ResourceDefinition definition = getResource(resource.getId()).orElse(null); if (definition != null) { if (merge) { resource.getActions() .stream() .map(ResourceActionDefinition::copy) .forEach(definition::addAction); } else { resources.remove(definition); } } resources.add(resource.copy());
393
102
495
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/dimension/DimensionUserBind.java
DimensionUserBind
readExternal
class DimensionUserBind implements Externalizable { private static final long serialVersionUID = -6849794470754667710L; private String userId; private String dimensionType; private String dimensionId; @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(userId); out.writeUTF(dimensionType); out.writeUTF(dimensionId); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
userId = in.readUTF(); dimensionType = in.readUTF(); dimensionId = in.readUTF();
158
33
191
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/dimension/DimensionUserDetail.java
DimensionUserDetail
merge
class DimensionUserDetail implements Serializable { private static final long serialVersionUID = -6849794470754667710L; private String userId; private List<Dimension> dimensions; public DimensionUserDetail merge(DimensionUserDetail detail) {<FILL_FUNCTION_BODY>} }
DimensionUserDetail newDetail = new DimensionUserDetail(); newDetail.setUserId(userId); newDetail.setDimensions(new ArrayList<>()); if (null != dimensions) { newDetail.dimensions.addAll(dimensions); } if (null != detail.getDimensions()) { newDetail.dimensions.addAll(detail.getDimensions()); } return newDetail;
93
110
203
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/setting/StringSourceSettingHolder.java
StringSourceSettingHolder
convert
class StringSourceSettingHolder implements SettingValueHolder { private String value; private UserSettingPermission permission; public static SettingValueHolder of(String value, UserSettingPermission permission) { if (value == null) { return SettingValueHolder.NULL; } return new StringSourceSettingHolder(value, permission); } @Override public <T> Optional<List<T>> asList(Class<T> t) { return getNativeValue() .map(v -> JSON.parseArray(v, t)); } protected <T> T convert(String value, Class<T> t) {<FILL_FUNCTION_BODY>} @Override @SuppressWarnings("all") public <T> Optional<T> as(Class<T> t) { if (t == String.class) { return (Optional) asString(); } else if (Long.class == t || long.class == t) { return (Optional) asLong(); } else if (Integer.class == t || int.class == t) { return (Optional) asInt(); } else if (Double.class == t || double.class == t) { return (Optional) asDouble(); } return getNativeValue().map(v -> convert(v, t)); } @Override public Optional<String> asString() { return getNativeValue(); } @Override public Optional<Long> asLong() { return getNativeValue().map(StringUtils::toLong); } @Override public Optional<Integer> asInt() { return getNativeValue().map(StringUtils::toInt); } @Override public Optional<Double> asDouble() { return getNativeValue().map(StringUtils::toDouble); } private Optional<String> getNativeValue() { return Optional.ofNullable(value); } @Override public Optional<Object> getValue() { return Optional.ofNullable(value); } }
if (t.isEnum()) { if (EnumDict.class.isAssignableFrom(t)) { T val = (T) EnumDict.find((Class) t, value).orElse(null); if (null != val) { return val; } } for (T enumConstant : t.getEnumConstants()) { if (((Enum) enumConstant).name().equalsIgnoreCase(value)) { return enumConstant; } } } return JSON.parseObject(value, t);
517
141
658
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/simple/CompositeReactiveAuthenticationManager.java
CompositeReactiveAuthenticationManager
authenticate
class CompositeReactiveAuthenticationManager implements ReactiveAuthenticationManager { private final List<ReactiveAuthenticationManagerProvider> providers; @Override public Mono<Authentication> authenticate(Mono<AuthenticationRequest> request) {<FILL_FUNCTION_BODY>} @Override public Mono<Authentication> getByUserId(String userId) { return Flux .fromStream(providers .stream() .map(manager -> manager .getByUserId(userId) .onErrorResume((err) -> { log.warn("get user [{}] authentication error", userId, err); return Mono.empty(); }) )) .flatMap(Function.identity()) .collectList() .filter(CollectionUtils::isNotEmpty) .map(all -> { if (all.size() == 1) { return all.get(0); } SimpleAuthentication authentication = new SimpleAuthentication(); for (Authentication auth : all) { authentication.merge(auth); } return authentication; }); } }
return Flux.concat(providers .stream() .map(manager -> manager .authenticate(request) .onErrorResume((err) -> { log.warn("get user authenticate error", err); return Mono.empty(); })) .collect(Collectors.toList())) .take(1) .next();
279
103
382
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/simple/DefaultAuthorizationAutoConfiguration.java
DefaultAuthorizationAutoConfiguration
authenticationCustomMessageConverter
class DefaultAuthorizationAutoConfiguration { @Bean @ConditionalOnMissingBean(UserTokenManager.class) @ConfigurationProperties(prefix = "hsweb.user-token") public UserTokenManager userTokenManager() { return new DefaultUserTokenManager(); } @Bean @ConditionalOnMissingBean // @ConditionalOnBean(ReactiveAuthenticationManagerProvider.class) public ReactiveAuthenticationManager reactiveAuthenticationManager(List<ReactiveAuthenticationManagerProvider> providers) { return new CompositeReactiveAuthenticationManager(providers); } @Bean @ConditionalOnBean(ReactiveAuthenticationManager.class) public UserTokenReactiveAuthenticationSupplier userTokenReactiveAuthenticationSupplier(UserTokenManager userTokenManager, ReactiveAuthenticationManager authenticationManager) { UserTokenReactiveAuthenticationSupplier supplier = new UserTokenReactiveAuthenticationSupplier(userTokenManager, authenticationManager); ReactiveAuthenticationHolder.addSupplier(supplier); return supplier; } @Bean @ConditionalOnBean(AuthenticationManager.class) public UserTokenAuthenticationSupplier userTokenAuthenticationSupplier(UserTokenManager userTokenManager, AuthenticationManager authenticationManager) { UserTokenAuthenticationSupplier supplier = new UserTokenAuthenticationSupplier(userTokenManager, authenticationManager); AuthenticationHolder.addSupplier(supplier); return supplier; } @Bean @ConditionalOnMissingBean(DataAccessConfigBuilderFactory.class) @ConfigurationProperties(prefix = "hsweb.authorization.data-access", ignoreInvalidFields = true) public SimpleDataAccessConfigBuilderFactory dataAccessConfigBuilderFactory() { return new SimpleDataAccessConfigBuilderFactory(); } @Bean @ConditionalOnMissingBean(TwoFactorValidatorManager.class) @ConfigurationProperties("hsweb.authorize.two-factor") public DefaultTwoFactorValidatorManager defaultTwoFactorValidatorManager() { return new DefaultTwoFactorValidatorManager(); } @Bean @ConditionalOnMissingBean(AuthenticationBuilderFactory.class) public AuthenticationBuilderFactory authenticationBuilderFactory(DataAccessConfigBuilderFactory dataAccessConfigBuilderFactory) { return new SimpleAuthenticationBuilderFactory(dataAccessConfigBuilderFactory); } @Bean public CustomMessageConverter authenticationCustomMessageConverter(AuthenticationBuilderFactory factory) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnMissingBean(DimensionManager.class) public DimensionManager defaultDimensionManager(ObjectProvider<DimensionUserBindProvider>bindProviders, ObjectProvider<DimensionProvider> providers){ DefaultDimensionManager manager = new DefaultDimensionManager(); bindProviders.forEach(manager::addBindProvider); providers.forEach(manager::addProvider); return manager; } }
return new CustomMessageConverter() { @Override public boolean support(Class clazz) { return clazz == Authentication.class; } @Override public Object convert(Class clazz, byte[] message) { String json = new String(message); return factory.create().json(json).build(); } };
682
91
773
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/simple/DefaultDimensionManager.java
DefaultDimensionManager
getUserDimension
class DefaultDimensionManager implements DimensionManager { private final List<DimensionProvider> dimensionProviders = new CopyOnWriteArrayList<>(); private final List<DimensionUserBindProvider> bindProviders = new CopyOnWriteArrayList<>(); private final Mono<Map<String, DimensionProvider>> providerMapping = Flux .defer(() -> Flux.fromIterable(dimensionProviders)) .flatMap(provider -> provider .getAllType() .map(type -> Tuples.of(type.getId(), provider))) .collectMap(Tuple2::getT1, Tuple2::getT2); public DefaultDimensionManager() { } public void addProvider(DimensionProvider provider) { dimensionProviders.add(provider); } public void addBindProvider(DimensionUserBindProvider bindProvider) { bindProviders.add(bindProvider); } private Mono<Map<String, DimensionProvider>> providerMapping() { return providerMapping; } @Override public Flux<DimensionUserDetail> getUserDimension(Collection<String> userId) {<FILL_FUNCTION_BODY>} }
return this .providerMapping() .flatMapMany(providerMapping -> Flux .fromIterable(bindProviders) //获取绑定信息 .flatMap(provider -> provider.getDimensionBindInfo(userId)) .groupBy(DimensionUserBind::getDimensionType) .flatMap(group -> { String type = group.key(); Flux<DimensionUserBind> binds = group.cache(); DimensionProvider provider = providerMapping.get(type); if (null == provider) { return Mono.empty(); } //获取维度信息 return binds .map(DimensionUserBind::getDimensionId) .collect(Collectors.toSet()) .flatMapMany(idList -> provider.getDimensionsById(SimpleDimensionType.of(type), idList)) .collectMap(Dimension::getId, Function.identity()) .flatMapMany(mapping -> binds .groupBy(DimensionUserBind::getUserId) .flatMap(userGroup -> Mono .zip( Mono.just(userGroup.key()), userGroup .<Dimension>handle((bind, sink) -> { Dimension dimension = mapping.get(bind.getDimensionId()); if (dimension != null) { sink.next(dimension); } }) .collectList(), DimensionUserDetail::of )) ); }) ) .groupBy(DimensionUserDetail::getUserId) .flatMap(group->group.reduce(DimensionUserDetail::merge));
300
428
728
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/simple/SimpleAuthentication.java
SimpleAuthentication
copy
class SimpleAuthentication implements Authentication { private static final long serialVersionUID = -2898863220255336528L; private User user; private List<Permission> permissions = new ArrayList<>(); private List<Dimension> dimensions = new ArrayList<>(); private Map<String, Serializable> attributes = new HashMap<>(); public static Authentication of() { return new SimpleAuthentication(); } @Override @SuppressWarnings("unchecked") public <T extends Serializable> Optional<T> getAttribute(String name) { return Optional.ofNullable((T) attributes.get(name)); } @Override public Map<String, Serializable> getAttributes() { return attributes; } public SimpleAuthentication merge(Authentication authentication) { Map<String, Permission> mePermissionGroup = permissions .stream() .collect(Collectors.toMap(Permission::getId, Function.identity())); if (authentication.getUser() != null) { user = authentication.getUser(); } attributes.putAll(authentication.getAttributes()); for (Permission permission : authentication.getPermissions()) { Permission me = mePermissionGroup.get(permission.getId()); if (me == null) { permissions.add(permission.copy()); continue; } me.getActions().addAll(permission.getActions()); me.getDataAccesses().addAll(permission.getDataAccesses()); } for (Dimension dimension : authentication.getDimensions()) { if (!getDimension(dimension.getType(), dimension.getId()).isPresent()) { dimensions.add(dimension); } } return this; } @Override public Authentication copy(BiPredicate<Permission, String> permissionFilter, Predicate<Dimension> dimension) {<FILL_FUNCTION_BODY>} public void setUser(User user) { this.user = user; dimensions.add(user); } public void setDimensions(List<Dimension> dimensions) { this.dimensions.addAll(dimensions); } public void addDimension(Dimension dimension) { this.dimensions.add(dimension); } }
SimpleAuthentication authentication = new SimpleAuthentication(); authentication.setDimensions(dimensions.stream().filter(dimension).collect(Collectors.toList())); authentication.setPermissions(permissions .stream() .map(permission -> permission.copy(action -> permissionFilter.test(permission, action), conf -> true)) .filter(per -> !per.getActions().isEmpty()) .collect(Collectors.toList()) ); authentication.setUser(user); authentication.setAttributes(new HashMap<>(attributes)); return authentication;
586
145
731
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/simple/SimplePermission.java
SimplePermission
getActions
class SimplePermission implements Permission { private static final long serialVersionUID = 7587266693680162184L; private String id; private String name; private Set<String> actions; private Set<DataAccessConfig> dataAccesses; private Map<String, Object> options; public Set<String> getActions() {<FILL_FUNCTION_BODY>} public Set<DataAccessConfig> getDataAccesses() { if (dataAccesses == null) { dataAccesses = new java.util.HashSet<>(); } return dataAccesses; } @Override public Permission copy(Predicate<String> actionFilter, Predicate<DataAccessConfig> dataAccessFilter) { SimplePermission permission = new SimplePermission(); permission.setId(id); permission.setName(name); permission.setActions(getActions().stream().filter(actionFilter).collect(Collectors.toSet())); permission.setDataAccesses(getDataAccesses().stream().filter(dataAccessFilter).collect(Collectors.toSet())); if (options != null) { permission.setOptions(new HashMap<>(options)); } return permission; } public Permission copy() { return copy(action -> true, conf -> true); } @Override public String toString() { return id + (CollectionUtils.isNotEmpty(actions) ? ":" + String.join(",", actions) : ""); } }
if (actions == null) { actions = new java.util.HashSet<>(); } return actions;
397
33
430
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/simple/builder/SimpleAuthenticationBuilder.java
SimpleAuthenticationBuilder
permission
class SimpleAuthenticationBuilder implements AuthenticationBuilder { private SimpleAuthentication authentication = new SimpleAuthentication(); private DataAccessConfigBuilderFactory dataBuilderFactory; public SimpleAuthenticationBuilder(DataAccessConfigBuilderFactory dataBuilderFactory) { this.dataBuilderFactory = dataBuilderFactory; } public void setDataBuilderFactory(DataAccessConfigBuilderFactory dataBuilderFactory) { this.dataBuilderFactory = dataBuilderFactory; } @Override public AuthenticationBuilder user(User user) { Objects.requireNonNull(user); authentication.setUser(user); return this; } @Override public AuthenticationBuilder user(String user) { return user(JSON.parseObject(user, SimpleUser.class)); } @Override public AuthenticationBuilder user(Map<String, String> user) { Objects.requireNonNull(user.get("id")); user(SimpleUser.builder() .id(user.get("id")) .username(user.get("username")) .name(user.get("name")) .userType(user.get("type")) .build()); return this; } @Override public AuthenticationBuilder role(List<Role> role) { authentication.getDimensions().addAll(role); return this; } @Override @SuppressWarnings("unchecked") public AuthenticationBuilder role(String role) { return role((List) JSON.parseArray(role, SimpleRole.class)); } @Override public AuthenticationBuilder permission(List<Permission> permission) { authentication.setPermissions(permission); return this; } @Override public AuthenticationBuilder permission(String permissionJson) {<FILL_FUNCTION_BODY>} @Override public AuthenticationBuilder attributes(String attributes) { authentication.getAttributes().putAll(JSON.<Map<String, Serializable>>parseObject(attributes, Map.class)); return this; } @Override public AuthenticationBuilder attributes(Map<String, Serializable> permission) { authentication.getAttributes().putAll(permission); return this; } public AuthenticationBuilder dimension(JSONArray json) { if (json == null) { return this; } List<Dimension> dimensions = new ArrayList<>(); for (int i = 0; i < json.size(); i++) { JSONObject jsonObject = json.getJSONObject(i); Object type = jsonObject.get("type"); dimensions.add( SimpleDimension.of( jsonObject.getString("id"), jsonObject.getString("name"), type instanceof String?SimpleDimensionType.of(String.valueOf(type)):jsonObject.getJSONObject("type").toJavaObject(SimpleDimensionType.class), jsonObject.getJSONObject("options") )); } authentication.setDimensions(dimensions); return this; } @Override public AuthenticationBuilder json(String json) { JSONObject jsonObject = JSON.parseObject(json); user(jsonObject.getObject("user", SimpleUser.class)); if (jsonObject.containsKey("roles")) { role(jsonObject.getJSONArray("roles").toJSONString()); } if (jsonObject.containsKey("permissions")) { permission(jsonObject.getJSONArray("permissions").toJSONString()); } if (jsonObject.containsKey("dimensions")) { dimension(jsonObject.getJSONArray("dimensions")); } return this; } @Override public Authentication build() { return authentication; } }
JSONArray jsonArray = JSON.parseArray(permissionJson); List<Permission> permissions = new ArrayList<>(); for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); SimplePermission permission = new SimplePermission(); permission.setId(jsonObject.getString("id")); permission.setName(jsonObject.getString("name")); permission.setOptions(jsonObject.getJSONObject("options")); JSONArray actions = jsonObject.getJSONArray("actions"); if (actions != null) { permission.setActions(new HashSet<>(actions.toJavaList(String.class))); } JSONArray dataAccess = jsonObject.getJSONArray("dataAccesses"); if (null != dataAccess) { permission.setDataAccesses(dataAccess.stream().map(JSONObject.class::cast) .map(dataJson -> dataBuilderFactory.create().fromJson(dataJson.toJSONString()).build()) .filter(Objects::nonNull) .collect(Collectors.toSet())); } permissions.add(permission); } authentication.setPermissions(permissions); return this;
928
300
1,228
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/simple/builder/SimpleDataAccessConfigBuilder.java
SimpleDataAccessConfigBuilder
build
class SimpleDataAccessConfigBuilder implements DataAccessConfigBuilder { private List<DataAccessConfigConverter> converts; private Map<String, Object> config = new HashMap<>(); public SimpleDataAccessConfigBuilder(List<DataAccessConfigConverter> converts) { Objects.requireNonNull(converts); this.converts = converts; } @Override public DataAccessConfigBuilder fromJson(String json) { config.putAll(JSON.parseObject(json)); return this; } @Override public DataAccessConfigBuilder fromMap(Map<String, Object> map) { config.putAll(map); return this; } @Override public DataAccessConfig build() {<FILL_FUNCTION_BODY>} }
Objects.requireNonNull(config); JSONObject jsonObject = new JSONObject(config); String type = jsonObject.getString("type"); String action = jsonObject.getString("action"); String config = jsonObject.getString("config"); Objects.requireNonNull(type); Objects.requireNonNull(action); if (config == null) { config = jsonObject.toJSONString(); } String finalConfig = config; return converts.stream() .filter(convert -> convert.isSupport(type, action, finalConfig)) .map(convert -> convert.convert(type, action, finalConfig)) .findFirst() .orElse(null);
203
182
385
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/simple/builder/SimpleDataAccessConfigBuilderFactory.java
SimpleDataAccessConfigBuilderFactory
createConfig
class SimpleDataAccessConfigBuilderFactory implements DataAccessConfigBuilderFactory { private List<String> defaultSupportConvert = Arrays.asList( OWN_CREATED, DIMENSION_SCOPE, DENY_FIELDS); private List<DataAccessConfigConverter> converts = new LinkedList<>(); public SimpleDataAccessConfigBuilderFactory addConvert(DataAccessConfigConverter configBuilderConvert) { Objects.requireNonNull(configBuilderConvert); converts.add(configBuilderConvert); return this; } public void setDefaultSupportConvert(List<String> defaultSupportConvert) { this.defaultSupportConvert = defaultSupportConvert; } public List<String> getDefaultSupportConvert() { return defaultSupportConvert; } protected DataAccessConfigConverter createJsonConfig(String supportType, Class<? extends AbstractDataAccessConfig> clazz) { return createConfig(supportType, (action, config) -> JSON.parseObject(config, clazz)); } protected DataAccessConfigConverter createConfig(String supportType, BiFunction<String, String, ? extends DataAccessConfig> function) {<FILL_FUNCTION_BODY>} @PostConstruct public void init() { if (defaultSupportConvert.contains(DENY_FIELDS)) { converts.add(createJsonConfig(DENY_FIELDS, SimpleFieldFilterDataAccessConfig.class)); } if (defaultSupportConvert.contains(DIMENSION_SCOPE)) { converts.add(createJsonConfig(DIMENSION_SCOPE, DimensionDataAccessConfig.class)); } if (defaultSupportConvert.contains(OWN_CREATED)) { converts.add(createConfig(OWN_CREATED, (action, config) -> new SimpleOwnCreatedDataAccessConfig(action))); } } @Override public DataAccessConfigBuilder create() { return new SimpleDataAccessConfigBuilder(converts); } }
return new DataAccessConfigConverter() { @Override public boolean isSupport(String type, String action, String config) { return supportType.equals(type); } @Override public DataAccessConfig convert(String type, String action, String config) { DataAccessConfig conf = function.apply(action, config); if (conf instanceof AbstractDataAccessConfig) { ((AbstractDataAccessConfig) conf).setAction(action); } return conf; } };
503
126
629
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/token/LocalUserToken.java
LocalUserToken
copy
class LocalUserToken implements UserToken { private static final long serialVersionUID = 1L; private String userId; private String token; private String type = "default"; private volatile TokenState state; private AtomicLong requestTimesCounter = new AtomicLong(0); private volatile long lastRequestTime = System.currentTimeMillis(); private volatile long firstRequestTime = System.currentTimeMillis(); private volatile long requestTimes; private long maxInactiveInterval; @Override public long getMaxInactiveInterval() { return maxInactiveInterval; } public void setMaxInactiveInterval(long maxInactiveInterval) { this.maxInactiveInterval = maxInactiveInterval; } public LocalUserToken(String userId, String token) { this.userId = userId; this.token = token; } public LocalUserToken() { } @Override public String getUserId() { return userId; } @Override public long getRequestTimes() { return requestTimesCounter.get(); } @Override public long getLastRequestTime() { return lastRequestTime; } @Override public long getSignInTime() { return firstRequestTime; } @Override public String getToken() { return token; } @Override public TokenState getState() { if (state == TokenState.normal) { checkExpired(); } return state; } @Override public boolean checkExpired() { if (UserToken.super.checkExpired()) { setState(TokenState.expired); return true; } return false; } public void setState(TokenState state) { this.state = state; } public void setUserId(String userId) { this.userId = userId; } public void setToken(String token) { this.token = token; } public void setFirstRequestTime(long firstRequestTime) { this.firstRequestTime = firstRequestTime; } public void setLastRequestTime(long lastRequestTime) { this.lastRequestTime = lastRequestTime; } public void setRequestTimes(long requestTimes) { this.requestTimes = requestTimes; requestTimesCounter.set(requestTimes); } public void touch() { requestTimesCounter.addAndGet(1); lastRequestTime = System.currentTimeMillis(); } public String getType() { return type; } public void setType(String type) { this.type = type; } public LocalUserToken copy() {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return token.hashCode(); } @Override public boolean equals(Object obj) { return obj != null && hashCode() == obj.hashCode(); } }
LocalUserToken userToken = new LocalUserToken(); userToken.firstRequestTime = firstRequestTime; userToken.lastRequestTime = lastRequestTime; userToken.requestTimesCounter = new AtomicLong(requestTimesCounter.get()); userToken.token = token; userToken.userId = userId; userToken.state = state; userToken.maxInactiveInterval = maxInactiveInterval; userToken.type = type; return userToken;
793
121
914
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/token/ReactiveTokenAuthenticationSupplier.java
ReactiveTokenAuthenticationSupplier
get
class ReactiveTokenAuthenticationSupplier implements ReactiveAuthenticationSupplier { private final TokenAuthenticationManager tokenManager; @Override public Mono<Authentication> get(String userId) { return Mono.empty(); } @Override public Mono<Authentication> get() {<FILL_FUNCTION_BODY>} }
return Mono .deferContextual(context -> context .<ParsedToken>getOrEmpty(ParsedToken.class) .map(t -> tokenManager.getByToken(t.getToken())) .orElse(Mono.empty()));
88
72
160
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/token/UserTokenAuthenticationSupplier.java
UserTokenAuthenticationSupplier
setThirdPartAuthenticationManager
class UserTokenAuthenticationSupplier implements AuthenticationSupplier { private AuthenticationManager defaultAuthenticationManager; private UserTokenManager userTokenManager; private Map<String, ThirdPartAuthenticationManager> thirdPartAuthenticationManager = new HashMap<>(); public UserTokenAuthenticationSupplier(UserTokenManager userTokenManager, AuthenticationManager defaultAuthenticationManager) { this.defaultAuthenticationManager = defaultAuthenticationManager; this.userTokenManager = userTokenManager; } @Autowired(required = false) public void setThirdPartAuthenticationManager(List<ThirdPartAuthenticationManager> thirdPartReactiveAuthenticationManager) {<FILL_FUNCTION_BODY>} @Override public Optional<Authentication> get(String userId) { if (userId == null) { return Optional.empty(); } return get(this.defaultAuthenticationManager, userId); } protected Optional<Authentication> get(ThirdPartAuthenticationManager authenticationManager, String userId) { if (null == userId) { return Optional.empty(); } if (null == authenticationManager) { return this.defaultAuthenticationManager.getByUserId(userId); } return authenticationManager.getByUserId(userId); } protected Optional<Authentication> get(AuthenticationManager authenticationManager, String userId) { if (null == userId) { return Optional.empty(); } if (null == authenticationManager) { authenticationManager = this.defaultAuthenticationManager; } return authenticationManager.getByUserId(userId); } @Override public Optional<Authentication> get() { return ContextUtils.currentContext() .get(ContextKey.of(ParsedToken.class)) .map(t -> userTokenManager.getByToken(t.getToken())) .map(tokenMono -> tokenMono .map(token -> get(thirdPartAuthenticationManager.get(token.getType()), token.getUserId())) .flatMap(Mono::justOrEmpty)) .flatMap(Mono::blockOptional); } }
for (ThirdPartAuthenticationManager manager : thirdPartReactiveAuthenticationManager) { this.thirdPartAuthenticationManager.put(manager.getTokenType(), manager); }
523
44
567
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/token/UserTokenReactiveAuthenticationSupplier.java
UserTokenReactiveAuthenticationSupplier
get
class UserTokenReactiveAuthenticationSupplier implements ReactiveAuthenticationSupplier { private final ReactiveAuthenticationManager defaultAuthenticationManager; private final UserTokenManager userTokenManager; private final Map<String, ThirdPartReactiveAuthenticationManager> thirdPartAuthenticationManager = new HashMap<>(); public UserTokenReactiveAuthenticationSupplier(UserTokenManager userTokenManager, ReactiveAuthenticationManager defaultAuthenticationManager) { this.defaultAuthenticationManager = defaultAuthenticationManager; this.userTokenManager = userTokenManager; } @Autowired(required = false) public void setThirdPartAuthenticationManager(List<ThirdPartReactiveAuthenticationManager> thirdPartReactiveAuthenticationManager) { for (ThirdPartReactiveAuthenticationManager manager : thirdPartReactiveAuthenticationManager) { this.thirdPartAuthenticationManager.put(manager.getTokenType(), manager); } } @Override public Mono<Authentication> get(String userId) { if (userId == null) { return null; } return get(this.defaultAuthenticationManager, userId); } protected Mono<Authentication> get(ThirdPartReactiveAuthenticationManager authenticationManager, String userId) { if (null == userId) { return null; } if (null == authenticationManager) { return this.defaultAuthenticationManager.getByUserId(userId); } return authenticationManager.getByUserId(userId); } protected Mono<Authentication> get(ReactiveAuthenticationManager authenticationManager, String userId) {<FILL_FUNCTION_BODY>} @Override public Mono<Authentication> get() { return Mono .deferContextual(context -> context .<ParsedToken>getOrEmpty(ParsedToken.class) .map(t -> userTokenManager .getByToken(t.getToken()) .flatMap(token -> { //已过期则返回空 if (token.isExpired()) { return Mono.empty(); } if(!token.validate()){ return Mono.empty(); } Mono<Void> before = userTokenManager.touch(token.getToken()); if (token instanceof AuthenticationUserToken) { return before.thenReturn(((AuthenticationUserToken) token).getAuthentication()); } return before.then(get(thirdPartAuthenticationManager.get(token.getType()), token.getUserId())); })) .orElse(Mono.empty())) ; } }
if (null == userId) { return null; } if (null == authenticationManager) { authenticationManager = this.defaultAuthenticationManager; } return authenticationManager.getByUserId(userId);
637
59
696
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/token/redis/RedisTokenAuthenticationManager.java
RedisTokenAuthenticationManager
putAuthentication
class RedisTokenAuthenticationManager implements TokenAuthenticationManager { private final ReactiveRedisOperations<String, Authentication> operations; @SuppressWarnings("all") public RedisTokenAuthenticationManager(ReactiveRedisConnectionFactory connectionFactory) { this(new ReactiveRedisTemplate<>( connectionFactory, RedisSerializationContext.<String, Authentication>newSerializationContext() .key(RedisSerializer.string()) .value((RedisSerializer) RedisSerializer.java()) .hashKey(RedisSerializer.string()) .hashValue(RedisSerializer.java()) .build() )); } public RedisTokenAuthenticationManager(ReactiveRedisOperations<String, Authentication> operations) { this.operations = operations; } @Override public Mono<Authentication> getByToken(String token) { return operations .opsForValue() .get("token-auth:" + token); } @Override public Mono<Void> removeToken(String token) { return operations .delete(token) .then(); } @Override public Mono<Void> putAuthentication(String token, Authentication auth, Duration ttl) {<FILL_FUNCTION_BODY>} }
return ttl.isNegative() ? operations .opsForValue() .set("token-auth:" + token, auth) .then() : operations .opsForValue() .set("token-auth:" + token, auth, ttl) .then() ;
327
79
406
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/token/redis/SimpleUserToken.java
SimpleUserToken
of
class SimpleUserToken implements UserToken { private String userId; private String token; private long requestTimes; private long lastRequestTime; private long signInTime; private TokenState state; private String type; private long maxInactiveInterval; public static SimpleUserToken of(Map<String, Object> map) {<FILL_FUNCTION_BODY>} public TokenState getState() { if (state == TokenState.normal) { checkExpired(); } return state; } @Override public boolean checkExpired() { if (UserToken.super.checkExpired()) { setState(TokenState.expired); return true; } return false; } }
Object authentication = map.get("authentication"); if (authentication instanceof Authentication) { return FastBeanCopier.copy(map, new SimpleAuthenticationUserToken(((Authentication) authentication))); } return FastBeanCopier.copy(map, new SimpleUserToken());
205
71
276
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/twofactor/defaults/DefaultTwoFactorValidator.java
DefaultTwoFactorValidator
verify
class DefaultTwoFactorValidator implements TwoFactorValidator { @Getter private String provider; private Function<String, Boolean> validator; private Supplier<TwoFactorToken> tokenSupplier; @Override public boolean verify(String code, long timeout) {<FILL_FUNCTION_BODY>} @Override public boolean expired() { return tokenSupplier.get().expired(); } }
boolean success = validator.apply(code); if (success) { tokenSupplier.get().generate(timeout); } return success;
114
42
156
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/twofactor/defaults/DefaultTwoFactorValidatorManager.java
DefaultTwoFactorValidatorManager
postProcessAfterInitialization
class DefaultTwoFactorValidatorManager implements TwoFactorValidatorManager, BeanPostProcessor { @Getter @Setter private String defaultProvider = "totp"; private Map<String, TwoFactorValidatorProvider> providers = new HashMap<>(); @Override public TwoFactorValidator getValidator(String userId, String operation, String provider) { if (provider == null) { provider = defaultProvider; } TwoFactorValidatorProvider validatorProvider = providers.get(provider); if (validatorProvider == null) { return new UnsupportedTwoFactorValidator(provider); } return validatorProvider.createTwoFactorValidator(userId, operation); } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>} }
if (bean instanceof TwoFactorValidatorProvider) { TwoFactorValidatorProvider provider = ((TwoFactorValidatorProvider) bean); providers.put(provider.getProvider(), provider); if (provider.getProvider().equalsIgnoreCase(defaultProvider)) { providers.put("default", provider); } } return bean;
249
85
334
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/twofactor/defaults/DefaultTwoFactorValidatorProvider.java
DefaultTwoFactorValidatorProvider
createTwoFactorValidator
class DefaultTwoFactorValidatorProvider implements TwoFactorValidatorProvider { private String provider; private TwoFactorTokenManager twoFactorTokenManager; public DefaultTwoFactorValidatorProvider(String provider, TwoFactorTokenManager twoFactorTokenManager) { this.provider = provider; this.twoFactorTokenManager = twoFactorTokenManager; } protected abstract boolean validate(String userId, String code); @Override public TwoFactorValidator createTwoFactorValidator(String userId, String operation) {<FILL_FUNCTION_BODY>} }
return new DefaultTwoFactorValidator(getProvider(), code -> validate(userId, code), () -> twoFactorTokenManager.getToken(userId, operation));
145
43
188
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/twofactor/defaults/HashMapTwoFactorTokenManager.java
TwoFactorTokenInfo
getToken
class TwoFactorTokenInfo implements Serializable { private static final long serialVersionUID = -5246224779564760241L; private volatile long lastRequestTime = System.currentTimeMillis(); private long timeOut; private boolean isExpire() { return System.currentTimeMillis() - lastRequestTime >= timeOut; } } private String createTokenInfoKey(String userId, String operation) { return userId + "_" + operation; } private TwoFactorTokenInfo getTokenInfo(String userId, String operation) { return Optional.ofNullable(tokens.get(createTokenInfoKey(userId, operation))) .map(WeakReference::get) .orElse(null); } @Override public TwoFactorToken getToken(String userId, String operation) {<FILL_FUNCTION_BODY>
return new TwoFactorToken() { private static final long serialVersionUID = -5148037320548431456L; @Override public void generate(long timeout) { TwoFactorTokenInfo info = new TwoFactorTokenInfo(); info.timeOut = timeout; tokens.put(createTokenInfoKey(userId, operation), new WeakReference<>(info)); } @Override public boolean expired() { TwoFactorTokenInfo info = getTokenInfo(userId, operation); if (info == null) { return true; } if (info.isExpire()) { tokens.remove(createTokenInfoKey(userId, operation)); return true; } info.lastRequestTime = System.currentTimeMillis(); return false; } };
235
222
457
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/aop/AopAuthorizingController.java
AopAuthorizingController
handleReactive0
class AopAuthorizingController extends StaticMethodMatcherPointcutAdvisor implements CommandLineRunner, MethodInterceptor { private static final long serialVersionUID = 1154190623020670672L; @Autowired private ApplicationEventPublisher eventPublisher; @Autowired private AuthorizingHandler authorizingHandler; @Autowired private AopMethodAuthorizeDefinitionParser aopMethodAuthorizeDefinitionParser; // private DefaultAopMethodAuthorizeDefinitionParser defaultParser = new DefaultAopMethodAuthorizeDefinitionParser(); private boolean autoParse = false; public void setAutoParse(boolean autoParse) { this.autoParse = autoParse; } protected Publisher<?> handleReactive0(AuthorizeDefinition definition, MethodInterceptorHolder holder, AuthorizingContext context, Supplier<? extends Publisher<?>> invoker) {<FILL_FUNCTION_BODY>} @SneakyThrows private <T> T doProceed(MethodInvocation invocation) { return (T) invocation.proceed(); } @Override public Object invoke(MethodInvocation methodInvocation) throws Throwable { MethodInterceptorHolder holder = MethodInterceptorHolder.create(methodInvocation); MethodInterceptorContext paramContext = holder.createParamContext(); AuthorizeDefinition definition = aopMethodAuthorizeDefinitionParser.parse(methodInvocation.getThis().getClass(), methodInvocation.getMethod(), paramContext); Object result = null; boolean isControl = false; if (null != definition && !definition.isEmpty()) { AuthorizingContext context = new AuthorizingContext(); context.setDefinition(definition); context.setParamContext(paramContext); Class<?> returnType = methodInvocation.getMethod().getReturnType(); //handle reactive method if (Publisher.class.isAssignableFrom(returnType)) { Publisher publisher = handleReactive0(definition, holder, context, () -> doProceed(methodInvocation)); if (Mono.class.isAssignableFrom(returnType)) { return Mono.from(publisher); } else if (Flux.class.isAssignableFrom(returnType)) { return Flux.from(publisher); } throw new UnsupportedOperationException("unsupported reactive type:" + returnType); } Authentication authentication = Authentication.current().orElseThrow(UnAuthorizedException::new); context.setAuthentication(authentication); isControl = true; Phased dataAccessPhased = definition.getResources().getPhased(); if (definition.getPhased() == Phased.before) { //RDAC before authorizingHandler.handRBAC(context); //方法调用前验证数据权限 if (dataAccessPhased == Phased.before) { authorizingHandler.handleDataAccess(context); } result = methodInvocation.proceed(); //方法调用后验证数据权限 if (dataAccessPhased == Phased.after) { context.setParamContext(holder.createParamContext(result)); authorizingHandler.handleDataAccess(context); } } else { //方法调用前验证数据权限 if (dataAccessPhased == Phased.before) { authorizingHandler.handleDataAccess(context); } result = methodInvocation.proceed(); context.setParamContext(holder.createParamContext(result)); authorizingHandler.handRBAC(context); //方法调用后验证数据权限 if (dataAccessPhased == Phased.after) { authorizingHandler.handleDataAccess(context); } } } if (!isControl) { result = methodInvocation.proceed(); } return result; } public AopAuthorizingController(AuthorizingHandler authorizingHandler, AopMethodAuthorizeDefinitionParser aopMethodAuthorizeDefinitionParser) { this.authorizingHandler = authorizingHandler; this.aopMethodAuthorizeDefinitionParser = aopMethodAuthorizeDefinitionParser; setAdvice(this); } @Override public boolean matches(Method method, Class<?> aClass) { Authorize authorize; boolean support = AnnotationUtils.findAnnotation(aClass, Controller.class) != null || AnnotationUtils.findAnnotation(aClass, RestController.class) != null || ((authorize = AnnotationUtils.findAnnotation(aClass, method, Authorize.class)) != null && !authorize.ignore() ); if (support && autoParse) { aopMethodAuthorizeDefinitionParser.parse(aClass, method); } return support; } @Override public void run(String... args) throws Exception { if (autoParse) { List<AuthorizeDefinition> definitions = aopMethodAuthorizeDefinitionParser.getAllParsed() .stream() .filter(def -> !def.isEmpty()) .collect(Collectors.toList()); log.info("publish AuthorizeDefinitionInitializedEvent,definition size:{}", definitions.size()); eventPublisher.publishEvent(new AuthorizeDefinitionInitializedEvent(definitions)); // defaultParser.destroy(); } } }
return Authentication .currentReactive() .switchIfEmpty(Mono.error(UnAuthorizedException::new)) .flatMapMany(auth -> { context.setAuthentication(auth); Function<Runnable, Publisher> afterRuner = runnable -> { MethodInterceptorContext interceptorContext = holder.createParamContext(invoker.get()); context.setParamContext(interceptorContext); runnable.run(); return (Publisher<?>) interceptorContext.getInvokeResult(); }; if (context.getDefinition().getPhased() != Phased.after) { authorizingHandler.handRBAC(context); if (context.getDefinition().getResources().getPhased() != Phased.after) { authorizingHandler.handleDataAccess(context); return invoker.get(); } else { return afterRuner.apply(() -> authorizingHandler.handleDataAccess(context)); } } else { if (context.getDefinition().getResources().getPhased() != Phased.after) { authorizingHandler.handleDataAccess(context); return invoker.get(); } else { return afterRuner.apply(() -> { authorizingHandler.handRBAC(context); authorizingHandler.handleDataAccess(context); }); } } });
1,364
354
1,718
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/aop/DefaultAopMethodAuthorizeDefinitionParser.java
DefaultAopMethodAuthorizeDefinitionParser
parse
class DefaultAopMethodAuthorizeDefinitionParser implements AopMethodAuthorizeDefinitionParser { private final Map<CacheKey, AuthorizeDefinition> cache = new ConcurrentHashMap<>(); private List<AopMethodAuthorizeDefinitionCustomizerParser> parserCustomizers; private static final Set<String> excludeMethodName = new HashSet<>(Arrays.asList("toString", "clone", "hashCode", "getClass")); @Autowired(required = false) public void setParserCustomizers(List<AopMethodAuthorizeDefinitionCustomizerParser> parserCustomizers) { this.parserCustomizers = parserCustomizers; } @Override public List<AuthorizeDefinition> getAllParsed() { return new ArrayList<>(cache.values()); } @Override @SuppressWarnings("all") public AuthorizeDefinition parse(Class<?> target, Method method, MethodInterceptorContext context) {<FILL_FUNCTION_BODY>} public CacheKey buildCacheKey(Class<?> target, Method method) { return new CacheKey(ClassUtils.getUserClass(target), method); } @EqualsAndHashCode static class CacheKey { private final Class<?> type; private final Method method; public CacheKey(Class<?> type, Method method) { this.type = type; this.method = method; } } public void destroy() { cache.clear(); } static boolean isIgnoreMethod(Method method) { //不是public的方法 if(!Modifier.isPublic(method.getModifiers())){ return true; } //没有以下注解 return null == AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class) && null == AnnotatedElementUtils.findMergedAnnotation(method, ResourceAction.class); } }
if (excludeMethodName.contains(method.getName())) { return null; } CacheKey key = buildCacheKey(target, method); AuthorizeDefinition definition = cache.get(key); if (definition instanceof EmptyAuthorizeDefinition) { return null; } if (null != definition) { return definition; } //使用自定义 if (!CollectionUtils.isEmpty(parserCustomizers)) { definition = parserCustomizers .stream() .map(customizer -> customizer.parse(target, method, context)) .filter(Objects::nonNull) .findAny().orElse(null); if (definition instanceof EmptyAuthorizeDefinition) { return null; } if (definition != null) { return definition; } } Authorize annotation = AnnotationUtils.findAnnotation(target, method, Authorize.class); if (isIgnoreMethod(method) || (annotation != null && annotation.ignore())) { cache.put(key, EmptyAuthorizeDefinition.instance); return null; } synchronized (cache) { return cache.computeIfAbsent(key, (__) -> { return DefaultBasicAuthorizeDefinition.from(target, method); }); }
475
327
802
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/configuration/AuthorizingHandlerAutoConfiguration.java
DataAccessHandlerProcessor
postProcessAfterInitialization
class DataAccessHandlerProcessor implements BeanPostProcessor { @Autowired private DefaultDataAccessController defaultDataAccessController; @Override public Object postProcessBeforeInitialization(Object bean, String beanName) { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) {<FILL_FUNCTION_BODY>} }
if (bean instanceof DataAccessHandler) { defaultDataAccessController.addHandler(((DataAccessHandler) bean)); } return bean;
100
39
139
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/configuration/BasicAuthorizationTokenParser.java
BasicAuthorizationTokenParser
parseToken
class BasicAuthorizationTokenParser implements UserTokenForTypeParser { private final AuthenticationManager authenticationManager; private final UserTokenManager userTokenManager; @Override public String getTokenType() { return "basic"; } public BasicAuthorizationTokenParser(AuthenticationManager authenticationManager, UserTokenManager userTokenManager) { this.authenticationManager = authenticationManager; this.userTokenManager = userTokenManager; } @Override public ParsedToken parseToken(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
String authorization = request.getHeader("Authorization"); if (authorization == null) { return null; } if (authorization.contains(" ")) { String[] info = authorization.split("[ ]"); if (info[0].equalsIgnoreCase(getTokenType())) { authorization = info[1]; } } try { String usernameAndPassword = new String(Base64.decodeBase64(authorization)); UserToken token = userTokenManager.getByToken(usernameAndPassword).blockOptional().orElse(null); if (token != null && token.isNormal()) { return new ParsedToken() { @Override public String getToken() { return usernameAndPassword; } @Override public String getType() { return getTokenType(); } }; } if (usernameAndPassword.contains(":")) { String[] arr = usernameAndPassword.split("[:]"); Authentication authentication = authenticationManager .authenticate(new PlainTextUsernamePasswordAuthenticationRequest(arr[0], arr[1])) ; if (authentication != null) { return new AuthorizedToken() { @Override public String getUserId() { return authentication.getUser().getId(); } @Override public String getToken() { return usernameAndPassword; } @Override public String getType() { return getTokenType(); } @Override public long getMaxInactiveInterval() { //60分钟有效期 return 60 * 60 * 1000L; } }; } } } catch (Exception e) { return null; } return null;
144
455
599
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/configuration/WebMvcAuthorizingConfiguration.java
WebMvcAuthorizingConfiguration
webUserTokenInterceptorConfigurer
class WebMvcAuthorizingConfiguration { @Bean @Order(Ordered.HIGHEST_PRECEDENCE) @ConditionalOnBean(AopMethodAuthorizeDefinitionParser.class) public WebMvcConfigurer webUserTokenInterceptorConfigurer(UserTokenManager userTokenManager, AopMethodAuthorizeDefinitionParser parser, List<UserTokenParser> userTokenParser) {<FILL_FUNCTION_BODY>} @Bean public UserOnSignIn userOnSignIn(UserTokenManager userTokenManager) { return new UserOnSignIn(userTokenManager); } @Bean public UserOnSignOut userOnSignOut(UserTokenManager userTokenManager) { return new UserOnSignOut(userTokenManager); } @SuppressWarnings("all") @ConfigurationProperties(prefix = "hsweb.authorize.token.default") public ServletUserTokenGenPar servletUserTokenGenPar() { return new ServletUserTokenGenPar(); } @Bean @ConditionalOnMissingBean(UserTokenParser.class) public UserTokenParser userTokenParser() { return new SessionIdUserTokenParser(); } @Bean public SessionIdUserTokenGenerator sessionIdUserTokenGenerator() { return new SessionIdUserTokenGenerator(); } @Bean @ConditionalOnProperty(prefix = "hsweb.authorize.two-factor", name = "enable", havingValue = "true") @Order(100) public WebMvcConfigurer twoFactorHandlerConfigurer(TwoFactorValidatorManager manager) { return new WebMvcConfigurer() { @Override public void addInterceptors(@Nonnull InterceptorRegistry registry) { registry.addInterceptor(new TwoFactorHandlerInterceptorAdapter(manager)); } }; } }
return new WebMvcConfigurer() { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new WebUserTokenInterceptor(userTokenManager, userTokenParser, parser)); } };
472
69
541
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/define/AopAuthorizeDefinitionParser.java
AopAuthorizeDefinitionParser
initMethodDataAccessAnnotation
class AopAuthorizeDefinitionParser { private static final Set<Class<? extends Annotation>> types = new HashSet<>(Arrays.asList( Authorize.class, DataAccess.class, Dimension.class, Resource.class, ResourceAction.class, DataAccessType.class )); private final Set<Annotation> methodAnnotation; private final Set<Annotation> classAnnotation; private final Map<Class<? extends Annotation>, List<Annotation>> classAnnotationGroup; private final Map<Class<? extends Annotation>, List<Annotation>> methodAnnotationGroup; private final DefaultBasicAuthorizeDefinition definition; AopAuthorizeDefinitionParser(Class<?> targetClass, Method method) { definition = new DefaultBasicAuthorizeDefinition(); definition.setTargetClass(targetClass); definition.setTargetMethod(method); methodAnnotation = AnnotatedElementUtils.findAllMergedAnnotations(method, types); classAnnotation = AnnotatedElementUtils.findAllMergedAnnotations(targetClass, types); classAnnotationGroup = classAnnotation .stream() .collect(Collectors.groupingBy(Annotation::annotationType)); methodAnnotationGroup = methodAnnotation .stream() .collect(Collectors.groupingBy(Annotation::annotationType)); } private void initClassAnnotation() { for (Annotation annotation : classAnnotation) { if (annotation instanceof Authorize) { definition.putAnnotation(((Authorize) annotation)); } if (annotation instanceof Resource) { definition.putAnnotation(((Resource) annotation)); } } } private void initMethodAnnotation() { for (Annotation annotation : methodAnnotation) { if (annotation instanceof Authorize) { definition.putAnnotation(((Authorize) annotation)); } if (annotation instanceof Resource) { definition.putAnnotation(((Resource) annotation)); } if (annotation instanceof Dimension) { definition.putAnnotation(((Dimension) annotation)); } } } private void initClassDataAccessAnnotation() { for (Annotation annotation : classAnnotation) { if (annotation instanceof DataAccessType || annotation instanceof DataAccess) { for (ResourceDefinition resource : definition.getResources().getResources()) { for (ResourceActionDefinition action : resource.getActions()) { if (annotation instanceof DataAccessType) { definition.putAnnotation(action, (DataAccessType) annotation); } else { definition.putAnnotation(action, (DataAccess) annotation); } } } } } } private void initMethodDataAccessAnnotation() {<FILL_FUNCTION_BODY>} AopAuthorizeDefinition parse() { //没有任何注解 if (CollectionUtils.isEmpty(classAnnotation) && CollectionUtils.isEmpty(methodAnnotation)) { return EmptyAuthorizeDefinition.instance; } initClassAnnotation(); initClassDataAccessAnnotation(); initMethodAnnotation(); initMethodDataAccessAnnotation(); return definition; } private <T extends Annotation> Stream<T> getAnnotationByType(Class<T> type) { return Optional.ofNullable(methodAnnotationGroup.getOrDefault(type, classAnnotationGroup.get(type))) .map(Collection::stream) .orElseGet(Stream::empty) .map(type::cast); } }
for (Annotation annotation : methodAnnotation) { if (annotation instanceof ResourceAction) { getAnnotationByType(Resource.class) .map(res -> definition.getResources().getResource(res.id()).orElse(null)) .filter(Objects::nonNull) .forEach(res -> { ResourceAction ra = (ResourceAction) annotation; ResourceActionDefinition action = definition.putAnnotation(res, ra); getAnnotationByType(DataAccessType.class) .findFirst() .ifPresent(dat -> definition.putAnnotation(action, dat)); }); } Optional<ResourceActionDefinition> actionDefinition = getAnnotationByType(Resource.class) .map(res -> definition.getResources().getResource(res.id()).orElse(null)) .filter(Objects::nonNull) .flatMap(res -> getAnnotationByType(ResourceAction.class) .map(ra -> res.getAction(ra.id()) .orElse(null)) ) .filter(Objects::nonNull) .findFirst(); if (annotation instanceof DataAccessType) { actionDefinition.ifPresent(ra -> definition.putAnnotation(ra, (DataAccessType) annotation)); } if (annotation instanceof DataAccess) { actionDefinition.ifPresent(ra -> { definition.putAnnotation(ra, (DataAccess) annotation); getAnnotationByType(DataAccessType.class) .findFirst() .ifPresent(dat -> definition.putAnnotation(ra, dat)); }); } }
853
397
1,250
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/define/DefaultBasicAuthorizeDefinition.java
DefaultBasicAuthorizeDefinition
putAnnotation
class DefaultBasicAuthorizeDefinition implements AopAuthorizeDefinition { @JsonIgnore private Class<?> targetClass; @JsonIgnore private Method targetMethod; private ResourcesDefinition resources = new ResourcesDefinition(); private DimensionsDefinition dimensions = new DimensionsDefinition(); private String message = "error.access_denied"; private Phased phased = Phased.before; @Override public boolean isEmpty() { return false; } private static final Set<Class<? extends Annotation>> types = new HashSet<>(Arrays.asList( Authorize.class, DataAccess.class, Dimension.class, Resource.class, ResourceAction.class, DataAccessType.class )); public static AopAuthorizeDefinition from(Class<?> targetClass, Method method) { AopAuthorizeDefinitionParser parser = new AopAuthorizeDefinitionParser(targetClass, method); return parser.parse(); } public void putAnnotation(Authorize ann) {<FILL_FUNCTION_BODY>} public void putAnnotation(Dimension ann) { if (ann.ignore()) { getDimensions().getDimensions().clear(); return; } DimensionDefinition definition = new DimensionDefinition(); definition.setTypeId(ann.type()); definition.setDimensionId(new HashSet<>(Arrays.asList(ann.id()))); definition.setLogical(ann.logical()); getDimensions().addDimension(definition); } public void putAnnotation(Resource ann) { ResourceDefinition resource = new ResourceDefinition(); resource.setId(ann.id()); resource.setName(ann.name()); resource.setLogical(ann.logical()); resource.setPhased(ann.phased()); resource.setDescription(String.join("\n", ann.description())); for (ResourceAction action : ann.actions()) { putAnnotation(resource, action); } resource.setGroup(new ArrayList<>(Arrays.asList(ann.group()))); setPhased(ann.phased()); getResources().setPhased(ann.phased()); resources.addResource(resource, ann.merge()); } public ResourceActionDefinition putAnnotation(ResourceDefinition definition, ResourceAction ann) { ResourceActionDefinition actionDefinition = new ResourceActionDefinition(); actionDefinition.setId(ann.id()); actionDefinition.setName(ann.name()); actionDefinition.setDescription(String.join("\n", ann.description())); for (DataAccess dataAccess : ann.dataAccess()) { putAnnotation(actionDefinition, dataAccess); } definition.addAction(actionDefinition); return actionDefinition; } public void putAnnotation(ResourceActionDefinition definition, DataAccess ann) { if (ann.ignore()) { return; } DataAccessTypeDefinition typeDefinition = new DataAccessTypeDefinition(); for (DataAccessType dataAccessType : ann.type()) { if (dataAccessType.ignore()) { continue; } typeDefinition.setId(dataAccessType.id()); typeDefinition.setName(dataAccessType.name()); typeDefinition.setController(dataAccessType.controller()); typeDefinition.setConfiguration(dataAccessType.configuration()); typeDefinition.setDescription(String.join("\n", dataAccessType.description())); } if (StringUtils.isEmpty(typeDefinition.getId())) { return; } definition.getDataAccess() .getDataAccessTypes() .add(typeDefinition); } public void putAnnotation(ResourceActionDefinition definition, DataAccessType dataAccessType) { if (dataAccessType.ignore()) { return; } DataAccessTypeDefinition typeDefinition = new DataAccessTypeDefinition(); typeDefinition.setId(dataAccessType.id()); typeDefinition.setName(dataAccessType.name()); typeDefinition.setController(dataAccessType.controller()); typeDefinition.setConfiguration(dataAccessType.configuration()); typeDefinition.setDescription(String.join("\n", dataAccessType.description())); definition.getDataAccess() .getDataAccessTypes() .add(typeDefinition); } }
if (!ann.merge()) { getResources().getResources().clear(); getDimensions().getDimensions().clear(); } setPhased(ann.phased()); getResources().setPhased(ann.phased()); for (Resource resource : ann.resources()) { putAnnotation(resource); } for (Dimension dimension : ann.dimension()) { putAnnotation(dimension); }
1,060
109
1,169
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/embed/EmbedAuthenticationInfo.java
PermissionInfo
toAuthentication
class PermissionInfo { private String id; private String name; private Set<String> actions = new HashSet<>(); private List<Map<String, Object>> dataAccesses = new ArrayList<>(); } public Authentication toAuthentication(DataAccessConfigBuilderFactory factory) {<FILL_FUNCTION_BODY>
SimpleAuthentication authentication = new SimpleAuthentication(); SimpleUser user = new SimpleUser(); user.setId(id); user.setName(name); user.setUsername(username); user.setUserType(type); authentication.setUser(user); authentication.getDimensions().addAll(roles); List<Permission> permissionList = new ArrayList<>(); permissionList.addAll(permissions.stream() .map(info -> { SimplePermission permission = new SimplePermission(); permission.setId(info.getId()); permission.setName(info.getName()); permission.setActions(info.getActions()); permission.setDataAccesses(info.getDataAccesses() .stream().map(conf -> factory.create() .fromMap(conf) .build()).collect(Collectors.toSet())); return permission; }) .collect(Collectors.toList())); permissionList.addAll(permissionsSimple.entrySet().stream() .map(entry -> { SimplePermission permission = new SimplePermission(); permission.setId(entry.getKey()); permission.setActions(new HashSet<>(entry.getValue())); return permission; }).collect(Collectors.toList())); authentication.setPermissions(permissionList); return authentication;
85
334
419
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/embed/EmbedAuthenticationProperties.java
EmbedAuthenticationProperties
afterPropertiesSet
class EmbedAuthenticationProperties implements InitializingBean { private Map<String, Authentication> authentications = new HashMap<>(); @Getter @Setter private Map<String, EmbedAuthenticationInfo> users = new HashMap<>(); @Autowired(required = false) private DataAccessConfigBuilderFactory dataAccessConfigBuilderFactory = new SimpleDataAccessConfigBuilderFactory(); @Override public void afterPropertiesSet() {<FILL_FUNCTION_BODY>} public Authentication authenticate(AuthenticationRequest request) { if (MapUtils.isEmpty(users)) { return null; } if (request instanceof PlainTextUsernamePasswordAuthenticationRequest) { PlainTextUsernamePasswordAuthenticationRequest pwdReq = ((PlainTextUsernamePasswordAuthenticationRequest) request); for (EmbedAuthenticationInfo user : users.values()) { if (pwdReq.getUsername().equals(user.getUsername())) { if (pwdReq.getPassword().equals(user.getPassword())) { return user.toAuthentication(dataAccessConfigBuilderFactory); } return null; } } return null; } throw new UnsupportedOperationException("不支持的授权请求:" + request); } public Optional<Authentication> getAuthentication(String userId) { return Optional.ofNullable(authentications.get(userId)); } }
users.forEach((id, properties) -> { if (StringUtils.isEmpty(properties.getId())) { properties.setId(id); } for (EmbedAuthenticationInfo.PermissionInfo permissionInfo : properties.getPermissions()) { for (Map<String, Object> objectMap : permissionInfo.getDataAccesses()) { for (Map.Entry<String, Object> stringObjectEntry : objectMap.entrySet()) { if (stringObjectEntry.getValue() instanceof Map) { Map<?, ?> mapVal = ((Map) stringObjectEntry.getValue()); boolean maybeIsList = mapVal .keySet() .stream() .allMatch(org.hswebframework.utils.StringUtils::isInt); if (maybeIsList) { stringObjectEntry.setValue(mapVal.values()); } } } } } authentications.put(id, properties.toAuthentication(dataAccessConfigBuilderFactory)); });
354
243
597
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/embed/EmbedReactiveAuthenticationManager.java
EmbedReactiveAuthenticationManager
authenticate
class EmbedReactiveAuthenticationManager implements ReactiveAuthenticationManagerProvider { private final EmbedAuthenticationProperties properties; @Override public Mono<Authentication> authenticate(Mono<AuthenticationRequest> request) {<FILL_FUNCTION_BODY>} @Override public Mono<Authentication> getByUserId(String userId) { return Mono.justOrEmpty(properties.getAuthentication(userId)); } }
if (MapUtils.isEmpty(properties.getUsers())) { return Mono.empty(); } return request. handle((req, sink) -> { Authentication auth = properties.authenticate(req); if (auth != null) { sink.next(auth); } });
111
84
195
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/AuthorizationLoginLoggerInfoHandler.java
AuthorizationLoginLoggerInfoHandler
fillLoggerInfoAuth
class AuthorizationLoginLoggerInfoHandler { @EventListener public void fillLoggerInfoAuth(AuthorizationSuccessEvent event) {<FILL_FUNCTION_BODY>} }
event.async( //填充操作日志用户认证信息 Mono.deferContextual(ctx -> { ctx.<AccessLoggerInfo>getOrEmpty(AccessLoggerInfo.class) .ifPresent(loggerInfo -> { Authentication auth = event.getAuthentication(); loggerInfo.putContext("userId", auth.getUser().getId()); loggerInfo.putContext("username", auth.getUser().getUsername()); loggerInfo.putContext("userName", auth.getUser().getName()); }); // FIXME: 2024/3/26 未传递用户维度信息,如有需要也可通过上下文传递 return Mono.empty(); }) );
44
183
227
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/DefaultAuthorizingHandler.java
DefaultAuthorizingHandler
handleDataAccess
class DefaultAuthorizingHandler implements AuthorizingHandler { private DataAccessController dataAccessController; private ApplicationEventPublisher eventPublisher; public DefaultAuthorizingHandler(DataAccessController dataAccessController) { this.dataAccessController = dataAccessController; } public DefaultAuthorizingHandler() { } public void setDataAccessController(DataAccessController dataAccessController) { this.dataAccessController = dataAccessController; } @Autowired public void setEventPublisher(ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } @Override public void handRBAC(AuthorizingContext context) { if (handleEvent(context, HandleType.RBAC)) { return; } //进行rdac权限控制 handleRBAC(context.getAuthentication(), context.getDefinition()); } private boolean handleEvent(AuthorizingContext context, HandleType type) { if (null != eventPublisher) { AuthorizingHandleBeforeEvent event = new AuthorizingHandleBeforeEvent(context, type); eventPublisher.publishEvent(event); if (!event.isExecute()) { if (event.isAllow()) { return true; } else { throw new AccessDenyException(event.getMessage()); } } } return false; } public void handleDataAccess(AuthorizingContext context) {<FILL_FUNCTION_BODY>} protected void handleRBAC(Authentication authentication, AuthorizeDefinition definition) { ResourcesDefinition resources = definition.getResources(); if (!resources.hasPermission(authentication)) { throw new AccessDenyException(definition.getMessage(),definition.getDescription()); } } }
if (dataAccessController == null) { log.warn("dataAccessController is null,skip result access control!"); return; } if (context.getDefinition().getResources() == null) { return; } if (handleEvent(context, HandleType.DATA)) { return; } DataAccessController finalAccessController = dataAccessController; Authentication autz = context.getAuthentication(); boolean isAccess = context.getDefinition() .getResources() .getDataAccessResources() .stream() .allMatch(resource -> { Permission permission = autz.getPermission(resource.getId()).orElseThrow(AccessDenyException::new); return resource.getDataAccessAction() .stream() .allMatch(act -> permission.getDataAccesses(act.getId()) .stream() .allMatch(dataAccessConfig -> finalAccessController.doAccess(dataAccessConfig, context))); }); if (!isAccess) { throw new AccessDenyException(context.getDefinition().getMessage()); }
447
275
722
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/UserAllowPermissionHandler.java
UserAllowPermissionHandler
handEvent
class UserAllowPermissionHandler { @Getter @Setter private Map<String, Map<String, String>> allows = new HashMap<>(); private final PathMatcher pathMatcher = new AntPathMatcher("."); @EventListener public void handEvent(AuthorizingHandleBeforeEvent event) {<FILL_FUNCTION_BODY>} }
if (allows.isEmpty() || event.getHandleType() == HandleType.DATA) { return; } AuthorizingContext context = event.getContext(); // class full name.method String path = ClassUtils.getUserClass(context.getParamContext() .getTarget()) .getName().concat(".") .concat(context.getParamContext() .getMethod().getName()); AtomicBoolean allow = new AtomicBoolean(); for (Map.Entry<String, Map<String, String>> entry : allows.entrySet()) { String dimension = entry.getKey(); if ("user".equals(dimension)) { String userId = context.getAuthentication().getUser().getId(); allow.set(Optional.ofNullable(entry.getValue().get(userId)) .filter(pattern -> "*".equals(pattern) || pathMatcher.match(pattern, path)) .isPresent()); } else { //其他维度 for (Map.Entry<String, String> confEntry : entry.getValue().entrySet()) { context.getAuthentication() .getDimension(dimension, confEntry.getKey()) .ifPresent(dim -> { String pattern = confEntry.getValue(); allow.set("*".equals(pattern) || pathMatcher.match(confEntry.getValue(), path)); }); } } if (allow.get()) { event.setAllow(true); return; } }
92
372
464
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/access/DataAccessHandlerContext.java
DataAccessHandlerContext
of
class DataAccessHandlerContext { private Class<?> entityType; private ReactiveRepository<?, Object> repository; private Authentication authentication; private List<Dimension> dimensions; private MethodInterceptorContext paramContext; private AuthorizeDefinition definition; public static DataAccessHandlerContext of(AuthorizingContext context, String type) {<FILL_FUNCTION_BODY>} }
DataAccessHandlerContext requestContext = new DataAccessHandlerContext(); Authentication authentication = context.getAuthentication(); requestContext.setDimensions(authentication.getDimensions(type)); requestContext.setAuthentication(context.getAuthentication()); requestContext.setParamContext(context.getParamContext()); requestContext.setDefinition(context.getDefinition()); Object target = context.getParamContext().getTarget(); Class entityType = ClassUtils.getGenericType(org.springframework.util.ClassUtils.getUserClass(target)); if (entityType != Object.class) { requestContext.setEntityType(entityType); } if (target instanceof ReactiveQueryController) { requestContext.setRepository(((ReactiveQueryController) target).getRepository()); } else if (target instanceof ReactiveSaveController) { requestContext.setRepository(((ReactiveSaveController) target).getRepository()); } else if (target instanceof ReactiveDeleteController) { requestContext.setRepository(((ReactiveDeleteController) target).getRepository()); } else if (target instanceof ReactiveServiceQueryController) { requestContext.setRepository(((ReactiveServiceQueryController) target).getService().getRepository()); } else if (target instanceof ReactiveServiceSaveController) { requestContext.setRepository(((ReactiveServiceSaveController) target).getService().getRepository()); } else if (target instanceof ReactiveServiceDeleteController) { requestContext.setRepository(((ReactiveServiceDeleteController) target).getService().getRepository()); } // TODO: 2019-11-18 not reactive implements return requestContext;
105
401
506
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/access/DefaultDataAccessController.java
DefaultDataAccessController
doAccess
class DefaultDataAccessController implements DataAccessController { private DataAccessController parent; private List<DataAccessHandler> handlers = new LinkedList<>(); public DefaultDataAccessController() { this(null); } public DefaultDataAccessController(DataAccessController parent) { if (parent == this) { throw new UnsupportedOperationException(); } this.parent = parent; addHandler(new FieldFilterDataAccessHandler()) .addHandler(new DimensionDataAccessHandler()); } @Override public boolean doAccess(DataAccessConfig access, AuthorizingContext context) {<FILL_FUNCTION_BODY>} public DefaultDataAccessController addHandler(DataAccessHandler handler) { handlers.add(handler); return this; } public void setHandlers(List<DataAccessHandler> handlers) { this.handlers = handlers; } public List<DataAccessHandler> getHandlers() { return handlers; } }
if (parent != null) { parent.doAccess(access, context); } return handlers.stream() .filter(handler -> handler.isSupport(access)) .allMatch(handler -> handler.handle(access, context));
256
67
323
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/access/FieldFilterDataAccessHandler.java
FieldFilterDataAccessHandler
handle
class FieldFilterDataAccessHandler implements DataAccessHandler { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public boolean isSupport(DataAccessConfig access) { return access instanceof FieldFilterDataAccessConfig; } @Override public boolean handle(DataAccessConfig access, AuthorizingContext context) {<FILL_FUNCTION_BODY>} protected void applyUpdateParam(FieldFilterDataAccessConfig config, Object... parameter) { for (Object data : parameter) { for (String field : config.getFields()) { try { //设置值为null,跳过修改 BeanUtilsBean.getInstance() .getPropertyUtils() .setProperty(data, field, null); } catch (Exception e) { logger.warn("can't set {} null", field, e); } } } } /** * @param accesses 不可操作的字段 * @param params 参数上下文 * @return true * @see BeanUtilsBean * @see org.apache.commons.beanutils.PropertyUtilsBean */ protected boolean doUpdateAccess(FieldFilterDataAccessConfig accesses, AuthorizingContext params) { boolean reactive = params.getParamContext().handleReactiveArguments(publisher -> { if (publisher instanceof Mono) { return Mono.from(publisher) .doOnNext(data -> applyUpdateParam(accesses, data)); } if (publisher instanceof Flux) { return Flux.from(publisher) .doOnNext(data -> applyUpdateParam(accesses, data)); } return publisher; }); if (reactive) { return true; } applyUpdateParam(accesses, params.getParamContext().getArguments()); return true; } @SuppressWarnings("all") protected void applyQueryParam(FieldFilterDataAccessConfig config, Object param) { if (param instanceof QueryParam) { Set<String> denyFields = config.getFields(); ((QueryParam) param).excludes(denyFields.toArray(new String[0])); return; } Object r = InvokeResultUtils.convertRealResult(param); if (r instanceof Collection) { ((Collection) r).forEach(o -> setObjectPropertyNull(o, config.getFields())); } else { setObjectPropertyNull(r, config.getFields()); } } @SuppressWarnings("all") protected boolean doQueryAccess(FieldFilterDataAccessConfig access, AuthorizingContext context) { if (context.getDefinition().getResources().getPhased() == Phased.before) { boolean reactive = context .getParamContext() .handleReactiveArguments(publisher -> { if (publisher instanceof Mono) { return Mono.from(publisher) .doOnNext(param -> { applyQueryParam(access, param); }); } return publisher; }); if (reactive) { return true; } for (Object argument : context.getParamContext().getArguments()) { applyQueryParam(access, argument); } } else { if (context.getParamContext().getInvokeResult() instanceof Publisher) { context.getParamContext().setInvokeResult( Flux.from((Publisher<?>) context.getParamContext().getInvokeResult()) .doOnNext(result -> { applyQueryParam(access, result); }) ); return true; } applyQueryParam(access, context.getParamContext().getInvokeResult()); } return true; } protected void setObjectPropertyNull(Object obj, Set<String> fields) { if (null == obj) { return; } for (String field : fields) { try { BeanUtilsBean.getInstance().getPropertyUtils().setProperty(obj, field, null); } catch (Exception ignore) { } } } }
FieldFilterDataAccessConfig filterDataAccessConfig = ((FieldFilterDataAccessConfig) access); switch (access.getAction()) { case Permission.ACTION_QUERY: case Permission.ACTION_GET: return doQueryAccess(filterDataAccessConfig, context); case Permission.ACTION_ADD: case Permission.ACTION_SAVE: case Permission.ACTION_UPDATE: return doUpdateAccess(filterDataAccessConfig, context); default: if (logger.isDebugEnabled()) { logger.debug("field filter not support for {}", access.getAction()); } return true; }
1,045
164
1,209
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/access/InvokeResultUtils.java
InvokeResultUtils
convertRealResult
class InvokeResultUtils { public static Object convertRealResult(Object result) {<FILL_FUNCTION_BODY>} }
if (result instanceof ResponseEntity) { result = ((ResponseEntity) result).getBody(); } // if (result instanceof ResponseMessage) { // result = ((ResponseMessage) result).getResult(); // } // if (result instanceof PagerResult) { // result = ((PagerResult) result).getData(); // } return result;
34
94
128
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/twofactor/TwoFactorHandlerInterceptorAdapter.java
TwoFactorHandlerInterceptorAdapter
preHandle
class TwoFactorHandlerInterceptorAdapter extends HandlerInterceptorAdapter { private final TwoFactorValidatorManager validatorManager; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {<FILL_FUNCTION_BODY>} }
if (handler instanceof HandlerMethod) { HandlerMethod method = ((HandlerMethod) handler); TwoFactor factor = method.getMethodAnnotation(TwoFactor.class); if (factor == null || factor.ignore()) { return true; } String userId = Authentication.current() .map(Authentication::getUser) .map(User::getId) .orElse(null); TwoFactorValidator validator = validatorManager.getValidator(userId, factor.value(), factor.provider()); if (!validator.expired()) { return true; } String code = request.getParameter(factor.parameter()); if (code == null) { code = request.getHeader(factor.parameter()); } if (StringUtils.isEmpty(code)) { throw new NeedTwoFactorException("validation.need_two_factor_verify", factor.provider()); } else if (!validator.verify(code, factor.timeout())) { throw new NeedTwoFactorException(factor.message(), factor.provider()); } } return super.preHandle(request, response, handler);
74
285
359
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/AuthorizationController.java
AuthorizationController
doLogin
class AuthorizationController { @Autowired private ApplicationEventPublisher eventPublisher; @Autowired private ReactiveAuthenticationManager authenticationManager; @GetMapping("/me") @Authorize @Operation(summary = "当前登录用户权限信息") public Mono<Authentication> me() { return Authentication.currentReactive() .switchIfEmpty(Mono.error(UnAuthorizedException::new)); } @PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_VALUE) @Authorize(ignore = true) @AccessLogger(ignoreParameter = {"parameter"}) @Operation(summary = "登录", description = "必要参数:username,password.根据配置不同,其他参数也不同,如:验证码等.") public Mono<Map<String, Object>> authorizeByJson(@Parameter(example = "{\"username\":\"admin\",\"password\":\"admin\"}") @RequestBody Mono<Map<String, Object>> parameter) { return doLogin(parameter); } /** * <img src="https://raw.githubusercontent.com/hs-web/hsweb-framework/4.0.x/hsweb-authorization/hsweb-authorization-basic/img/autz-flow.png"> */ @SneakyThrows private Mono<Map<String, Object>> doLogin(Mono<Map<String, Object>> parameter) {<FILL_FUNCTION_BODY>} private Mono<Authentication> doAuthorize(AuthorizationBeforeEvent event) { Mono<Authentication> authenticationMono; if (event.isAuthorized()) { if (event.getAuthentication() != null) { authenticationMono = Mono.just(event.getAuthentication()); } else { authenticationMono = ReactiveAuthenticationHolder .get(event.getUserId()) .switchIfEmpty(Mono.error(() -> new AuthenticationException(AuthenticationException.USER_DISABLED))); } } else { authenticationMono = authenticationManager .authenticate(Mono.just(new PlainTextUsernamePasswordAuthenticationRequest(event.getUsername(), event.getPassword()))) .switchIfEmpty(Mono.error(() -> new AuthenticationException(AuthenticationException.ILLEGAL_PASSWORD))); } return authenticationMono; } }
return parameter.flatMap(parameters -> { String username_ = String.valueOf(parameters.getOrDefault("username", "")); String password_ = String.valueOf(parameters.getOrDefault("password", "")); Assert.hasLength(username_, "validation.username_must_not_be_empty"); Assert.hasLength(password_, "validation.password_must_not_be_empty"); Function<String, Object> parameterGetter = parameters::get; return Mono .defer(() -> { AuthorizationDecodeEvent decodeEvent = new AuthorizationDecodeEvent(username_, password_, parameterGetter); return decodeEvent .publish(eventPublisher) .then(Mono.defer(() -> { String username = decodeEvent.getUsername(); String password = decodeEvent.getPassword(); AuthorizationBeforeEvent beforeEvent = new AuthorizationBeforeEvent(username, password, parameterGetter); return beforeEvent .publish(eventPublisher) .then(Mono.defer(() -> doAuthorize(beforeEvent) .flatMap(auth -> { //触发授权成功事件 AuthorizationSuccessEvent event = new AuthorizationSuccessEvent(auth, parameterGetter); event.getResult().put("userId", auth.getUser().getId()); return event .publish(eventPublisher) .then(Mono.fromCallable(event::getResult)); }))); })); }) .onErrorResume(err -> { AuthorizationFailedEvent failedEvent = new AuthorizationFailedEvent(username_, password_, parameterGetter); failedEvent.setException(err); return failedEvent .publish(eventPublisher) .then(Mono.error(failedEvent::getException)); }); });
603
463
1,066
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/BearerTokenParser.java
BearerTokenParser
parseToken
class BearerTokenParser implements ReactiveUserTokenParser { @Override public Mono<ParsedToken> parseToken(ServerWebExchange exchange) {<FILL_FUNCTION_BODY>} }
String token = exchange .getRequest() .getHeaders() .getFirst(HttpHeaders.AUTHORIZATION); if (token != null && token.startsWith("Bearer ")) { return Mono.just(ParsedToken.ofBearer(token.substring(7))); } return Mono.empty();
52
93
145
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/DefaultUserTokenGenPar.java
DefaultUserTokenGenPar
parseToken
class DefaultUserTokenGenPar implements ReactiveUserTokenGenerator, ReactiveUserTokenParser { private long timeout = TimeUnit.MINUTES.toMillis(30); @SuppressWarnings("all") private String headerName = "X-Access-Token"; private String parameterName = ":X_Access_Token"; @Override public String getTokenType() { return "default"; } @Override public GeneratedToken generate(Authentication authentication) { String token = IDGenerator.MD5.generate(); return new GeneratedToken() { @Override public Map<String, Object> getResponse() { return Collections.singletonMap("expires", timeout); } @Override public String getToken() { return token; } @Override public String getType() { return getTokenType(); } @Override public long getTimeout() { return timeout; } }; } @Override public Mono<ParsedToken> parseToken(ServerWebExchange exchange) {<FILL_FUNCTION_BODY>} }
String token = Optional.ofNullable(exchange.getRequest() .getHeaders() .getFirst(headerName)) .orElseGet(() -> exchange.getRequest().getQueryParams().getFirst(parameterName)); if (token == null) { return Mono.empty(); } return Mono.just(ParsedToken.of(getTokenType(),token,(_header,_token)->_header.set(headerName,_token)));
292
118
410
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/ReactiveUserTokenController.java
ReactiveUserTokenController
resetToken
class ReactiveUserTokenController { private UserTokenManager userTokenManager; private ReactiveAuthenticationManager authenticationManager; @Autowired @Lazy public void setUserTokenManager(UserTokenManager userTokenManager) { this.userTokenManager = userTokenManager; } @Autowired @Lazy public void setAuthenticationManager(ReactiveAuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @GetMapping("/user-token/reset") @Authorize(merge = false) @Operation(summary = "重置当前用户的令牌") public Mono<Boolean> resetToken() {<FILL_FUNCTION_BODY>} @PutMapping("/user-token/check") @Operation(summary = "检查所有已过期的token并移除") @SaveAction public Mono<Boolean> checkExpiredToken() { return userTokenManager .checkExpiredToken() .thenReturn(true); } @GetMapping("/user-token/token/{token}") @Operation(summary = "根据token获取令牌信息") @QueryAction public Mono<UserToken> getByToken(@PathVariable String token) { return userTokenManager.getByToken(token); } @GetMapping("/user-token/user/{userId}") @Operation(summary = "根据用户ID获取全部令牌信息") @QueryAction public Flux<UserToken> getByUserId(@PathVariable String userId) { return userTokenManager.getByUserId(userId); } @GetMapping("/user-token/user/{userId}/logged") @Operation(summary = "根据用户ID判断用户是否已经登录") @QueryAction public Mono<Boolean> userIsLoggedIn(@PathVariable String userId) { return userTokenManager.userIsLoggedIn(userId); } @GetMapping("/user-token/token/{token}/logged") @Operation(summary = "根据令牌判断用户是否已经登录") @QueryAction public Mono<Boolean> tokenIsLoggedIn(@PathVariable String token) { return userTokenManager.tokenIsLoggedIn(token); } @GetMapping("/user-token/user/total") @Operation(summary = "获取当前已经登录的用户数量") @Authorize(merge = false) public Mono<Integer> totalUser() { return userTokenManager.totalUser(); } @GetMapping("/user-token/token/total") @Operation(summary = "获取当前已经登录的令牌数量") @Authorize(merge = false) public Mono<Integer> totalToken() { return userTokenManager.totalToken(); } @GetMapping("/user-token") @Operation(summary = "获取全部用户令牌信息") @QueryAction public Flux<UserToken> allLoggedUser() { return userTokenManager.allLoggedUser(); } @DeleteMapping("/user-token/user/{userId}") @Operation(summary = "根据用户id将用户踢下线") @SaveAction public Mono<Void> signOutByUserId(@PathVariable String userId) { return userTokenManager.signOutByUserId(userId); } @DeleteMapping("/user-token/token/{token}") @Operation(summary = "根据令牌将用户踢下线") @SaveAction public Mono<Void> signOutByToken(@PathVariable String token) { return userTokenManager.signOutByToken(token); } @SaveAction @PutMapping("/user-token/user/{userId}/{state}") @Operation(summary = "根据用户id更新用户令牌状态") public Mono<Void> changeUserState(@PathVariable String userId, @PathVariable TokenState state) { return userTokenManager.changeUserState(userId, state); } @PutMapping("/user-token/token/{token}/{state}") @Operation(summary = "根据令牌更新用户令牌状态") @SaveAction public Mono<Void> changeTokenState(@PathVariable String token, @PathVariable TokenState state) { return userTokenManager.changeTokenState(token, state); } // // @PostMapping("/user-token/{token}/{type}/{userId}/{maxInactiveInterval}") // @Operation(summary = "将用户设置为登录") // @SaveAction // public Mono<UserToken> signIn(@PathVariable String token, @PathVariable String type, @PathVariable String userId, @PathVariable long maxInactiveInterval) { // return userTokenManager.signIn(token, type, userId, maxInactiveInterval); // } @GetMapping("/user-token/{token}/touch") @Operation(summary = "更新token有效期") @SaveAction public Mono<Void> touch(@PathVariable String token) { return userTokenManager.touch(token); } @GetMapping("/user-auth/{userId}") @Operation(summary = "根据用户id获取权限信息") @SaveAction public Mono<Authentication> userAuthInfo(@PathVariable String userId) { return authenticationManager.getByUserId(userId); } }
return Mono .<ParsedToken>deferContextual(ctx -> Mono.justOrEmpty(ctx.getOrEmpty(ParsedToken.class))) .flatMap(token -> userTokenManager.signOutByToken(token.getToken())) .thenReturn(true);
1,351
76
1,427
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/ServletUserTokenGenPar.java
ServletUserTokenGenPar
generate
class ServletUserTokenGenPar implements UserTokenParser, UserTokenGenerator { private long timeout = TimeUnit.MINUTES.toMillis(30); private String headerName = "X-Access-Token"; @Override public String getSupportTokenType() { return "default"; } @Override public GeneratedToken generate(Authentication authentication) {<FILL_FUNCTION_BODY>} @Override public ParsedToken parseToken(HttpServletRequest request) { String token = Optional .ofNullable(request.getHeader(headerName)) .orElseGet(() -> request.getParameter(":X_Access_Token")); if (StringUtils.hasText(token)) { return ParsedToken.of(getSupportTokenType(), token); } return null; } }
String token = IDGenerator.MD5.generate(); return new GeneratedToken() { @Override public Map<String, Object> getResponse() { return Collections.singletonMap("expires", timeout); } @Override public String getToken() { return token; } @Override public String getType() { return getSupportTokenType(); } @Override public long getTimeout() { return timeout; } };
212
130
342
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/SessionIdUserTokenGenerator.java
SessionIdUserTokenGenerator
generate
class SessionIdUserTokenGenerator implements UserTokenGenerator, Serializable { private static final long serialVersionUID = -9197243220777237431L; @Override public String getSupportTokenType() { return TOKEN_TYPE_SESSION_ID; } @Override public GeneratedToken generate(Authentication authentication) {<FILL_FUNCTION_BODY>} }
HttpServletRequest request = WebUtils.getHttpServletRequest(); if (null == request) { throw new UnsupportedOperationException(); } int timeout = request.getSession().getMaxInactiveInterval() * 1000; String sessionId = request.getSession().getId(); return new GeneratedToken() { private static final long serialVersionUID = 3964183451883410929L; @Override public Map<String, Object> getResponse() { return new java.util.HashMap<>(); } @Override public String getToken() { return sessionId; } @Override public String getType() { return TOKEN_TYPE_SESSION_ID; } @Override public long getTimeout() { return timeout; } };
110
226
336
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/SessionIdUserTokenParser.java
SessionIdUserTokenParser
parseToken
class SessionIdUserTokenParser implements UserTokenParser { protected UserTokenManager userTokenManager; @Autowired public void setUserTokenManager(UserTokenManager userTokenManager) { this.userTokenManager = userTokenManager; } @Override public ParsedToken parseToken(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
HttpSession session = request.getSession(false); if (session != null) { String sessionId = session.getId(); UserToken token = userTokenManager.getByToken(sessionId).block(); long interval = session.getMaxInactiveInterval(); //当前已登录token已失效但是session未失效 if (token != null && token.isExpired()) { String userId = token.getUserId(); return new AuthorizedToken() { @Override public String getUserId() { return userId; } @Override public String getToken() { return sessionId; } @Override public String getType() { return TOKEN_TYPE_SESSION_ID; } @Override public long getMaxInactiveInterval() { return interval; } }; } return new ParsedToken() { @Override public String getToken() { return session.getId(); } @Override public String getType() { return TOKEN_TYPE_SESSION_ID; } }; } return null;
98
298
396
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/UserOnSignIn.java
UserOnSignIn
onApplicationEvent
class UserOnSignIn { /** * 默认到令牌类型 * * @see UserToken#getType() * @see SessionIdUserTokenGenerator#getSupportTokenType() */ private String defaultTokenType = "sessionId"; /** * 令牌管理器 */ private UserTokenManager userTokenManager; private List<UserTokenGenerator> userTokenGenerators = new ArrayList<>(); public UserOnSignIn(UserTokenManager userTokenManager) { this.userTokenManager = userTokenManager; } public void setDefaultTokenType(String defaultTokenType) { this.defaultTokenType = defaultTokenType; } @Autowired(required = false) public void setUserTokenGenerators(List<UserTokenGenerator> userTokenGenerators) { this.userTokenGenerators = userTokenGenerators; } @EventListener public void onApplicationEvent(AuthorizationSuccessEvent event) {<FILL_FUNCTION_BODY>} }
UserToken token = UserTokenHolder.currentToken(); String tokenType = (String) event.getParameter("token_type").orElse(defaultTokenType); if (token != null) { //先退出已登陆的用户 event.async(userTokenManager.signOutByToken(token.getToken())); } //创建token GeneratedToken newToken = userTokenGenerators.stream() .filter(generator -> generator.getSupportTokenType().equals(tokenType)) .findFirst() .orElseThrow(() -> new UnsupportedOperationException(tokenType)) .generate(event.getAuthentication()); //登入 event.async(userTokenManager.signIn(newToken.getToken(), newToken.getType(), event.getAuthentication().getUser().getId(), newToken.getTimeout()).then()); //响应结果 event.getResult().putAll(newToken.getResponse());
258
234
492
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/UserOnSignOut.java
UserOnSignOut
geToken
class UserOnSignOut { private final UserTokenManager userTokenManager; public UserOnSignOut(UserTokenManager userTokenManager) { this.userTokenManager = userTokenManager; } private String geToken() {<FILL_FUNCTION_BODY>} @EventListener public void onApplicationEvent(AuthorizationExitEvent event) { event.async(userTokenManager.signOutByToken(geToken())); } }
UserToken token = UserTokenHolder.currentToken(); return null != token ? token.getToken() : "";
114
31
145
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/UserTokenWebFilter.java
UserTokenWebFilter
filter
class UserTokenWebFilter implements WebFilter, BeanPostProcessor { private final List<ReactiveUserTokenParser> parsers = new ArrayList<>(); private final Map<String, ReactiveUserTokenGenerator> tokenGeneratorMap = new HashMap<>(); @Autowired private UserTokenManager userTokenManager; @Override @NonNull public Mono<Void> filter(@NonNull ServerWebExchange exchange, WebFilterChain chain) {<FILL_FUNCTION_BODY>} @EventListener public void handleUserSign(AuthorizationSuccessEvent event) { ReactiveUserTokenGenerator generator = event .<String>getParameter("tokenType") .map(tokenGeneratorMap::get) .orElseGet(() -> tokenGeneratorMap.get("default")); if (generator != null) { GeneratedToken token = generator.generate(event.getAuthentication()); event.getResult().putAll(token.getResponse()); if (StringUtils.hasText(token.getToken())) { event.getResult().put("token", token.getToken()); long expires = event.getParameter("expires") .map(String::valueOf) .map(Long::parseLong) .orElse(token.getTimeout()); event.getResult().put("expires", expires); event.async(userTokenManager .signIn(token.getToken(), token.getType(), event .getAuthentication() .getUser() .getId(), expires) .doOnNext(t -> log.debug("user [{}] sign in", t.getUserId())) .then()); } } } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof ReactiveUserTokenGenerator) { ReactiveUserTokenGenerator generator = ((ReactiveUserTokenGenerator) bean); tokenGeneratorMap.put(generator.getTokenType(), generator); } if (bean instanceof ReactiveUserTokenParser) { parsers.add(((ReactiveUserTokenParser) bean)); } return bean; } }
return Flux .fromIterable(parsers) .flatMap(parser -> parser.parseToken(exchange)) .next() .map(token -> chain .filter(exchange) .contextWrite(Context.of(ParsedToken.class, token))) .defaultIfEmpty(chain.filter(exchange)) .flatMap(Function.identity()) .contextWrite(ReactiveLogger.start("requestId", exchange.getRequest().getId()));
537
125
662
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/WebUserTokenInterceptor.java
WebUserTokenInterceptor
preHandle
class WebUserTokenInterceptor extends HandlerInterceptorAdapter { private final UserTokenManager userTokenManager; private final List<UserTokenParser> userTokenParser; private final AopMethodAuthorizeDefinitionParser parser; private final boolean enableBasicAuthorization; public WebUserTokenInterceptor(UserTokenManager userTokenManager, List<UserTokenParser> userTokenParser, AopMethodAuthorizeDefinitionParser definitionParser) { this.userTokenManager = userTokenManager; this.userTokenParser = userTokenParser; this.parser = definitionParser; enableBasicAuthorization = userTokenParser .stream() .filter(UserTokenForTypeParser.class::isInstance) .anyMatch(parser -> "basic".equalsIgnoreCase(((UserTokenForTypeParser) parser).getTokenType())); } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {<FILL_FUNCTION_BODY>} }
List<ParsedToken> tokens = userTokenParser .stream() .map(parser -> parser.parseToken(request)) .filter(Objects::nonNull) .collect(Collectors.toList()); if (tokens.isEmpty()) { if (enableBasicAuthorization && handler instanceof HandlerMethod) { HandlerMethod method = ((HandlerMethod) handler); AuthorizeDefinition definition = parser.parse(method.getBeanType(), method.getMethod()); if (null != definition) { response.addHeader("WWW-Authenticate", " Basic realm=\"\""); } } return true; } for (ParsedToken parsedToken : tokens) { UserToken userToken = null; String token = parsedToken.getToken(); if (userTokenManager.tokenIsLoggedIn(token).blockOptional().orElse(false)) { userToken = userTokenManager.getByToken(token).blockOptional().orElse(null); } if ((userToken == null || userToken.isExpired()) && parsedToken instanceof AuthorizedToken) { //先踢出旧token userTokenManager.signOutByToken(token).subscribe(); userToken = userTokenManager .signIn(parsedToken.getToken(), parsedToken.getType(), ((AuthorizedToken) parsedToken).getUserId(), ((AuthorizedToken) parsedToken) .getMaxInactiveInterval()) .block(); } if (null != userToken) { userTokenManager.touch(token).subscribe(); UserTokenHolder.setCurrent(userToken); } } return true;
251
412
663
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-oauth2/src/main/java/org/hswebframework/web/oauth2/server/OAuth2Client.java
OAuth2Client
validateSecret
class OAuth2Client { @NotBlank private String clientId; @NotBlank private String clientSecret; @NotBlank private String name; private String description; @NotBlank private String redirectUrl; //client 所属用户 private String userId; public void validateRedirectUri(String redirectUri) { if (StringUtils.isEmpty(redirectUri) || (!redirectUri.startsWith(this.redirectUrl))) { throw new OAuth2Exception(ErrorType.ILLEGAL_REDIRECT_URI); } } public void validateSecret(String secret) {<FILL_FUNCTION_BODY>} }
if (StringUtils.isEmpty(secret) || (!secret.equals(this.clientSecret))) { throw new OAuth2Exception(ErrorType.ILLEGAL_CLIENT_SECRET); }
186
53
239
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-oauth2/src/main/java/org/hswebframework/web/oauth2/server/OAuth2Request.java
OAuth2Request
with
class OAuth2Request { private Map<String, String> parameters; public Optional<String> getParameter(String key) { return Optional.ofNullable(parameters) .map(params -> params.get(key)); } public OAuth2Request with(String parameter, String key) {<FILL_FUNCTION_BODY>} }
if (parameters == null) { parameters = new HashMap<>(); } parameters.put(parameter, key); return this;
93
39
132
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-oauth2/src/main/java/org/hswebframework/web/oauth2/server/OAuth2Response.java
OAuth2Response
with
class OAuth2Response implements Serializable { @Hidden private Map<String,Object> parameters; public OAuth2Response with(String parameter, Object key) {<FILL_FUNCTION_BODY>} }
if (parameters == null) { parameters = new HashMap<>(); } parameters.put(parameter, key); return this;
57
39
96
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-oauth2/src/main/java/org/hswebframework/web/oauth2/server/OAuth2ServerAutoConfiguration.java
ReactiveOAuth2ServerAutoConfiguration
oAuth2GrantService
class ReactiveOAuth2ServerAutoConfiguration { @Bean @ConditionalOnMissingBean public AccessTokenManager accessTokenManager(ReactiveRedisOperations<Object, Object> redis, UserTokenManager tokenManager, OAuth2Properties properties) { @SuppressWarnings("all") RedisAccessTokenManager manager = new RedisAccessTokenManager((ReactiveRedisOperations) redis, tokenManager); manager.setTokenExpireIn((int) properties.getTokenExpireIn().getSeconds()); manager.setRefreshExpireIn((int) properties.getRefreshTokenIn().getSeconds()); return manager; } @Bean @ConditionalOnMissingBean public ClientCredentialGranter clientCredentialGranter(ReactiveAuthenticationManager authenticationManager, AccessTokenManager accessTokenManager, ApplicationEventPublisher eventPublisher) { return new DefaultClientCredentialGranter(authenticationManager, accessTokenManager,eventPublisher); } @Bean @ConditionalOnMissingBean public AuthorizationCodeGranter authorizationCodeGranter(AccessTokenManager tokenManager, ApplicationEventPublisher eventPublisher, ReactiveRedisConnectionFactory redisConnectionFactory) { return new DefaultAuthorizationCodeGranter(tokenManager,eventPublisher, redisConnectionFactory); } @Bean @ConditionalOnMissingBean public RefreshTokenGranter refreshTokenGranter(AccessTokenManager tokenManager) { return new DefaultRefreshTokenGranter(tokenManager); } @Bean @ConditionalOnMissingBean public OAuth2GrantService oAuth2GrantService(ObjectProvider<AuthorizationCodeGranter> codeProvider, ObjectProvider<ClientCredentialGranter> credentialProvider, ObjectProvider<RefreshTokenGranter> refreshProvider) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnMissingBean @ConditionalOnBean(OAuth2ClientManager.class) public OAuth2AuthorizeController oAuth2AuthorizeController(OAuth2GrantService grantService, OAuth2ClientManager clientManager) { return new OAuth2AuthorizeController(grantService, clientManager); } }
CompositeOAuth2GrantService grantService = new CompositeOAuth2GrantService(); grantService.setAuthorizationCodeGranter(codeProvider.getIfAvailable()); grantService.setClientCredentialGranter(credentialProvider.getIfAvailable()); grantService.setRefreshTokenGranter(refreshProvider.getIfAvailable()); return grantService;
568
95
663
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-oauth2/src/main/java/org/hswebframework/web/oauth2/server/auth/ReactiveOAuth2AccessTokenParser.java
ReactiveOAuth2AccessTokenParser
parseToken
class ReactiveOAuth2AccessTokenParser implements ReactiveUserTokenParser, ReactiveAuthenticationSupplier { private final AccessTokenManager accessTokenManager; @Override public Mono<ParsedToken> parseToken(ServerWebExchange exchange) {<FILL_FUNCTION_BODY>} @Override public Mono<Authentication> get(String userId) { return Mono.empty(); } @Override public Mono<Authentication> get() { return Mono .deferContextual(context -> context .<ParsedToken>getOrEmpty(ParsedToken.class) .filter(token -> "oauth2".equals(token.getType())) .map(t -> accessTokenManager.getAuthenticationByToken(t.getToken())) .orElse(Mono.empty())); } }
String token = exchange.getRequest().getQueryParams().getFirst("access_token"); if (!StringUtils.hasText(token)) { token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION); if (StringUtils.hasText(token)) { String[] typeAndToken = token.split("[ ]"); if (typeAndToken.length == 2 && typeAndToken[0].equalsIgnoreCase("bearer")) { token = typeAndToken[1]; } } } if (StringUtils.hasText(token)) { return Mono.just(ParsedToken.of("oauth2", token)); } return Mono.empty();
216
182
398
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-oauth2/src/main/java/org/hswebframework/web/oauth2/server/code/DefaultAuthorizationCodeGranter.java
DefaultAuthorizationCodeGranter
requestToken
class DefaultAuthorizationCodeGranter implements AuthorizationCodeGranter { private final AccessTokenManager accessTokenManager; private final ApplicationEventPublisher eventPublisher; private final ReactiveRedisOperations<String, AuthorizationCodeCache> redis; @SuppressWarnings("all") public DefaultAuthorizationCodeGranter(AccessTokenManager accessTokenManager, ApplicationEventPublisher eventPublisher, ReactiveRedisConnectionFactory connectionFactory) { this(accessTokenManager, eventPublisher, new ReactiveRedisTemplate<>(connectionFactory, RedisSerializationContext .newSerializationContext() .key((RedisSerializer) RedisSerializer.string()) .value(RedisSerializer.java()) .hashKey(RedisSerializer.string()) .hashValue(RedisSerializer.java()) .build() )); } @Override public Mono<AuthorizationCodeResponse> requestCode(AuthorizationCodeRequest request) { OAuth2Client client = request.getClient(); Authentication authentication = request.getAuthentication(); AuthorizationCodeCache codeCache = new AuthorizationCodeCache(); String code = IDGenerator.MD5.generate(); request.getParameter(OAuth2Constants.scope).map(String::valueOf).ifPresent(codeCache::setScope); codeCache.setCode(code); codeCache.setClientId(client.getClientId()); ScopePredicate permissionPredicate = OAuth2ScopeUtils.createScopePredicate(codeCache.getScope()); Authentication copy = authentication.copy( (permission, action) -> permissionPredicate.test(permission.getId(), action), dimension -> permissionPredicate.test(dimension.getType().getId(), dimension.getId())); copy.setAttribute("scope", codeCache.getScope()); codeCache.setAuthentication(copy); return redis .opsForValue() .set(getRedisKey(code), codeCache, Duration.ofMinutes(5)) .thenReturn(new AuthorizationCodeResponse(code)); } private String getRedisKey(String code) { return "oauth2-code:" + code; } @Override public Mono<AccessToken> requestToken(AuthorizationCodeTokenRequest request) {<FILL_FUNCTION_BODY>} }
return Mono .justOrEmpty(request.code()) .map(this::getRedisKey) .flatMap(redis.opsForValue()::get) .switchIfEmpty(Mono.error(() -> new OAuth2Exception(ErrorType.ILLEGAL_CODE))) //移除code .flatMap(cache -> redis.opsForValue().delete(getRedisKey(cache.getCode())).thenReturn(cache)) .flatMap(cache -> { if (!request.getClient().getClientId().equals(cache.getClientId())) { return Mono.error(new OAuth2Exception(ErrorType.ILLEGAL_CLIENT_ID)); } return accessTokenManager .createAccessToken(cache.getClientId(), cache.getAuthentication(), false) .flatMap(token -> new OAuth2GrantedEvent(request.getClient(), token, cache.getAuthentication(), cache.getScope(), GrantType.authorization_code, request.getParameters()) .publish(eventPublisher) .onErrorResume(err -> accessTokenManager .removeToken(cache.getClientId(), token.getAccessToken()) .then(Mono.error(err))) .thenReturn(token)); }) ;
584
337
921
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-oauth2/src/main/java/org/hswebframework/web/oauth2/server/credential/DefaultClientCredentialGranter.java
DefaultClientCredentialGranter
requestToken
class DefaultClientCredentialGranter implements ClientCredentialGranter { private final ReactiveAuthenticationManager authenticationManager; private final AccessTokenManager accessTokenManager; private final ApplicationEventPublisher eventPublisher; @Override public Mono<AccessToken> requestToken(ClientCredentialRequest request) {<FILL_FUNCTION_BODY>} }
OAuth2Client client = request.getClient(); return authenticationManager .getByUserId(client.getUserId()) .flatMap(auth -> accessTokenManager .createAccessToken(client.getClientId(), auth, true) .flatMap(token -> new OAuth2GrantedEvent(client, token, auth, "*", GrantType.client_credentials, request.getParameters()) .publish(eventPublisher) .onErrorResume(err -> accessTokenManager .removeToken(client.getClientId(), token.getAccessToken()) .then(Mono.error(err))) .thenReturn(token)) );
92
180
272
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-oauth2/src/main/java/org/hswebframework/web/oauth2/server/impl/RedisAccessToken.java
RedisAccessToken
storeAuth
class RedisAccessToken implements Serializable { private String clientId; private String accessToken; private String refreshToken; private long createTime; private Authentication authentication; private boolean singleton; public boolean storeAuth() {<FILL_FUNCTION_BODY>} public AccessToken toAccessToken(int expiresIn) { AccessToken token = new AccessToken(); token.setAccessToken(accessToken); token.setRefreshToken(refreshToken); token.setExpiresIn(expiresIn); return token; } }
boolean allowAllScope = authentication .getAttribute("scope") .map("*"::equals) .orElse(false); //不是单例,并且没有授予全部权限 return !singleton && !allowAllScope;
152
64
216
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-oauth2/src/main/java/org/hswebframework/web/oauth2/server/utils/OAuth2ScopeUtils.java
OAuth2ScopeUtils
createScopePredicate
class OAuth2ScopeUtils { public static ScopePredicate createScopePredicate(String scopeStr) {<FILL_FUNCTION_BODY>} }
if (StringUtils.isEmpty(scopeStr)) { return ((permission, action) -> false); } String[] scopes = scopeStr.split("[ ,\n]"); Map<String, Set<String>> actions = new HashMap<>(); for (String scope : scopes) { String[] permissions = scope.split("[:]"); String per = permissions[0]; Set<String> acts = actions.computeIfAbsent(per, k -> new HashSet<>()); acts.addAll(Arrays.asList(permissions).subList(1, permissions.length)); } //全部授权 if (actions.containsKey("*")) { return ((permission, action) -> true); } return ((permission, action) -> Optional .ofNullable(actions.get(permission)) .map(acts -> action.length == 0 || acts.contains("*") || acts.containsAll(Arrays.asList(action))) .orElse(false));
41
251
292
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-authorization/hsweb-authorization-oauth2/src/main/java/org/hswebframework/web/oauth2/server/web/OAuth2AuthorizeController.java
OAuth2AuthorizeController
authorizeByCode
class OAuth2AuthorizeController { private final OAuth2GrantService oAuth2GrantService; private final OAuth2ClientManager clientManager; @GetMapping(value = "/authorize", params = "response_type=code") @Operation(summary = "申请授权码,并获取重定向地址", parameters = { @Parameter(name = "client_id", required = true), @Parameter(name = "redirect_uri", required = true), @Parameter(name = "state"), @Parameter(name = "response_type", description = "固定值为code") }) public Mono<String> authorizeByCode(ServerWebExchange exchange) {<FILL_FUNCTION_BODY>} @GetMapping(value = "/token") @Operation(summary = "(GET)申请token", parameters = { @Parameter(name = "client_id"), @Parameter(name = "client_secret"), @Parameter(name = "code", description = "grantType为authorization_code时不能为空"), @Parameter(name = "grant_type", schema = @Schema(implementation = GrantType.class)) }) @Authorize(ignore = true) public Mono<ResponseEntity<AccessToken>> requestTokenByCode( @RequestParam("grant_type") GrantType grantType, ServerWebExchange exchange) { Map<String, String> params = exchange.getRequest().getQueryParams().toSingleValueMap(); Tuple2<String,String> clientIdAndSecret = getClientIdAndClientSecret(params,exchange); return this .getOAuth2Client(clientIdAndSecret.getT1()) .doOnNext(client -> client.validateSecret(clientIdAndSecret.getT2())) .flatMap(client -> grantType.requestToken(oAuth2GrantService, client, new HashMap<>(params))) .map(ResponseEntity::ok); } @PostMapping(value = "/token", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) @Operation(summary = "(POST)申请token", parameters = { @Parameter(name = "client_id"), @Parameter(name = "client_secret"), @Parameter(name = "code", description = "grantType为authorization_code时不能为空"), @Parameter(name = "grant_type", schema = @Schema(implementation = GrantType.class)) }) @Authorize(ignore = true) public Mono<ResponseEntity<AccessToken>> requestTokenByCode(ServerWebExchange exchange) { return exchange .getFormData() .map(MultiValueMap::toSingleValueMap) .flatMap(params -> { Tuple2<String,String> clientIdAndSecret = getClientIdAndClientSecret(params,exchange); GrantType grantType = GrantType.of(params.get("grant_type")); return this .getOAuth2Client(clientIdAndSecret.getT1()) .doOnNext(client -> client.validateSecret(clientIdAndSecret.getT2())) .flatMap(client -> grantType.requestToken(oAuth2GrantService, client, new HashMap<>(params))) .map(ResponseEntity::ok); }); } private Tuple2<String, String> getClientIdAndClientSecret(Map<String, String> params, ServerWebExchange exchange) { String authorization = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION); if (authorization != null && authorization.startsWith("Basic ")) { String[] arr = new String(Base64.decodeBase64(authorization.substring(5))).split(":"); if (arr.length >= 2) { return Tuples.of(arr[0], arr[1]); } return Tuples.of(arr[0], arr[0]); } return Tuples.of(params.getOrDefault("client_id",""),params.getOrDefault("client_secret","")); } public enum GrantType { authorization_code { @Override Mono<AccessToken> requestToken(OAuth2GrantService service, OAuth2Client client, Map<String, String> param) { return service .authorizationCode() .requestToken(new AuthorizationCodeTokenRequest(client, param)); } }, client_credentials { @Override Mono<AccessToken> requestToken(OAuth2GrantService service, OAuth2Client client, Map<String, String> param) { return service .clientCredential() .requestToken(new ClientCredentialRequest(client, param)); } }, refresh_token { @Override Mono<AccessToken> requestToken(OAuth2GrantService service, OAuth2Client client, Map<String, String> param) { return service .refreshToken() .requestToken(new RefreshTokenRequest(client, param)); } }; abstract Mono<AccessToken> requestToken(OAuth2GrantService service, OAuth2Client client, Map<String, String> param); static GrantType of(String name) { try { return GrantType.valueOf(name); } catch (Throwable e) { throw new OAuth2Exception(ErrorType.UNSUPPORTED_GRANT_TYPE); } } } @SneakyThrows public static String urlEncode(String url) { return URLEncoder.encode(url, "utf-8"); } static String buildRedirect(String redirectUri, Map<String, Object> params) { String paramsString = params.entrySet() .stream() .map(e -> e.getKey() + "=" + urlEncode(String.valueOf(e.getValue()))) .collect(Collectors.joining("&")); if (redirectUri.contains("?")) { return redirectUri + "&" + paramsString; } return redirectUri + "?" + paramsString; } private Mono<OAuth2Client> getOAuth2Client(String id) { return clientManager .getClient(id) .switchIfEmpty(Mono.error(() -> new OAuth2Exception(ErrorType.ILLEGAL_CLIENT_ID))); } }
Map<String, String> param = new HashMap<>(exchange.getRequest().getQueryParams().toSingleValueMap()); return Authentication .currentReactive() .switchIfEmpty(Mono.error(UnAuthorizedException::new)) .flatMap(auth -> this .getOAuth2Client(param.get("client_id")) .flatMap(client -> { String redirectUri = param.getOrDefault("redirect_uri", client.getRedirectUrl()); client.validateRedirectUri(redirectUri); return oAuth2GrantService .authorizationCode() .requestCode(new AuthorizationCodeRequest(client, auth, param)) .doOnNext(response -> { Optional .ofNullable(param.get("state")) .ifPresent(state -> response.with("state", state)); }) .map(response -> buildRedirect(redirectUri, response.getParameters())); }));
1,610
244
1,854
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-commons/hsweb-commons-api/src/main/java/org/hswebframework/web/api/crud/entity/EntityFactoryHolder.java
EntityFactoryHolder
get
class EntityFactoryHolder { static EntityFactory FACTORY; public static EntityFactory get() {<FILL_FUNCTION_BODY>} public static <T> T newInstance(Class<T> type, Supplier<T> mapper) { if (FACTORY != null) { return FACTORY.newInstance(type,mapper); } return mapper.get(); } }
if (FACTORY == null) { throw new IllegalStateException("EntityFactory Not Ready Yet"); } return FACTORY;
114
39
153
<no_super_class>
hs-web_hsweb-framework
hsweb-framework/hsweb-commons/hsweb-commons-api/src/main/java/org/hswebframework/web/api/crud/entity/EntityFactoryHolderConfiguration.java
EntityFactoryHolderConfiguration
entityFactoryHolder
class EntityFactoryHolderConfiguration { @Bean public ApplicationContextAware entityFactoryHolder() {<FILL_FUNCTION_BODY>} }
return context -> { try { EntityFactoryHolder.FACTORY = context.getBean(EntityFactory.class); } catch (BeansException ignore) { } };
41
54
95
<no_super_class>