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 |
|---|---|---|---|---|---|---|---|---|---|
zlt2000_microservices-platform | microservices-platform/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/config/SsoLogoutSuccessHandler.java | SsoLogoutSuccessHandler | onLogoutSuccess | class SsoLogoutSuccessHandler implements LogoutSuccessHandler {
@Value("${zlt.logout-uri:''}")
private String logoutUri;
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authen... |
OAuth2Authentication oauth2Authentication = (OAuth2Authentication)authentication;
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)oauth2Authentication.getDetails();
String accessToken = details.getTokenValue();
redirectStrategy.sendRedirect(request, response, logoutUri+accessToken);
| 96 | 83 | 179 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/controller/HomeController.java | HomeController | home | class HomeController {
@GetMapping("/")
public String home(ModelMap modelMap, Authentication authentication) {<FILL_FUNCTION_BODY>}
} |
OAuth2Authentication oauth2Authentication = (OAuth2Authentication)authentication;
modelMap.put("username", oauth2Authentication.getName());
modelMap.put("authorities", oauth2Authentication.getAuthorities());
modelMap.put("clientId", oauth2Authentication.getOAuth2Request().getClientId())... | 42 | 128 | 170 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-demo/sso-demo/web-sso/src/main/java/com/sso/demo/controller/ApiController.java | ApiController | getAccessToken | class ApiController {
@Value("${zlt.sso.client-id:}")
private String clientId;
@Value("${zlt.sso.client-secret:}")
private String clientSecret;
@Value("${zlt.sso.redirect-uri:}")
private String redirectUri;
@Value("${zlt.sso.access-token-uri:}")
private String accessTokenUri;
@Va... |
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
byte[] authorization = (clientId + ":" + clientSecret).getBytes("UTF-8");
String base64Auth = Base64.encodeBase64String(authori... | 736 | 248 | 984 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2ServerAuthSuccessHandler.java | Oauth2ServerAuthSuccessHandler | onAuthenticationSuccess | class Oauth2ServerAuthSuccessHandler implements ServerAuthenticationSuccessHandler {
@Override
public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {<FILL_FUNCTION_BODY>}
} |
MultiValueMap<String, String> headerValues = new LinkedMultiValueMap<>(4);
Object principal = authentication.getPrincipal();
if (principal instanceof OAuth2IntrospectionAuthenticatedPrincipal authenticatedPrincipal) {
Map<String, Object> claims = authenticatedPrincipal.getAttribute... | 60 | 375 | 435 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/PermissionAuthManager.java | PermissionAuthManager | findMenuByRoleCodes | class PermissionAuthManager extends DefaultPermissionServiceImpl implements ReactiveAuthorizationManager<AuthorizationContext> {
@Resource
private AsynMenuService asynMenuService;
@Override
public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext authorizationC... |
Future<List<SysMenu>> futureResult = asynMenuService.findByRoleCodes(roleCodes);
try {
return futureResult.get();
} catch (Exception e) {
log.error("asynMenuService.findMenuByRoleCodes-error", e);
}
return Collections.emptyList();
| 211 | 86 | 297 | <methods>public non-sealed void <init>() ,public abstract List<com.central.common.model.SysMenu> findMenuByRoleCodes(java.lang.String) ,public boolean hasPermission(org.springframework.security.core.Authentication, java.lang.String, java.lang.String) <variables>private final org.springframework.util.AntPathMatcher antP... |
zlt2000_microservices-platform | microservices-platform/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/CorsConfig.java | CorsConfig | corsFilter | class CorsConfig {
private static final String ALL = "*";
@Order(Ordered.HIGHEST_PRECEDENCE)
@Bean
public CorsWebFilter corsFilter() {<FILL_FUNCTION_BODY>}
} |
CorsConfiguration config = new CorsConfiguration();
// cookie跨域
config.setAllowCredentials(Boolean.TRUE);
config.addAllowedMethod(ALL);
config.addAllowedOriginPattern(ALL);
config.addAllowedHeader(ALL);
// 配置前端js允许访问的自定义响应头
config.addExposedHeader("setTok... | 66 | 149 | 215 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/FeignConfig.java | FeignConfig | feignHttpMessageConverter | class FeignConfig {
@Bean
public Decoder feignDecoder() {
return new ResponseEntityDecoder(new SpringDecoder(feignHttpMessageConverter()));
}
public ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {<FILL_FUNCTION_BODY>}
public static class GateWayMappingJackson2HttpMessage... |
final HttpMessageConverters httpMessageConverters = new HttpMessageConverters(new GateWayMappingJackson2HttpMessageConverter());
return () -> httpMessageConverters;
| 178 | 48 | 226 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/error/JsonErrorWebExceptionHandler.java | JsonErrorWebExceptionHandler | getHttpStatus | class JsonErrorWebExceptionHandler extends DefaultErrorWebExceptionHandler {
public JsonErrorWebExceptionHandler(ErrorAttributes errorAttributes, WebProperties.Resources resourceProperties,
ErrorProperties errorProperties, ApplicationContext applicationContext) {
supe... |
int httpStatus;
/*if (error instanceof InvalidTokenException) {
InvalidTokenException ex = (InvalidTokenException)error;
httpStatus = ex.getHttpErrorCode();
} else {
httpStatus = HttpStatus.INTERNAL_SERVER_ERROR.value();
}*/
httpStatus = HttpS... | 620 | 98 | 718 | <methods>public void <init>(org.springframework.boot.web.reactive.error.ErrorAttributes, org.springframework.boot.autoconfigure.web.WebProperties.Resources, org.springframework.boot.autoconfigure.web.ErrorProperties, org.springframework.context.ApplicationContext) <variables>private static final Map<org.springframework... |
zlt2000_microservices-platform | microservices-platform/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/fallback/MenuServiceFallbackFactory.java | MenuServiceFallbackFactory | create | class MenuServiceFallbackFactory implements FallbackFactory<MenuService> {
@Override
public MenuService create(Throwable throwable) {<FILL_FUNCTION_BODY>}
} |
return roleIds -> {
log.error("调用findByRoleCodes异常:{}", roleIds, throwable);
return CollectionUtil.newArrayList();
};
| 48 | 47 | 95 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/RequestStatisticsFilter.java | RequestStatisticsFilter | getOperatingSystem | class RequestStatisticsFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
Map<String, String> headers = request.getHeaders().toSingleValueMap();
UserAgent ... |
if (StrUtil.isNotEmpty(operatingSystem)) {
if (operatingSystem.contains("MAC_OS_X")) {
return "MAC_OS_X";
} else if (operatingSystem.contains("ANDROID")) {
return "ANDROID";
}
}
return operatingSystem;
| 377 | 83 | 460 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/TraceFilter.java | TraceFilter | filter | class TraceFilter implements GlobalFilter, Ordered {
@Autowired
private TraceProperties traceProperties;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
... |
if (traceProperties.getEnable()) {
//链路追踪id
MDCTraceUtils.addTrace();
ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
.headers(h -> {
h.add(MDCTraceUtils.TRACE_ID_HEADER, MDCTraceUtils.getTraceId());
... | 102 | 173 | 275 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/VersionLbIsolationFilter.java | VersionLbIsolationFilter | filter | class VersionLbIsolationFilter implements GlobalFilter, Ordered {
@Value("${"+ ConfigConstants.CONFIG_LOADBALANCE_ISOLATION_ENABLE+":}")
private Boolean enableVersionControl;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {<FILL_FUNCTION_BODY>}
@Override
... |
if(Boolean.TRUE.equals(enableVersionControl)
&& exchange.getRequest().getQueryParams().containsKey(CommonConstant.Z_L_T_VERSION)){
String version = exchange.getRequest().getQueryParams().get(CommonConstant.Z_L_T_VERSION).get(0);
ServerHttpRequest rebuildRequest = exchang... | 126 | 173 | 299 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/route/NacosRouteDefinitionRepository.java | NacosRouteDefinitionRepository | addListener | class NacosRouteDefinitionRepository implements RouteDefinitionRepository {
private static final String SCG_DATA_ID = "scg-routes";
private static final String SCG_GROUP_ID = "SCG_GATEWAY";
private ApplicationEventPublisher publisher;
private NacosConfigProperties nacosConfigProperties;
public Na... |
try {
nacosConfigProperties.configServiceInstance().addListener(SCG_DATA_ID, SCG_GROUP_ID, new Listener() {
@Override
public Executor getExecutor() {
return null;
}
@Override
public void receiveConf... | 459 | 136 | 595 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/utils/ReactiveAddrUtil.java | ReactiveAddrUtil | getRemoteAddr | class ReactiveAddrUtil {
private final static String UNKNOWN_STR = "unknown";
/**
* 获取客户端IP地址
*/
public static String getRemoteAddr(ServerHttpRequest request) {<FILL_FUNCTION_BODY>}
private static boolean isEmptyIP(String ip) {
if (StrUtil.isEmpty(ip) || UNKNOWN_STR.equalsIgnoreCase(i... |
Map<String, String> headers = request.getHeaders().toSingleValueMap();
String ip = headers.get("X-Forwarded-For");
if (isEmptyIP(ip)) {
ip = headers.get("Proxy-Client-IP");
if (isEmptyIP(ip)) {
ip = headers.get("WL-Proxy-Client-IP");
if (i... | 207 | 345 | 552 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-monitor/log-center/src/main/java/com/central/log/controller/SysLogController.java | SysLogController | traceLog | class SysLogController {
/**
* 系统日志索引名
*/
private static final String SYS_LOG_INDEXNAME = "sys-log-*";
@Resource
private IQueryService queryService;
@Resource
private TraceLogService traceLogService;
@Operation(summary = "系统日志全文搜索列表")
@GetMapping(value = "/sysLo... |
PageResult<JsonNode> pageResult = queryService.strQuery(SYS_LOG_INDEXNAME, searchDto);
List<JsonNode> jsonNodeList = pageResult.getData();
List<TraceLog> logList;
if (jsonNodeList != null) {
logList = traceLogService.transTraceLog(jsonNodeList);
} else {
... | 232 | 149 | 381 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-monitor/log-center/src/main/java/com/central/log/service/TraceLogService.java | TraceLogService | transTraceLog | class TraceLogService {
public List<TraceLog> transTraceLog(List<JsonNode> jsonNodeList) {<FILL_FUNCTION_BODY>}
/**
* 通过集合来去重
*/
private boolean checkLog(String logKey, Set<String> logSet) {
if (logSet.contains(logKey)) {
return false;
} else {
logSet.add(l... |
List<TraceLog> logList = new ArrayList<>();
Set<String> logSet = new HashSet<>();
jsonNodeList.forEach(e -> {
TraceLog log = JsonUtil.toObject(e, TraceLog.class);
String spanId = log.getSpanId();
if (StrUtil.isNotEmpty(spanId)) {
if (spanId.le... | 179 | 189 | 368 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-monitor/sc-admin/src/main/java/com/central/gateway/monitor/config/SecuritySecureConfig.java | SecuritySecureConfig | securityFilterChain | class SecuritySecureConfig {
private final String adminContextPath;
public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
this.adminContextPath = adminServerProperties.getContextPath();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) t... |
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(adminContextPath + "/");
http.authorizeHttpRequests(authorizeRequests -> {
... | 97 | 275 | 372 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/component/CustomAccessTokenResponseHttpMessageConverter.java | CustomAccessTokenResponseHttpMessageConverter | writeInternal | class CustomAccessTokenResponseHttpMessageConverter extends OAuth2AccessTokenResponseHttpMessageConverter {
private Converter<OAuth2AccessTokenResponse, Map<String, Object>> accessTokenResponseParametersConverter = new DefaultOAuth2AccessTokenResponseMapConverter();
private static final ParameterizedTypeReferen... |
try {
Map<String, Object> tokenResponseParameters = this.accessTokenResponseParametersConverter.convert(tokenResponse);
GenericHttpMessageConverter<Object> jsonMessageConverter = new MappingJackson2HttpMessageConverter(objectMapper);
jsonMessageConverter.write(Result.succeed... | 184 | 153 | 337 | <methods>public void <init>() ,public final void setAccessTokenResponseConverter(Converter<Map<java.lang.String,java.lang.Object>,org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse>) ,public final void setAccessTokenResponseParametersConverter(Converter<org.springframework.security.oauth2.core.... |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/component/CustomeOAuth2TokenCustomizer.java | CustomeOAuth2TokenCustomizer | customize | class CustomeOAuth2TokenCustomizer implements OAuth2TokenCustomizer<OAuth2TokenClaimsContext> {
@Override
public void customize(OAuth2TokenClaimsContext context) {<FILL_FUNCTION_BODY>}
} |
OAuth2TokenClaimsSet.Builder claims = context.getClaims();
AbstractAuthenticationToken authenticationToken = context.getAuthorizationGrant();
if (authenticationToken instanceof BaseAuthenticationToken baseAuthenticationToken) {
LoginAppUser user = (LoginAppUser) context.getPrincipal().getPrincipal();
clai... | 60 | 184 | 244 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/component/LoginProcessSetTenantFilter.java | LoginProcessSetTenantFilter | doFilterInternal | class LoginProcessSetTenantFilter extends OncePerRequestFilter {
private static final String SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST";
private RequestMatcher requiresAuthenticationRequestMatcher;
public LoginProcessSetTenantFilter() {
requiresAuthenticationRequestMatcher = new AntPathRequest... |
try {
DefaultSavedRequest savedRequest = (DefaultSavedRequest)request.getSession().getAttribute(SAVED_REQUEST);
if (savedRequest != null) {
String[] clientIds = savedRequest.getParameterValues("client_id");
if (ArrayUtil.isNotEmpty(clientIds)) {
... | 252 | 139 | 391 | <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-uaa/src/main/java/com/central/oauth/config/FormIdentityLoginConfigurer.java | FormIdentityLoginConfigurer | init | class FormIdentityLoginConfigurer extends AbstractHttpConfigurer<FormIdentityLoginConfigurer, HttpSecurity> {
private final LogoutSuccessHandler logoutSuccessHandler;
private final LogoutHandler logoutHandler;
@Override
public void init(HttpSecurity http) throws Exception {<FILL_FUNCTION_BODY>}
} |
http.formLogin(formLogin -> formLogin
.loginPage(SecurityConstants.LOGIN_PAGE)
.loginProcessingUrl(SecurityConstants.OAUTH_LOGIN_PRO_URL)
.successHandler(new SavedRequestAwareAuthenticationSuccessHandler()))
.logout(logout -> logout
... | 82 | 236 | 318 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/config/SecurityConfig.java | SecurityConfig | authenticationSuccessHandler | class SecurityConfig {
/**
* token内容增强
*/
@Bean
public OAuth2TokenCustomizer<JwtEncodingContext> jwtTokenCustomizer(){
return context -> {
JwtClaimsSet.Builder claims = context.getClaims();
claims.claim(SecurityConstants.LICENSE_NAME, SecurityConstants.PROJECT_LICENSE);
// 客户端模式不返回具体用户信息
if (Author... |
return (request, response, authentication) -> {
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
(OAuth2AccessTokenAuthenticationToken) authentication;
OAuth2AccessToken accessToken = accessTokenAuthentication.getAccessToken();
OAuth2RefreshToken refreshToken = accessTokenAuthenticatio... | 809 | 374 | 1,183 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/controller/ValidateCodeController.java | ValidateCodeController | createCode | class ValidateCodeController {
@Autowired
private IValidateCodeService validateCodeService;
/**
* 创建验证码
*
* @throws Exception
*/
@GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{deviceId}")
public void createCode(@PathVariable String deviceId, HttpSe... |
Assert.notNull(deviceId, "机器码不能为空");
Assert.notNull(deviceId, "机器码不能为空");
// 设置请求头为输出图片类型
response.setContentType("image/jpeg");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0)... | 263 | 230 | 493 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutHandler.java | OauthLogoutHandler | logout | class OauthLogoutHandler implements LogoutHandler {
private final OAuth2AuthorizationService oAuth2AuthorizationService;
private final SecurityProperties securityProperties;
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {<FILL_FUNCTION_BODY>}
} |
Assert.notNull(oAuth2AuthorizationService, "oAuth2AuthorizationService must be set");
String token = request.getParameter("token");
if (StrUtil.isEmpty(token)) {
token = AuthUtils.extractToken(request);
}
if(StrUtil.isNotEmpty(token)){
OAuth2Authorization existingAccessToken = oAuth2AuthorizationServic... | 74 | 225 | 299 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutSuccessHandler.java | OauthLogoutSuccessHandler | onLogoutSuccess | class OauthLogoutSuccessHandler implements LogoutSuccessHandler {
private static final String REDIRECT_URL = "redirect_url";
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private final UnifiedLogoutService unifiedLogoutService;
private final SecurityProperties securityProperties;
... |
if (securityProperties.getAuth().getUnifiedLogout()) {
unifiedLogoutService.allLogout();
}
String redirectUri = request.getParameter(REDIRECT_URL);
if (StrUtil.isNotEmpty(redirectUri)) {
//重定向指定的地址
redirectStrategy.sendRedirect(request, response, redirectUri);
} else {
ResponseUtil.responseWrite... | 120 | 127 | 247 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/model/SupplierDeferredSecurityContext.java | SupplierDeferredSecurityContext | init | class SupplierDeferredSecurityContext implements DeferredSecurityContext {
private static final Log logger = LogFactory.getLog(SupplierDeferredSecurityContext.class);
private final Supplier<SecurityContext> supplier;
private final SecurityContextHolderStrategy strategy;
private SecurityContext securityContext;
pri... |
if (this.securityContext != null) {
return;
}
this.securityContext = this.supplier.get();
this.missingContext = (this.securityContext == null);
if (this.missingContext) {
this.securityContext = this.strategy.createEmptyContext();
if (logger.isTraceEnabled()) {
logger.trace(LogMessage.format("Cr... | 185 | 119 | 304 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java | ClientServiceImpl | saveClient | class ClientServiceImpl extends SuperServiceImpl<ClientMapper, Client> implements IClientService {
private final static String LOCK_KEY_CLIENTID = "clientId:";
private final PasswordEncoder passwordEncoder;
private final DistributedLock lock;
@Override
public void saveClient(Client client... |
client.setClientSecret(passwordEncoder.encode(client.getClientSecretStr()));
String clientId = client.getClientId();
if (client.getId() == null) {
client.setCreatorId(LoginUserContextHolder.getUser().getId());
}
super.saveOrUpdateIdempotency(client, lock
... | 374 | 138 | 512 | <methods>public non-sealed void <init>() ,public boolean saveIdempotency(com.central.oauth.model.Client, com.central.common.lock.DistributedLock, java.lang.String, Wrapper<com.central.oauth.model.Client>, java.lang.String) throws java.lang.Exception,public boolean saveIdempotency(com.central.oauth.model.Client, com.cen... |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/service/impl/CustomRegisteredClientRepository.java | CustomRegisteredClientRepository | findByClientId | class CustomRegisteredClientRepository implements RegisteredClientRepository {
private final RegisteredClientService clientService;
@Override
public void save(RegisteredClient registeredClient) {
}
@Override
public RegisteredClient findById(String id) {
return this.findByClientId(id);
... |
ClientDto clientObj = clientService.loadClientByClientId(clientId);
if (clientObj == null) {
return null;
}
RegisteredClient.Builder builder = RegisteredClient.withId(clientObj.getClientId())
.clientId(clientObj.getClientId())
.clientSecret(cl... | 113 | 544 | 657 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisOAuth2AuthorizationConsentService.java | RedisOAuth2AuthorizationConsentService | findById | class RedisOAuth2AuthorizationConsentService implements OAuth2AuthorizationConsentService {
private final RedissonClient redissonClient;;
private final static Long TIMEOUT = 10L;
@Override
public void save(OAuth2AuthorizationConsent authorizationConsent) {
Assert.notNull(authorizationConsent, "authorizationCon... |
Assert.hasText(registeredClientId, "registeredClientId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
return (OAuth2AuthorizationConsent) redissonClient.getBucket(buildKey(registeredClientId, principalName)).get();
| 331 | 78 | 409 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisSecurityContextRepository.java | RedisSecurityContextRepository | readSecurityContextFromRedis | class RedisSecurityContextRepository implements SecurityContextRepository {
/**
* 认证信息存储前缀
*/
public static final String SECURITY_CONTEXT_PREFIX_KEY = "security_context:";
/**
* 随机字符串请求头名字
*/
public static final String NONCE_HEADER_NAME = "nonceId";
private final static Serializ... |
if (request == null) {
return null;
}
String nonce = getNonce(request);
if (StrUtil.isEmpty(nonce)) {
return null;
}
// 根据缓存id获取认证信息
RBucket<SecurityContext> rBucket = this.getBucket(nonce);
SecurityContext context = rBucket.get();... | 889 | 148 | 1,037 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisTokensServiceImpl.java | RedisTokensServiceImpl | listTokens | class RedisTokensServiceImpl implements ITokensService {
private final static SerializationCodec AUTH_CODEC = new SerializationCodec();
private static final String AUTHORIZATION = "token";
private final RedissonClient redisson;
@Override
public PageResult<TokenVo> listTokens(Map<String, Object> par... |
Integer page = MapUtils.getInteger(params, "page");
Integer limit = MapUtils.getInteger(params, "limit");
int[] startEnds = PageUtil.transToStartEnd(page-1, limit);
//根据请求参数生成redis的key
String redisKey = getRedisKey(params, clientId);
RList<String> tokenList = redisson.ge... | 301 | 520 | 821 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/service/impl/RegisteredClientService.java | RegisteredClientService | delClient | class RegisteredClientService {
private final IClientService clientService;
private final RedissonClient redisson;
public void saveClient(Client client) throws Exception {
clientService.saveClient(client);
ClientDto clientDto = BeanUtil.copyProperties(client, ClientDto.class);
redis... |
Client client = clientService.getById(id);
if (client != null) {
clientService.delClient(id);
redisson.getBucket(clientRedisKey(client.getClientId())).delete();
}
| 674 | 62 | 736 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/service/impl/UnifiedLogoutService.java | UnifiedLogoutService | getLogoutNotifyUrl | class UnifiedLogoutService {
private final static String LOGOUT_NOTIFY_URL_KEY = "LOGOUT_NOTIFY_URL_LIST";
private final RestTemplate restTemplate;
private final TaskExecutor taskExecutor;
private final RegisteredClientService clientService;
private final RedisOAuth2AuthorizationService authoriz... |
String username = UsernameHolder.getContext();
Set<String> logoutNotifyUrls = new HashSet<>();
try {
List<ClientDto> clientDetails = clientService.list();
Map<String, Object> informationMap;
for (ClientDto client : clientDetails) {
information... | 639 | 281 | 920 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceFactory.java | UserDetailServiceFactory | getService | class UserDetailServiceFactory {
private static final String ERROR_MSG = "Cannot find the implementation class for the account type {}";
@Resource
private List<ZltUserDetailsService> userDetailsServices;
public ZltUserDetailsService getService(Authentication authentication) {
String accountTyp... |
if (StrUtil.isEmpty(accountType)) {
accountType = SecurityConstants.DEF_ACCOUNT_TYPE;
}
log.info("UserDetailServiceFactory.getService:{}", accountType);
if (CollUtil.isNotEmpty(userDetailsServices)) {
for (ZltUserDetailsService userService : userDetailsServices) ... | 127 | 139 | 266 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java | UserDetailServiceImpl | loadUserByUsername | class UserDetailServiceImpl implements ZltUserDetailsService {
private static final String ACCOUNT_TYPE = SecurityConstants.DEF_ACCOUNT_TYPE;
@Resource
private UserService userService;
@Override
public boolean supports(String accountType) {
return ACCOUNT_TYPE.equals(accountType);
}
... |
SysUser sysUser = userService.findByUsername(username);
if (sysUser == null) {
throw new InternalAuthenticationServiceException("用户名或密码错误");
}
checkUser(sysUser);
return LoginUserUtils.getLoginAppUser(sysUser);
| 293 | 73 | 366 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/service/impl/ValidateCodeServiceImpl.java | ValidateCodeServiceImpl | validate | class ValidateCodeServiceImpl implements IValidateCodeService {
private final RedissonClient redisson;
private final UserService userService;
/**
* 保存用户验证码,和randomStr绑定
*
* @param deviceId 客户端生成
* @param imageCode 验证码信息
*/
@Override
public void saveImageCode(St... |
if (StrUtil.isBlank(deviceId)) {
throw new CustomOAuth2AuthenticationException("请在请求参数中携带deviceId参数");
}
String code = this.getCode(deviceId);
if (StrUtil.isBlank(validCode)) {
throw new CustomOAuth2AuthenticationException("请填写验证码");
}
i... | 861 | 194 | 1,055 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/support/base/BaseAuthenticationConverter.java | BaseAuthenticationConverter | getAdditionalParameters | class BaseAuthenticationConverter implements AuthenticationConverter {
@Override
public Authentication convert(HttpServletRequest request) {
String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
if (!this.supportGrantType().equals(grantType)) {
return null;
... |
Map<String, Object> additionalParameters = new HashMap<>();
parameters.forEach((key, value) -> {
if (!key.equals(OAuth2ParameterNames.GRANT_TYPE) &&
!key.equals(OAuth2ParameterNames.SCOPE)) {
boolean isAdd = true;
if (ArrayUtil.isNotEmpty(... | 481 | 169 | 650 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/support/base/BaseAuthenticationProvider.java | BaseAuthenticationProvider | authenticate | class BaseAuthenticationProvider implements AuthenticationProvider {
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-4.3";
private static final OAuth2TokenType ID_TOKEN_TOKEN_TYPE = new OAuth2TokenType(OidcParameterNames.ID_TOKEN);
private final OAuth2Authoriza... |
BaseAuthenticationToken authToken = (BaseAuthenticationToken) authentication;
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(authToken);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
Set<String> authorizedSco... | 468 | 1,533 | 2,001 | <no_super_class> |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/support/mobile/MobileAuthenticationConverter.java | MobileAuthenticationConverter | getToken | class MobileAuthenticationConverter extends BaseAuthenticationConverter {
private final static String PARAM_MOBILE= "mobile";
@Override
protected String supportGrantType() {
return MobileAuthenticationToken.GRANT_TYPE.getValue();
}
@Override
protected List<String> paramNames() {
... |
String mobile = OAuthEndpointUtils.getParam(parameters, PARAM_MOBILE);
String password = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.PASSWORD);
return new MobileAuthenticationToken(mobile, password);
| 138 | 61 | 199 | <methods>public non-sealed void <init>() ,public org.springframework.security.core.Authentication convert(jakarta.servlet.http.HttpServletRequest) ,public Map<java.lang.String,java.lang.Object> getAdditionalParameters(MultiValueMap<java.lang.String,java.lang.String>, List<java.lang.String>) ,public org.springframework.... |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/support/mobile/MobileAuthenticationProvider.java | MobileAuthenticationProvider | getPrincipal | class MobileAuthenticationProvider extends BaseAuthenticationProvider {
private UserDetailServiceFactory userDetailsServiceFactory;
private PasswordEncoder passwordEncoder;
public MobileAuthenticationProvider(OAuth2AuthorizationService authorizationService
, OAuth2TokenGenerator<? extends OAuth... |
MobileAuthenticationToken authToken = (MobileAuthenticationToken) authentication;
String mobile = (String) authToken.getPrincipal();
String password = authToken.getCredentials();
UserDetails userDetails;
try {
userDetails = userDetailsServiceFactory.getService(authTo... | 272 | 178 | 450 | <methods>public void <init>(OAuth2AuthorizationService, OAuth2TokenGenerator<? extends org.springframework.security.oauth2.core.OAuth2Token>) ,public org.springframework.security.core.Authentication authenticate(org.springframework.security.core.Authentication) <variables>private static final java.lang.String ERROR_URI... |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/support/openid/OpenIdAuthenticationProvider.java | OpenIdAuthenticationProvider | getPrincipal | class OpenIdAuthenticationProvider extends BaseAuthenticationProvider {
private UserDetailServiceFactory userDetailsServiceFactory;
public OpenIdAuthenticationProvider(OAuth2AuthorizationService authorizationService
, OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator
, UserDeta... |
OpenIdAuthenticationToken authToken = (OpenIdAuthenticationToken) authentication;
String openId = (String) authToken.getPrincipal();
UserDetails userDetails;
try {
userDetails = userDetailsServiceFactory.getService(authToken).loadUserByUserId(openId);
} catch (Authen... | 226 | 147 | 373 | <methods>public void <init>(OAuth2AuthorizationService, OAuth2TokenGenerator<? extends org.springframework.security.oauth2.core.OAuth2Token>) ,public org.springframework.security.core.Authentication authenticate(org.springframework.security.core.Authentication) <variables>private static final java.lang.String ERROR_URI... |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/support/password/PasswordAuthenticationConverter.java | PasswordAuthenticationConverter | getToken | class PasswordAuthenticationConverter extends BaseAuthenticationConverter {
@Override
protected String supportGrantType() {
return PasswordAuthenticationToken.GRANT_TYPE.getValue();
}
@Override
protected List<String> paramNames() {
return List.of(OAuth2ParameterNames.USERNAME, OAuth... |
String username = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.USERNAME);
String password = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.PASSWORD);
return new PasswordAuthenticationToken(username, password);
| 126 | 64 | 190 | <methods>public non-sealed void <init>() ,public org.springframework.security.core.Authentication convert(jakarta.servlet.http.HttpServletRequest) ,public Map<java.lang.String,java.lang.Object> getAdditionalParameters(MultiValueMap<java.lang.String,java.lang.String>, List<java.lang.String>) ,public org.springframework.... |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/support/password/PasswordAuthenticationProvider.java | PasswordAuthenticationProvider | getPrincipal | class PasswordAuthenticationProvider extends BaseAuthenticationProvider {
private final UserDetailServiceFactory userDetailsServiceFactory;
private final PasswordEncoder passwordEncoder;
public PasswordAuthenticationProvider(OAuth2AuthorizationService authorizationService
, OAuth2TokenGenerator... |
PasswordAuthenticationToken authToken = (PasswordAuthenticationToken) authentication;
String username = (String) authToken.getPrincipal();
String password = authToken.getCredentials();
UserDetails userDetails;
try {
userDetails = userDetailsServiceFactory.getService(... | 278 | 181 | 459 | <methods>public void <init>(OAuth2AuthorizationService, OAuth2TokenGenerator<? extends org.springframework.security.oauth2.core.OAuth2Token>) ,public org.springframework.security.core.Authentication authenticate(org.springframework.security.core.Authentication) <variables>private static final java.lang.String ERROR_URI... |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/support/passwordCode/PasswordCodeAuthenticationConverter.java | PasswordCodeAuthenticationConverter | getToken | class PasswordCodeAuthenticationConverter extends BaseAuthenticationConverter {
private final static String PARAM_DEVICEID = "deviceId";
private final static String PARAM_VALIDCODE = "validCode";
@Override
protected String supportGrantType() {
return PasswordCodeAuthenticationToken.GRANT_TYPE.ge... |
String username = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.USERNAME);
String password = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.PASSWORD);
String deviceId = OAuthEndpointUtils.getParam(parameters, PARAM_DEVICEID);
String validCode = OAuthEndpoint... | 176 | 116 | 292 | <methods>public non-sealed void <init>() ,public org.springframework.security.core.Authentication convert(jakarta.servlet.http.HttpServletRequest) ,public Map<java.lang.String,java.lang.Object> getAdditionalParameters(MultiValueMap<java.lang.String,java.lang.String>, List<java.lang.String>) ,public org.springframework.... |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/support/passwordCode/PasswordCodeAuthenticationProvider.java | PasswordCodeAuthenticationProvider | getPrincipal | class PasswordCodeAuthenticationProvider extends BaseAuthenticationProvider {
private final UserDetailServiceFactory userDetailsServiceFactory;
private final PasswordEncoder passwordEncoder;
private final IValidateCodeService validateCodeService;
public PasswordCodeAuthenticationProvider(OAuth2Authoriz... |
PasswordCodeAuthenticationToken authToken = (PasswordCodeAuthenticationToken) authentication;
String deviceId = authToken.getDeviceId();
String validCode = authToken.getValidCode();
//校验图形验证码
validateCodeService.validate(deviceId, validCode);
String username = (String)... | 318 | 239 | 557 | <methods>public void <init>(OAuth2AuthorizationService, OAuth2TokenGenerator<? extends org.springframework.security.oauth2.core.OAuth2Token>) ,public org.springframework.security.core.Authentication authenticate(org.springframework.security.core.Authentication) <variables>private static final java.lang.String ERROR_URI... |
zlt2000_microservices-platform | microservices-platform/zlt-uaa/src/main/java/com/central/oauth/utils/OAuthEndpointUtils.java | OAuthEndpointUtils | getParameters | class OAuthEndpointUtils {
public static final String ACCESS_TOKEN_REQUEST_ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
private OAuthEndpointUtils() {
}
public static MultiValueMap<String, String> getParameters(HttpServletRequest request) {<FILL_FUNCTION_BODY>}
public s... |
Map<String, String[]> parameterMap = request.getParameterMap();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(parameterMap.size());
parameterMap.forEach((key, values) -> {
if (values.length > 0) {
for (String value : values) {
... | 738 | 104 | 842 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/controller/AccountController.java | AccountController | fetch | class AccountController {
private final DiscordLoadBalancer loadBalancer;
@ApiOperation(value = "指定ID获取账号")
@GetMapping("/{id}/fetch")
public DiscordAccount fetch(@ApiParam(value = "账号ID") @PathVariable String id) {<FILL_FUNCTION_BODY>}
@ApiOperation(value = "查询所有账号")
@GetMapping("/list")
public List<DiscordAc... |
DiscordInstance instance = this.loadBalancer.getDiscordInstance(id);
return instance == null ? null : instance.account();
| 143 | 37 | 180 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/controller/TaskController.java | TaskController | listByIds | class TaskController {
private final TaskStoreService taskStoreService;
private final DiscordLoadBalancer discordLoadBalancer;
@ApiOperation(value = "指定ID获取任务")
@GetMapping("/{id}/fetch")
public Task fetch(@ApiParam(value = "任务ID") @PathVariable String id) {
Optional<Task> queueTaskOptional = this.discordLoadBa... |
if (conditionDTO.getIds() == null) {
return Collections.emptyList();
}
List<Task> result = new ArrayList<>();
Set<String> notInQueueIds = new HashSet<>(conditionDTO.getIds());
this.discordLoadBalancer.getQueueTasks().forEach(t -> {
if (conditionDTO.getIds().contains(t.getId())) {
result.add(t);
... | 375 | 194 | 569 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/domain/DomainObject.java | DomainObject | getProperties | class DomainObject implements Serializable {
@Getter
@Setter
@ApiModelProperty("ID")
protected String id;
@Setter
protected Map<String, Object> properties; // 扩展属性,仅支持基本类型
@JsonIgnore
private final transient Object lock = new Object();
public void sleep() throws InterruptedException {
synchronized (this.l... |
if (this.properties == null) {
this.properties = new HashMap<>();
}
return this.properties;
| 385 | 35 | 420 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/loadbalancer/DiscordInstanceImpl.java | DiscordInstanceImpl | submitTask | class DiscordInstanceImpl implements DiscordInstance {
private final DiscordAccount account;
private final WebSocketStarter socketStarter;
private final DiscordService service;
private final TaskStoreService taskStoreService;
private final NotifyService notifyService;
private final ThreadPoolTaskExecutor taskExe... |
this.taskStoreService.save(task);
int currentWaitNumbers;
try {
currentWaitNumbers = this.taskExecutor.getThreadPoolExecutor().getQueue().size();
Future<?> future = this.taskExecutor.submit(() -> executeTask(task, discordSubmit));
this.taskFutureMap.put(task.getId(), future);
this.queueTasks.add(task... | 1,529 | 431 | 1,960 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/loadbalancer/DiscordLoadBalancer.java | DiscordLoadBalancer | getDiscordInstance | class DiscordLoadBalancer {
private final IRule rule;
private final List<DiscordInstance> instances = Collections.synchronizedList(new ArrayList<>());
public List<DiscordInstance> getAllInstances() {
return this.instances;
}
public List<DiscordInstance> getAliveInstances() {
return this.instances.stream().f... |
if (CharSequenceUtil.isBlank(instanceId)) {
return null;
}
return this.instances.stream()
.filter(instance -> CharSequenceUtil.equals(instanceId, instance.getInstanceId()))
.findFirst().orElse(null);
| 310 | 71 | 381 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/loadbalancer/rule/BestWaitIdleRule.java | BestWaitIdleRule | choose | class BestWaitIdleRule implements IRule {
@Override
public DiscordInstance choose(List<DiscordInstance> instances) {<FILL_FUNCTION_BODY>}
} |
if (instances.isEmpty()) {
return null;
}
Map<Integer, List<DiscordInstance>> map = instances.stream()
.collect(Collectors.groupingBy(i -> {
int wait = i.getRunningFutures().size() - i.account().getCoreSize();
return wait >= 0 ? wait : -1;
}));
List<DiscordInstance> instanceList = map.entr... | 46 | 152 | 198 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/loadbalancer/rule/RoundRobinRule.java | RoundRobinRule | choose | class RoundRobinRule implements IRule {
private final AtomicInteger position = new AtomicInteger(0);
@Override
public DiscordInstance choose(List<DiscordInstance> instances) {<FILL_FUNCTION_BODY>}
private int incrementAndGet() {
int current;
int next;
do {
current = this.position.get();
next = current... |
if (instances.isEmpty()) {
return null;
}
int pos = incrementAndGet();
return instances.get(pos % instances.size());
| 138 | 43 | 181 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/service/NotifyServiceImpl.java | NotifyServiceImpl | convertOrder | class NotifyServiceImpl implements NotifyService {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final ThreadPoolTaskExecutor executor;
private final TimedCache<String, String> taskStatusMap = CacheUtil.newTimedCache(Duration.ofHours(1).toMillis());
public NotifyServiceImpl(ProxyPro... |
String[] split = statusStr.split(":");
TaskStatus status = TaskStatus.valueOf(split[0]);
if (status != TaskStatus.IN_PROGRESS || split.length == 1) {
return status.getOrder();
}
String progress = split[1];
if (progress.endsWith("%")) {
return status.getOrder() + Float.parseFloat(progress.substring(0,... | 905 | 139 | 1,044 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/service/TaskServiceImpl.java | TaskServiceImpl | submitImagine | class TaskServiceImpl implements TaskService {
private final TaskStoreService taskStoreService;
private final DiscordLoadBalancer discordLoadBalancer;
@Override
public SubmitResultVO submitImagine(Task task, List<DataUrl> dataUrls) {<FILL_FUNCTION_BODY>}
@Override
public SubmitResultVO submitUpscale(Task task, ... |
DiscordInstance instance = this.discordLoadBalancer.chooseInstance();
if (instance == null) {
return SubmitResultVO.fail(ReturnCode.NOT_FOUND, "无可用的账号实例");
}
task.setProperty(Constants.TASK_PROPERTY_DISCORD_INSTANCE_ID, instance.getInstanceId());
return instance.submitTask(task, () -> {
List<String> im... | 1,279 | 474 | 1,753 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/service/store/RedisTaskStoreServiceImpl.java | RedisTaskStoreServiceImpl | list | class RedisTaskStoreServiceImpl implements TaskStoreService {
private static final String KEY_PREFIX = "mj-task-store::";
private final Duration timeout;
private final RedisTemplate<String, Task> redisTemplate;
public RedisTaskStoreServiceImpl(Duration timeout, RedisTemplate<String, Task> redisTemplate) {
this.... |
Set<String> keys = this.redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match(KEY_PREFIX + "*").count(1000).build());
return cursor.stream().map(String::new).collect(Collectors.toSet());
});
if (keys == null || keys.isEmpt... | 339 | 174 | 513 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/service/translate/BaiduTranslateServiceImpl.java | BaiduTranslateServiceImpl | translateToEnglish | class BaiduTranslateServiceImpl implements TranslateService {
private static final String TRANSLATE_API = "https://fanyi-api.baidu.com/api/trans/vip/translate";
private final String appid;
private final String appSecret;
public BaiduTranslateServiceImpl(ProxyProperties.BaiduTranslateConfig translateConfig) {
th... |
if (!containsChinese(prompt)) {
return prompt;
}
String salt = RandomUtil.randomNumbers(5);
String sign = MD5.create().digestHex(this.appid + prompt + salt + this.appSecret);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, S... | 215 | 517 | 732 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/service/translate/GPTTranslateServiceImpl.java | GPTTranslateServiceImpl | translateToEnglish | class GPTTranslateServiceImpl implements TranslateService {
private final OpenAiClient openAiClient;
private final ProxyProperties.OpenaiConfig openaiConfig;
public GPTTranslateServiceImpl(ProxyProperties properties) {
this.openaiConfig = properties.getOpenai();
if (CharSequenceUtil.isBlank(this.openaiConfig.ge... |
if (!containsChinese(prompt)) {
return prompt;
}
Message m1 = Message.builder().role(Message.Role.SYSTEM).content("把中文翻译成英文").build();
Message m2 = Message.builder().role(Message.Role.USER).content(prompt).build();
ChatCompletion chatCompletion = ChatCompletion.builder()
.messages(Arrays.asList(m1, m2... | 513 | 290 | 803 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/support/ApiAuthorizeInterceptor.java | ApiAuthorizeInterceptor | preHandle | class ApiAuthorizeInterceptor implements HandlerInterceptor {
private final ProxyProperties properties;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {<FILL_FUNCTION_BODY>}
} |
if (CharSequenceUtil.isBlank(this.properties.getApiSecret())) {
return true;
}
String apiSecret = request.getHeader(Constants.API_SECRET_HEADER_NAME);
boolean authorized = CharSequenceUtil.equals(apiSecret, this.properties.getApiSecret());
if (!authorized) {
response.setStatus(HttpServletResponse.SC_UN... | 65 | 116 | 181 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/support/DiscordAccountHelper.java | DiscordAccountHelper | createDiscordInstance | class DiscordAccountHelper {
private final DiscordHelper discordHelper;
private final ProxyProperties properties;
private final RestTemplate restTemplate;
private final TaskStoreService taskStoreService;
private final NotifyService notifyService;
private final List<MessageHandler> messageHandlers;
private final ... |
if (!CharSequenceUtil.isAllNotBlank(account.getGuildId(), account.getChannelId(), account.getUserToken())) {
throw new IllegalArgumentException("guildId, channelId, userToken must not be blank");
}
if (CharSequenceUtil.isBlank(account.getUserAgent())) {
account.setUserAgent(Constants.DEFAULT_DISCORD_USER_A... | 107 | 227 | 334 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/support/DiscordAccountInitializer.java | DiscordAccountInitializer | run | class DiscordAccountInitializer implements ApplicationRunner {
private final DiscordLoadBalancer discordLoadBalancer;
private final DiscordAccountHelper discordAccountHelper;
private final ProxyProperties properties;
@Override
public void run(ApplicationArguments args) throws Exception {<FILL_FUNCTION_BODY>}
} |
ProxyProperties.ProxyConfig proxy = this.properties.getProxy();
if (Strings.isNotBlank(proxy.getHost())) {
System.setProperty("http.proxyHost", proxy.getHost());
System.setProperty("http.proxyPort", String.valueOf(proxy.getPort()));
System.setProperty("https.proxyHost", proxy.getHost());
System.setProp... | 76 | 562 | 638 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/support/DiscordHelper.java | DiscordHelper | getMessageHash | class DiscordHelper {
private final ProxyProperties properties;
/**
* DISCORD_SERVER_URL.
*/
public static final String DISCORD_SERVER_URL = "https://discord.com";
/**
* DISCORD_CDN_URL.
*/
public static final String DISCORD_CDN_URL = "https://cdn.discordapp.com";
/**
* DISCORD_WSS_URL.
*/
public sta... |
if (CharSequenceUtil.isBlank(imageUrl)) {
return null;
}
if (CharSequenceUtil.endWith(imageUrl, "_grid_0.webp")) {
int hashStartIndex = imageUrl.lastIndexOf("/");
if (hashStartIndex < 0) {
return null;
}
return CharSequenceUtil.sub(imageUrl, hashStartIndex + 1, imageUrl.length() - "_grid_0.web... | 842 | 182 | 1,024 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/support/SpringContextHolder.java | SpringContextHolder | getApplicationContext | class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext APPLICATION_CONTEXT;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
APPLICATION_CONTEXT = applicationContext;
}
public static ApplicationContext getApplic... |
if (APPLICATION_CONTEXT == null) {
throw new IllegalStateException("SpringContextHolder is not ready.");
}
return APPLICATION_CONTEXT;
| 84 | 47 | 131 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/support/Task.java | Task | fail | class Task extends DomainObject {
@Serial
private static final long serialVersionUID = -674915748204390789L;
@ApiModelProperty("任务类型")
private TaskAction action;
@ApiModelProperty("任务状态")
private TaskStatus status = TaskStatus.NOT_START;
@ApiModelProperty("提示词")
private String prompt;
@ApiModelProperty("提示词-... |
this.finishTime = System.currentTimeMillis();
this.status = TaskStatus.FAILURE;
this.failReason = reason;
this.progress = "";
| 360 | 47 | 407 | <methods>public non-sealed void <init>() ,public void awake() ,public Map<java.lang.String,java.lang.Object> getProperties() ,public java.lang.Object getProperty(java.lang.String) ,public T getProperty(java.lang.String, Class<T>) ,public T getProperty(java.lang.String, Class<T>, T) ,public T getPropertyGeneric(java.lan... |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/support/TaskCondition.java | TaskCondition | test | class TaskCondition implements Predicate<Task> {
private String id;
private Set<TaskStatus> statusSet;
private Set<TaskAction> actionSet;
private String prompt;
private String promptEn;
private String description;
private String finalPromptEn;
private String messageId;
private String messageHash;
private S... |
if (task == null) {
return false;
}
if (CharSequenceUtil.isNotBlank(this.id) && !this.id.equals(task.getId())) {
return false;
}
if (this.statusSet != null && !this.statusSet.isEmpty() && !this.statusSet.contains(task.getStatus())) {
return false;
}
if (this.actionSet != null && !this.actionSet.... | 116 | 571 | 687 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/support/TaskTimeoutSchedule.java | TaskTimeoutSchedule | checkTasks | class TaskTimeoutSchedule {
private final DiscordLoadBalancer discordLoadBalancer;
@Scheduled(fixedRate = 30000L)
public void checkTasks() {<FILL_FUNCTION_BODY>}
} |
this.discordLoadBalancer.getAliveInstances().forEach(instance -> {
long timeout = TimeUnit.MINUTES.toMillis(instance.account().getTimeoutMinutes());
List<Task> tasks = instance.getRunningTasks().stream()
.filter(t -> System.currentTimeMillis() - t.getStartTime() > timeout)
.toList();
for (Task tas... | 58 | 244 | 302 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/util/AsyncLockUtils.java | AsyncLockUtils | waitForLock | class AsyncLockUtils {
private static final TimedCache<String, LockObject> LOCK_MAP = CacheUtil.newTimedCache(Duration.ofDays(1).toMillis());
public static synchronized LockObject getLock(String key) {
return LOCK_MAP.get(key);
}
public static LockObject waitForLock(String key, Duration duration) throws Timeout... |
LockObject lockObject;
synchronized (LOCK_MAP) {
if (LOCK_MAP.containsKey(key)) {
lockObject = LOCK_MAP.get(key);
} else {
lockObject = new LockObject(key);
LOCK_MAP.put(key, lockObject);
}
}
Future<?> future = ThreadUtil.execAsync(() -> {
try {
lockObject.sleep();
} catch (Inter... | 146 | 271 | 417 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/util/BannedPromptUtils.java | BannedPromptUtils | checkBanned | class BannedPromptUtils {
private static final String BANNED_WORDS_FILE_PATH = "/home/spring/config/banned-words.txt";
private final List<String> BANNED_WORDS;
static {
List<String> lines;
File file = new File(BANNED_WORDS_FILE_PATH);
if (file.exists()) {
lines = FileUtil.readLines(file, StandardCharsets.U... |
String finalPromptEn = promptEn.toLowerCase(Locale.ENGLISH);
for (String word : BANNED_WORDS) {
Matcher matcher = Pattern.compile("\\b" + word + "\\b").matcher(finalPromptEn);
if (matcher.find()) {
int index = CharSequenceUtil.indexOfIgnoreCase(promptEn, word);
throw new BannedPromptException(promptE... | 239 | 133 | 372 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/util/ConvertUtils.java | ConvertUtils | convertChangeParams | class ConvertUtils {
/**
* content正则匹配prompt和进度.
*/
public static final String CONTENT_REGEX = ".*?\\*\\*(.*?)\\*\\*.+<@\\d+> \\((.*?)\\)";
public static ContentParseData parseContent(String content) {
return parseContent(content, CONTENT_REGEX);
}
public static ContentParseData parseContent(String content... |
List<String> split = CharSequenceUtil.split(content, " ");
if (split.size() != 2) {
return null;
}
String action = split.get(1).toLowerCase();
TaskChangeParams changeParams = new TaskChangeParams();
changeParams.setId(split.get(0));
if (action.charAt(0) == 'u') {
changeParams.setAction(TaskAction.U... | 405 | 283 | 688 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/util/MimeTypeUtils.java | MimeTypeUtils | guessFileSuffix | class MimeTypeUtils {
private final Map<String, List<String>> MIME_TYPE_MAP;
static {
MIME_TYPE_MAP = new HashMap<>();
var resource = MimeTypeUtils.class.getResource("/mime.types");
var lines = FileUtil.readLines(resource, StandardCharsets.UTF_8);
for (var line : lines) {
if (CharSequenceUtil.isBlank(line... |
if (CharSequenceUtil.isBlank(mimeType)) {
return null;
}
String key = mimeType;
if (!MIME_TYPE_MAP.containsKey(key)) {
key = MIME_TYPE_MAP.keySet().stream().filter(k -> CharSequenceUtil.startWithIgnoreCase(mimeType, k))
.findFirst().orElse(null);
}
var suffixList = MIME_TYPE_MAP.get(key);
if (... | 197 | 157 | 354 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/util/SnowFlake.java | SnowFlake | nextId | class SnowFlake {
private long workerId;
private long datacenterId;
private long sequence = 0L;
private final long twepoch;
private final long sequenceMask;
private final long workerIdShift;
private final long datacenterIdShift;
private final long timestampLeftShift;
private long lastTimestamp = -1L;
private ... |
long currentTimestamp = timeGen();
if (currentTimestamp < this.lastTimestamp) {
long offset = this.lastTimestamp - currentTimestamp;
if (offset > this.timeOffset) {
throw new ValidateException("Clock moved backwards, refusing to generate id for [" + offset + "ms]");
}
try {
this.wait(offset << ... | 1,071 | 468 | 1,539 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/wss/handle/BlendSuccessHandler.java | BlendSuccessHandler | handle | class BlendSuccessHandler extends MessageHandler {
@Override
public int order() {
return 89;
}
@Override
public void handle(DiscordInstance instance, MessageType messageType, DataObject message) {<FILL_FUNCTION_BODY>}
} |
String content = getMessageContent(message);
ContentParseData parseData = ConvertUtils.parseContent(content);
if (parseData == null || !MessageType.CREATE.equals(messageType)) {
return;
}
String interactionName = getInteractionName(message);
if ("blend".equals(interactionName)) {
// blend任务开始时,设置prom... | 67 | 248 | 315 | <methods>public non-sealed void <init>() ,public abstract void handle(com.github.novicezk.midjourney.loadbalancer.DiscordInstance, com.github.novicezk.midjourney.enums.MessageType, net.dv8tion.jda.api.utils.data.DataObject) ,public int order() <variables>protected com.github.novicezk.midjourney.support.DiscordHelper di... |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/wss/handle/DescribeSuccessHandler.java | DescribeSuccessHandler | handle | class DescribeSuccessHandler extends MessageHandler {
@Override
public int order() {
return 10;
}
@Override
public void handle(DiscordInstance instance, MessageType messageType, DataObject message) {<FILL_FUNCTION_BODY>}
private void finishDescribeTask(DiscordInstance instance, DataObject message, String pro... |
String messageId = message.getString("id");
if (MessageType.CREATE.equals(messageType)) {
String interactionName = getInteractionName(message);
if (!"describe".equals(interactionName)) {
return;
}
// 任务开始
message.put(Constants.MJ_MESSAGE_HANDLED, true);
String nonce = getMessageNonce(message)... | 393 | 206 | 599 | <methods>public non-sealed void <init>() ,public abstract void handle(com.github.novicezk.midjourney.loadbalancer.DiscordInstance, com.github.novicezk.midjourney.enums.MessageType, net.dv8tion.jda.api.utils.data.DataObject) ,public int order() <variables>protected com.github.novicezk.midjourney.support.DiscordHelper di... |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/wss/handle/ErrorMessageHandler.java | ErrorMessageHandler | handle | class ErrorMessageHandler extends MessageHandler {
@Override
public int order() {
return 2;
}
@Override
public void handle(DiscordInstance instance, MessageType messageType, DataObject message) {<FILL_FUNCTION_BODY>}
private Task findTaskWhenError(DiscordInstance instance, MessageType messageType, DataObject... |
String content = getMessageContent(message);
if (CharSequenceUtil.startWith(content, "Failed")) {
// mj官方异常
message.put(Constants.MJ_MESSAGE_HANDLED, true);
String nonce = getMessageNonce(message);
Task task = instance.getRunningTaskByNonce(nonce);
if (task != null) {
task.fail(content);
tas... | 257 | 735 | 992 | <methods>public non-sealed void <init>() ,public abstract void handle(com.github.novicezk.midjourney.loadbalancer.DiscordInstance, com.github.novicezk.midjourney.enums.MessageType, net.dv8tion.jda.api.utils.data.DataObject) ,public int order() <variables>protected com.github.novicezk.midjourney.support.DiscordHelper di... |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/wss/handle/ImagineSuccessHandler.java | ImagineSuccessHandler | handle | class ImagineSuccessHandler extends MessageHandler {
private static final String CONTENT_REGEX = "\\*\\*(.*?)\\*\\* - <@\\d+> \\((.*?)\\)";
@Override
public int order() {
return 101;
}
@Override
public void handle(DiscordInstance instance, MessageType messageType, DataObject message) {<FILL_FUNCTION_BODY>}
} |
String content = getMessageContent(message);
ContentParseData parseData = ConvertUtils.parseContent(content, CONTENT_REGEX);
if (MessageType.CREATE.equals(messageType) && parseData != null && hasImage(message)) {
TaskCondition condition = new TaskCondition()
.setActionSet(Set.of(TaskAction.IMAGINE))
... | 105 | 135 | 240 | <methods>public non-sealed void <init>() ,public abstract void handle(com.github.novicezk.midjourney.loadbalancer.DiscordInstance, com.github.novicezk.midjourney.enums.MessageType, net.dv8tion.jda.api.utils.data.DataObject) ,public int order() <variables>protected com.github.novicezk.midjourney.support.DiscordHelper di... |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/wss/handle/MessageHandler.java | MessageHandler | getImageUrl | class MessageHandler {
@Resource
protected DiscordLoadBalancer discordLoadBalancer;
@Resource
protected DiscordHelper discordHelper;
public abstract void handle(DiscordInstance instance, MessageType messageType, DataObject message);
public int order() {
return 100;
}
protected String getMessageContent(Data... |
DataArray attachments = message.getArray("attachments");
if (!attachments.isEmpty()) {
String imageUrl = attachments.getObject(0).getString("url");
return replaceCdnUrl(imageUrl);
}
return null;
| 864 | 68 | 932 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/wss/handle/RerollSuccessHandler.java | RerollSuccessHandler | handle | class RerollSuccessHandler extends MessageHandler {
private static final String CONTENT_REGEX_1 = "\\*\\*(.*?)\\*\\* - <@\\d+> \\((.*?)\\)";
private static final String CONTENT_REGEX_2 = "\\*\\*(.*?)\\*\\* - Variations by <@\\d+> \\((.*?)\\)";
private static final String CONTENT_REGEX_3 = "\\*\\*(.*?)\\*\\* - Variat... |
String content = getMessageContent(message);
ContentParseData parseData = getParseData(content);
if (MessageType.CREATE.equals(messageType) && parseData != null && hasImage(message)) {
TaskCondition condition = new TaskCondition()
.setActionSet(Set.of(TaskAction.REROLL))
.setFinalPromptEn(parseData.... | 293 | 128 | 421 | <methods>public non-sealed void <init>() ,public abstract void handle(com.github.novicezk.midjourney.loadbalancer.DiscordInstance, com.github.novicezk.midjourney.enums.MessageType, net.dv8tion.jda.api.utils.data.DataObject) ,public int order() <variables>protected com.github.novicezk.midjourney.support.DiscordHelper di... |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/wss/handle/StartAndProgressHandler.java | StartAndProgressHandler | handle | class StartAndProgressHandler extends MessageHandler {
@Override
public int order() {
return 90;
}
@Override
public void handle(DiscordInstance instance, MessageType messageType, DataObject message) {<FILL_FUNCTION_BODY>}
} |
String nonce = getMessageNonce(message);
String content = getMessageContent(message);
ContentParseData parseData = ConvertUtils.parseContent(content);
if (MessageType.CREATE.equals(messageType) && CharSequenceUtil.isNotBlank(nonce)) {
// 任务开始
Task task = instance.getRunningTaskByNonce(nonce);
if (task... | 68 | 541 | 609 | <methods>public non-sealed void <init>() ,public abstract void handle(com.github.novicezk.midjourney.loadbalancer.DiscordInstance, com.github.novicezk.midjourney.enums.MessageType, net.dv8tion.jda.api.utils.data.DataObject) ,public int order() <variables>protected com.github.novicezk.midjourney.support.DiscordHelper di... |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/wss/handle/UpscaleSuccessHandler.java | UpscaleSuccessHandler | handle | class UpscaleSuccessHandler extends MessageHandler {
private static final String CONTENT_REGEX_1 = "\\*\\*(.*?)\\*\\* - Upscaled \\(.*?\\) by <@\\d+> \\((.*?)\\)";
private static final String CONTENT_REGEX_2 = "\\*\\*(.*?)\\*\\* - Upscaled by <@\\d+> \\((.*?)\\)";
private static final String CONTENT_REGEX_3 = "\\*\\... |
String content = getMessageContent(message);
ContentParseData parseData = getParseData(content);
if (MessageType.CREATE.equals(messageType) && parseData != null && hasImage(message)) {
TaskCondition condition = new TaskCondition()
.setActionSet(Set.of(TaskAction.UPSCALE))
.setFinalPromptEn(parseData... | 363 | 128 | 491 | <methods>public non-sealed void <init>() ,public abstract void handle(com.github.novicezk.midjourney.loadbalancer.DiscordInstance, com.github.novicezk.midjourney.enums.MessageType, net.dv8tion.jda.api.utils.data.DataObject) ,public int order() <variables>protected com.github.novicezk.midjourney.support.DiscordHelper di... |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/wss/handle/VariationSuccessHandler.java | VariationSuccessHandler | handle | class VariationSuccessHandler extends MessageHandler {
private static final String CONTENT_REGEX_1 = "\\*\\*(.*?)\\*\\* - Variations by <@\\d+> \\((.*?)\\)";
private static final String CONTENT_REGEX_2 = "\\*\\*(.*?)\\*\\* - Variations \\(.*?\\) by <@\\d+> \\((.*?)\\)";
@Override
public void handle(DiscordInstance... |
String content = getMessageContent(message);
ContentParseData parseData = getParseData(content);
if (MessageType.CREATE.equals(messageType) && parseData != null && hasImage(message)) {
TaskCondition condition = new TaskCondition()
.setActionSet(Set.of(TaskAction.VARIATION))
.setFinalPromptEn(parseDa... | 219 | 127 | 346 | <methods>public non-sealed void <init>() ,public abstract void handle(com.github.novicezk.midjourney.loadbalancer.DiscordInstance, com.github.novicezk.midjourney.enums.MessageType, net.dv8tion.jda.api.utils.data.DataObject) ,public int order() <variables>protected com.github.novicezk.midjourney.support.DiscordHelper di... |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/wss/user/SpringUserWebSocketStarter.java | SpringUserWebSocketStarter | notifyWssLock | class SpringUserWebSocketStarter implements WebSocketStarter {
private static final int CONNECT_RETRY_LIMIT = 5;
private final DiscordAccount account;
private final UserMessageListener userMessageListener;
private final String wssServer;
private final String resumeWss;
private boolean running = false;
private ... |
AsyncLockUtils.LockObject lock = AsyncLockUtils.getLock("wss:" + this.account.getId());
if (lock != null) {
lock.setProperty("code", code);
lock.setProperty("description", reason);
lock.awake();
}
| 1,790 | 77 | 1,867 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/com/github/novicezk/midjourney/wss/user/UserMessageListener.java | UserMessageListener | onMessage | class UserMessageListener {
private DiscordInstance instance;
private final List<MessageHandler> messageHandlers;
public UserMessageListener(List<MessageHandler> messageHandlers) {
this.messageHandlers = messageHandlers;
}
public void setInstance(DiscordInstance instance) {
this.instance = instance;
}
pub... |
MessageType messageType = MessageType.of(raw.getString("t"));
if (messageType == null || MessageType.DELETE == messageType) {
return;
}
DataObject data = raw.getObject("d");
if (ignoreAndLogMessage(data, messageType)) {
return;
}
ThreadUtil.sleep(50);
for (MessageHandler messageHandler : this.mes... | 251 | 163 | 414 | <no_super_class> |
novicezk_midjourney-proxy | midjourney-proxy/src/main/java/spring/config/BeanConfig.java | BeanConfig | discordAccountHelper | class BeanConfig {
@Autowired
private ApplicationContext applicationContext;
@Autowired
private ProxyProperties properties;
@Bean
TranslateService translateService() {
return switch (this.properties.getTranslateWay()) {
case BAIDU -> new BaiduTranslateServiceImpl(this.properties.getBaiduTranslate());
cas... |
var resources = this.applicationContext.getResources("classpath:api-params/*.json");
Map<String, String> paramsMap = new HashMap<>();
for (var resource : resources) {
String filename = resource.getFilename();
String params = IoUtil.readUtf8(resource.getInputStream());
paramsMap.put(filename.substring(0,... | 559 | 144 | 703 | <no_super_class> |
modelmapper_modelmapper | modelmapper/benchmarks/src/main/java/org/modelmapper/benchmarks/GiantModelBenchmark.java | GiantModelBenchmark | main | class GiantModelBenchmark {
@Benchmark
public void measureSubclass() {
Class<? extends GiantEntity> sourceType = new GiantEntity() {}.getClass();
Class<? extends GiantDto> destType = new GiantDto() {}.getClass();
new ModelMapper().createTypeMap(sourceType, destType);
}
@Benchmark
public void mea... |
Options options = new OptionsBuilder()
.include(GiantModelBenchmark.class.getSimpleName())
.forks(1)
.build();
new Runner(options).run();
| 163 | 53 | 216 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/Conditions.java | OrCondition | equals | class OrCondition<S, D> extends AbstractCondition<S, D> implements Serializable {
private static final long serialVersionUID = 0;
private final Condition<S, D> a;
private final Condition<S, D> b;
OrCondition(Condition<S, D> a, Condition<S, D> b) {
this.a = a;
this.b = b;
}
... |
return other instanceof OrCondition && ((OrCondition<?, ?>) other).a.equals(a)
&& ((OrCondition<?, ?>) other).b.equals(b);
| 263 | 49 | 312 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/Converters.java | Collection | first | class Collection {
/**
* Provides a helper method to create a collection converter that will map each element based on the {@code elementConverter}.
*
* <pre>
* using(Collection.map(String::toUpperCase)).map();
* using(Collection.map(ele -> new Destination(ele)).map();
* </p... |
return new ChainableConverter<java.util.Collection<S>, S>() {
@Override
public <D> org.modelmapper.Converter<java.util.Collection<S>, D> to(Class<D> destinationType) {
return new org.modelmapper.Converter<java.util.Collection<S>, D>() {
@Override
public D c... | 540 | 412 | 952 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/convention/InexactMatcher.java | InexactMatcher | matchToken | class InexactMatcher {
protected final PropertyNameInfo propertyNameInfo;
protected final List<Tokens> sourceTokens;
protected final List<Tokens> destTokens;
InexactMatcher(PropertyNameInfo propertyNameInfo) {
this.propertyNameInfo = propertyNameInfo;
sourceTokens = propertyNameInfo.getSourcePropertyTo... |
while (srcStrIterator.hasNext() && destStrIterator.hasNext()) {
char srcChar = srcStrIterator.next();
char destChar = destStrIterator.next();
if (Character.toUpperCase(srcChar) != Character.toUpperCase(destChar)
|| Character.toLowerCase(srcChar) != Character.toLowerCase(destChar))
... | 1,438 | 110 | 1,548 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/convention/LooseMatchingStrategy.java | Matcher | match | class Matcher extends InexactMatcher {
Matcher(PropertyNameInfo propertyNameInfo) {
super(propertyNameInfo);
}
boolean match() {<FILL_FUNCTION_BODY>}
boolean matchLastDestTokens() {
Tokens tokens = destTokens.get(destTokens.size() - 1);
for (int destTokenIndex = 0; destToken... |
if (!matchLastDestTokens())
return false;
for (Tokens destTokens : propertyNameInfo.getDestinationPropertyTokens()) {
for (int destTokenIndex = 0; destTokenIndex < destTokens.size(); destTokenIndex++) {
DestTokensMatcher matchedTokens = matchSourcePropertyName(destTokens, d... | 220 | 143 | 363 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/convention/NameTransformers.java | NameTransformers | transform | class NameTransformers {
/**
* Transforms accessor names to their simple property name according to the JavaBeans convention.
* Class and field names are unchanged.
*/
public static final NameTransformer JAVABEANS_ACCESSOR = new NameTransformer() {
public String transform(String name, NameableTyp... |
if (NameableType.METHOD.equals(nameableType)) {
if (name.startsWith("get") && name.length() > 3)
return Strings.decapitalize(name.substring(3));
else if (name.startsWith("is") && name.length() > 2)
return Strings.decapitalize(name.substring(2));
}
return n... | 670 | 115 | 785 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/convention/NamingConventions.java | NamingConventions | applies | class NamingConventions {
/**
* JavaBeans naming convention for accessors.
*/
public static final NamingConvention JAVABEANS_ACCESSOR = new NamingConvention() {
public boolean applies(String propertyName, PropertyType propertyType) {<FILL_FUNCTION_BODY>}
@Override
public String toString()... |
return PropertyType.FIELD.equals(propertyType)
|| (propertyName.startsWith("get") && propertyName.length() > 3)
|| (propertyName.startsWith("is") && propertyName.length() > 2);
| 710 | 64 | 774 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/convention/StandardMatchingStrategy.java | Matcher | match | class Matcher extends InexactMatcher {
Matcher(PropertyNameInfo propertyNameInfo) {
super(propertyNameInfo);
}
boolean match() {<FILL_FUNCTION_BODY>}
} |
Set<Integer> matchSources = new HashSet<Integer>();
for (Tokens destTokens : propertyNameInfo.getDestinationPropertyTokens()) {
for (int destTokenIndex = 0; destTokenIndex < destTokens.size();) {
DestTokensMatcher matchedTokens = matchSourcePropertyName(destTokens, destTokenIndex);
... | 57 | 210 | 267 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/convention/StrictMatchingStrategy.java | StrictMatchingStrategy | matches | class StrictMatchingStrategy implements MatchingStrategy {
@Override
public boolean isExact() {
return true;
}
@Override
public boolean matches(PropertyNameInfo propertyNameInfo) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "Strict";
}
} |
List<Tokens> sourceTokens = propertyNameInfo.getSourcePropertyTokens();
List<Tokens> destTokens = propertyNameInfo.getDestinationPropertyTokens();
if (sourceTokens.size() != destTokens.size())
return false;
for (int propIndex = 0; propIndex < destTokens.size(); propIndex++) {
Tokens... | 102 | 235 | 337 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/internal/BridgeClassLoaderFactory.java | BridgeClassLoader | getAllExtendedOrImplementedTypesRecursively | class BridgeClassLoader extends ClassLoader {
private final ClassLoader internalClassSpace; // Bridging the internal lib class space as described in https://www.infoq.com/articles/code-generation-with-osgi
private final Set<ClassLoader> additionalClassLoaders; // Additional Class Loaders in attempt to solve h... |
Class<?> clazz = clazzArg;
List<Class<?>> res = new ArrayList<Class<?>>();
do {
res.add(clazz);
// First, add all the interfaces implemented by this class
Class<?>[] interfaces = clazz.getInterfaces();
if (interfaces.length > 0) {
res.addAll(Arrays.asList(interfa... | 1,033 | 304 | 1,337 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/internal/Errors.java | Converter | format | class Converter<T> {
final Class<T> type;
Converter(Class<T> type) {
this.type = type;
}
boolean appliesTo(Object subject) {
return subject != null && type.isAssignableFrom(subject.getClass());
}
String convert(Object subject) {
return toString(type.cast(subject)... |
@SuppressWarnings("resource")
Formatter fmt = new Formatter().format(heading).format(":%n%n");
int index = 1;
boolean displayCauses = getOnlyCause(errorMessages) == null;
for (ErrorMessage errorMessage : errorMessages) {
fmt.format("%s) %s%n", index++, errorMessage.getMessage());
... | 195 | 254 | 449 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/internal/ExplicitMappingBuilder.java | MappingOptions | visitPropertyMap | class MappingOptions {
Condition<?, ?> condition;
Converter<?, ?> converter;
Provider<?> provider;
int skipType;
boolean mapFromSource;
void reset() {
condition = null;
converter = null;
provider = null;
skipType = 0;
mapFromSource = false;
}
}
... |
String propertyMapClassName = propertyMap.getClass().getName();
try {
ClassReader cr = new ClassReader(propertyMap.getClass().getClassLoader().getResourceAsStream(
propertyMapClassName.replace('.', '/') + ".class"));
ExplicitMappingVisitor visitor = new ExplicitMappingVisitor(error... | 1,716 | 207 | 1,923 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/internal/MappingImpl.java | MappingImpl | getOptions | class MappingImpl implements InternalMapping, Comparable<MappingImpl> {
private final List<PropertyInfo> destinationMutators;
private final boolean explicit;
private final String path;
private int skipType;
private Condition<?, ?> condition;
protected Provider<?> provider;
protected Converter<?, ?>... |
MappingOptions options = new MappingOptions();
options.skipType = skipType;
options.condition = condition;
options.converter = converter;
options.provider = provider;
return options;
| 932 | 62 | 994 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/internal/PropertyInfoImpl.java | ValueReaderPropertyInfo | create | class ValueReaderPropertyInfo extends PropertyInfoImpl<Member> implements Accessor {
private ValueReader.Member<Object> valueReaderMember;
@SuppressWarnings("unchecked")
ValueReaderPropertyInfo(ValueReader.Member<?> valueReaderMember, Class<?> initialType, String name) {
super(initialType, null,... |
final ValueReader<Object> uncheckedValueReader = (ValueReader<Object>) valueReader;
ValueReader.Member<?> valueReaderMember = new ValueReader.Member<Object>(Object.class) {
@Override
public Object get(Object source, String memberName) {
return uncheckedValueReader.get(source,... | 508 | 124 | 632 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/internal/PropertyInfoRegistry.java | PropertyInfoKey | fieldPropertyFor | class PropertyInfoKey {
private final Class<?> initialType;
private final String propertyName;
private final Configuration configuration;
PropertyInfoKey(Class<?> initialType, String propertyName, Configuration configuration) {
this.initialType = initialType;
this.propertyName = prop... |
PropertyInfoKey key = new PropertyInfoKey(type, name, configuration);
FieldPropertyInfo fieldPropertyInfo = FIELD_CACHE.get(key);
if (fieldPropertyInfo == null) {
fieldPropertyInfo = new FieldPropertyInfo(type, field, name);
FIELD_CACHE.put(key, fieldPropertyInfo);
}
return fie... | 860 | 106 | 966 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/internal/PropertyInfoSetResolver.java | ResolveRequest | resolveProperties | class ResolveRequest<M extends AccessibleObject & Member, PI extends PropertyInfo> {
PropertyInfoResolver<M, PI> propertyResolver;
PropertyType propertyType;
Configuration config;
AccessLevel accessLevel;
NamingConvention namingConvention;
NameTransformer nameTransformer;
}
static ... |
if (!Types.mightContainsProperties(type) || Types.isInternalType(type)) {
return new LinkedHashMap<String, PI>();
}
Map<String, PI> properties = new LinkedHashMap<String, PI>();
Class<?> superType = type.getSuperclass();
if (superType != null && superType != Object.class && superType !=... | 1,227 | 407 | 1,634 | <no_super_class> |
modelmapper_modelmapper | modelmapper/core/src/main/java/org/modelmapper/internal/PropertyNameInfoImpl.java | PropertyNameInfoImpl | getSourceClassTokens | class PropertyNameInfoImpl implements PropertyNameInfo {
private final Class<?> sourceClass;
private final Configuration configuration;
private Tokens sourceClassTokens;
private Stack<Tokens> sourcePropertyTypeTokens;
private final Stack<Tokens> sourcePropertyTokens = new Stack<Tokens>();
private fina... |
if (sourceClassTokens == null) {
String className = configuration.getSourceNameTransformer().transform(
sourceClass.getSimpleName(), NameableType.CLASS);
sourceClassTokens = Tokens.of(configuration.getSourceNameTokenizer().tokenize(className,
NameableType.CLASS));
}
... | 1,149 | 99 | 1,248 | <no_super_class> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.