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.sendMet... | 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(ChannelHandlerConte... |
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;
... | 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, Cluste... |
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, ClusterMs... |
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.ge... | 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 m... |
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 {... | 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 a... | 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>
... |
try {
String contentJson = objectMapper.writeValueAsString(config);
GeneralConfig generalConfig2Save = GeneralConfig.builder()
.type(type())
.content(contentJson)
.build();
generalConfigDao.save(generalConfig2Save)... | 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()
... |
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 ... | 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 m... |
if (collectors == null || collectors.isEmpty()) {
return;
}
// Determine whether there are fixed tasks on the collector
collectors.forEach(collector -> {
List<CollectorMonitorBind> binds = this.collectorMonitorBindDao.findCollectorMonitorBindsByCollector(collecto... | 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>}
@Overrid... |
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 ... |
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 objectMapp... |
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 Sim... |
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... | 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";
/**
... |
// 初始化文件存储服务
if (config != null) {
switch (config.getType()) {
case OBS:
initObs(config);
break;
// case other object store service
default:
}
ctx.publishEvent(new ObjectStoreConf... | 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... |
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);
... | 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, p... |
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 (tagOption... |
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 ... |
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;
}
/**
... |
// 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 re... |
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
... |
PushMetricsDto.Metrics metrics;
PushMetricsDto pushMetricsDto = new PushMetricsDto();
if (lastPushMetrics.containsKey(monitorId)) {
metrics = lastPushMetrics.get(monitorId);
}
else {
try {
PushMetrics pushMetrics = metricsDao.findFirstByMo... | 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> nettyHoo... |
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;
... |
this.threadPool.execute(() -> {
ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setUncaughtExceptionHandler((thread, throwable) -> {
log.error("NettyClientWorker has uncaughtException.");
log.error(throwable.getMessage(),... | 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.NettyHoo... |
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 Net... |
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... | 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.NettyHoo... |
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 THRE... |
// Thread factory
ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setUncaughtExceptionHandler((thread, throwable) -> {
log.error("workerExecutor has uncaughtException.");
log.error(throwable.getMessage(), throwable); })
.... | 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> realTimeDataStor... |
AbstractHistoryDataStorage historyDataStorage = historyDataStorages.stream()
.filter(AbstractHistoryDataStorage::isServerAvailable).max((o1, o2) -> {
if (o1 instanceof HistoryJpaDatabaseDataStorage) {
return -1;
} else if (o2 insta... | 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<Co... |
AbstractRealTimeDataStorage realTimeDataStorage = realTimeDataStorages.stream()
.filter(AbstractRealTimeDataStorage::isServerAvailable)
.max((o1, o2) -> {
if (o1 instanceof RealTimeMemoryDataStorage) {
return -1;
} ... | 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(CommonDataQu... |
Runnable runnable = () -> {
Thread.currentThread().setName("warehouse-realtime-data-storage");
if (realTimeDataStorages != null && realTimeDataStorages.size() > 1) {
realTimeDataStorages.removeIf(item -> item instanceof RealTimeMemoryDataStorage);
}
... | 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_FU... |
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 = i... |
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 = propert... | 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 boole... |
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) {
i... |
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("[ ]")) {
... | 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 当前登录的用户权限信息
... |
return Flux
.merge(suppliers
.stream()
.map(function)
.collect(Collectors.toList()))
.collectList()
.filter(CollectionUtils::isNotEmpty)
.map(all -> {
... | 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,
Stri... |
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... |
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.getResource... |
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;
p... |
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<ResourceDefiniti... |
ResourceDefinition definition = getResource(resource.getId()).orElse(null);
if (definition != null) {
if (merge) {
resource.getActions()
.stream()
.map(ResourceActionDefinition::copy)
.forEach(definition... | 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.writ... |
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()) {
newDetai... | 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;
}
... |
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()) {
... | 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<Authent... |
return Flux.concat(providers
.stream()
.map(manager -> manager
.authenticate(request)
.onErrorResume((err) -> {
... | 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
// @Co... |
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(mess... | 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>> providerMappin... |
return this
.providerMapping()
.flatMapMany(providerMapping -> Flux
.fromIterable(bindProviders)
//获取绑定信息
.flatMap(provider -> provider.getDimensionBindInfo(userId))
.groupBy(Dimensio... | 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> attri... |
SimpleAuthentication authentication = new SimpleAuthentication();
authentication.setDimensions(dimensions.stream().filter(dimension).collect(Collectors.toList()));
authentication.setPermissions(permissions
.stream()
... | 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> ge... |
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.dat... |
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();
per... | 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);
... |
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.req... | 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 ... |
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 c... | 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 lo... |
LocalUserToken userToken = new LocalUserToken();
userToken.firstRequestTime = firstRequestTime;
userToken.lastRequestTime = lastRequestTime;
userToken.requestTimesCounter = new AtomicLong(requestTimesCounter.get());
userToken.token = token;
userToken.userId = userId;
... | 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_BO... |
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 UserTokenAuthe... |
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> thirdPartAuthenticationMan... |
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... |
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 SimpleUs... |
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
p... |
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... |
if (bean instanceof TwoFactorValidatorProvider) {
TwoFactorValidatorProvider provider = ((TwoFactorValidatorProvider) bean);
providers.put(provider.getProvider(), provider);
if (provider.getProvider().equalsIgnoreCase(defaultProvider)) {
providers.put("defaul... | 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;
... |
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() - ... |
return new TwoFactorToken() {
private static final long serialVersionUID = -5148037320548431456L;
@Override
public void generate(long timeout) {
TwoFactorTokenInfo info = new TwoFactorTokenInfo();
info.timeOut = timeout;
toke... | 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 authori... |
return Authentication
.currentReactive()
.switchIfEmpty(Mono.error(UnAuthorizedException::new))
.flatMapMany(auth -> {
context.setAuthentication(auth);
Function<Runnable, Publisher> afterRuner = runnable -> {
... | 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> excludeMethodN... |
if (excludeMethodName.contains(method.getName())) {
return null;
}
CacheKey key = buildCacheKey(target, method);
AuthorizeDefinition definition = cache.get(key);
if (definition instanceof EmptyAuthorizeDefinition) {
return null;
}
if (nul... | 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
... |
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(Authenti... |
String authorization = request.getHeader("Authorization");
if (authorization == null) {
return null;
}
if (authorization.contains(" ")) {
String[] info = authorization.split("[ ]");
if (info[0].equalsIgnoreCase(getTokenType())) {
autho... | 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,
AopMetho... |
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
... |
for (Annotation annotation : methodAnnotation) {
if (annotation instanceof ResourceAction) {
getAnnotationByType(Resource.class)
.map(res -> definition.getResources().getResource(res.id()).orElse(null))
.filter(Objects::nonNull)
... | 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();... |
if (!ann.merge()) {
getResources().getResources().clear();
getDimensions().getDimensions().clear();
}
setPhased(ann.phased());
getResources().setPhased(ann.phased());
for (Resource resource : ann.resources()) {
putAnnotation(resource);
... | 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_B... |
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().addA... | 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 da... |
users.forEach((id, properties) -> {
if (StringUtils.isEmpty(properties.getId())) {
properties.setId(id);
}
for (EmbedAuthenticationInfo.PermissionInfo permissionInfo : properties.getPermissions()) {
for (Map<String, Object> objectMap : permiss... | 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> ... |
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();
... | 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;
... |
if (dataAccessController == null) {
log.warn("dataAccessController is null,skip result access control!");
return;
}
if (context.getDefinition().getResources() == null) {
return;
}
if (handleEvent(context, HandleType.DATA)) {
retur... | 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())
.g... | 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 stat... |
DataAccessHandlerContext requestContext = new DataAccessHandlerContext();
Authentication authentication = context.getAuthentication();
requestContext.setDimensions(authentication.getDimensions(type));
requestContext.setAuthentication(context.getAuthentication());
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 != 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(Data... |
FieldFilterDataAccessConfig filterDataAccessConfig = ((FieldFilterDataAccessConfig) access);
switch (access.getAction()) {
case Permission.ACTION_QUERY:
case Permission.ACTION_GET:
return doQueryAccess(filterDataAccessConfig, context);
case Permissio... | 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 = ((Pager... | 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 = Authentic... | 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 Auth... |
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");
... | 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... |
String token = Optional.ofNullable(exchange.getRequest()
.getHeaders()
.getFirst(headerName))
.orElseGet(() -> exchange.getRequest().getQueryParams().getFirst(parameterName));
if (token == null) {
return Mono.empty();
}
return ... | 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
... |
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 ge... |
String token = IDGenerator.MD5.generate();
return new GeneratedToken() {
@Override
public Map<String, Object> getResponse() {
return Collections.singletonMap("expires", timeout);
}
@Override
public String getToken() {
... | 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 a... |
HttpServletRequest request = WebUtils.getHttpServletRequest();
if (null == request) {
throw new UnsupportedOperationException();
}
int timeout = request.getSession().getMaxInactiveInterval() * 1000;
String sessionId = request.getSession().getId();
return n... | 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(HttpServletRequ... |
HttpSession session = request.getSession(false);
if (session != null) {
String sessionId = session.getId();
UserToken token = userTokenManager.getByToken(sessionId).block();
long interval = session.getMaxInactiveInterval();
//当前已登录token已失效但是session未失效
... | 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> ... |
UserToken token = UserTokenHolder.currentToken();
String tokenType = (String) event.getParameter("token_type").orElse(defaultTokenType);
if (token != null) {
//先退出已登陆的用户
event.async(userTokenManager.signOutByToken(token.getToken()));
}
//创建token
... | 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(AuthorizationExitE... |
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
... |
return Flux
.fromIterable(parsers)
.flatMap(parser -> parser.parseToken(exchange))
.next()
.map(token -> chain
.filter(exchange)
.contextWrite(Context.of(ParsedToken.class, token)))
... | 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 WebUserTokenInt... |
List<ParsedToken> tokens = userTokenParser
.stream()
.map(parser -> parser.parseToken(request))
.filter(Objects::nonNull)
.collect(Collectors.toList());
if (tokens.isEmpty()) {
if (enableBasicAuthorization && handler instanceo... | 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(Stri... |
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,
... |
CompositeOAuth2GrantService grantService = new CompositeOAuth2GrantService();
grantService.setAuthorizationCodeGranter(codeProvider.getIfAvailable());
grantService.setClientCredentialGranter(credentialProvider.getIfAvailable());
grantService.setRefreshTokenGranter(refres... | 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> ge... |
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.spl... | 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 De... |
return Mono
.justOrEmpty(request.code())
.map(this::getRedisKey)
.flatMap(redis.opsForValue()::get)
.switchIfEmpty(Mono.error(() -> new OAuth2Exception(ErrorType.ILLEGAL_CODE)))
//移除code
.flatMap(cache -> redis.ops... | 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> requestToke... |
OAuth2Client client = request.getClient();
return authenticationManager
.getByUserId(client.getUserId())
.flatMap(auth -> accessTokenManager
.createAccessToken(client.getClientId(), auth, true)
.flatMap(token -> new OAuth... | 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 A... |
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("[:]");
... | 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", req... |
Map<String, String> param = new HashMap<>(exchange.getRequest().getQueryParams().toSingleValueMap());
return Authentication
.currentReactive()
.switchIfEmpty(Mono.error(UnAuthorizedException::new))
.flatMap(auth -> this
.getOAuth2... | 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);
... |
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> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.