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 |
|---|---|---|---|---|---|---|---|---|---|
tonikelope_megabasterd | megabasterd/src/main/java/com/tonikelope/megabasterd/SpeedMeter.java | SpeedMeter | run | class SpeedMeter implements Runnable {
public static final int SLEEP = 3000;
public static final int CHUNK_SPEED_QUEUE_MAX_SIZE = 20;
private static final Logger LOG = Logger.getLogger(SpeedMeter.class.getName());
private final JLabel _speed_label;
private final JLabel _rem_label;
private final... |
long global_speed, global_progress, global_size;
boolean visible = false;
_speed_label.setVisible(true);
_rem_label.setVisible(true);
_speed_label.setText("");
_rem_label.setText("");
do {
try {
if (!_transferences.isEmpty()) {
... | 1,053 | 642 | 1,695 | <no_super_class> |
tonikelope_megabasterd | megabasterd/src/main/java/com/tonikelope/megabasterd/SqliteSingleton.java | SqliteSingleton | getConn | class SqliteSingleton {
public static final String SQLITE_FILE = "megabasterd.db";
public static final int VALIDATION_TIMEOUT = 15;
private static final Logger LOG = Logger.getLogger(SqliteSingleton.class.getName());
public static SqliteSingleton getInstance() {
return LazyHolder.INSTANCE;
... |
Connection conn = null;
try {
if (!_connections_map.containsKey(Thread.currentThread()) || !(conn = _connections_map.get(Thread.currentThread())).isValid(VALIDATION_TIMEOUT)) {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sq... | 263 | 222 | 485 | <no_super_class> |
tonikelope_megabasterd | megabasterd/src/main/java/com/tonikelope/megabasterd/StreamChunk.java | StreamChunk | getOutputStream | class StreamChunk {
private static final Logger LOG = Logger.getLogger(StreamChunk.class.getName());
private final long _offset;
private final long _size;
private final String _url;
private final ByteArrayOutInputStream _data_os;
private boolean _writable;
public StreamChunk(long offset, ... |
if (!_writable) {
throw new IOException("Chunk outputstream is not available!");
}
return _data_os;
| 450 | 40 | 490 | <no_super_class> |
tonikelope_megabasterd | megabasterd/src/main/java/com/tonikelope/megabasterd/StreamChunkManager.java | StreamChunkManager | run | class StreamChunkManager implements Runnable, SecureMultiThreadNotifiable {
public static final int CHUNK_SIZE = 1048576;
public static final int BUFFER_CHUNKS_SIZE = 20;
private static final Logger LOG = Logger.getLogger(StreamChunkManager.class.getName());
private long _next_offset_required;
priv... |
try {
LOG.log(Level.INFO, "{0} StreamChunkManager: let''s do some work! Start: {1} End: {2}", new Object[]{Thread.currentThread().getName(), _start_offset, _end_offset});
while (!_exit && _bytes_written < _end_offset) {
while (!_exit && _bytes_written < _end_offset... | 1,122 | 492 | 1,614 | <no_super_class> |
tonikelope_megabasterd | megabasterd/src/main/java/com/tonikelope/megabasterd/StreamThrottlerSupervisor.java | StreamThrottlerSupervisor | run | class StreamThrottlerSupervisor implements Runnable, SecureMultiThreadNotifiable {
private static final Logger LOG = Logger.getLogger(StreamThrottlerSupervisor.class.getName());
private ConcurrentLinkedQueue<Integer> _input_slice_queue, _output_slice_queue;
private final int _slice_size;
private vol... |
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
synchronized (_timer_lock) {
_timer_lock.notify();
}
}
};
ConcurrentLinkedQueue<Integer> old_input_que... | 1,002 | 432 | 1,434 | <no_super_class> |
tonikelope_megabasterd | megabasterd/src/main/java/com/tonikelope/megabasterd/ThrottledInputStream.java | ThrottledInputStream | read | class ThrottledInputStream extends InputStream {
private static final Logger LOG = Logger.getLogger(ThrottledInputStream.class.getName());
private final InputStream _rawStream;
private final StreamThrottlerSupervisor _stream_supervisor;
private Integer _slice_size;
private boolean _stream_finis... |
int readLen;
if (_stream_supervisor.getMaxBytesPerSecInput() > 0) {
if (!_stream_finish) {
throttle(len);
readLen = _rawStream.read(b, off, _slice_size != null ? _slice_size : len);
if (readLen == -1) {
_stream_finis... | 877 | 232 | 1,109 | <methods>public void <init>() ,public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public static java.io.InputStream nullInputStream() ,public abstract int read() throws java.io.IOException,public int read(b... |
tonikelope_megabasterd | megabasterd/src/main/java/com/tonikelope/megabasterd/ThrottledOutputStream.java | ThrottledOutputStream | write | class ThrottledOutputStream extends OutputStream {
private static final Logger LOG = Logger.getLogger(ThrottledOutputStream.class.getName());
private final OutputStream _rawStream;
private final StreamThrottlerSupervisor _stream_supervisor;
private Integer _slice_size;
public ThrottledOutputStr... |
if (_stream_supervisor.getMaxBytesPerSecOutput() > 0) {
int written = 0;
do {
throttle(len - written);
_rawStream.write(b, off + written, _slice_size != null ? _slice_size : len - written);
written += _slice_size != null ? _slice_siz... | 454 | 135 | 589 | <methods>public void <init>() ,public void close() throws java.io.IOException,public void flush() throws java.io.IOException,public static java.io.OutputStream nullOutputStream() ,public abstract void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], in... |
tonikelope_megabasterd | megabasterd/src/main/java/com/tonikelope/megabasterd/UploadMACGenerator.java | UploadMACGenerator | run | class UploadMACGenerator implements Runnable, SecureSingleThreadNotifiable {
private static final Logger LOG = Logger.getLogger(UploadMACGenerator.class.getName());
private final Upload _upload;
private final Object _secure_notify_lock;
private volatile boolean _notified;
private volatile boolean ... |
LOG.log(Level.INFO, "{0} MAC GENERATOR {1} Hello!", new Object[]{Thread.currentThread().getName(), getUpload().getFile_name()});
try {
long chunk_id = 1L, tot = 0L;
boolean mac = false;
int cbc_per = 0;
int[] file_mac = new int[]{0, 0, 0, 0};
... | 410 | 1,616 | 2,026 | <no_super_class> |
tonikelope_megabasterd | megabasterd/src/main/java/com/tonikelope/megabasterd/UploadManager.java | UploadManager | copyAllLinksToClipboard | class UploadManager extends TransferenceManager {
private static final Logger LOG = Logger.getLogger(UploadManager.class.getName());
private final Object _log_file_lock;
public UploadManager(MainPanel main_panel) {
super(main_panel, main_panel.getMax_ul(), main_panel.getView().getStatus_up_label... |
int total = 0;
ArrayList<String> links = new ArrayList<>();
String out = "";
for (Transference t : _transference_waitstart_aux_queue) {
Upload up = (Upload) t;
links.add(up.getFile_name() + " [" + up.getMa().getEmail() + "] " + (up.getFolder_link() != null ? ... | 678 | 553 | 1,231 | <methods>public void <init>(com.tonikelope.megabasterd.MainPanel, int, javax.swing.JLabel, javax.swing.JPanel, javax.swing.JButton, javax.swing.JButton, javax.swing.MenuElement) ,public void bottomWaitQueue(com.tonikelope.megabasterd.Transference) ,public int calcTotalSlotsCount() ,public void cancelAllTransferences() ... |
tonikelope_megabasterd | megabasterd/src/main/java/com/tonikelope/megabasterd/WarningExitMessage.java | WarningExitMessage | initComponents | class WarningExitMessage extends javax.swing.JDialog {
MainPanel _main_panel;
boolean _restart;
/**
* Creates new form WarningExitMessage
*/
public WarningExitMessage(java.awt.Frame parent, boolean modal, MainPanel main_panel, boolean restart) {
super(parent, modal);
MiscTool... |
jPanel1 = new javax.swing.JPanel();
warning_label = new javax.swing.JLabel();
exit_button = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("Exit");
setUndecorated(true);
jPanel1.setBorder(new java... | 467 | 1,063 | 1,530 | <methods>public void <init>() ,public void <init>(java.awt.Frame) ,public void <init>(java.awt.Dialog) ,public void <init>(java.awt.Window) ,public void <init>(java.awt.Frame, boolean) ,public void <init>(java.awt.Frame, java.lang.String) ,public void <init>(java.awt.Dialog, boolean) ,public void <init>(java.awt.Dialog... |
zlt2000_microservices-platform | microservices-platform/zlt-business/code-generator/src/main/java/com/central/generator/controller/SysGeneratorController.java | SysGeneratorController | makeCode | class SysGeneratorController {
@Autowired
private SysGeneratorService sysGeneratorService;
/**
* 列表
*/
@ResponseBody
@GetMapping("/list")
public PageResult getTableList(@RequestParam Map<String, Object> params) {
return sysGeneratorService.queryList(params);
}
... |
byte[] data = sysGeneratorService.generatorCode(tables.split(","));
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"generator.zip\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stre... | 160 | 111 | 271 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-business/code-generator/src/main/java/com/central/generator/service/impl/SysGeneratorServiceImpl.java | SysGeneratorServiceImpl | generatorCode | class SysGeneratorServiceImpl extends ServiceImpl implements SysGeneratorService {
@Autowired
private SysGeneratorMapper sysGeneratorMapper;
@Override
public PageResult<Map<String, Object>> queryList(Map<String, Object> map) {
Page<Map<String, Object>> page = new Page<>(MapUtils.getIntege... |
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (
ZipOutputStream zip = new ZipOutputStream(outputStream)
) {
for (String tableName : tableNames) {
//查询表信息
Map<String, String> table = queryTable(tableName);... | 294 | 176 | 470 | <methods>public void <init>() ,public BaseMapper#RAW getBaseMapper() ,public Class#RAW getEntityClass() ,public Map#RAW getMap(Wrapper#RAW) ,public java.lang.Object getObj(Wrapper#RAW, Function#RAW) ,public java.lang.Object getOne(Wrapper#RAW, boolean) ,public Optional#RAW getOneOpt(Wrapper#RAW, boolean) ,public boolea... |
zlt2000_microservices-platform | microservices-platform/zlt-business/file-center/src/main/java/com/central/file/controller/FileController.java | FileController | delete | class FileController {
@Resource
private IFileService fileService;
/**
* 文件上传
* 根据fileType选择上传方式
*
* @param file
* @return
* @throws Exception
*/
@PostMapping("/files-anon")
public FileInfo upload(@RequestParam("file") MultipartFile file) throws Excep... |
try {
fileService.delete(id);
return Result.succeed("操作成功");
} catch (Exception ex) {
return Result.failed("操作失败");
}
| 275 | 57 | 332 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-business/file-center/src/main/java/com/central/file/service/impl/AbstractIFileService.java | AbstractIFileService | findList | class AbstractIFileService extends ServiceImpl<FileMapper, FileInfo> implements IFileService {
private static final String FILE_SPLIT = ".";
@Override
public FileInfo upload(MultipartFile file) {
FileInfo fileInfo = FileUtil.getFileInfo(file);
if (!fileInfo.getName().contains(FILE_SPL... |
Page<FileInfo> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
List<FileInfo> list = baseMapper.findList(page, params);
return PageResult.<FileInfo>builder().data(list).code(0).count(page.getTotal()).build();
| 495 | 90 | 585 | <methods>public void <init>() ,public com.central.file.mapper.FileMapper getBaseMapper() ,public Class<com.central.file.model.FileInfo> getEntityClass() ,public Map<java.lang.String,java.lang.Object> getMap(Wrapper<com.central.file.model.FileInfo>) ,public V getObj(Wrapper<com.central.file.model.FileInfo>, Function<? s... |
zlt2000_microservices-platform | microservices-platform/zlt-business/file-center/src/main/java/com/central/file/service/impl/S3Service.java | S3Service | out | class S3Service extends AbstractIFileService {
@Resource
private S3Template s3Template;
@Override
protected String fileType() {
return FileServerProperties.TYPE_S3;
}
@Override
protected ObjectInfo uploadFile(MultipartFile file) {
return s3Template.upload(file);
}
... |
FileInfo fileInfo = baseMapper.selectById(id);
if (fileInfo != null) {
S3Object s3Object = parsePath(fileInfo.getPath());
s3Template.out(s3Object.bucketName, s3Object.objectName, os);
}
| 343 | 75 | 418 | <methods>public non-sealed void <init>() ,public void delete(java.lang.String) ,public PageResult<com.central.file.model.FileInfo> findList(Map<java.lang.String,java.lang.Object>) ,public com.central.file.model.FileInfo upload(org.springframework.web.multipart.MultipartFile) <variables>private static final java.lang.St... |
zlt2000_microservices-platform | microservices-platform/zlt-business/file-center/src/main/java/com/central/file/utils/FileUtil.java | FileUtil | deleteFile | class FileUtil {
private FileUtil() {
throw new IllegalStateException("Utility class");
}
public static FileInfo getFileInfo(MultipartFile file) {
FileInfo fileInfo = new FileInfo();
fileInfo.setId(IdUtil.fastSimpleUUID());
fileInfo.setName(file.getOriginalFilename());
fileInfo.setContentType(fil... |
File file = new File(pathname);
if (file.exists()) {
boolean flag = file.delete();
if (flag) {
File[] files = file.getParentFile().listFiles();
if (files == null || files.length == 0) {
file.getParentFile().delete();
}
}
return flag;
}
return false;
| 470 | 115 | 585 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-business/search-center/search-client/src/main/java/com/central/search/client/feign/fallback/AggregationServiceFallbackFactory.java | AggregationServiceFallbackFactory | create | class AggregationServiceFallbackFactory implements FallbackFactory<AggregationService> {
@Override
public AggregationService create(Throwable throwable) {<FILL_FUNCTION_BODY>}
} |
return (indexName, routing) -> {
log.error("通过索引{}搜索异常:{}", indexName, throwable);
return MapUtil.newHashMap(0);
};
| 53 | 51 | 104 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-business/search-center/search-client/src/main/java/com/central/search/client/feign/fallback/SearchServiceFallbackFactory.java | SearchServiceFallbackFactory | create | class SearchServiceFallbackFactory implements FallbackFactory<SearchService> {
@Override
public SearchService create(Throwable throwable) {<FILL_FUNCTION_BODY>}
} |
return (indexName, searchDto) -> {
log.error("通过索引{}搜索异常:{}", indexName, throwable);
return PageResult.<JsonNode>builder().build();
};
| 48 | 55 | 103 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-business/search-center/search-client/src/main/java/com/central/search/client/service/impl/QueryServiceImpl.java | QueryServiceImpl | setLogicDelQueryStr | class QueryServiceImpl implements IQueryService {
@Resource
private SearchService searchService;
@Resource
private AggregationService aggregationService;
@Override
public PageResult<JsonNode> strQuery(String indexName, SearchDto searchDto) {
return strQuery(indexName, searchDto, null);... |
if (logicDelDto != null
&& StrUtil.isNotEmpty(logicDelDto.getLogicDelField())
&& StrUtil.isNotEmpty(logicDelDto.getLogicNotDelValue())) {
String result;
//搜索条件
String queryStr = searchDto.getQueryStr();
//拼凑逻辑删除的条件
Stri... | 334 | 188 | 522 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-business/search-center/search-server/src/main/java/com/central/admin/controller/IndexController.java | IndexController | createIndex | class IndexController {
@Autowired
private IIndexService indexService;
@Autowired
private IndexProperties indexProperties;
@PostMapping("/index")
public Result createIndex(@RequestBody IndexDto indexDto) throws IOException {<FILL_FUNCTION_BODY>}
/**
* 索引列表
*/
@GetMapping("/i... |
if (indexDto.getNumberOfShards() == null) {
indexDto.setNumberOfShards(1);
}
if (indexDto.getNumberOfReplicas() == null) {
indexDto.setNumberOfReplicas(0);
}
indexService.create(indexDto);
return Result.succeed("操作成功");
| 287 | 98 | 385 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-business/search-center/search-server/src/main/java/com/central/admin/service/impl/IndexServiceImpl.java | IndexServiceImpl | show | class IndexServiceImpl implements IIndexService {
private ObjectMapper mapper = new ObjectMapper();
private final RestHighLevelClient client;
public IndexServiceImpl(RestHighLevelClient client) {
this.client = client;
}
@Override
public boolean create(IndexDto indexDto) throws IOExcep... |
GetIndexRequest request = new GetIndexRequest(indexName);
GetIndexResponse getIndexResponse = client
.indices().get(request, RequestOptions.DEFAULT);
MappingMetadata mappingMetadata = getIndexResponse.getMappings().get(indexName);
Map<String, Object> mappOpenMap = mappin... | 631 | 323 | 954 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-business/search-center/search-server/src/main/java/com/central/search/controller/SearchController.java | SearchController | strQuery | class SearchController {
private final ISearchService searchService;
public SearchController(ISearchService searchService) {
this.searchService = searchService;
}
/**
* 查询文档列表
* @param indexName 索引名
* @param searchDto 搜索Dto
*/
@PostMapping("/{indexName}")
public Pag... |
if (searchDto == null) {
searchDto = new SearchDto();
}
return searchService.strQuery(indexName, searchDto);
| 143 | 44 | 187 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-business/search-center/search-server/src/main/java/com/central/search/service/impl/SearchServiceImpl.java | SearchServiceImpl | strQuery | class SearchServiceImpl implements ISearchService {
private final RestHighLevelClient client;
public SearchServiceImpl(RestHighLevelClient client) {
this.client = client;
}
/**
* StringQuery通用搜索
* @param indexName 索引名
* @param searchDto 搜索Dto
* @return
*/
@Override... |
return SearchBuilder.builder(client, indexName)
.setStringQuery(searchDto.getQueryStr())
.addSort(searchDto.getSortCol(), searchDto.getSortOrder())
.setIsHighlight(searchDto.getIsHighlighter())
.getPage(searchDto.getPage(), searchDto.getLimit());
... | 133 | 91 | 224 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-business/user-center/src/main/java/com/central/user/controller/SysMenuController.java | SysMenuController | treeBuilder | class SysMenuController {
@Autowired
private ISysMenuService menuService;
/**
* 两层循环实现建树
*
* @param sysMenus
* @return
*/
public static List<SysMenu> treeBuilder(List<SysMenu> sysMenus) {<FILL_FUNCTION_BODY>}
/**
* 删除菜单
*
* @param id
*/
... |
List<SysMenu> menus = new ArrayList<>();
for (SysMenu sysMenu : sysMenus) {
if (ObjectUtil.equal(-1L, sysMenu.getParentId())) {
menus.add(sysMenu);
}
for (SysMenu menu : sysMenus) {
if (menu.getParentId().equals(sysMenu.getId())... | 1,461 | 176 | 1,637 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-business/user-center/src/main/java/com/central/user/controller/SysRoleController.java | SysRoleController | deleteRole | class SysRoleController {
@Autowired
private ISysRoleService sysRoleService;
/**
* 后台管理查询角色
* @param params
* @return
*/
@Operation(summary = "后台管理查询角色")
@GetMapping("/roles")
public PageResult<SysRole> findRoles(@RequestParam Map<String, Object> params) {
... |
try {
if (id == 1L) {
return Result.failed("管理员不可以删除");
}
sysRoleService.deleteRole(id);
return Result.succeed("操作成功");
} catch (Exception e) {
log.error("role-deleteRole-error", e);
return Result.failed("操... | 424 | 105 | 529 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysMenuServiceImpl.java | SysMenuServiceImpl | setMenuToRole | class SysMenuServiceImpl extends SuperServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {
@Resource
private ISysRoleMenuService roleMenuService;
@Transactional(rollbackFor = Exception.class)
@Override
public void setMenuToRole(Long roleId, Set<Long> menuIds) {<FILL_FUNCTION_BODY>}
/**
*... |
roleMenuService.delete(roleId, null);
if (!CollectionUtils.isEmpty(menuIds)) {
List<SysRoleMenu> roleMenus = new ArrayList<>(menuIds.size());
menuIds.forEach(menuId -> roleMenus.add(new SysRoleMenu(roleId, menuId)));
roleMenuService.saveBatch(roleMenus);
}
| 550 | 109 | 659 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysRoleServiceImpl.java | SysRoleServiceImpl | saveRole | class SysRoleServiceImpl extends SuperServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
private final static String LOCK_KEY_ROLECODE = "rolecode:";
@Resource
private SysUserRoleMapper userRoleMapper;
@Resource
private SysRoleMenuMapper roleMenuMapper;
@Autowired
... |
String roleCode = sysRole.getCode();
super.saveIdempotency(sysRole, lock
, LOCK_KEY_ROLECODE+roleCode, new QueryWrapper<SysRole>().eq("code", roleCode), "角色code已存在");
| 546 | 70 | 616 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/component/CustomAuthorizationServiceIntrospector.java | CustomAuthorizationServiceIntrospector | introspect | class CustomAuthorizationServiceIntrospector implements OpaqueTokenIntrospector {
private final OAuth2AuthorizationService authorizationService;
@Override
public OAuth2AuthenticatedPrincipal introspect(String token) {<FILL_FUNCTION_BODY>}
} |
OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
if (Objects.isNull(authorization)) {
throw new InvalidBearerTokenException("invalid_token: " + token);
}
// 客户端模式默认返回
if (AuthorizationGrantType.CLIENT_CREDENT... | 70 | 298 | 368 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/component/CustomBearerTokenResolver.java | CustomBearerTokenResolver | isParameterTokenEnabledForRequest | class CustomBearerTokenResolver implements BearerTokenResolver {
private final boolean allowFormEncodedBodyParameter = false;
private final boolean allowUriQueryParameter = true;
private final String bearerTokenHeaderName = HttpHeaders.AUTHORIZATION;
private final PathMatcher pathMatcher = new AntPathMatcher();
... |
return ((this.allowFormEncodedBodyParameter && "POST".equals(request.getMethod())
&& MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(request.getContentType()))
|| (this.allowUriQueryParameter && "GET".equals(request.getMethod())));
| 584 | 76 | 660 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/component/CustomReactiveAuthorizationServiceIntrospector.java | CustomReactiveAuthorizationServiceIntrospector | convertClaimsSet | class CustomReactiveAuthorizationServiceIntrospector implements ReactiveOpaqueTokenIntrospector {
@Override
public Mono<OAuth2AuthenticatedPrincipal> introspect(String accessTokenValue) {
return Mono.just(accessTokenValue)
.map(AuthUtils::checkAccessTokenToAuth)
.map(this... |
Map<String, Object> claims = new HashMap<>();
Collection<GrantedAuthority> authorities = new ArrayList<>();
claims.put(SecurityConstants.CLIENT_ID, authorization.getRegisteredClientId());
claims.putAll(authorization.getAttributes());
Authentication authentication = (Authentica... | 200 | 152 | 352 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/component/CustomServerBearerTokenAuthConverter.java | CustomServerBearerTokenAuthConverter | token | class CustomServerBearerTokenAuthConverter implements ServerAuthenticationConverter {
private final PathMatcher pathMatcher = new AntPathMatcher();
private static final Pattern authorizationPattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-._~+/]+=*)$",
Pattern.CASE_INSENSITIVE);
private ... |
boolean match = Arrays.stream(permitProperties.getUrls())
.anyMatch(url -> pathMatcher.match(url, request.getURI().getPath()));
if (match) {
return null;
}
String authorizationHeaderToken = resolveFromAuthorizationHeader(request.getHeaders());
Strin... | 920 | 209 | 1,129 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/BaseSecurityConfig.java | BaseSecurityConfig | jwkSource | class BaseSecurityConfig {
@Bean
public OAuth2AuthorizationService oAuth2AuthorizationService(SecurityProperties securityProperties, RedissonClient redisson) {
String tokenType = securityProperties.getResourceServer().getTokenType();
if (TokenType.MEMORY.getName().equals(tokenType)) {
... |
RBucket<String> rBucket = redisson.getBucket(SecurityConstants.AUTHORIZATION_JWS_PREFIX_KEY);
String jwkSetCache = rBucket.get();
JWKSet jwkSet;
// 多个服务共用同一个 jwkSource 对象
if (StrUtil.isEmpty(jwkSetCache)) {
KeyPair keyPair = generateRsaKey();
RSAPublicKey... | 662 | 373 | 1,035 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/DefaultWebFluxResourceServerConf.java | DefaultWebFluxResourceServerConf | getAuthWebFilter | class DefaultWebFluxResourceServerConf {
@Resource
private SecurityProperties securityProperties;
@Resource
private ServerAuthenticationEntryPoint serverAuthenticationEntryPoint;
@Resource
private ServerAccessDeniedHandler serverAccessDeniedHandler;
@Autowired(required = false)
privat... |
AuthenticationWebFilter oauth2 = new AuthenticationWebFilter(this.getAuthenticationManager());
oauth2.setServerAuthenticationConverter(this.getAuthenticationConverter());
oauth2.setAuthenticationFailureHandler(this.getFailureHandler());
if (successHandler != null) {
oauth2.s... | 697 | 94 | 791 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/WcAuthConfigurator.java | WcAuthConfigurator | checkOrigin | class WcAuthConfigurator extends ServerEndpointConfig.Configurator {
@Override
public boolean checkOrigin(String originHeaderValue) {<FILL_FUNCTION_BODY>}
} |
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
try {
//检查token有效性
AuthUtils.checkAccessToken(servletRequestAttributes.getRequest());
} catch (Exception e) {
log.error("WebSocket-auth... | 48 | 99 | 147 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/PermitProperties.java | PermitProperties | getUrls | class PermitProperties {
/**
* 监控中心和swagger需要访问的url
*/
private static final String[] ENDPOINTS = {
SecurityConstants.LOGIN_PAGE,
SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/**",
"/doc.html", "/swagger-ui.html", "/v3/api-docs/**", "/swagger-ui/**",
... |
if (httpUrls == null || httpUrls.length == 0) {
return ENDPOINTS;
}
List<String> list = new ArrayList<>();
for (String url : ENDPOINTS) {
list.add(url);
}
for (String url : httpUrls) {
list.add(url);
}
return... | 217 | 120 | 337 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/DefaultPermissionServiceImpl.java | DefaultPermissionServiceImpl | hasPermission | class DefaultPermissionServiceImpl {
@Autowired
private SecurityProperties securityProperties;
private final AntPathMatcher antPathMatcher = new AntPathMatcher();
/**
* 查询当前用户拥有的资源权限
* @param roleCodes 角色code列表,多个以','隔开
* @return
*/
public abstract List<SysMenu> findMenuByRole... |
// 前端跨域OPTIONS请求预检放行 也可通过前端配置代理实现
if (HttpMethod.OPTIONS.name().equalsIgnoreCase(requestMethod)) {
return true;
}
if (!(authentication instanceof AnonymousAuthenticationToken)) {
//判断是否开启url权限验证
if (!securityProperties.getAuth().getUrlPermission().get... | 344 | 605 | 949 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java | AuthUtils | extractClientId | class AuthUtils {
private AuthUtils() {
throw new IllegalStateException("Utility class");
}
private static final String BASIC_ = "Basic ";
private static final Pattern authorizationPattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-:._~+/]+=*)$",
Pattern.CASE_INSENSITIV... |
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith(BASIC_)) {
throw new CustomOAuth2AuthorizationException("The client information in the request header is empty");
}
String[] clientArr = extractHeaderClient(header);
re... | 1,310 | 92 | 1,402 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/config/BannerInitializer.java | BannerInitializer | initialize | class BannerInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {<FILL_FUNCTION_BODY>}
} |
if (!(applicationContext instanceof AnnotationConfigApplicationContext)) {
LogoBanner logoBanner = new LogoBanner(BannerInitializer.class, "/zltmp/logo.txt", "Welcome to zlt", 5, 6, new Color[5], true);
CustomBanner.show(logoBanner, new Description(BannerConstant.VERSION + ":", CommonCo... | 50 | 181 | 231 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/config/DefaultAsycTaskConfig.java | DefaultAsycTaskConfig | taskExecutor | class DefaultAsycTaskConfig {
/**
* 线程池维护线程的最小数量.
*/
@Value("${asyc-task.corePoolSize:10}")
private int corePoolSize;
/**
* 线程池维护线程的最大数量
*/
@Value("${asyc-task.maxPoolSize:200}")
private int maxPoolSize;
/**
* 队列最大长度
*/
@Value("${asyc-task.queueCapacity:1... |
ThreadPoolTaskExecutor executor = new CustomThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix(threadNamePrefix);
/*
rejection-policy:当p... | 227 | 166 | 393 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/datascope/mp/interceptor/EnableQuerySqlLogInnerInterceptor.java | EnableQuerySqlLogInnerInterceptor | beforeQuery | class EnableQuerySqlLogInnerInterceptor implements InnerInterceptor{
private InnerInterceptor delegate;
public EnableQuerySqlLogInnerInterceptor(InnerInterceptor delegate) {
Assert.notNull(delegate, "委派类不能为空");
this.delegate = delegate;
}
@Override
public void beforeQuery(Executor ... |
PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);
String sql = boundSql.getSql();
log.info("执行mapperId{},原始sql为{}", ms.getId(), sql);
delegate.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
log.info("执行mapperId{}, 修改sql为{}", ms.getId(), m... | 137 | 112 | 249 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/datascope/mp/sql/handler/CreatorDataScopeSqlHandler.java | CreatorDataScopeSqlHandler | handleScopeSql | class CreatorDataScopeSqlHandler implements SqlHandler{
@Resource
UserService userService;
@Resource
private DataScopeProperties dataScopeProperties;
/**
* 返回需要增加的where条件,返回空字符的话则代表不需要权限控制
*
* @return where条件
* 如果角色是全部权限的话则不进行控制,如果是个人权限的话则自动加入create_id = user_id
*/
@O... |
LoginAppUser user = LoginUserContextHolder.getUser();
Assert.notNull(user, "登陆人不能为空");
List<SysRole> roleList = userService.findRolesByUserId(user.getId());
return StrUtil.isBlank(dataScopeProperties.getCreatorIdColumnName())
||CollUtil.isEmpty(roleList)
... | 138 | 233 | 371 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java | UserServiceFallbackFactory | create | class UserServiceFallbackFactory implements FallbackFactory<UserService> {
@Override
public UserService create(Throwable throwable) {<FILL_FUNCTION_BODY>}
} |
return new UserService() {
@Override
public SysUser selectByUsername(String username) {
log.error("通过用户名查询用户异常:{}", username, throwable);
return new SysUser();
}
@Override
public SysUser findByUsername(String username)... | 48 | 388 | 436 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/lock/LockAspect.java | LockAspect | aroundLock | class LockAspect {
@Autowired(required = false)
private DistributedLock locker;
/**
* 用于SpEL表达式解析.
*/
private SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
/**
* 用于获取方法参数定义名字.
*/
private DefaultParameterNameDiscoverer nameDiscoverer = new DefaultPar... |
if (lock == null) {
// 获取类上的注解
lock = point.getTarget().getClass().getDeclaredAnnotation(Lock.class);
}
String lockKey = lock.key();
if (locker == null) {
throw new LockException("DistributedLock is null");
}
if (StrUtil.isEmpty(lockKe... | 358 | 336 | 694 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/passwordEncoder/SM3PasswordEncoder.java | SM3PasswordEncoder | matches | class SM3PasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
return SmUtil.sm3(rawPassword.toString());
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {<FILL_FUNCTION_BODY>}
} |
if (rawPassword == null) {
throw new IllegalArgumentException("rawPassword cannot be null");
}
if (encodedPassword == null || encodedPassword.length() == 0) {
log.warn("Empty encoded password");
return false;
}
String rawPasswordEncoded = this... | 81 | 95 | 176 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/properties/DataScopeProperties.java | DataScopeProperties | setIgnoreSqls | class DataScopeProperties {
private static final Set<String> INGORE_SQL_ID = ImmutableSet
.of("com.central.user.mapper.findRolesByUserId"
, "com.central.user.mapper.SysUserMapper.selectList"
, "com.central.user.mapper.SysUserRoleMapper.findRolesByUserId"
... |
Set<String> ingoreSet = new HashSet<>();
ingoreSet.addAll(INGORE_SQL_ID);
if(CollUtil.isNotEmpty(ignoreSqls)){
ingoreSet.addAll(ignoreSqls);
}
this.ignoreSqls = ingoreSet;
| 447 | 81 | 528 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/service/impl/SuperServiceImpl.java | SuperServiceImpl | saveIdempotency | class SuperServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements ISuperService<T> {
@Override
public boolean saveIdempotency(T entity, DistributedLock locker, String lockKey, Wrapper<T> countWrapper, String msg) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public boolean sav... |
if (locker == null) {
throw new LockException("DistributedLock is null");
}
if (StrUtil.isEmpty(lockKey)) {
throw new LockException("lockKey is null");
}
try (
ZLock lock = locker.tryLock(lockKey, 10, 60, TimeUnit.SECONDS);
... | 488 | 209 | 697 | <methods>public void <init>() ,public M getBaseMapper() ,public Class<T> getEntityClass() ,public Map<java.lang.String,java.lang.Object> getMap(Wrapper<T>) ,public V getObj(Wrapper<T>, Function<? super java.lang.Object,V>) ,public T getOne(Wrapper<T>, boolean) ,public Optional<T> getOneOpt(Wrapper<T>, boolean) ,public ... |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/AddrUtil.java | AddrUtil | getRemoteAddr | class AddrUtil {
private final static String UNKNOWN_STR = "unknown";
/**
* 获取客户端IP地址
*/
public static String getRemoteAddr(HttpServletRequest request) {<FILL_FUNCTION_BODY>}
private static boolean isEmptyIP(String ip) {
if (StrUtil.isEmpty(ip) || UNKNOWN_STR.equalsIgnoreCase(ip)) {
... |
String ip = request.getHeader("X-Forwarded-For");
if (isEmptyIP(ip)) {
ip = request.getHeader("Proxy-Client-IP");
if (isEmptyIP(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
if (isEmptyIP(ip)) {
ip = request.getHeader("H... | 206 | 323 | 529 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/CustomBanner.java | CustomBanner | show | class CustomBanner {
public static void show(LogoBanner logoBanner, Description... descriptionList) {<FILL_FUNCTION_BODY>}
} |
String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true");
if (!Boolean.valueOf(bannerShown)) {
return;
}
System.out.println("");
String bannerShownAnsiMode = System.getProperty(BannerConstant.BANNER_SHOWN_ANSI_MODE, "false");
if (Boolean.... | 44 | 238 | 282 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/ExcelUtil.java | ExcelUtil | defaultExport | class ExcelUtil {
private ExcelUtil() {
throw new IllegalStateException("Utility class");
}
/**
* 导出
*
* @param list 数据列表
* @param title 标题
* @param sheetName sheet名称
* @param pojoClass 元素类型
* @param fileName 文件名
* @param is... |
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.XSSF);
if (workbook != null) {
downLoadExcel(fileName, response, workbook);
}
| 1,000 | 56 | 1,056 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/JsonUtil.java | JsonUtil | parse | class JsonUtil {
private final static ObjectMapper MAPPER = new ObjectMapper();
static {
// 忽略在json字符串中存在,但是在java对象中不存在对应属性的情况
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 忽略空Bean转json的错误
MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS... |
if (StringUtils.isBlank(json)) {
return null;
}
try {
return MAPPER.readTree(json);
} catch (IOException e) {
throw new RuntimeException(e);
}
| 1,757 | 62 | 1,819 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/LoginUserUtils.java | LoginUserUtils | getLoginAppUser | class LoginUserUtils {
private final static String ATT_PERMISSIONS = "permissions";
/**
* 获取当前登录人
*/
public static LoginAppUser getCurrentUser(HttpServletRequest request, boolean isFull) {
LoginAppUser user = null;
Authentication authentication = SecurityContextHolder.getContext(... |
List<SysRole> sysRoles = sysUser.getRoles();
Collection<GrantedAuthority> authorities = new HashSet<>();
if (sysRoles != null) {
sysRoles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getCode())));
}
return new LoginAppUser(sysUser.getId()
... | 1,237 | 146 | 1,383 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/PwdEncoderUtil.java | PwdEncoderUtil | getDelegatingPasswordEncoder | class PwdEncoderUtil {
public static PasswordEncoder getDelegatingPasswordEncoder(String encodingId) {<FILL_FUNCTION_BODY>}
} |
Map<String, PasswordEncoder> encoders = new HashMap<>();
encoders.put("bcrypt", new BCryptPasswordEncoder());
encoders.put("ldap", new LdapShaPasswordEncoder());
encoders.put("MD4", new Md4PasswordEncoder());
encoders.put("MD5", new MessageDigestPasswordEncoder("MD5"));
... | 43 | 403 | 446 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/ResponseUtil.java | ResponseUtil | responseWriter | class ResponseUtil {
private ResponseUtil() {
throw new IllegalStateException("Utility class");
}
/**
* 通过流写到前端
*
* @param objectMapper 对象序列化
* @param response
* @param msg 返回信息
* @param httpStatus 返回状态码
* @throws IOException
*/
public static vo... |
Result result = Result.of(null, httpStatus, msg);
responseWrite(objectMapper, response, result);
| 415 | 31 | 446 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/RsaUtils.java | RsaUtils | encrypt | class RsaUtils {
/**
* 默认"RSA"="RSA/ECB/PKCS1Padding"
*/
private static final String CIPHER_INSTANCE = "RSA/ECB/PKCS1Padding";
/**
* 公钥加密
* @param content 要加密的内容
* @param publicKey 公钥
*/
public static String encrypt(String content, PublicKey publicKey) {
try{
... |
try{
Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(content);
}catch (Exception e){
e.printStackTrace();
}
return null;
| 835 | 82 | 917 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/Sequence.java | Sequence | getMaxWorkerId | class Sequence {
/**
* 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
*/
private final long twepoch = 1288834974657L;
/**
* 机器标识位数
*/
private final long workerIdBits = 5L;
private final long datacenterIdBits = 5L;
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
private f... |
StringBuilder mpid = new StringBuilder();
mpid.append(datacenterId);
String name = ManagementFactory.getRuntimeMXBean().getName();
if (StrUtil.isNotEmpty(name)) {
/*
* GET jvmPid
*/
mpid.append(name.split(StringPool.AT)[0]);
}
... | 1,473 | 142 | 1,615 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/WebfluxResponseUtil.java | WebfluxResponseUtil | responseWrite | class WebfluxResponseUtil {
/**
* webflux的response返回json对象
*/
public static Mono<Void> responseWriter(ServerWebExchange exchange, int httpStatus, String msg) {
Result result = Result.of(null, httpStatus, msg);
return responseWrite(exchange, httpStatus, result);
}
public static... |
if (httpStatus == 0) {
httpStatus = HttpStatus.INTERNAL_SERVER_ERROR.value();
}
ServerHttpResponse response = exchange.getResponse();
response.getHeaders().setAccessControlAllowCredentials(true);
response.getHeaders().setAccessControlAllowOrigin("*");
respons... | 246 | 196 | 442 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/LoginUserFilter.java | LoginUserFilter | doFilterInternal | class LoginUserFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws IOException, ServletException {<FILL_FUNCTION_BODY>}
} |
try {
LoginAppUser user = LoginUserUtils.getCurrentUser(request, false);
LoginUserContextHolder.setUser(user);
filterChain.doFilter(request, response);
} finally {
LoginUserContextHolder.clear();
}
| 61 | 67 | 128 | <methods>public void <init>() ,public final void doFilter(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, jakarta.servlet.FilterChain) throws jakarta.servlet.ServletException, java.io.IOException<variables>public static final java.lang.String ALREADY_FILTERED_SUFFIX |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/TenantFilter.java | TenantFilter | doFilterInternal | class TenantFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws IOException, ServletException {<FILL_FUNCTION_BODY>}
} |
try {
//优先获取请求参数中的tenantId值
String tenantId = request.getParameter(CommonConstant.TENANT_ID_PARAM);
if (StrUtil.isEmpty(tenantId)) {
tenantId = request.getHeader(SecurityConstants.TENANT_HEADER);
}
//保存租户id
if (StrUtil.isNo... | 61 | 150 | 211 | <methods>public void <init>() ,public final void doFilter(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, jakarta.servlet.FilterChain) throws jakarta.servlet.ServletException, java.io.IOException<variables>public static final java.lang.String ALREADY_FILTERED_SUFFIX |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/DateMetaObjectHandler.java | DateMetaObjectHandler | insertFill | class DateMetaObjectHandler implements MetaObjectHandler {
private MybatisPlusAutoFillProperties autoFillProperties;
public DateMetaObjectHandler(MybatisPlusAutoFillProperties autoFillProperties) {
this.autoFillProperties = autoFillProperties;
}
/**
* 是否开启了插入填充
*/
@Over... |
Object createTime = getFieldValByName(autoFillProperties.getCreateTimeField(), metaObject);
Object updateTime = getFieldValByName(autoFillProperties.getUpdateTimeField(), metaObject);
if (createTime == null || updateTime == null) {
Date date = new Date();
if (create... | 300 | 159 | 459 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/MybatisPlusAutoConfigure.java | MybatisPlusAutoConfigure | paginationInterceptor | class MybatisPlusAutoConfigure {
@Autowired
private TenantLineHandler tenantLineHandler;
@Autowired
private TenantProperties tenantProperties;
@Autowired
private MybatisPlusAutoFillProperties autoFillProperties;
@Autowired
private DataScopeProperties dataScopeProperties;
@Bean
... |
MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
boolean enableTenant = tenantProperties.getEnable();
//是否开启多租户隔离
if (enableTenant) {
CustomTenantInterceptor tenantInterceptor = new CustomTenantInterceptor(
tenantLineHandler, tenantPro... | 259 | 252 | 511 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/TenantAutoConfigure.java | TenantAutoConfigure | tenantLineHandler | class TenantAutoConfigure {
@Autowired
private TenantProperties tenantProperties;
@Bean
public TenantLineHandler tenantLineHandler() {<FILL_FUNCTION_BODY>}
} |
return new TenantLineHandler() {
/**
* 获取租户id
*/
@Override
public Expression getTenantId() {
String tenant = TenantContextHolder.getTenant();
if (tenant != null) {
return new StringValue(TenantCont... | 54 | 184 | 238 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/interceptor/CustomTenantInterceptor.java | CustomTenantInterceptor | beforeQuery | class CustomTenantInterceptor extends TenantLineInnerInterceptor {
private List<String> ignoreSqls;
public CustomTenantInterceptor(TenantLineHandler tenantLineHandler, List<String> ignoreSqls) {
super(tenantLineHandler);
this.ignoreSqls = ignoreSqls;
}
@Override
public void beforeQ... |
if (isIgnoreMappedStatement(ms.getId())) {
return;
}
super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
| 189 | 48 | 237 | <methods>public void <init>() ,public void <init>(com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler) ,public void beforePrepare(org.apache.ibatis.executor.statement.StatementHandler, java.sql.Connection, java.lang.Integer) ,public void beforeQuery(org.apache.ibatis.executor.Executor, org.apache.ibati... |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/config/RestAutoConfigure.java | RestAutoConfigure | elasticsearchClient | class RestAutoConfigure extends AbstractElasticsearchConfiguration {
private final static String SCHEME = "http";
private final static String URI_SPLIT = ":";
@Resource
private ElasticsearchProperties restProperties;
@Resource
private RestClientPoolProperties poolProperties;
@Override
... |
List<String> urlArr = restProperties.getUris();
HttpHost[] httpPostArr = new HttpHost[urlArr.size()];
for (int i = 0; i < urlArr.size(); i++) {
HttpHost httpHost = new HttpHost(urlArr.get(i).split(URI_SPLIT)[0].trim(),
Integer.parseInt(urlArr.get(i).split(URI_SPL... | 102 | 416 | 518 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/chooser/RandomRuleChooser.java | RandomRuleChooser | choose | class RandomRuleChooser implements IRuleChooser {
@Override
public ServiceInstance choose(List<ServiceInstance> instances) {<FILL_FUNCTION_BODY>}
} |
if(CollectionUtils.isNotEmpty(instances)){
int randomValue = ThreadLocalRandom.current().nextInt(instances.size());
ServiceInstance serviceInstance = instances.get(randomValue);
log.info("选择了ip为{}, 端口为:{}的服务", serviceInstance.getHost(), serviceInstance.getPort());
... | 47 | 99 | 146 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/chooser/RoundRuleChooser.java | RoundRuleChooser | choose | class RoundRuleChooser implements IRuleChooser{
private AtomicInteger position;
public RoundRuleChooser() {
this.position = new AtomicInteger(1000);
}
@Override
public ServiceInstance choose(List<ServiceInstance> instances) {<FILL_FUNCTION_BODY>}
} |
if(CollectionUtils.isNotEmpty(instances)){
ServiceInstance serviceInstance = instances.get(Math.abs(position.incrementAndGet() % instances.size()));
log.info("选择了ip为{}, 端口为:{}的服务", serviceInstance.getHost(), serviceInstance.getPort());
return serviceInstance;
}
... | 87 | 92 | 179 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/FeignHttpInterceptorConfig.java | FeignHttpInterceptorConfig | extractHeaderToken | class FeignHttpInterceptorConfig {
protected List<String> requestHeaders = new ArrayList<>();
@PostConstruct
public void initialize() {
requestHeaders.add(SecurityConstants.USER_ID_HEADER);
requestHeaders.add(SecurityConstants.USER_HEADER);
requestHeaders.add(SecurityConstants.ROLE_... |
Enumeration<String> headers = request.getHeaders(CommonConstant.TOKEN_HEADER);
while (headers.hasMoreElements()) {
String value = headers.nextElement();
if ((value.toLowerCase().startsWith(CommonConstant.BEARER_TYPE.toLowerCase()))) {
String authHeaderValue = val... | 522 | 167 | 689 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/FeignInterceptorConfig.java | FeignInterceptorConfig | baseFeignInterceptor | class FeignInterceptorConfig {
/**
* 使用feign client访问别的微服务时,将上游传过来的client等信息放入header传递给下一个服务
*/
@Bean
public RequestInterceptor baseFeignInterceptor() {<FILL_FUNCTION_BODY>}
} |
return template -> {
//传递client
String tenant = TenantContextHolder.getTenant();
if (StrUtil.isNotEmpty(tenant)) {
template.header(SecurityConstants.TENANT_HEADER, tenant);
}
};
| 81 | 69 | 150 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/VersionLoadBalancerConfig.java | VersionLoadBalancerConfig | customRuleChooser | class VersionLoadBalancerConfig{
private IRuleChooser defaultRuleChooser = null;
@Bean
@ConditionalOnMissingBean(IRuleChooser.class)
@ConditionalOnProperty(prefix = ConfigConstants.CONFIG_LOADBALANCE_ISOLATION, value = "chooser")
public IRuleChooser customRuleChooser(Environment environment, Appli... |
IRuleChooser chooser = new RoundRuleChooser();
if (environment.containsProperty(ConfigConstants.CONFIG_LOADBALANCE_ISOLATION_CHOOSER)) {
String chooserRuleClassString = environment.getProperty(ConfigConstants.CONFIG_LOADBALANCE_ISOLATION_CHOOSER);
if(StringUtils.isNotBlank(choo... | 318 | 280 | 598 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/VersionRegisterBeanPostProcessor.java | VersionRegisterBeanPostProcessor | postProcessBeforeInitialization | class VersionRegisterBeanPostProcessor implements BeanPostProcessor {
@Value("${"+ ConfigConstants.CONFIG_LOADBALANCE_VERSION+":}")
private String version;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>}
} |
if(bean instanceof NacosDiscoveryProperties && StringUtils.isNotBlank(version)){
NacosDiscoveryProperties nacosDiscoveryProperties = (NacosDiscoveryProperties) bean;
nacosDiscoveryProperties.getMetadata().putIfAbsent(CommonConstant.METADATA_VERSION, version);
}
return be... | 83 | 88 | 171 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/loadbalancer/VersionLoadBalancer.java | VersionLoadBalancer | getInstanceResponse | class VersionLoadBalancer implements ReactorServiceInstanceLoadBalancer {
private final static String KEY_DEFAULT = "default";
private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSuppliers;
private String serviceId;
private IRuleChooser ruleChooser;
public VersionLoadBalancer... |
List<ServiceInstance> filteredServiceIstanceList = instances;
if(StringUtils.isNotBlank(version)){
if(CollectionUtils.isNotEmpty(instances)){
filteredServiceIstanceList = instances.stream()
.filter(item->item.getMetadata().containsKey(CommonConstant.M... | 643 | 441 | 1,084 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/utils/QueryUtils.java | QueryUtils | getQueryMap | class QueryUtils {
/**
* 通过query字符串得到参数的map
* @param queryString ?后的字符
* @return
*/
public static Map<String, String> getQueryMap(String queryString){<FILL_FUNCTION_BODY>}
/**
* 通过url获取参数map
* @param uri
* @return
*/
public static Map<String, String> getQueryMap(... |
if(StringUtils.isNotBlank(queryString)){
return Arrays.stream(queryString.split("&")).map(item -> item.split("="))
.collect(Collectors.toMap(key -> key[0], value -> value.length > 1 && StringUtils.isNotBlank(value[1]) ? value[1] : ""));
}
return Collections.empty... | 154 | 104 | 258 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/aspect/AuditLogAspect.java | AuditLogAspect | getAudit | class AuditLogAspect {
@Value("${spring.application.name}")
private String applicationName;
private AuditLogProperties auditLogProperties;
private IAuditService auditService;
public AuditLogAspect(AuditLogProperties auditLogProperties, IAuditService auditService) {
this.auditLogProperties ... |
Audit audit = new Audit();
audit.setTimestamp(LocalDateTime.now());
audit.setApplicationName(applicationName);
MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
audit.setClassName(methodSignature.getDeclaringTypeName());
audit.setMethodName(me... | 616 | 279 | 895 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/monitor/PointUtil.java | PointEntry | getPropertiesStr | class PointEntry {
String id;
String type;
Object properties;
}
/**
* 格式为:{时间}|{来源}|{对象id}|{类型}|{对象属性(以&分割)}
* 例子1:2016-07-27 23:37:23|business-center|1|user-login|ip=xxx.xxx.xx&userName=张三&userType=后台管理员
* 例子2:2016-07-27 23:37:23|file-center|c0a895e1145267864501... |
Object properties = this.pointEntry.getProperties();
StringBuilder result = new StringBuilder();
if (!ObjectUtils.isEmpty(properties)) {
//解析map
if (properties instanceof Map) {
Map proMap = (Map)properties;
Iterator<Map.Entry> ite ... | 557 | 333 | 890 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/impl/DbAuditServiceImpl.java | DbAuditServiceImpl | init | class DbAuditServiceImpl implements IAuditService {
private static final String INSERT_SQL = " insert into sys_logger " +
" (application_name, class_name, method_name, user_id, user_name, client_id, operation, timestamp) " +
" values (?,?,?,?,?,?,?,?)";
private final JdbcTemplate jdbcTe... |
String sql = "CREATE TABLE IF NOT EXISTS `sys_logger` (\n" +
" `id` int(11) NOT NULL AUTO_INCREMENT,\n" +
" `application_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '应用名',\n" +
" `class_name` varchar(128) CHARACTER SET utf8 COLLA... | 331 | 414 | 745 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/impl/LoggerAuditServiceImpl.java | LoggerAuditServiceImpl | save | class LoggerAuditServiceImpl implements IAuditService {
private static final String MSG_PATTERN = "{}|{}|{}|{}|{}|{}|{}|{}";
/**
* 格式为:{时间}|{应用名}|{类名}|{方法名}|{用户id}|{用户名}|{租户id}|{操作信息}
* 例子:2020-02-04 09:13:34.650|user-center|com.central.user.controller.SysUserController|saveOrUpdate|1|admin|webApp|新增... |
log.debug(MSG_PATTERN
, audit.getTimestamp().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))
, audit.getApplicationName(), audit.getClassName(), audit.getMethodName()
, audit.getUserId(), audit.getUserName(), audit.getClientId()
, a... | 196 | 98 | 294 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/DubboTraceFilter.java | DubboTraceFilter | invoke | class DubboTraceFilter implements Filter {
/**
* 服务消费者:传递traceId给下游服务
* 服务提供者:获取traceId并赋值给MDC
*/
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {<FILL_FUNCTION_BODY>}
} |
boolean isProviderSide = RpcContext.getContext().isProviderSide();
if (isProviderSide) { //服务提供者逻辑
String traceId = invocation.getAttachment(MDCTraceUtils.KEY_TRACE_ID);
String spanId = invocation.getAttachment(MDCTraceUtils.KEY_SPAN_ID);
if (StrUtil.isEmpty(traceId)... | 91 | 286 | 377 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/FeignTraceConfig.java | FeignTraceConfig | feignTraceInterceptor | class FeignTraceConfig {
@Resource
private TraceProperties traceProperties;
@Bean
public RequestInterceptor feignTraceInterceptor() {<FILL_FUNCTION_BODY>}
} |
return template -> {
if (traceProperties.getEnable()) {
//传递日志traceId
String traceId = MDCTraceUtils.getTraceId();
if (StrUtil.isNotEmpty(traceId)) {
template.header(MDCTraceUtils.TRACE_ID_HEADER, traceId);
temp... | 54 | 124 | 178 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/MDCTraceUtils.java | MDCTraceUtils | addTrace | class MDCTraceUtils {
/**
* 追踪id的名称
*/
public static final String KEY_TRACE_ID = "traceId";
/**
* 块id的名称
*/
public static final String KEY_SPAN_ID = "spanId";
/**
* 日志链路追踪id信息头
*/
public static final String TRACE_ID_HEADER = "x-traceId-header";
/**
* 日志链路块... |
String traceId = createTraceId();
MDC.put(KEY_TRACE_ID, traceId);
MDC.put(KEY_SPAN_ID, "0");
initSpanNumber();
| 601 | 53 | 654 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/WebTraceFilter.java | WebTraceFilter | doFilterInternal | class WebTraceFilter extends OncePerRequestFilter {
@Resource
private TraceProperties traceProperties;
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
return !traceProperties.getEnable();
}
@Override
protected void doFilterInternal(HttpServletRequest reque... |
try {
String traceId = request.getHeader(MDCTraceUtils.TRACE_ID_HEADER);
String spanId = request.getHeader(MDCTraceUtils.SPAN_ID_HEADER);
if (StrUtil.isEmpty(traceId)) {
MDCTraceUtils.addTrace();
} else {
MDCTraceUtils.putTrace(tra... | 107 | 137 | 244 | <methods>public void <init>() ,public final void doFilter(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, jakarta.servlet.FilterChain) throws jakarta.servlet.ServletException, java.io.IOException<variables>public static final java.lang.String ALREADY_FILTERED_SUFFIX |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-log-spring-boot-starter/src/main/java/org/slf4j/TtlMDCAdapter.java | TtlMDCAdapter | get | class TtlMDCAdapter implements MDCAdapter {
final ThreadLocal<Map<String, String>> readWriteThreadLocalMap = new TransmittableThreadLocal<>();
final ThreadLocal<Map<String, String>> readOnlyThreadLocalMap = new TransmittableThreadLocal<>();
private final ThreadLocalMapOfStacks threadLocalMapOfDeques = new T... |
Map<String, String> hashMap = readWriteThreadLocalMap.get();
if ((hashMap != null) && (key != null)) {
return hashMap.get(key);
} else {
return null;
}
| 1,249 | 64 | 1,313 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/FdfsTemplate.java | FdfsTemplate | download | class FdfsTemplate {
@Resource
private FileServerProperties fileProperties;
@Resource
private FastFileStorageClient storageClient;
@SneakyThrows
public ObjectInfo upload(String objectName, InputStream is) {
return upload(objectName, is, is.available());
}
@SneakyThrows
pub... |
if (!StringUtils.isEmpty(objectPath)) {
StorePath storePath = StorePath.parseFromUrl(objectPath);
return storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), callback);
}
return null;
| 442 | 64 | 506 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/S3Template.java | S3Template | upload | class S3Template implements InitializingBean {
private static final String DEF_CONTEXT_TYPE = "application/octet-stream";
private static final String PATH_SPLIT = "/";
@Autowired
private FileServerProperties fileProperties;
private AmazonS3 amazonS3;
@Override
public void afterPropertiesS... |
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(size);
objectMetadata.setContentType(contentType);
PutObjectRequest putObjectRequest = new PutObjectRequest(
bucketName, objectName, is, objectMetadata);
putObjectRequest.getReq... | 968 | 165 | 1,133 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/RedisAutoConfigure.java | RedisAutoConfigure | keyGenerator | class RedisAutoConfigure {
@Resource
private CacheManagerProperties cacheManagerProperties;
@Bean
public RedisSerializer<String> redisKeySerializer() {
return RedisSerializer.string();
}
@Bean
public RedisSerializer<Object> redisValueSerializer() {
return RedisSe... |
return (target, method, objects) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(":" + method.getName() + ":");
for (Object obj : objects) {
sb.append(obj.toString());
}
... | 783 | 98 | 881 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/lock/RedisDistributedLock.java | RedisDistributedLock | lock | class RedisDistributedLock {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
private ThreadLocal<String> lockFlag = new ThreadLocal<>();
private static final String UNLOCK_LUA;
/*
* 通过lua脚本释放锁,来达到释放锁的原子操作
*/
static {
UNLOCK_LUA = "if redis.call(\"... |
boolean result = setRedis(key, expire);
// 如果获取锁失败,按照传入的重试次数进行重试
while ((!result) && retryTimes-- > 0) {
try {
log.debug("get redisDistributeLock failed, retrying..." + retryTimes);
Thread.sleep(sleepMillis);
} catch (InterruptedExc... | 941 | 160 | 1,101 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/lock/RedissonDistributedLock.java | RedissonDistributedLock | getLock | class RedissonDistributedLock implements DistributedLock {
@Autowired
private RedissonClient redisson;
private ZLock getLock(String key, boolean isFair) {<FILL_FUNCTION_BODY>}
@Override
public ZLock lock(String key, long leaseTime, TimeUnit unit, boolean isFair) {
ZLock zLock = getLock(key... |
RLock lock;
if (isFair) {
lock = redisson.getFairLock(CommonConstant.LOCK_KEY_PREFIX + ":" + key);
} else {
lock = redisson.getLock(CommonConstant.LOCK_KEY_PREFIX + ":" + key);
}
return new ZLock(lock, this);
| 342 | 89 | 431 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-sentinel-spring-boot-starter/src/main/java/com/central/sentinel/config/SentinelAutoConfigure.java | WebmvcHandler | webmvcBlockExceptionHandler | class WebmvcHandler {
@Bean
public BlockExceptionHandler webmvcBlockExceptionHandler() {<FILL_FUNCTION_BODY>}
} |
return (request, response, e) -> {
response.setStatus(429);
Result result = Result.failed(e.getMessage());
response.getWriter().print(JSONUtil.toJsonStr(result));
};
| 43 | 67 | 110 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/ZookeeperAutoConfiguration.java | ZookeeperAutoConfiguration | curatorFramework | class ZookeeperAutoConfiguration {
/**
* 初始化连接
*/
@Bean(initMethod = "start", destroyMethod = "close")
@ConditionalOnMissingBean
public CuratorFramework curatorFramework(ZookeeperProperty property) {<FILL_FUNCTION_BODY>}
} |
RetryPolicy retryPolicy = new ExponentialBackoffRetry(property.getBaseSleepTime(), property.getMaxRetries());
return CuratorFrameworkFactory.builder()
.connectString(property.getConnectString())
.connectionTimeoutMs(property.getConnectionTimeout())
.sessi... | 80 | 99 | 179 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/lock/ZookeeperDistributedLock.java | ZookeeperDistributedLock | tryLock | class ZookeeperDistributedLock implements DistributedLock {
@Resource
private CuratorFramework client;
private ZLock getLock(String key) {
InterProcessMutex lock = new InterProcessMutex(client, getPath(key));
return new ZLock(lock, this);
}
@Override
public ZLock lock(String ke... |
ZLock zLock = this.getLock(key);
InterProcessMutex ipm = (InterProcessMutex)zLock.getLock();
if (ipm.acquire(waitTime, unit)) {
return zLock;
}
return null;
| 366 | 68 | 434 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/template/ZookeeperTemplate.java | ZookeeperTemplate | watchTree | class ZookeeperTemplate {
private final CuratorFramework client;
public ZookeeperTemplate(CuratorFramework client) {
this.client = client;
}
/**
* 创建空节点,默认持久节点
*
* @param path 节点路径
* @param node 节点名称
* @return 完整路径
*/
@SneakyThrows
public String createNode... |
CuratorCacheListener curatorCacheListener = CuratorCacheListener.builder()
.forTreeCache(client, listener)
.build();
CuratorCache curatorCache = CuratorCache.builder(client, path).build();
curatorCache.listenable().addListener(curatorCacheListener);
curat... | 1,823 | 83 | 1,906 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-demo/rocketmq-demo/rocketmq-produce/src/main/java/com/rocketmq/RocketMqProduceApplication.java | CustomRunner | run | class CustomRunner implements CommandLineRunner {
@Autowired
private SenderService senderService;
@Override
public void run(String... args) {<FILL_FUNCTION_BODY>}
} |
int count = 5;
for (int index = 1; index <= count; index++) {
String msgContent = "msg-" + index;
if (index % 2 == 0) {
senderService.send(msgContent);
} else {
senderService.sendWithTags(new Order((long)ind... | 55 | 98 | 153 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-demo/rocketmq-demo/rocketmq-produce/src/main/java/com/rocketmq/demo/service/SenderService.java | SenderService | sendWithTags | class SenderService {
private final static String TEST_OUT = "test-out-0";
@Resource
private StreamBridge streamBridge;
/**
* 发送字符消息
*/
public void send(String msg) {
streamBridge.send(TEST_OUT, MessageBuilder.withPayload(msg).build());
}
/**
* 发送带tag的对象消息
*/
public <T> void sendWithTags(T msg, Str... |
Message<T> message = MessageBuilder.withPayload(msg)
.setHeader(MessageConst.PROPERTY_TAGS, tag)
.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
.build();
streamBridge.send(TEST_OUT, message);
| 134 | 84 | 218 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/controller/OrderController.java | OrderController | consumeError | class OrderController {
private final static String ORDER_OUT = "order-out-0";
private final StreamBridge streamBridge;
public OrderController(StreamBridge streamBridge) {
this.streamBridge = streamBridge;
}
/**
* 正常情况
*/
@GetMapping("/success")
public String success() {
... |
Order order = new Order();
order.setOrderId(IdGenerator.getId());
order.setOrderNo(RandomUtil.randomString(4));
Message<Order> message = MessageBuilder
.withPayload(order)
.setHeader("orderId", order.getOrderId())
.setHeader("consumeError... | 402 | 122 | 524 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/listener/OrderTransactionListenerImpl.java | OrderTransactionListenerImpl | executeLocalTransaction | class OrderTransactionListenerImpl implements TransactionListener {
@Resource
private IOrderService orderService;
/**
* 提交本地事务
*/
@Override
public LocalTransactionState executeLocalTransaction(Message message, Object arg) {<FILL_FUNCTION_BODY>}
/**
* 事务回查接口
*
* 如果事务消息一直没提交,则... |
//插入订单数据
String orderJson = new String((message.getBody()));
Order order = JsonUtil.toObject(orderJson, Order.class);
orderService.save(order);
String produceError = message.getProperty("produceError");
if ("1".equals(produceError)) {
System.err.println("==... | 309 | 170 | 479 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/service/impl/IntegralReceiveService.java | IntegralReceiveService | receiveDlq | class IntegralReceiveService {
@Bean
public Consumer<Message<Order>> receive() {
return message -> {
//模拟消费异常
String consumeError = (String)message.getHeaders().get("consumeError");
if ("1".equals(consumeError)) {
System.err.println("============Except... |
return message -> {
String orderId = (String)message.getHeaders().get("orderId");
System.err.println("============消费死信队列消息,记录日志并预警:" + orderId);
};
| 212 | 62 | 274 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-demo/seata-demo/account-service/src/main/java/com/central/account/service/AccountService.java | AccountService | reduce | class AccountService {
@Resource
private AccountMapper accountMapper;
/**
* 减账号金额
*/
//@Transactional(rollbackFor = Exception.class)
public void reduce(String userId, int money) {<FILL_FUNCTION_BODY>}
} |
if ("U002".equals(userId)) {
throw new RuntimeException("this is a mock Exception");
}
QueryWrapper<Account> wrapper = new QueryWrapper<>();
wrapper.setEntity(new Account().setUserId(userId));
Account account = accountMapper.selectOne(wrapper);
account.setMo... | 75 | 106 | 181 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-demo/seata-demo/order-service/src/main/java/com/central/order/service/OrderService.java | OrderService | create | class OrderService {
@Resource
private AccountFeignClient accountFeignClient;
@Resource
private OrderMapper orderMapper;
//@Transactional(rollbackFor = Exception.class)
public void create(String userId, String commodityCode, Integer count) {<FILL_FUNCTION_BODY>}
} |
//订单金额
Integer orderMoney = count * 2;
Order order = new Order()
.setUserId(userId)
.setCommodityCode(commodityCode)
.setCount(count)
.setMoney(orderMoney);
orderMapper.insert(order);
accountFeignClient.reduce(use... | 83 | 100 | 183 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-demo/seata-demo/storage-service/src/main/java/com/central/storage/service/StorageService.java | StorageService | deduct | class StorageService {
@Resource
private StorageMapper storageMapper;
/**
* 减库存
*
* @param commodityCode 商品编号
* @param count 数量
*/
//@Transactional(rollbackFor = Exception.class)
public void deduct(String commodityCode, int count) {<FILL_FUNCTION_BODY>}
} |
QueryWrapper<Storage> wrapper = new QueryWrapper<>();
wrapper.setEntity(new Storage().setCommodityCode(commodityCode));
Storage storage = storageMapper.selectOne(wrapper);
storage.setCount(storage.getCount() - count);
storageMapper.updateById(storage);
| 100 | 77 | 177 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-demo/sharding-jdbc-demo/src/main/java/com/sharding/demo/controller/UserController.java | UserController | initDate | class UserController {
private final IUserService userService;
@Autowired
public UserController(IUserService userService) {
this.userService = userService;
}
/**
* 初始化数据
*/
@GetMapping("/init")
public String initDate() {<FILL_FUNCTION_BODY>}
/**
* 查询列表
*/
... |
String companyId;
for (int i = 0; i < 100; i++) {
User u = new User();
if (i % 2 == 0) {
companyId = "alibaba";
} else {
companyId = "baidu";
}
u.setCompanyId(companyId);
u.setName(String.valueOf(i))... | 235 | 119 | 354 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-demo/sso-demo/oidc-sso/src/main/java/com/sso/demo/controller/ApiController.java | ApiController | getAccessToken | class ApiController {
private static final String PUBKEY_START = "-----BEGIN PUBLIC KEY-----";
private static final String PUBKEY_END = "-----END PUBLIC KEY-----";
@Value("${zlt.sso.client-id:}")
private String clientId;
@Value("${zlt.sso.client-secret:}")
private String clientSecret;
@Va... |
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
String base64Auth = this.getBase64ClientParam();
headers.add("Authorization", "Basic " + base64Auth);
MultiValueMap<St... | 1,720 | 228 | 1,948 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/config/SecurityConfig.java | SecurityConfig | securityFilterChain | class SecurityConfig {
@Value("${security.oauth2.sso.login-path:}")
private String loginPath;
@Resource
private LogoutSuccessHandler ssoLogoutSuccessHandler;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<FILL_FUNCTION_BODY>}
} |
/*http.authorizeHttpRequests().anyRequest().authenticated()
.and()
.csrf().disable()
.logout()
.logoutSuccessHandler(ssoLogoutSuccessHandler);
if (StrUtil.isNotEmpty(loginPath)) {
http.formLogin().loginProcessingUrl(log... | 88 | 96 | 184 | <no_super_class> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.