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 authentication) throws IOException {<FILL_FUNCTION_BODY>}
}
|
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());
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)oauth2Authentication.getDetails();
modelMap.put("token", details.getTokenValue());
return "index";
| 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;
@Value("${zlt.sso.user-info-uri:}")
private String userInfoUri;
private final static Map<String, Map<String, Object>> localTokenMap = new HashMap<>();
@GetMapping("/token/{code}")
public String tokenInfo(@PathVariable String code) throws UnsupportedEncodingException {
//获取token
Map tokenMap = getAccessToken(code);
String accessToken = (String)tokenMap.get("access_token");
//获取用户信息
Map userMap = getUserInfo(accessToken);
List<String> roles = getRoles(userMap);
Map result = new HashMap(2);
String username = (String)userMap.get("username");
result.put("username", username);
result.put("roles", roles);
localTokenMap.put(accessToken, result);
return accessToken;
}
/**
* 获取token
*/
public Map getAccessToken(String code) throws UnsupportedEncodingException {<FILL_FUNCTION_BODY>}
/**
* 获取用户信息
*/
public Map getUserInfo(String accessToken) {
RestTemplate restTemplate = new RestTemplate();
Map result = restTemplate.getForObject(userInfoUri+"?access_token="+accessToken, Map.class);
return (Map)result.get("datas");
}
private List<String> getRoles(Map userMap) {
List<Map<String, String>> roles = (List<Map<String, String>>)userMap.get("roles");
List<String> result = new ArrayList<>();
if (CollectionUtil.isNotEmpty(roles)) {
roles.forEach(e -> {
result.add(e.get("code"));
});
}
return result;
}
@GetMapping("/user")
public Map<String, Object> user(HttpServletRequest request) {
String token = request.getParameter("access_token");
return localTokenMap.get(token);
}
@GetMapping("/logoutNotify")
public void logoutNotify(HttpServletRequest request) {
String tokens = request.getParameter("tokens");
log.info("=====logoutNotify: " + tokens);
if (StrUtil.isNotEmpty(tokens)) {
for (String accessToken : tokens.split(",")) {
localTokenMap.remove(accessToken);
}
}
}
}
|
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(authorization);
headers.add("Authorization", "Basic " + base64Auth);
MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
param.add("code", code);
param.add("grant_type", "authorization_code");
param.add("redirect_uri", redirectUri);
param.add("scope", "app");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
ResponseEntity<Map> response = restTemplate.postForEntity(accessTokenUri, request , Map.class);
Map result = response.getBody();
return result;
| 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.getAttributes();
Authentication auth = (Authentication)claims.get(Principal.class.getName());
LoginAppUser user = LoginUserUtils.getUser(auth);
if (user != null) {
headerValues.add(SecurityConstants.USER_ID_HEADER, String.valueOf(user.getId()));
headerValues.add(SecurityConstants.USER_HEADER, user.getUsername());
}
headerValues.add(SecurityConstants.ROLE_HEADER, CollectionUtil.join(authentication.getAuthorities(), ","));
headerValues.add(SecurityConstants.TENANT_HEADER, (String)claims.get(SecurityConstants.CLIENT_ID));
headerValues.add(SecurityConstants.ACCOUNT_TYPE_HEADER, (String)claims.get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME));
}
ServerWebExchange exchange = webFilterExchange.getExchange();
ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
.headers(h -> h.addAll(headerValues))
.build();
ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build();
return webFilterExchange.getChain().filter(build);
| 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 authorizationContext) {
return authentication.map(auth -> {
ServerWebExchange exchange = authorizationContext.getExchange();
ServerHttpRequest request = exchange.getRequest();
boolean isPermission = super.hasPermission(auth, request.getMethod().name(), request.getURI().getPath());
return new AuthorizationDecision(isPermission);
}).defaultIfEmpty(new AuthorizationDecision(false));
}
@Override
public List<SysMenu> findMenuByRoleCodes(String roleCodes) {<FILL_FUNCTION_BODY>}
}
|
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 antPathMatcher,private com.central.oauth2.common.properties.SecurityProperties securityProperties
|
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("setToken");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
| 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 GateWayMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
GateWayMappingJackson2HttpMessageConverter(){
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.valueOf(MediaType.TEXT_HTML_VALUE + ";charset=UTF-8"));
setSupportedMediaTypes(mediaTypes);
}
}
}
|
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) {
super(errorAttributes, resourceProperties, errorProperties, applicationContext);
}
/**
* 获取异常属性
*/
@Override
protected Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
Throwable error = super.getError(request);
return responseError(request, error);
}
/**
* 指定响应处理方法为JSON处理的方法
* @param errorAttributes
*/
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
/**
* 根据code获取对应的HttpStatus
* @param errorAttributes
*/
@Override
protected int getHttpStatus(Map<String, Object> errorAttributes) {
Integer httpStatus = (Integer) errorAttributes.remove("httpStatus");
return httpStatus != null ? httpStatus : HttpStatus.INTERNAL_SERVER_ERROR.value();
}
/**
* 构建异常信息
* @param request
* @param ex
* @return
*/
private String buildMessage(ServerRequest request, Throwable ex) {
StringBuilder message = new StringBuilder("Failed to handle request [");
message.append(request.methodName());
message.append(" ");
message.append(request.uri());
message.append("]");
if (ex != null) {
message.append(": ");
message.append(ex.getMessage());
}
return message.toString();
}
/**
* 构建返回的JSON数据格式
*/
private Map<String, Object> responseError(ServerRequest request, Throwable error) {
String errorMessage = buildMessage(request, error);
int httpStatus = 200;//getHttpStatus(error);
Map<String, Object> map = new HashMap<>();
map.put("resp_code", 1);
map.put("resp_msg", errorMessage);
map.put("datas", null);
map.put("httpStatus", httpStatus);
return map;
}
private int getHttpStatus(Throwable error) {<FILL_FUNCTION_BODY>}
}
|
int httpStatus;
/*if (error instanceof InvalidTokenException) {
InvalidTokenException ex = (InvalidTokenException)error;
httpStatus = ex.getHttpErrorCode();
} else {
httpStatus = HttpStatus.INTERNAL_SERVER_ERROR.value();
}*/
httpStatus = HttpStatus.INTERNAL_SERVER_ERROR.value();
return httpStatus;
| 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.http.HttpStatus.Series,java.lang.String> SERIES_VIEWS,private static final org.springframework.http.MediaType TEXT_HTML_UTF8,private final org.springframework.boot.autoconfigure.web.ErrorProperties errorProperties
|
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 userAgent = UserAgent.parseUserAgentString(headers.get("User-Agent"));
//埋点
PointUtil.debug("1", "request-statistics",
"ip=" + ReactiveAddrUtil.getRemoteAddr(request)
+ "&browser=" + getBrowser(userAgent.getBrowser().name())
+ "&operatingSystem=" + getOperatingSystem(userAgent.getOperatingSystem().name()));
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
private String getBrowser(String browser) {
if (StrUtil.isNotEmpty(browser)) {
if (browser.contains("CHROME")) {
return "CHROME";
} else if (browser.contains("FIREFOX")) {
return "FIREFOX";
} else if (browser.contains("SAFARI")) {
return "SAFARI";
} else if (browser.contains("EDGE")) {
return "EDGE";
}
}
return browser;
}
private String getOperatingSystem(String operatingSystem) {<FILL_FUNCTION_BODY>}
}
|
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());
h.add(MDCTraceUtils.SPAN_ID_HEADER, MDCTraceUtils.getNextSpanId());
})
.build();
ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build();
return chain.filter(build);
}
return chain.filter(exchange);
| 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
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
|
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 = exchange.getRequest().mutate().headers(header -> {
header.add(CommonConstant.Z_L_T_VERSION, version);
}).build();
ServerWebExchange rebuildServerWebExchange = exchange.mutate().request(rebuildRequest).build();
return chain.filter(rebuildServerWebExchange);
}
return chain.filter(exchange);
| 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 NacosRouteDefinitionRepository(ApplicationEventPublisher publisher, NacosConfigProperties nacosConfigProperties) {
this.publisher = publisher;
this.nacosConfigProperties = nacosConfigProperties;
addListener();
}
@Override
public Flux<RouteDefinition> getRouteDefinitions() {
try {
String content = nacosConfigProperties.configServiceInstance().getConfig(SCG_DATA_ID, SCG_GROUP_ID,5000);
List<RouteDefinition> routeDefinitions = getListByStr(content);
return Flux.fromIterable(routeDefinitions);
} catch (NacosException e) {
log.error("getRouteDefinitions by nacos error", e);
}
return Flux.fromIterable(CollUtil.newArrayList());
}
/**
* 添加Nacos监听
*/
private void addListener() {<FILL_FUNCTION_BODY>}
@Override
public Mono<Void> save(Mono<RouteDefinition> route) {
return null;
}
@Override
public Mono<Void> delete(Mono<String> routeId) {
return null;
}
private List<RouteDefinition> getListByStr(String content) {
if (StrUtil.isNotEmpty(content)) {
return JsonUtil.toList(content, RouteDefinition.class);
}
return new ArrayList<>(0);
}
}
|
try {
nacosConfigProperties.configServiceInstance().addListener(SCG_DATA_ID, SCG_GROUP_ID, new Listener() {
@Override
public Executor getExecutor() {
return null;
}
@Override
public void receiveConfigInfo(String configInfo) {
publisher.publishEvent(new RefreshRoutesEvent(this));
}
});
} catch (NacosException e) {
log.error("nacos-addListener-error", e);
}
| 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(ip)) {
return true;
}
return false;
}
/**
* 获取本机的IP地址
*/
public static String getLocalAddr() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.error("InetAddress.getLocalHost()-error", e);
}
return "";
}
}
|
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 (isEmptyIP(ip)) {
ip = headers.get("HTTP_CLIENT_IP");
if (isEmptyIP(ip)) {
ip = headers.get("HTTP_X_FORWARDED_FOR");
if (isEmptyIP(ip)) {
ip = request.getRemoteAddress().getAddress().getHostAddress();
if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
// 根据网卡取本机配置的IP
ip = getLocalAddr();
}
}
}
}
}
} else if (ip.length() > 15) {
String[] ips = ip.split(",");
for (int index = 0; index < ips.length; index++) {
String strIp = ips[index];
if (!isEmptyIP(ip)) {
ip = strIp;
break;
}
}
}
return ip;
| 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 = "/sysLog")
public PageResult<JsonNode> sysLog(SearchDto searchDto) {
return queryService.strQuery(SYS_LOG_INDEXNAME, searchDto);
}
@Operation(summary = "系统日志链路列表")
@GetMapping(value = "/traceLog")
public PageResult<TraceLog> traceLog(SearchDto searchDto) {<FILL_FUNCTION_BODY>}
}
|
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 {
logList = new ArrayList<>(0);
}
return PageResult.<TraceLog>builder().data(logList).code(0).count((long) logList.size()).build();
| 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(logKey);
return true;
}
}
private String genLogKey(TraceLog log) {
return StrUtil.format("{}_{}_{}_{}", log.getAppName(), log.getSpanId(), log.getServerIp(), log.getServerPort());
}
}
|
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.length() == 1) {
log.setParentId("-1");
} else {
log.setParentId(spanId.substring(0, spanId.length() - 2));
}
if (checkLog(genLogKey(log), logSet)) {
logList.add(log);
}
}
});
return logList;
| 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) throws Exception {<FILL_FUNCTION_BODY>}
}
|
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(adminContextPath + "/");
http.authorizeHttpRequests(authorizeRequests -> {
// 授权服务器关闭basic认证
authorizeRequests
.requestMatchers(adminContextPath + "/assets/**").permitAll()
.requestMatchers(adminContextPath + "/login").permitAll()
.anyRequest().authenticated();
})
.formLogin(formLogin -> formLogin.loginPage(adminContextPath + "/login").successHandler(successHandler))
.logout(logout -> logout.logoutUrl(adminContextPath + "/logout"))
.httpBasic(Customizer.withDefaults())
.headers(header -> header.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
.csrf(AbstractHttpConfigurer::disable);
return http.build();
| 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 ParameterizedTypeReference<Result<Map<String, Object>>> STRING_OBJECT_MAP = new ParameterizedTypeReference<>() {};
private final ObjectMapper objectMapper;
public CustomAccessTokenResponseHttpMessageConverter(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
protected void writeInternal(OAuth2AccessTokenResponse tokenResponse, HttpOutputMessage outputMessage)
throws HttpMessageNotWritableException {<FILL_FUNCTION_BODY>}
}
|
try {
Map<String, Object> tokenResponseParameters = this.accessTokenResponseParametersConverter.convert(tokenResponse);
GenericHttpMessageConverter<Object> jsonMessageConverter = new MappingJackson2HttpMessageConverter(objectMapper);
jsonMessageConverter.write(Result.succeed(tokenResponseParameters), STRING_OBJECT_MAP.getType(), MediaType.APPLICATION_JSON, outputMessage);
}
catch (Exception ex) {
throw new HttpMessageNotWritableException(
"An error occurred writing the OAuth 2.0 Access Token Response: " + ex.getMessage(), ex);
}
| 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.endpoint.OAuth2AccessTokenResponse,Map<java.lang.String,java.lang.Object>>) <variables>private static final java.nio.charset.Charset DEFAULT_CHARSET,private static final ParameterizedTypeReference<Map<java.lang.String,java.lang.Object>> STRING_OBJECT_MAP,private Converter<Map<java.lang.String,java.lang.Object>,org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse> accessTokenResponseConverter,private Converter<org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse,Map<java.lang.String,java.lang.Object>> accessTokenResponseParametersConverter,private GenericHttpMessageConverter<java.lang.Object> jsonMessageConverter
|
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();
claims.claim(SecurityConstants.DETAILS_USER_ID, user.getId());
claims.claim(SecurityConstants.USERNAME, user.getUsername());
String account_type = (String)baseAuthenticationToken.getAdditionalParameters().get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
claims.claim(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, account_type);
}
| 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 AntPathRequestMatcher(SecurityConstants.OAUTH_LOGIN_PRO_URL, HttpMethod.POST.name());
}
/**
* 返回true代表不执行过滤器,false代表执行
*/
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
if (requiresAuthentication(request)) {
return false;
}
return true;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {<FILL_FUNCTION_BODY>}
private boolean requiresAuthentication(HttpServletRequest request) {
return requiresAuthenticationRequestMatcher.matches(request);
}
}
|
try {
DefaultSavedRequest savedRequest = (DefaultSavedRequest)request.getSession().getAttribute(SAVED_REQUEST);
if (savedRequest != null) {
String[] clientIds = savedRequest.getParameterValues("client_id");
if (ArrayUtil.isNotEmpty(clientIds)) {
//保存租户id
TenantContextHolder.setTenant(clientIds[0]);
}
}
chain.doFilter(request, response);
} finally {
TenantContextHolder.clear();
}
| 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
.logoutUrl(SecurityConstants.LOGOUT_URL)
.logoutSuccessHandler(logoutSuccessHandler)
.addLogoutHandler(logoutHandler)
.deleteCookies("JSESSIONID")
.clearAuthentication(true)
.invalidateHttpSession(true))
.headers(header -> header
// 避免iframe同源无法登录许iframe
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED));
| 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 (AuthorizationGrantType.CLIENT_CREDENTIALS.equals(context.getAuthorizationGrantType().getValue())) {
return;
}
if (context.getTokenType().equals(OAuth2TokenType.ACCESS_TOKEN)) {
claims.claim(SecurityConstants.DETAILS_USER, context.getPrincipal().getPrincipal());
} else if (context.getTokenType().getValue().equals(OidcParameterNames.ID_TOKEN)) {
claims.claim(IdTokenClaimNames.AUTH_TIME, Date.from(Instant.now()));
StandardSessionIdGenerator standardSessionIdGenerator = new StandardSessionIdGenerator();
claims.claim("sid", standardSessionIdGenerator.generateSessionId());
}
};
}
/**
* 令牌生成规则实现
*/
@Bean
public OAuth2TokenGenerator oAuth2TokenGenerator(JwtEncoder jwtEncoder, OAuth2TokenCustomizer<JwtEncodingContext> jwtTokenCustomizer) {
JwtGenerator jwtGenerator = new JwtGenerator(jwtEncoder);
jwtGenerator.setJwtCustomizer(jwtTokenCustomizer);
OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
accessTokenGenerator.setAccessTokenCustomizer(new CustomeOAuth2TokenCustomizer());
return new DelegatingOAuth2TokenGenerator(
jwtGenerator,
accessTokenGenerator,
new OAuth2RefreshTokenGenerator()
);
}
/**
* 授权服务信息配置
*/
@Bean
public AuthorizationServerSettings authorizationServerSettings(SecurityProperties securityProperties) {
return AuthorizationServerSettings.builder()
.issuer(securityProperties.getAuth().getIssuer())
.authorizationEndpoint(SecurityConstants.AUTH_CODE_URL)
.tokenEndpoint(SecurityConstants.OAUTH_TOKEN_URL)
.tokenIntrospectionEndpoint(SecurityConstants.OAUTH_CHECK_TOKEN_URL)
.jwkSetEndpoint(SecurityConstants.OAUTH_JWKS_URL)
.build();
}
/**
* 授权错误处理
*/
@Bean
public AuthenticationFailureHandler authenticationFailureHandler(ObjectMapper objectMapper) {
return (request, response, authException) -> {
String msg = null;
if (StrUtil.isNotEmpty(authException.getMessage())) {
msg = authException.getMessage();
} else if (authException instanceof OAuth2AuthenticationException exception) {
msg = exception.getError().getErrorCode();
}
ResponseUtil.responseFailed(objectMapper, response, msg);
};
}
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler(ObjectMapper objectMapper) {<FILL_FUNCTION_BODY>}
}
|
return (request, response, authentication) -> {
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
(OAuth2AccessTokenAuthenticationToken) authentication;
OAuth2AccessToken accessToken = accessTokenAuthentication.getAccessToken();
OAuth2RefreshToken refreshToken = accessTokenAuthentication.getRefreshToken();
Map<String, Object> additionalParameters = accessTokenAuthentication.getAdditionalParameters();
OAuth2AccessTokenResponse.Builder builder =
OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue())
.tokenType(accessToken.getTokenType())
.scopes(accessToken.getScopes());
if (accessToken.getIssuedAt() != null && accessToken.getExpiresAt() != null) {
builder.expiresIn(ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()));
}
if (refreshToken != null) {
builder.refreshToken(refreshToken.getTokenValue());
}
if (!CollectionUtils.isEmpty(additionalParameters)) {
builder.additionalParameters(additionalParameters);
}
OAuth2AccessTokenResponse accessTokenResponse = builder.build();
ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
CustomAccessTokenResponseHttpMessageConverter converter = new CustomAccessTokenResponseHttpMessageConverter(objectMapper);
converter.write(accessTokenResponse, null, httpResponse);
};
| 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, HttpServletResponse response) throws IOException {<FILL_FUNCTION_BODY>}
/**
* 发送手机验证码
* 后期要加接口限制
*
* @param mobile 手机号
* @return R
*/
@ResponseBody
@GetMapping(SecurityConstants.MOBILE_VALIDATE_CODE_URL_PREFIX + "/{mobile}")
public Result<String> createCode(@PathVariable String mobile) {
Assert.notNull(mobile, "手机号不能为空");
return validateCodeService.sendSmsCode(mobile);
}
}
|
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);
// 三个参数分别为宽、高、验证码字符数、干扰线宽度
LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 35, 4, 10);
// 保存验证码
validateCodeService.saveImageCode(deviceId, captcha.getCode().toLowerCase());
// 输出图片流
captcha.write(response.getOutputStream());
| 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 = oAuth2AuthorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
if (existingAccessToken != null) {
if (securityProperties.getAuth().getUnifiedLogout()) {
UsernameHolder.setContext(existingAccessToken.getPrincipalName());
}
oAuth2AuthorizationService.remove(existingAccessToken);
log.info("remove existingAccessToken!", existingAccessToken.getAccessToken().getToken().getTokenType());
}
}
| 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;
private final ObjectMapper objectMapper;
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {<FILL_FUNCTION_BODY>}
}
|
if (securityProperties.getAuth().getUnifiedLogout()) {
unifiedLogoutService.allLogout();
}
String redirectUri = request.getParameter(REDIRECT_URL);
if (StrUtil.isNotEmpty(redirectUri)) {
//重定向指定的地址
redirectStrategy.sendRedirect(request, response, redirectUri);
} else {
ResponseUtil.responseWriter(objectMapper, response, "登出成功", 0);
}
| 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;
private boolean missingContext;
public SupplierDeferredSecurityContext(Supplier<SecurityContext> supplier, SecurityContextHolderStrategy strategy) {
this.supplier = supplier;
this.strategy = strategy;
}
@Override
public SecurityContext get() {
init();
return this.securityContext;
}
@Override
public boolean isGenerated() {
init();
return this.missingContext;
}
private void init() {<FILL_FUNCTION_BODY>}
}
|
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("Created %s", this.securityContext));
}
}
| 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) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public PageResult<Client> listClient(Map<String, Object> params, boolean isPage) {
Page<Client> page;
if (isPage) {
page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
} else {
page = new Page<>(1, -1);
}
List<Client> list = baseMapper.findList(page, params);
page.setRecords(list);
return PageResult.<Client>builder().data(list).code(0).count(page.getTotal()).build();
}
@Override
public void delClient(long id) {
baseMapper.deleteById(id);
}
@Override
public Client loadClientByClientId(String clientId) {
QueryWrapper<Client> wrapper = Wrappers.query();
wrapper.eq("client_id", clientId);
return this.getOne(wrapper);
}
}
|
client.setClientSecret(passwordEncoder.encode(client.getClientSecretStr()));
String clientId = client.getClientId();
if (client.getId() == null) {
client.setCreatorId(LoginUserContextHolder.getUser().getId());
}
super.saveOrUpdateIdempotency(client, lock
, LOCK_KEY_CLIENTID+clientId
, new QueryWrapper<Client>().eq("client_id", clientId)
, clientId + "已存在");
| 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.central.common.lock.DistributedLock, java.lang.String, Wrapper<com.central.oauth.model.Client>) throws java.lang.Exception,public boolean saveOrUpdateIdempotency(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 saveOrUpdateIdempotency(com.central.oauth.model.Client, com.central.common.lock.DistributedLock, java.lang.String, Wrapper<com.central.oauth.model.Client>) throws java.lang.Exception<variables>
|
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);
}
@Override
public RegisteredClient findByClientId(String clientId) {<FILL_FUNCTION_BODY>}
}
|
ClientDto clientObj = clientService.loadClientByClientId(clientId);
if (clientObj == null) {
return null;
}
RegisteredClient.Builder builder = RegisteredClient.withId(clientObj.getClientId())
.clientId(clientObj.getClientId())
.clientSecret(clientObj.getClientSecret())
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
if (StrUtil.isNotBlank(clientObj.getAuthorizedGrantTypes())) {
for (String authorizedGrantType : clientObj.getAuthorizedGrantTypes().split(StrUtil.COMMA)) {
builder.authorizationGrantType(new AuthorizationGrantType(authorizedGrantType));
}
}
if (StrUtil.isNotBlank(clientObj.getWebServerRedirectUri())) {
for (String redirectUri : clientObj.getWebServerRedirectUri().split(StrUtil.COMMA)) {
builder.redirectUri(redirectUri);
}
}
if (StrUtil.isNotBlank(clientObj.getScope())) {
for (String scope : clientObj.getScope().split(StrUtil.COMMA)) {
builder.scope(scope);
}
}
OAuth2TokenFormat tokenFormat;
if (OAuth2TokenFormat.SELF_CONTAINED.getValue().equals(clientObj.getTokenFormat())) {
tokenFormat = OAuth2TokenFormat.SELF_CONTAINED;
} else {
tokenFormat = OAuth2TokenFormat.REFERENCE;
}
return builder
.tokenSettings(
TokenSettings.builder()
.accessTokenFormat(tokenFormat)
.accessTokenTimeToLive(Duration.ofSeconds(clientObj.getAccessTokenValiditySeconds()))
.refreshTokenTimeToLive(Duration.ofSeconds(clientObj.getRefreshTokenValiditySeconds()))
.build()
)
.clientSettings(
ClientSettings.builder()
.requireAuthorizationConsent(!BooleanUtil.toBoolean(clientObj.getAutoapprove()))
.build()
)
.build();
| 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, "authorizationConsent cannot be null");
redissonClient.getBucket(buildKey(authorizationConsent))
.set(authorizationConsent, Duration.ofMinutes(TIMEOUT));
}
@Override
public void remove(OAuth2AuthorizationConsent authorizationConsent) {
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
redissonClient.getBucket(buildKey(authorizationConsent)).delete();
}
@Override
public OAuth2AuthorizationConsent findById(String registeredClientId, String principalName) {<FILL_FUNCTION_BODY>}
private static String buildKey(String registeredClientId, String principalName) {
return "token:consent:" + registeredClientId + ":" + principalName;
}
private static String buildKey(OAuth2AuthorizationConsent authorizationConsent) {
return buildKey(authorizationConsent.getRegisteredClientId(), authorizationConsent.getPrincipalName());
}
}
|
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 SerializationCodec AUTH_CODEC = new SerializationCodec();
private final SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private final RedissonClient redissonClient;
@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
throw new UnsupportedOperationException("Method deprecated.");
}
@Override
public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
String nonce = getNonce(request);
if (StrUtil.isEmpty(nonce)) {
return;
}
// 如果当前的context是空的,则移除
SecurityContext emptyContext = this.securityContextHolderStrategy.createEmptyContext();
RBucket<SecurityContext> rBucket = this.getBucket(nonce);
if (emptyContext.equals(context)) {
rBucket.delete();
} else {
// 保存认证信息
rBucket.set(context, Duration.ofSeconds(SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS));
}
}
@Override
public boolean containsContext(HttpServletRequest request) {
String nonce = getNonce(request);
if (StrUtil.isEmpty(nonce)) {
return false;
}
// 检验当前请求是否有认证信息
return this.getBucket(nonce).get() != null;
}
@Override
public DeferredSecurityContext loadDeferredContext(HttpServletRequest request) {
Supplier<SecurityContext> supplier = () -> readSecurityContextFromRedis(request);
return new SupplierDeferredSecurityContext(supplier, this.securityContextHolderStrategy);
}
/**
* 从redis中获取认证信息
*
* @param request 当前请求
* @return 认证信息
*/
private SecurityContext readSecurityContextFromRedis(HttpServletRequest request) {<FILL_FUNCTION_BODY>}
/**
* 先从请求头中找,找不到去请求参数中找,找不到获取当前session的id
* 2023-07-11新增逻辑:获取当前session的sessionId
*
* @param request 当前请求
* @return 随机字符串(sessionId),这个字符串本来是前端生成,现在改为后端获取的sessionId
*/
private String getNonce(HttpServletRequest request) {
String nonce = request.getHeader(NONCE_HEADER_NAME);
if (StrUtil.isEmpty(nonce)) {
nonce = request.getParameter(NONCE_HEADER_NAME);
if (StrUtil.isEmpty(nonce)) {
HttpSession session = request.getSession(Boolean.FALSE);
if (session != null) {
nonce = session.getId();
}
}
}
return nonce;
}
private RBucket<SecurityContext> getBucket(String nonce) {
return redissonClient.getBucket(SECURITY_CONTEXT_PREFIX_KEY + nonce, AUTH_CODEC);
}
}
|
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();
if (context != null) {
rBucket.expire(Duration.ofSeconds(SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS));
}
return context;
| 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> params, String clientId) {<FILL_FUNCTION_BODY>}
/**
* 根据请求参数生成redis的key
*/
private String getRedisKey(Map<String, Object> params, String clientId) {
String result;
String username = MapUtils.getString(params, "username");
if (StrUtil.isNotEmpty(username)) {
result = this.buildKey(SecurityConstants.REDIS_UNAME_TO_ACCESS, clientId + "::" + username);
} else {
result = this.buildKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS, clientId);
}
return result;
}
private String buildKey(String type, String id) {
return String.format("%s::%s::%s", AUTHORIZATION, type, id);
}
}
|
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.getList(redisKey);
long size = tokenList.size();
List<TokenVo> result = new ArrayList<>(limit);
//查询token集合
List<String> tokens = tokenList.range(startEnds[0], startEnds[1]-1);
if (tokens != null) {
for (String token : tokens) {
//构造token对象
TokenVo tokenVo = new TokenVo();
tokenVo.setTokenValue(token);
//获取用户信息
RBucket<OAuth2Authorization> rBucket = redisson.getBucket(buildKey(OAuth2ParameterNames.ACCESS_TOKEN, token), AUTH_CODEC);
OAuth2Authorization authorization = rBucket.get();
if (authorization != null) {
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
if (accessToken != null && accessToken.getExpiresAt() != null) {
tokenVo.setExpiration(Date.from(accessToken.getExpiresAt()));
}
tokenVo.setUsername(authorization.getPrincipalName());
tokenVo.setClientId(authorization.getRegisteredClientId());
tokenVo.setGrantType(authorization.getAuthorizationGrantType().getValue());
String accountType = (String)authorization.getAttributes().get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
tokenVo.setAccountType(accountType);
}
result.add(tokenVo);
}
}
return PageResult.<TokenVo>builder().data(result).code(0).count(size).build();
| 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);
redisson.getBucket(clientRedisKey(client.getClientId())).set(clientDto);
}
public PageResult<ClientDto> listClient(Map<String, Object> params, boolean isPage) {
PageResult<Client> clientPage = clientService.listClient(params, isPage);
PageResult<ClientDto> result = new PageResult<>();
result.setCode(clientPage.getCode());
result.setCount(clientPage.getCount());
result.setData(BeanUtil.copyToList(clientPage.getData(), ClientDto.class));
return result;
}
public ClientDto getById(long id) {
return BeanUtil.copyProperties(clientService.getById(id), ClientDto.class);
}
public void delClient(long id) {<FILL_FUNCTION_BODY>}
public ClientDto loadClientByClientId(String clientId) {
RBucket<ClientDto> clientBucket = redisson.getBucket(clientRedisKey(clientId));
ClientDto clientDto = clientBucket.get();
if (clientDto != null) {
return clientDto;
}
Client clientObj = clientService.loadClientByClientId(clientId);
clientDto = BeanUtil.copyProperties(clientObj, ClientDto.class);
clientBucket.set(clientDto);
return clientDto;
}
public void loadAllClientToCache() {
List<Client> clientList = clientService.list();
clientList.forEach(c -> {
ClientDto clientDto = BeanUtil.copyProperties(c, ClientDto.class);;
redisson.getBucket(clientRedisKey(c.getClientId())).set(clientDto);
});
}
public List<ClientDto> list() {
return BeanUtil.copyToList(clientService.list(), ClientDto.class);
}
public ClientDto getRegisteredClientByClientId(String clientId) {
Client clientObj = clientService.loadClientByClientId(clientId);
return BeanUtil.copyProperties(clientObj, ClientDto.class);
}
private String clientRedisKey(String clientId) {
return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
}
}
|
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 authorizationService;
public UnifiedLogoutService(RestTemplate restTemplate, TaskExecutor taskExecutor
, RegisteredClientService clientService
, @Autowired(required = false) RedisOAuth2AuthorizationService authorizationService) {
this.restTemplate = restTemplate;
this.taskExecutor = taskExecutor;
this.clientService = clientService;
this.authorizationService = authorizationService;
}
public void allLogout() {
if (authorizationService == null) {
throw new RuntimeException("the 'zlt.oauth2.token.store' parameter must be redis");
}
Set<String> urls = this.getLogoutNotifyUrl();
for (String url : urls) {
taskExecutor.execute(() -> {
try {
restTemplate.getForObject(url, Void.class);
} catch (Exception e) {
log.warn(e.getMessage());
}
});
}
}
/**
* 获取登出需要通知的地址集合
*/
private Set<String> getLogoutNotifyUrl() {<FILL_FUNCTION_BODY>}
private String getTokenValueStr(List<String> tokens) {
if (CollUtil.isNotEmpty(tokens)) {
return StrUtil.join( ",", tokens);
}
return null;
}
private Set<String> generateNotifyUrls(String[] urls, String tokenStr) {
Set<String> urlSet = new HashSet(urls.length);
for (String url : urls) {
StringBuilder urlBuilder = new StringBuilder(url);
if (url.contains("?")) {
urlBuilder.append("&");
} else {
urlBuilder.append("?");
}
urlBuilder.append("tokens=").append(tokenStr);
urlSet.add(urlBuilder.toString());
}
return urlSet;
}
private Map<String, Object> getInfoMap(String additionalInformation) {
if (StrUtil.isNotEmpty(additionalInformation)) {
return JSONUtil.toBean(additionalInformation, Map.class);
}
return Map.of();
}
}
|
String username = UsernameHolder.getContext();
Set<String> logoutNotifyUrls = new HashSet<>();
try {
List<ClientDto> clientDetails = clientService.list();
Map<String, Object> informationMap;
for (ClientDto client : clientDetails) {
informationMap = this.getInfoMap(client.getAdditionalInformation());
String urls = (String)informationMap.get(LOGOUT_NOTIFY_URL_KEY);
if (StrUtil.isNotEmpty(urls)) {
List<String> tokens = authorizationService.findTokensByClientIdAndUserName(client.getClientId(), username);
if (CollUtil.isNotEmpty(tokens)) {
//注销所有该用户名下的token
tokens.forEach(authorizationService::remove);
String tokenStr = getTokenValueStr(tokens);
logoutNotifyUrls.addAll(generateNotifyUrls(urls.split(","), tokenStr));
}
}
}
} finally {
UsernameHolder.clearContext();
}
return logoutNotifyUrls;
| 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 accountType = AuthUtils.getAccountType(authentication);
return this.getService(accountType);
}
public ZltUserDetailsService getService(String accountType) {<FILL_FUNCTION_BODY>}
}
|
if (StrUtil.isEmpty(accountType)) {
accountType = SecurityConstants.DEF_ACCOUNT_TYPE;
}
log.info("UserDetailServiceFactory.getService:{}", accountType);
if (CollUtil.isNotEmpty(userDetailsServices)) {
for (ZltUserDetailsService userService : userDetailsServices) {
if (userService.supports(accountType)) {
return userService;
}
}
}
throw new CustomOAuth2AuthenticationException(StrUtil.format(ERROR_MSG, accountType));
| 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);
}
@Override
public UserDetails loadUserByUsername(String username) {<FILL_FUNCTION_BODY>}
@Override
public UserDetails loadUserByUserId(String openId) {
SysUser sysUser = userService.findByOpenId(openId);
checkUser(sysUser);
return LoginUserUtils.getLoginAppUser(sysUser);
}
@Override
public UserDetails loadUserByMobile(String mobile) {
SysUser sysUser = userService.findByMobile(mobile);
checkUser(sysUser);
return LoginUserUtils.getLoginAppUser(sysUser);
}
private void checkUser(SysUser sysUser) {
if (sysUser != null && !sysUser.getEnabled()) {
throw new DisabledException("用户已作废");
}
}
}
|
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(String deviceId, String imageCode) {
this.getBucket(deviceId)
.set(imageCode, Duration.ofSeconds(SecurityConstants.DEFAULT_IMAGE_EXPIRE));
}
/**
* 发送验证码
* <p>
* 1. 先去redis 查询是否 60S内已经发送
* 2. 未发送: 判断手机号是否存 ? false :产生4位数字 手机号-验证码
* 3. 发往消息中心-》发送信息
* 4. 保存redis
*
* @param mobile 手机号
* @return true、false
*/
@Override
public Result<String> sendSmsCode(String mobile) {
RBucket<String> rBucket = this.getBucket(mobile);
Object tempCode = rBucket.get();
if (tempCode != null) {
log.error("用户:{}验证码未失效{}", mobile, tempCode);
return Result.failed("验证码未失效,请失效后再次申请");
}
SysUser user = userService.findByMobile(mobile);
if (user == null) {
log.error("根据用户手机号{}查询用户为空", mobile);
return Result.failed("手机号不存在");
}
String code = RandomUtil.randomNumbers(4);
log.info("短信发送请求消息中心 -> 手机号:{} -> 验证码:{}", mobile, code);
rBucket.set(code, Duration.ofSeconds(SecurityConstants.DEFAULT_IMAGE_EXPIRE));
return Result.succeed("true");
}
/**
* 获取验证码
* @param deviceId 前端唯一标识/手机号
*/
@Override
public String getCode(String deviceId) {
return this.getBucket(deviceId).get();
}
/**
* 删除验证码
* @param deviceId 前端唯一标识/手机号
*/
@Override
public void remove(String deviceId) {
this.getBucket(deviceId).delete();
}
/**
* 验证验证码
*/
@Override
public void validate(String deviceId, String validCode) {<FILL_FUNCTION_BODY>}
private String buildKey(String deviceId) {
return SecurityConstants.DEFAULT_CODE_KEY + ":" + deviceId;
}
private RBucket<String> getBucket(String deviceId) {
return redisson.getBucket(buildKey(deviceId));
}
}
|
if (StrUtil.isBlank(deviceId)) {
throw new CustomOAuth2AuthenticationException("请在请求参数中携带deviceId参数");
}
String code = this.getCode(deviceId);
if (StrUtil.isBlank(validCode)) {
throw new CustomOAuth2AuthenticationException("请填写验证码");
}
if (code == null) {
throw new CustomOAuth2AuthenticationException("验证码不存在或已过期");
}
if (!StrUtil.equals(code, validCode.toLowerCase())) {
throw new CustomOAuth2AuthenticationException("验证码不正确");
}
this.remove(deviceId);
| 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;
}
MultiValueMap<String, String> parameters = OAuthEndpointUtils.getParameters(request);
return this.getAuthentication(parameters);
}
public Authentication getAuthentication(MultiValueMap<String, String> parameters) {
Set<String> requestScopes = this.getRequestScopes(parameters);
Map<String, Object> additionalParameters = getAdditionalParameters(parameters, this.paramNames());
Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication();
BaseAuthenticationToken baseToken = this.getToken(parameters);
baseToken.setScopes(requestScopes);
baseToken.setAdditionalParameters(additionalParameters);
baseToken.setClientPrincipal(clientPrincipal);
return baseToken;
};
public Set<String> getRequestScopes(MultiValueMap<String, String> parameters) {
String scope = parameters.getFirst(OAuth2ParameterNames.SCOPE);
Set<String> requestedScopes = null;
if (StrUtil.isNotEmpty(scope)) {
requestedScopes = new HashSet<>(
Arrays.asList(StringUtils.delimitedListToStringArray(scope, " ")));
} else {
requestedScopes = Collections.emptySet();
}
return requestedScopes;
}
public Map<String, Object> getAdditionalParameters(MultiValueMap<String, String> parameters, List<String> paramName) {<FILL_FUNCTION_BODY>}
protected abstract String supportGrantType();
protected abstract List<String> paramNames();
protected abstract BaseAuthenticationToken getToken(MultiValueMap<String, String> parameters);
}
|
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(paramName)) {
for (String name : paramName) {
if (key.equals(name)) {
isAdd = false;
}
}
}
if (isAdd) {
additionalParameters.put(key, value.get(0));
}
}
});
return additionalParameters;
| 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 OAuth2AuthorizationService authorizationService;
private final OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator;
public BaseAuthenticationProvider(OAuth2AuthorizationService authorizationService
, OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator) {
Assert.notNull(authorizationService, "authorizationService cannot be null");
Assert.notNull(tokenGenerator, "tokenGenerator cannot be null");
this.authorizationService = authorizationService;
this.tokenGenerator = tokenGenerator;
}
@Override
public Authentication authenticate(Authentication authentication) {<FILL_FUNCTION_BODY>}
private OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInvalidClient(
BaseAuthenticationToken authentication) {
OAuth2ClientAuthenticationToken clientPrincipal = null;
if (OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication.getClientPrincipal().getClass())) {
clientPrincipal = (OAuth2ClientAuthenticationToken) authentication.getClientPrincipal();
}
if (clientPrincipal != null && clientPrincipal.isAuthenticated()) {
return clientPrincipal;
}
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT);
}
/**
* 执行登录验证逻辑
*/
protected abstract Authentication getPrincipal(Authentication authentication);
/**
* 获取 GrantType
*/
protected abstract AuthorizationGrantType grantType();
}
|
BaseAuthenticationToken authToken = (BaseAuthenticationToken) authentication;
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(authToken);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
Set<String> authorizedScopes = authToken.getScopes();
if (!CollectionUtils.isEmpty(authToken.getScopes())) {
for (String requestedScope : authToken.getScopes()) {
if (!registeredClient.getScopes().contains(requestedScope)) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_SCOPE);
}
}
}
// 执行登录验证逻辑
TenantContextHolder.setTenant(registeredClient.getClientId());
Authentication principal = this.getPrincipal(authentication);
TenantContextHolder.clear();
String accountType = (String)authToken.getAdditionalParameters().get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
if (StrUtil.isEmpty(accountType)) {
accountType = SecurityConstants.DEF_ACCOUNT_TYPE;
authToken.getAdditionalParameters().put(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, accountType);
}
// @formatter:off
DefaultOAuth2TokenContext.Builder tokenContextBuilder = DefaultOAuth2TokenContext.builder()
.registeredClient(registeredClient)
.principal(principal)
.authorizationServerContext(AuthorizationServerContextHolder.getContext())
.authorizedScopes(authorizedScopes)
.authorizationGrantType(this.grantType())
.authorizationGrant(authToken);
// @formatter:on
OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization
.withRegisteredClient(registeredClient)
.principalName(principal.getName())
.attribute(Principal.class.getName(), principal)
.attribute(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, accountType)
.authorizationGrantType(this.grantType())
.authorizedScopes(authorizedScopes);
// ----- Access token -----
OAuth2TokenContext tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.ACCESS_TOKEN).build();
OAuth2Token generatedAccessToken = this.tokenGenerator.generate(tokenContext);
if (generatedAccessToken == null) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
"The token generator failed to generate the access token.", ERROR_URI);
throw new OAuth2AuthenticationException(error);
}
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(),
generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
authorizationBuilder.id(accessToken.getTokenValue());
if (generatedAccessToken instanceof ClaimAccessor) {
authorizationBuilder.token(accessToken, (metadata) ->
metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims()));
} else {
authorizationBuilder.accessToken(accessToken);
}
// ----- Refresh token -----
OAuth2RefreshToken refreshToken = null;
if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) &&
// Do not issue refresh token to public client
!clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) {
tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build();
OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext);
if (!(generatedRefreshToken instanceof OAuth2RefreshToken)) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
"The token generator failed to generate the refresh token.", ERROR_URI);
throw new OAuth2AuthenticationException(error);
}
refreshToken = (OAuth2RefreshToken) generatedRefreshToken;
authorizationBuilder.refreshToken(refreshToken);
}
// ----- ID token -----
OidcIdToken idToken;
if (authorizedScopes.contains(OidcScopes.OPENID)) {
// @formatter:off
tokenContext = tokenContextBuilder
.tokenType(ID_TOKEN_TOKEN_TYPE)
.authorization(authorizationBuilder.build()) // ID token customizer may need access to the access token and/or refresh token
.build();
// @formatter:on
OAuth2Token generatedIdToken = this.tokenGenerator.generate(tokenContext);
if (!(generatedIdToken instanceof Jwt)) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
"The token generator failed to generate the ID token.", ERROR_URI);
throw new OAuth2AuthenticationException(error);
}
idToken = new OidcIdToken(generatedIdToken.getTokenValue(), generatedIdToken.getIssuedAt(),
generatedIdToken.getExpiresAt(), ((Jwt) generatedIdToken).getClaims());
authorizationBuilder.token(idToken, (metadata) ->
metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims()));
} else {
idToken = null;
}
OAuth2Authorization authorization = authorizationBuilder.build();
this.authorizationService.save(authorization);
Map<String, Object> additionalParameters = Collections.emptyMap();
if (idToken != null) {
additionalParameters = new HashMap<>();
additionalParameters.put(OidcParameterNames.ID_TOKEN, idToken.getTokenValue());
}
return new OAuth2AccessTokenAuthenticationToken(
registeredClient, clientPrincipal, accessToken, refreshToken, additionalParameters);
| 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() {
return List.of(PARAM_MOBILE, OAuth2ParameterNames.PASSWORD);
}
@Override
protected BaseAuthenticationToken getToken(MultiValueMap<String, String> parameters) {<FILL_FUNCTION_BODY>}
}
|
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.security.core.Authentication getAuthentication(MultiValueMap<java.lang.String,java.lang.String>) ,public Set<java.lang.String> getRequestScopes(MultiValueMap<java.lang.String,java.lang.String>) <variables>
|
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 OAuth2Token> tokenGenerator
, UserDetailServiceFactory userDetailsServiceFactory, PasswordEncoder passwordEncoder) {
super(authorizationService, tokenGenerator);
Assert.notNull(userDetailsServiceFactory, "userDetailsServiceFactory cannot be null");
Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
this.userDetailsServiceFactory = userDetailsServiceFactory;
this.passwordEncoder = passwordEncoder;
}
@Override
public boolean supports(Class<?> authentication) {
return MobileAuthenticationToken.class.isAssignableFrom(authentication);
}
@Override
protected Authentication getPrincipal(Authentication authentication) {<FILL_FUNCTION_BODY>}
@Override
protected AuthorizationGrantType grantType() {
return MobileAuthenticationToken.GRANT_TYPE;
}
}
|
MobileAuthenticationToken authToken = (MobileAuthenticationToken) authentication;
String mobile = (String) authToken.getPrincipal();
String password = authToken.getCredentials();
UserDetails userDetails;
try {
userDetails = userDetailsServiceFactory.getService(authToken).loadUserByMobile(mobile);
} catch (AuthenticationException e) {
throw new CustomOAuth2AuthenticationException(e.getMessage());
}
if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
throw new CustomOAuth2AuthenticationException("手机号或密码错误");
}
return new MobileAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
| 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,private static final OAuth2TokenType ID_TOKEN_TOKEN_TYPE,private final non-sealed OAuth2AuthorizationService authorizationService,private final non-sealed OAuth2TokenGenerator<? extends org.springframework.security.oauth2.core.OAuth2Token> tokenGenerator
|
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
, UserDetailServiceFactory userDetailsServiceFactory) {
super(authorizationService, tokenGenerator);
Assert.notNull(userDetailsServiceFactory, "userDetailsServiceFactory cannot be null");
this.userDetailsServiceFactory = userDetailsServiceFactory;
}
@Override
public boolean supports(Class<?> authentication) {
return OpenIdAuthenticationToken.class.isAssignableFrom(authentication);
}
@Override
protected Authentication getPrincipal(Authentication authentication) {<FILL_FUNCTION_BODY>}
@Override
protected AuthorizationGrantType grantType() {
return OpenIdAuthenticationToken.GRANT_TYPE;
}
}
|
OpenIdAuthenticationToken authToken = (OpenIdAuthenticationToken) authentication;
String openId = (String) authToken.getPrincipal();
UserDetails userDetails;
try {
userDetails = userDetailsServiceFactory.getService(authToken).loadUserByUserId(openId);
} catch (AuthenticationException e) {
throw new CustomOAuth2AuthenticationException(e.getMessage());
}
if (userDetails == null) {
throw new CustomOAuth2AuthenticationException("openId错误");
}
return new OpenIdAuthenticationToken(userDetails, userDetails.getAuthorities());
| 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,private static final OAuth2TokenType ID_TOKEN_TOKEN_TYPE,private final non-sealed OAuth2AuthorizationService authorizationService,private final non-sealed OAuth2TokenGenerator<? extends org.springframework.security.oauth2.core.OAuth2Token> tokenGenerator
|
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, OAuth2ParameterNames.PASSWORD);
}
@Override
protected BaseAuthenticationToken getToken(MultiValueMap<String, String> parameters) {<FILL_FUNCTION_BODY>}
}
|
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.security.core.Authentication getAuthentication(MultiValueMap<java.lang.String,java.lang.String>) ,public Set<java.lang.String> getRequestScopes(MultiValueMap<java.lang.String,java.lang.String>) <variables>
|
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<? extends OAuth2Token> tokenGenerator
, UserDetailServiceFactory userDetailsServiceFactory, PasswordEncoder passwordEncoder) {
super(authorizationService, tokenGenerator);
Assert.notNull(userDetailsServiceFactory, "userDetailsServiceFactory cannot be null");
Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
this.userDetailsServiceFactory = userDetailsServiceFactory;
this.passwordEncoder = passwordEncoder;
}
@Override
public boolean supports(Class<?> authentication) {
return PasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
@Override
protected Authentication getPrincipal(Authentication authentication) {<FILL_FUNCTION_BODY>}
@Override
protected AuthorizationGrantType grantType() {
return PasswordAuthenticationToken.GRANT_TYPE;
}
}
|
PasswordAuthenticationToken authToken = (PasswordAuthenticationToken) authentication;
String username = (String) authToken.getPrincipal();
String password = authToken.getCredentials();
UserDetails userDetails;
try {
userDetails = userDetailsServiceFactory.getService(authToken).loadUserByUsername(username);
} catch (AuthenticationException e) {
throw new CustomOAuth2AuthenticationException(e.getMessage());
}
if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
throw new CustomOAuth2AuthenticationException("用户名或密码错误");
}
return new PasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
| 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,private static final OAuth2TokenType ID_TOKEN_TOKEN_TYPE,private final non-sealed OAuth2AuthorizationService authorizationService,private final non-sealed OAuth2TokenGenerator<? extends org.springframework.security.oauth2.core.OAuth2Token> tokenGenerator
|
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.getValue();
}
@Override
protected List<String> paramNames() {
return List.of(OAuth2ParameterNames.USERNAME, OAuth2ParameterNames.PASSWORD
, PARAM_DEVICEID, PARAM_VALIDCODE);
}
@Override
protected BaseAuthenticationToken getToken(MultiValueMap<String, String> parameters) {<FILL_FUNCTION_BODY>}
}
|
String username = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.USERNAME);
String password = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.PASSWORD);
String deviceId = OAuthEndpointUtils.getParam(parameters, PARAM_DEVICEID);
String validCode = OAuthEndpointUtils.getParam(parameters, PARAM_VALIDCODE);
return new PasswordCodeAuthenticationToken(username, password, deviceId, validCode);
| 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.security.core.Authentication getAuthentication(MultiValueMap<java.lang.String,java.lang.String>) ,public Set<java.lang.String> getRequestScopes(MultiValueMap<java.lang.String,java.lang.String>) <variables>
|
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(OAuth2AuthorizationService authorizationService
, OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator
, UserDetailServiceFactory userDetailsServiceFactory, PasswordEncoder passwordEncoder
, IValidateCodeService validateCodeService) {
super(authorizationService, tokenGenerator);
Assert.notNull(userDetailsServiceFactory, "userDetailsServiceFactory cannot be null");
Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
this.userDetailsServiceFactory = userDetailsServiceFactory;
this.passwordEncoder = passwordEncoder;
this.validateCodeService = validateCodeService;
}
@Override
public boolean supports(Class<?> authentication) {
return PasswordCodeAuthenticationToken.class.isAssignableFrom(authentication);
}
@Override
protected Authentication getPrincipal(Authentication authentication) {<FILL_FUNCTION_BODY>}
@Override
protected AuthorizationGrantType grantType() {
return PasswordCodeAuthenticationToken.GRANT_TYPE;
}
}
|
PasswordCodeAuthenticationToken authToken = (PasswordCodeAuthenticationToken) authentication;
String deviceId = authToken.getDeviceId();
String validCode = authToken.getValidCode();
//校验图形验证码
validateCodeService.validate(deviceId, validCode);
String username = (String) authToken.getPrincipal();
String password = authToken.getCredentials();
UserDetails userDetails;
try {
userDetails = userDetailsServiceFactory.getService(authToken).loadUserByUsername(username);
} catch (AuthenticationException e) {
throw new CustomOAuth2AuthenticationException(e.getMessage());
}
if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
throw new CustomOAuth2AuthenticationException("用户名或密码错误");
}
return new PasswordCodeAuthenticationToken(userDetails, userDetails.getPassword(), deviceId, userDetails.getAuthorities());
| 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,private static final OAuth2TokenType ID_TOKEN_TOKEN_TYPE,private final non-sealed OAuth2AuthorizationService authorizationService,private final non-sealed OAuth2TokenGenerator<? extends org.springframework.security.oauth2.core.OAuth2Token> tokenGenerator
|
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 static String getParam(MultiValueMap<String, String> parameters, String paramName) {
String paramValue = parameters.getFirst(paramName);
if (!StringUtils.hasText(paramValue) || parameters.get(paramName).size() != 1) {
OAuthEndpointUtils.throwError(
OAuth2ErrorCodes.INVALID_REQUEST,
paramName,
OAuthEndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI);
}
return paramValue;
}
public static Map<String, Object> getParametersIfMatchesAuthorizationCodeGrantRequest(HttpServletRequest request, String... exclusions) {
if (!matchesAuthorizationCodeGrantRequest(request)) {
return Collections.emptyMap();
}
MultiValueMap<String, String> multiValueParameters = getParameters(request);
for (String exclusion : exclusions) {
multiValueParameters.remove(exclusion);
}
Map<String, Object> parameters = new HashMap<>();
multiValueParameters.forEach((key, value) ->
parameters.put(key, (value.size() == 1) ? value.get(0) : value.toArray(new String[0])));
return parameters;
}
public static boolean matchesAuthorizationCodeGrantRequest(HttpServletRequest request) {
return AuthorizationGrantType.AUTHORIZATION_CODE.getValue().equals(
request.getParameter(OAuth2ParameterNames.GRANT_TYPE)) &&
request.getParameter(OAuth2ParameterNames.CODE) != null;
}
public static boolean matchesPkceTokenRequest(HttpServletRequest request) {
return matchesAuthorizationCodeGrantRequest(request) &&
request.getParameter(PkceParameterNames.CODE_VERIFIER) != null;
}
public static void throwError(String errorCode, String parameterName, String errorUri) {
OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, errorUri);
throw new OAuth2AuthenticationException(error);
}
public static String normalizeUserCode(String userCode) {
Assert.hasText(userCode, "userCode cannot be empty");
StringBuilder sb = new StringBuilder(userCode.toUpperCase().replaceAll("[^A-Z\\d]+", ""));
Assert.isTrue(sb.length() == 8, "userCode must be exactly 8 alpha/numeric characters");
sb.insert(4, '-');
return sb.toString();
}
}
|
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) {
parameters.add(key, value);
}
}
});
return parameters;
| 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<DiscordAccount> list() {
return this.loadBalancer.getAllInstances().stream().map(DiscordInstance::account).toList();
}
}
|
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.discordLoadBalancer.getQueueTasks().stream()
.filter(t -> CharSequenceUtil.equals(t.getId(), id)).findFirst();
return queueTaskOptional.orElseGet(() -> this.taskStoreService.get(id));
}
@ApiOperation(value = "查询任务队列")
@GetMapping("/queue")
public List<Task> queue() {
return this.discordLoadBalancer.getQueueTasks().stream()
.sorted(Comparator.comparing(Task::getSubmitTime))
.toList();
}
@ApiOperation(value = "查询所有任务")
@GetMapping("/list")
public List<Task> list() {
return this.taskStoreService.list().stream()
.sorted((t1, t2) -> CompareUtil.compare(t2.getSubmitTime(), t1.getSubmitTime()))
.toList();
}
@ApiOperation(value = "根据ID列表查询任务")
@PostMapping("/list-by-condition")
public List<Task> listByIds(@RequestBody TaskConditionDTO conditionDTO) {<FILL_FUNCTION_BODY>}
}
|
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);
notInQueueIds.remove(t.getId());
}
});
notInQueueIds.forEach(id -> {
Task task = this.taskStoreService.get(id);
if (task != null) {
result.add(task);
}
});
return result;
| 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.lock) {
this.lock.wait();
}
}
public void awake() {
synchronized (this.lock) {
this.lock.notifyAll();
}
}
public DomainObject setProperty(String name, Object value) {
getProperties().put(name, value);
return this;
}
public DomainObject removeProperty(String name) {
getProperties().remove(name);
return this;
}
public Object getProperty(String name) {
return getProperties().get(name);
}
@SuppressWarnings("unchecked")
public <T> T getPropertyGeneric(String name) {
return (T) getProperty(name);
}
public <T> T getProperty(String name, Class<T> clz) {
return getProperty(name, clz, null);
}
public <T> T getProperty(String name, Class<T> clz, T defaultValue) {
Object value = getProperty(name);
return value == null ? defaultValue : clz.cast(value);
}
public Map<String, Object> getProperties() {<FILL_FUNCTION_BODY>}
}
|
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 taskExecutor;
private final List<Task> runningTasks;
private final List<Task> queueTasks;
private final Map<String, Future<?>> taskFutureMap = Collections.synchronizedMap(new HashMap<>());
public DiscordInstanceImpl(DiscordAccount account, WebSocketStarter socketStarter, RestTemplate restTemplate,
TaskStoreService taskStoreService, NotifyService notifyService, Map<String, String> paramsMap) {
this.account = account;
this.socketStarter = socketStarter;
this.taskStoreService = taskStoreService;
this.notifyService = notifyService;
this.service = new DiscordServiceImpl(account, restTemplate, paramsMap);
this.runningTasks = new CopyOnWriteArrayList<>();
this.queueTasks = new CopyOnWriteArrayList<>();
this.taskExecutor = new ThreadPoolTaskExecutor();
this.taskExecutor.setCorePoolSize(account.getCoreSize());
this.taskExecutor.setMaxPoolSize(account.getCoreSize());
this.taskExecutor.setQueueCapacity(account.getQueueSize());
this.taskExecutor.setThreadNamePrefix("TaskQueue-" + account.getDisplay() + "-");
this.taskExecutor.initialize();
}
@Override
public String getInstanceId() {
return this.account.getChannelId();
}
@Override
public DiscordAccount account() {
return this.account;
}
@Override
public boolean isAlive() {
return this.account.isEnable();
}
@Override
public void startWss() throws Exception {
this.socketStarter.start();
}
@Override
public List<Task> getRunningTasks() {
return this.runningTasks;
}
@Override
public List<Task> getQueueTasks() {
return this.queueTasks;
}
@Override
public void exitTask(Task task) {
try {
Future<?> future = this.taskFutureMap.get(task.getId());
if (future != null) {
future.cancel(true);
}
saveAndNotify(task);
} finally {
this.runningTasks.remove(task);
this.queueTasks.remove(task);
this.taskFutureMap.remove(task.getId());
}
}
@Override
public Map<String, Future<?>> getRunningFutures() {
return this.taskFutureMap;
}
@Override
public synchronized SubmitResultVO submitTask(Task task, Callable<Message<Void>> discordSubmit) {<FILL_FUNCTION_BODY>}
private void executeTask(Task task, Callable<Message<Void>> discordSubmit) {
this.runningTasks.add(task);
try {
Message<Void> result = discordSubmit.call();
task.setStartTime(System.currentTimeMillis());
if (result.getCode() != ReturnCode.SUCCESS) {
task.fail(result.getDescription());
saveAndNotify(task);
log.debug("task finished, id: {}, status: {}", task.getId(), task.getStatus());
return;
}
task.setStatus(TaskStatus.SUBMITTED);
task.setProgress("0%");
asyncSaveAndNotify(task);
do {
task.sleep();
asyncSaveAndNotify(task);
} while (task.getStatus() == TaskStatus.IN_PROGRESS);
log.debug("task finished, id: {}, status: {}", task.getId(), task.getStatus());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
log.error("task execute error", e);
task.fail("执行错误,系统异常");
saveAndNotify(task);
} finally {
this.runningTasks.remove(task);
this.queueTasks.remove(task);
this.taskFutureMap.remove(task.getId());
}
}
private void asyncSaveAndNotify(Task task) {
ThreadUtil.execute(() -> saveAndNotify(task));
}
private void saveAndNotify(Task task) {
this.taskStoreService.save(task);
this.notifyService.notifyTaskChange(task);
}
@Override
public Message<Void> imagine(String prompt, String nonce) {
return this.service.imagine(prompt, nonce);
}
@Override
public Message<Void> upscale(String messageId, int index, String messageHash, int messageFlags, String nonce) {
return this.service.upscale(messageId, index, messageHash, messageFlags, nonce);
}
@Override
public Message<Void> variation(String messageId, int index, String messageHash, int messageFlags, String nonce) {
return this.service.variation(messageId, index, messageHash, messageFlags, nonce);
}
@Override
public Message<Void> reroll(String messageId, String messageHash, int messageFlags, String nonce) {
return this.service.reroll(messageId, messageHash, messageFlags, nonce);
}
@Override
public Message<Void> describe(String finalFileName, String nonce) {
return this.service.describe(finalFileName, nonce);
}
@Override
public Message<Void> blend(List<String> finalFileNames, BlendDimensions dimensions, String nonce) {
return this.service.blend(finalFileNames, dimensions, nonce);
}
@Override
public Message<String> upload(String fileName, DataUrl dataUrl) {
return this.service.upload(fileName, dataUrl);
}
@Override
public Message<String> sendImageMessage(String content, String finalFileName) {
return this.service.sendImageMessage(content, finalFileName);
}
}
|
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);
} catch (RejectedExecutionException e) {
this.taskStoreService.delete(task.getId());
return SubmitResultVO.fail(ReturnCode.QUEUE_REJECTED, "队列已满,请稍后尝试")
.setProperty(Constants.TASK_PROPERTY_DISCORD_INSTANCE_ID, this.getInstanceId());
} catch (Exception e) {
log.error("submit task error", e);
return SubmitResultVO.fail(ReturnCode.FAILURE, "提交失败,系统异常")
.setProperty(Constants.TASK_PROPERTY_DISCORD_INSTANCE_ID, this.getInstanceId());
}
if (currentWaitNumbers == 0) {
return SubmitResultVO.of(ReturnCode.SUCCESS, "提交成功", task.getId())
.setProperty(Constants.TASK_PROPERTY_DISCORD_INSTANCE_ID, this.getInstanceId());
} else {
return SubmitResultVO.of(ReturnCode.IN_QUEUE, "排队中,前面还有" + currentWaitNumbers + "个任务", task.getId())
.setProperty("numberOfQueues", currentWaitNumbers)
.setProperty(Constants.TASK_PROPERTY_DISCORD_INSTANCE_ID, this.getInstanceId());
}
| 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().filter(DiscordInstance::isAlive).toList();
}
public DiscordInstance chooseInstance() {
return this.rule.choose(getAliveInstances());
}
public DiscordInstance getDiscordInstance(String instanceId) {<FILL_FUNCTION_BODY>}
public Set<String> getQueueTaskIds() {
Set<String> taskIds = Collections.synchronizedSet(new HashSet<>());
for (DiscordInstance instance : getAliveInstances()) {
taskIds.addAll(instance.getRunningFutures().keySet());
}
return taskIds;
}
public List<Task> getQueueTasks() {
List<Task> tasks = new ArrayList<>();
for (DiscordInstance instance : getAliveInstances()) {
tasks.addAll(instance.getQueueTasks());
}
return tasks;
}
}
|
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.entrySet().stream().min(Comparator.comparingInt(Map.Entry::getKey)).orElseThrow().getValue();
return RandomUtil.randomEle(instanceList);
| 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 == Integer.MAX_VALUE ? 0 : current + 1;
} while (!this.position.compareAndSet(current, next));
return next;
}
}
|
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(ProxyProperties properties) {
this.executor = new ThreadPoolTaskExecutor();
this.executor.setCorePoolSize(properties.getNotifyPoolSize());
this.executor.setThreadNamePrefix("TaskNotify-");
this.executor.initialize();
}
@Override
public synchronized void notifyTaskChange(Task task) {
String notifyHook = task.getPropertyGeneric(Constants.TASK_PROPERTY_NOTIFY_HOOK);
if (CharSequenceUtil.isBlank(notifyHook)) {
return;
}
String taskId = task.getId();
String statusStr = task.getStatus() + ":" + task.getProgress();
log.trace("Wait notify task change, task: {}({}), hook: {}", taskId, statusStr, notifyHook);
try {
String paramsStr = OBJECT_MAPPER.writeValueAsString(task);
this.executor.execute(() -> {
try {
executeNotify(taskId, statusStr, notifyHook, paramsStr);
} catch (Exception e) {
log.warn("Notify task change error, task: {}({}), hook: {}, msg: {}", taskId, statusStr, notifyHook, e.getMessage());
}
});
} catch (JsonProcessingException e) {
log.error(e.getMessage(), e);
}
}
private void executeNotify(String taskId, String currentStatusStr, String notifyHook, String paramsStr) {
synchronized (this.taskStatusMap) {
String existStatusStr = this.taskStatusMap.get(taskId, () -> currentStatusStr);
int compare = compareStatusStr(currentStatusStr, existStatusStr);
if (compare < 0) {
log.debug("Ignore this change, task: {}({})", taskId, currentStatusStr);
return;
}
this.taskStatusMap.put(taskId, currentStatusStr);
}
log.debug("推送任务变更, 任务: {}({}), hook: {}", taskId, currentStatusStr, notifyHook);
ResponseEntity<String> responseEntity = postJson(notifyHook, paramsStr);
if (!responseEntity.getStatusCode().is2xxSuccessful()) {
log.warn("Notify task change fail, task: {}({}), hook: {}, code: {}, msg: {}", taskId, currentStatusStr, notifyHook, responseEntity.getStatusCodeValue(), responseEntity.getBody());
}
}
private ResponseEntity<String> postJson(String notifyHook, String paramsJson) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> httpEntity = new HttpEntity<>(paramsJson, headers);
return new RestTemplate().postForEntity(notifyHook, httpEntity, String.class);
}
private int compareStatusStr(String statusStr1, String statusStr2) {
if (CharSequenceUtil.equals(statusStr1, statusStr2)) {
return 0;
}
float o1 = convertOrder(statusStr1);
float o2 = convertOrder(statusStr2);
return CompareUtil.compare(o1, o2);
}
private float convertOrder(String statusStr) {<FILL_FUNCTION_BODY>}
}
|
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, progress.length() - 1)) / 100;
} else {
return status.getOrder();
}
| 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, String targetMessageId, String targetMessageHash, int index, int messageFlags) {
String instanceId = task.getPropertyGeneric(Constants.TASK_PROPERTY_DISCORD_INSTANCE_ID);
DiscordInstance discordInstance = this.discordLoadBalancer.getDiscordInstance(instanceId);
if (discordInstance == null || !discordInstance.isAlive()) {
return SubmitResultVO.fail(ReturnCode.NOT_FOUND, "账号不可用: " + instanceId);
}
return discordInstance.submitTask(task, () -> discordInstance.upscale(targetMessageId, index, targetMessageHash, messageFlags, task.getPropertyGeneric(Constants.TASK_PROPERTY_NONCE)));
}
@Override
public SubmitResultVO submitVariation(Task task, String targetMessageId, String targetMessageHash, int index, int messageFlags) {
String instanceId = task.getPropertyGeneric(Constants.TASK_PROPERTY_DISCORD_INSTANCE_ID);
DiscordInstance discordInstance = this.discordLoadBalancer.getDiscordInstance(instanceId);
if (discordInstance == null || !discordInstance.isAlive()) {
return SubmitResultVO.fail(ReturnCode.NOT_FOUND, "账号不可用: " + instanceId);
}
return discordInstance.submitTask(task, () -> discordInstance.variation(targetMessageId, index, targetMessageHash, messageFlags, task.getPropertyGeneric(Constants.TASK_PROPERTY_NONCE)));
}
@Override
public SubmitResultVO submitReroll(Task task, String targetMessageId, String targetMessageHash, int messageFlags) {
String instanceId = task.getPropertyGeneric(Constants.TASK_PROPERTY_DISCORD_INSTANCE_ID);
DiscordInstance discordInstance = this.discordLoadBalancer.getDiscordInstance(instanceId);
if (discordInstance == null || !discordInstance.isAlive()) {
return SubmitResultVO.fail(ReturnCode.NOT_FOUND, "账号不可用: " + instanceId);
}
return discordInstance.submitTask(task, () -> discordInstance.reroll(targetMessageId, targetMessageHash, messageFlags, task.getPropertyGeneric(Constants.TASK_PROPERTY_NONCE)));
}
@Override
public SubmitResultVO submitDescribe(Task task, DataUrl dataUrl) {
DiscordInstance discordInstance = this.discordLoadBalancer.chooseInstance();
if (discordInstance == null) {
return SubmitResultVO.fail(ReturnCode.NOT_FOUND, "无可用的账号实例");
}
task.setProperty(Constants.TASK_PROPERTY_DISCORD_INSTANCE_ID, discordInstance.getInstanceId());
return discordInstance.submitTask(task, () -> {
String taskFileName = task.getId() + "." + MimeTypeUtils.guessFileSuffix(dataUrl.getMimeType());
Message<String> uploadResult = discordInstance.upload(taskFileName, dataUrl);
if (uploadResult.getCode() != ReturnCode.SUCCESS) {
return Message.of(uploadResult.getCode(), uploadResult.getDescription());
}
String finalFileName = uploadResult.getResult();
return discordInstance.describe(finalFileName, task.getPropertyGeneric(Constants.TASK_PROPERTY_NONCE));
});
}
@Override
public SubmitResultVO submitBlend(Task task, List<DataUrl> dataUrls, BlendDimensions dimensions) {
DiscordInstance discordInstance = this.discordLoadBalancer.chooseInstance();
if (discordInstance == null) {
return SubmitResultVO.fail(ReturnCode.NOT_FOUND, "无可用的账号实例");
}
task.setProperty(Constants.TASK_PROPERTY_DISCORD_INSTANCE_ID, discordInstance.getInstanceId());
return discordInstance.submitTask(task, () -> {
List<String> finalFileNames = new ArrayList<>();
for (DataUrl dataUrl : dataUrls) {
String taskFileName = task.getId() + "." + MimeTypeUtils.guessFileSuffix(dataUrl.getMimeType());
Message<String> uploadResult = discordInstance.upload(taskFileName, dataUrl);
if (uploadResult.getCode() != ReturnCode.SUCCESS) {
return Message.of(uploadResult.getCode(), uploadResult.getDescription());
}
finalFileNames.add(uploadResult.getResult());
}
return discordInstance.blend(finalFileNames, dimensions, task.getPropertyGeneric(Constants.TASK_PROPERTY_NONCE));
});
}
}
|
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> imageUrls = new ArrayList<>();
for (DataUrl dataUrl : dataUrls) {
String taskFileName = task.getId() + "." + MimeTypeUtils.guessFileSuffix(dataUrl.getMimeType());
Message<String> uploadResult = instance.upload(taskFileName, dataUrl);
if (uploadResult.getCode() != ReturnCode.SUCCESS) {
return Message.of(uploadResult.getCode(), uploadResult.getDescription());
}
String finalFileName = uploadResult.getResult();
Message<String> sendImageResult = instance.sendImageMessage("upload image: " + finalFileName, finalFileName);
if (sendImageResult.getCode() != ReturnCode.SUCCESS) {
return Message.of(sendImageResult.getCode(), sendImageResult.getDescription());
}
imageUrls.add(sendImageResult.getResult());
}
if (!imageUrls.isEmpty()) {
task.setPrompt(String.join(" ", imageUrls) + " " + task.getPrompt());
task.setPromptEn(String.join(" ", imageUrls) + " " + task.getPromptEn());
task.setDescription("/imagine " + task.getPrompt());
this.taskStoreService.save(task);
}
return instance.imagine(task.getPromptEn(), task.getPropertyGeneric(Constants.TASK_PROPERTY_NONCE));
});
| 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.timeout = timeout;
this.redisTemplate = redisTemplate;
}
@Override
public void save(Task task) {
this.redisTemplate.opsForValue().set(getRedisKey(task.getId()), task, this.timeout);
}
@Override
public void delete(String id) {
this.redisTemplate.delete(getRedisKey(id));
}
@Override
public Task get(String id) {
return this.redisTemplate.opsForValue().get(getRedisKey(id));
}
@Override
public List<Task> list() {<FILL_FUNCTION_BODY>}
@Override
public List<Task> list(TaskCondition condition) {
return list().stream().filter(condition).toList();
}
@Override
public Task findOne(TaskCondition condition) {
return list().stream().filter(condition).findFirst().orElse(null);
}
private String getRedisKey(String id) {
return KEY_PREFIX + id;
}
}
|
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.isEmpty()) {
return Collections.emptyList();
}
ValueOperations<String, Task> operations = this.redisTemplate.opsForValue();
return keys.stream().map(operations::get)
.filter(Objects::nonNull)
.toList();
| 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) {
this.appid = translateConfig.getAppid();
this.appSecret = translateConfig.getAppSecret();
if (!CharSequenceUtil.isAllNotBlank(this.appid, this.appSecret)) {
throw new BeanDefinitionValidationException("mj.baidu-translate.appid或mj.baidu-translate.app-secret未配置");
}
}
@Override
public String translateToEnglish(String prompt) {<FILL_FUNCTION_BODY>}
}
|
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, String> body = new LinkedMultiValueMap<>();
body.add("from", "zh");
body.add("to", "en");
body.add("appid", this.appid);
body.add("salt", salt);
body.add("q", prompt);
body.add("sign", sign);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);
try {
ResponseEntity<String> responseEntity = new RestTemplate().exchange(TRANSLATE_API, HttpMethod.POST, requestEntity, String.class);
if (responseEntity.getStatusCode() != HttpStatus.OK || CharSequenceUtil.isBlank(responseEntity.getBody())) {
throw new ValidateException(responseEntity.getStatusCodeValue() + " - " + responseEntity.getBody());
}
JSONObject result = new JSONObject(responseEntity.getBody());
if (result.has("error_code")) {
throw new ValidateException(result.getString("error_code") + " - " + result.getString("error_msg"));
}
List<String> strings = new ArrayList<>();
JSONArray transResult = result.getJSONArray("trans_result");
for (int i = 0; i < transResult.length(); i++) {
strings.add(transResult.getJSONObject(i).getString("dst"));
}
return CharSequenceUtil.join("\n", strings);
} catch (Exception e) {
log.warn("调用百度翻译失败: {}", e.getMessage());
}
return prompt;
| 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.getGptApiKey())) {
throw new BeanDefinitionValidationException("mj.openai.gpt-api-key未配置");
}
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.addInterceptor(new OpenAiResponseInterceptor())
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS);
if (CharSequenceUtil.isNotBlank(properties.getProxy().getHost())) {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(properties.getProxy().getHost(), properties.getProxy().getPort()));
okHttpBuilder.proxy(proxy);
}
OpenAiClient.Builder apiBuilder = OpenAiClient.builder()
.apiKey(Collections.singletonList(this.openaiConfig.getGptApiKey()))
.keyStrategy(new KeyRandomStrategy())
.okHttpClient(okHttpBuilder.build());
if (CharSequenceUtil.isNotBlank(this.openaiConfig.getGptApiUrl())) {
apiBuilder.apiHost(this.openaiConfig.getGptApiUrl());
}
this.openAiClient = apiBuilder.build();
}
@Override
public String translateToEnglish(String prompt) {<FILL_FUNCTION_BODY>}
}
|
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))
.model(this.openaiConfig.getModel())
.temperature(this.openaiConfig.getTemperature())
.maxTokens(this.openaiConfig.getMaxTokens())
.build();
ChatCompletionResponse chatCompletionResponse = this.openAiClient.chatCompletion(chatCompletion);
try {
List<ChatChoice> choices = chatCompletionResponse.getChoices();
if (!choices.isEmpty()) {
return choices.get(0).getMessage().getContent();
}
} catch (Exception e) {
log.warn("调用chat-gpt接口翻译中文失败: {}", e.getMessage());
}
return prompt;
| 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_UNAUTHORIZED);
}
return authorized;
| 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 Map<String, String> paramsMap;
public DiscordInstance createDiscordInstance(DiscordAccount account) {<FILL_FUNCTION_BODY>}
}
|
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_AGENT);
}
var messageListener = new UserMessageListener(this.messageHandlers);
var webSocketStarter = new SpringUserWebSocketStarter(this.discordHelper.getWss(), this.discordHelper.getResumeWss(), account, messageListener);
var discordInstance = new DiscordInstanceImpl(account, webSocketStarter, this.restTemplate, this.taskStoreService, this.notifyService, this.paramsMap);
messageListener.setInstance(discordInstance);
return discordInstance;
| 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.setProperty("https.proxyPort", String.valueOf(proxy.getPort()));
}
List<ProxyProperties.DiscordAccountConfig> configAccounts = this.properties.getAccounts();
if (CharSequenceUtil.isNotBlank(this.properties.getDiscord().getChannelId())) {
configAccounts.add(this.properties.getDiscord());
}
List<DiscordInstance> instances = this.discordLoadBalancer.getAllInstances();
for (ProxyProperties.DiscordAccountConfig configAccount : configAccounts) {
DiscordAccount account = new DiscordAccount();
BeanUtil.copyProperties(configAccount, account);
account.setId(configAccount.getChannelId());
try {
DiscordInstance instance = this.discordAccountHelper.createDiscordInstance(account);
if (!account.isEnable()) {
continue;
}
instance.startWss();
AsyncLockUtils.LockObject lock = AsyncLockUtils.waitForLock("wss:" + account.getChannelId(), Duration.ofSeconds(10));
if (ReturnCode.SUCCESS != lock.getProperty("code", Integer.class, 0)) {
throw new ValidateException(lock.getProperty("description", String.class));
}
instances.add(instance);
} catch (Exception e) {
log.error("Account({}) init fail, disabled: {}", account.getDisplay(), e.getMessage());
account.setEnable(false);
}
}
Set<String> enableInstanceIds = instances.stream().filter(DiscordInstance::isAlive).map(DiscordInstance::getInstanceId).collect(Collectors.toSet());
log.info("当前可用账号数 [{}] - {}", enableInstanceIds.size(), String.join(", ", enableInstanceIds));
| 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 static final String DISCORD_WSS_URL = "wss://gateway.discord.gg";
/**
* DISCORD_UPLOAD_URL.
*/
public static final String DISCORD_UPLOAD_URL = "https://discord-attachments-uploads-prd.storage.googleapis.com";
public String getServer() {
if (CharSequenceUtil.isBlank(this.properties.getNgDiscord().getServer())) {
return DISCORD_SERVER_URL;
}
String serverUrl = this.properties.getNgDiscord().getServer();
if (serverUrl.endsWith("/")) {
serverUrl = serverUrl.substring(0, serverUrl.length() - 1);
}
return serverUrl;
}
public String getCdn() {
if (CharSequenceUtil.isBlank(this.properties.getNgDiscord().getCdn())) {
return DISCORD_CDN_URL;
}
String cdnUrl = this.properties.getNgDiscord().getCdn();
if (cdnUrl.endsWith("/")) {
cdnUrl = cdnUrl.substring(0, cdnUrl.length() - 1);
}
return cdnUrl;
}
public String getWss() {
if (CharSequenceUtil.isBlank(this.properties.getNgDiscord().getWss())) {
return DISCORD_WSS_URL;
}
String wssUrl = this.properties.getNgDiscord().getWss();
if (wssUrl.endsWith("/")) {
wssUrl = wssUrl.substring(0, wssUrl.length() - 1);
}
return wssUrl;
}
public String getResumeWss() {
if (CharSequenceUtil.isBlank(this.properties.getNgDiscord().getResumeWss())) {
return null;
}
String resumeWss = this.properties.getNgDiscord().getResumeWss();
if (resumeWss.endsWith("/")) {
resumeWss = resumeWss.substring(0, resumeWss.length() - 1);
}
return resumeWss;
}
public String getDiscordUploadUrl(String uploadUrl) {
if (CharSequenceUtil.isBlank(this.properties.getNgDiscord().getUploadServer()) || CharSequenceUtil.isBlank(uploadUrl)) {
return uploadUrl;
}
String uploadServer = this.properties.getNgDiscord().getUploadServer();
if (uploadServer.endsWith("/")) {
uploadServer = uploadServer.substring(0, uploadServer.length() - 1);
}
return uploadUrl.replaceFirst(DISCORD_UPLOAD_URL, uploadServer);
}
public String getMessageHash(String imageUrl) {<FILL_FUNCTION_BODY>}
}
|
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.webp".length());
}
int hashStartIndex = imageUrl.lastIndexOf("_");
if (hashStartIndex < 0) {
return null;
}
return CharSequenceUtil.subBefore(imageUrl.substring(hashStartIndex + 1), ".", true);
| 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 getApplicationContext() {<FILL_FUNCTION_BODY>}
}
|
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("提示词-英文")
private String promptEn;
@ApiModelProperty("任务描述")
private String description;
@ApiModelProperty("自定义参数")
private String state;
@ApiModelProperty("提交时间")
private Long submitTime;
@ApiModelProperty("开始执行时间")
private Long startTime;
@ApiModelProperty("结束时间")
private Long finishTime;
@ApiModelProperty("图片url")
private String imageUrl;
@ApiModelProperty("任务进度")
private String progress;
@ApiModelProperty("失败原因")
private String failReason;
public void start() {
this.startTime = System.currentTimeMillis();
this.status = TaskStatus.SUBMITTED;
this.progress = "0%";
}
public void success() {
this.finishTime = System.currentTimeMillis();
this.status = TaskStatus.SUCCESS;
this.progress = "100%";
}
public void fail(String reason) {<FILL_FUNCTION_BODY>}
}
|
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.lang.String) ,public com.github.novicezk.midjourney.domain.DomainObject removeProperty(java.lang.String) ,public com.github.novicezk.midjourney.domain.DomainObject setProperty(java.lang.String, java.lang.Object) ,public void sleep() throws java.lang.InterruptedException<variables>protected java.lang.String id,private final transient java.lang.Object lock,protected Map<java.lang.String,java.lang.Object> properties
|
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 String progressMessageId;
private String nonce;
@Override
public boolean test(Task task) {<FILL_FUNCTION_BODY>}
}
|
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.isEmpty() && !this.actionSet.contains(task.getAction())) {
return false;
}
if (CharSequenceUtil.isNotBlank(this.prompt) && !this.prompt.equals(task.getPrompt())) {
return false;
}
if (CharSequenceUtil.isNotBlank(this.promptEn) && !this.promptEn.equals(task.getPromptEn())) {
return false;
}
if (CharSequenceUtil.isNotBlank(this.description) && !CharSequenceUtil.contains(task.getDescription(), this.description)) {
return false;
}
if (CharSequenceUtil.isNotBlank(this.finalPromptEn) && !this.finalPromptEn.equals(task.getProperty(Constants.TASK_PROPERTY_FINAL_PROMPT))) {
return false;
}
if (CharSequenceUtil.isNotBlank(this.messageId) && !this.messageId.equals(task.getProperty(Constants.TASK_PROPERTY_MESSAGE_ID))) {
return false;
}
if (CharSequenceUtil.isNotBlank(this.messageHash) && !this.messageHash.equals(task.getProperty(Constants.TASK_PROPERTY_MESSAGE_HASH))) {
return false;
}
if (CharSequenceUtil.isNotBlank(this.progressMessageId) && !this.progressMessageId.equals(task.getProperty(Constants.TASK_PROPERTY_PROGRESS_MESSAGE_ID))) {
return false;
}
if (CharSequenceUtil.isNotBlank(this.nonce) && !this.nonce.equals(task.getProperty(Constants.TASK_PROPERTY_NONCE))) {
return false;
}
return true;
| 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 task : tasks) {
if (Set.of(TaskStatus.FAILURE, TaskStatus.SUCCESS).contains(task.getStatus())) {
log.warn("[{}] - task status is failure/success but is in the queue, end it. id: {}", instance.account().getDisplay(), task.getId());
} else {
log.debug("[{}] - task timeout, id: {}", instance.account().getDisplay(), task.getId());
task.fail("任务超时");
}
instance.exitTask(task);
}
});
| 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 TimeoutException {<FILL_FUNCTION_BODY>}
public static class LockObject extends DomainObject {
public LockObject(String id) {
this.id = id;
}
}
}
|
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 (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
try {
future.get(duration.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
// do nothing
} catch (TimeoutException e) {
future.cancel(true);
throw new TimeoutException("Wait Timeout");
} finally {
LOCK_MAP.remove(lockObject.getId());
}
return lockObject;
| 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.UTF_8);
} else {
var resource = BannedPromptUtils.class.getResource("/banned-words.txt");
lines = FileUtil.readLines(resource, StandardCharsets.UTF_8);
}
BANNED_WORDS = lines.stream().filter(CharSequenceUtil::isNotBlank).toList();
}
public static void checkBanned(String promptEn) throws BannedPromptException {<FILL_FUNCTION_BODY>}
}
|
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(promptEn.substring(index, index + word.length()));
}
}
| 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, String regex) {
if (CharSequenceUtil.isBlank(content)) {
return null;
}
Matcher matcher = Pattern.compile(regex).matcher(content);
if (!matcher.find()) {
return null;
}
ContentParseData parseData = new ContentParseData();
parseData.setPrompt(matcher.group(1));
parseData.setStatus(matcher.group(2));
return parseData;
}
public static List<DataUrl> convertBase64Array(List<String> base64Array) throws MalformedURLException {
if (base64Array == null || base64Array.isEmpty()) {
return Collections.emptyList();
}
IDataUrlSerializer serializer = new DataUrlSerializer();
List<DataUrl> dataUrlList = new ArrayList<>();
for (String base64 : base64Array) {
DataUrl dataUrl = serializer.unserialize(base64);
dataUrlList.add(dataUrl);
}
return dataUrlList;
}
public static TaskChangeParams convertChangeParams(String content) {<FILL_FUNCTION_BODY>}
}
|
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.UPSCALE);
} else if (action.charAt(0) == 'v') {
changeParams.setAction(TaskAction.VARIATION);
} else if (action.equals("r")) {
changeParams.setAction(TaskAction.REROLL);
return changeParams;
} else {
return null;
}
try {
int index = Integer.parseInt(action.substring(1, 2));
if (index < 1 || index > 4) {
return null;
}
changeParams.setIndex(index);
} catch (Exception e) {
return null;
}
return changeParams;
| 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)) {
continue;
}
var arr = line.split(":");
MIME_TYPE_MAP.put(arr[0], CharSequenceUtil.split(arr[1], ' '));
}
}
public static String guessFileSuffix(String mimeType) {<FILL_FUNCTION_BODY>}
}
|
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 (suffixList == null || suffixList.isEmpty()) {
return null;
}
return suffixList.iterator().next();
| 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 final boolean randomSequence;
private long count = 0L;
private final long timeOffset;
private final ThreadLocalRandom tlr = ThreadLocalRandom.current();
public static final SnowFlake INSTANCE = new SnowFlake();
private SnowFlake() {
this(false, 10, null, 5L, 5L, 12L);
}
private SnowFlake(boolean randomSequence, long timeOffset, Date epochDate, long workerIdBits, long datacenterIdBits, long sequenceBits) {
if (null != epochDate) {
this.twepoch = epochDate.getTime();
} else {
// 2012/12/12 23:59:59 GMT
this.twepoch = 1355327999000L;
}
long maxWorkerId = ~(-1L << workerIdBits);
long maxDatacenterId = ~(-1L << datacenterIdBits);
this.sequenceMask = ~(-1L << sequenceBits);
this.workerIdShift = sequenceBits;
this.datacenterIdShift = sequenceBits + workerIdBits;
this.timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
this.randomSequence = randomSequence;
this.timeOffset = timeOffset;
try {
this.datacenterId = getDatacenterId(maxDatacenterId);
this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
} catch (Exception e) {
log.warn("datacenterId or workerId generate error: {}, set default value", e.getMessage());
this.datacenterId = 4;
this.workerId = 1;
}
}
public synchronized String nextId() {<FILL_FUNCTION_BODY>}
private static long getDatacenterId(long maxDatacenterId) {
long id = 0L;
try {
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
if (network == null) {
id = 1L;
} else {
byte[] mac = network.getHardwareAddress();
if (null != mac) {
id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
id = id % (maxDatacenterId + 1);
}
}
} catch (Exception e) {
throw new SnowFlakeException(e);
}
return id;
}
private static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
StringBuilder macIpPid = new StringBuilder();
macIpPid.append(datacenterId);
try {
String name = ManagementFactory.getRuntimeMXBean().getName();
if (name != null && !name.isEmpty()) {
macIpPid.append(name.split("@")[0]);
}
String hostIp = InetAddress.getLocalHost().getHostAddress();
String ipStr = hostIp.replace("\\.", "");
macIpPid.append(ipStr);
} catch (Exception e) {
throw new SnowFlakeException(e);
}
return (macIpPid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
}
private long tillNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
}
|
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);
} catch (InterruptedException e) {
throw new SnowFlakeException(e);
}
currentTimestamp = timeGen();
if (currentTimestamp < this.lastTimestamp) {
throw new SnowFlakeException("Clock moved backwards, refusing to generate id for [" + offset + "ms]");
}
}
if (this.lastTimestamp == currentTimestamp) {
long tempSequence = this.sequence + 1;
if (this.randomSequence) {
this.sequence = tempSequence & this.sequenceMask;
this.count = (this.count + 1) & this.sequenceMask;
if (this.count == 0) {
currentTimestamp = this.tillNextMillis(this.lastTimestamp);
}
} else {
this.sequence = tempSequence & this.sequenceMask;
if (this.sequence == 0) {
currentTimestamp = this.tillNextMillis(lastTimestamp);
}
}
} else {
this.sequence = this.randomSequence ? this.tlr.nextLong(this.sequenceMask + 1) : 0L;
this.count = 0L;
}
this.lastTimestamp = currentTimestamp;
long id = ((currentTimestamp - this.twepoch) << this.timestampLeftShift) |
(this.datacenterId << this.datacenterIdShift) |
(this.workerId << this.workerIdShift) |
this.sequence;
return String.valueOf(id);
| 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任务开始时,设置prompt
Task task = instance.getRunningTaskByNonce(getMessageNonce(message));
if (task != null) {
task.setPromptEn(parseData.getPrompt());
task.setPrompt(parseData.getPrompt());
}
}
if (hasImage(message)) {
TaskCondition condition = new TaskCondition()
.setActionSet(Set.of(TaskAction.BLEND))
.setFinalPromptEn(parseData.getPrompt());
findAndFinishImageTask(instance, condition, parseData.getPrompt(), message);
}
| 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 discordHelper,protected com.github.novicezk.midjourney.loadbalancer.DiscordLoadBalancer discordLoadBalancer
|
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 progressMessageId) {
DataArray embeds = message.getArray("embeds");
if (CharSequenceUtil.isBlank(progressMessageId) || embeds.isEmpty()) {
return;
}
TaskCondition condition = new TaskCondition().setActionSet(Set.of(TaskAction.DESCRIBE)).setProgressMessageId(progressMessageId);
Task task = instance.findRunningTask(condition).findFirst().orElse(null);
if (task == null) {
return;
}
message.put(Constants.MJ_MESSAGE_HANDLED, true);
String description = embeds.getObject(0).getString("description");
task.setPrompt(description);
task.setPromptEn(description);
task.setProperty(Constants.TASK_PROPERTY_FINAL_PROMPT, description);
Optional<DataObject> imageOptional = embeds.getObject(0).optObject("image");
if (imageOptional.isPresent()) {
String imageUrl = imageOptional.get().getString("url");
task.setImageUrl(replaceCdnUrl(imageUrl));
}
finishTask(task, message);
task.awake();
}
}
|
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);
Task task = instance.getRunningTaskByNonce(nonce);
if (task == null) {
return;
}
task.setProperty(Constants.TASK_PROPERTY_PROGRESS_MESSAGE_ID, messageId);
} else if (MessageType.UPDATE.equals(messageType)) {
finishDescribeTask(instance, message, messageId);
}
| 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 discordHelper,protected com.github.novicezk.midjourney.loadbalancer.DiscordLoadBalancer discordLoadBalancer
|
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 message) {
String progressMessageId = null;
if (MessageType.CREATE.equals(messageType)) {
progressMessageId = getReferenceMessageId(message);
} else if (MessageType.UPDATE.equals(messageType)) {
progressMessageId = message.getString("id");
}
if (CharSequenceUtil.isBlank(progressMessageId)) {
return null;
}
TaskCondition condition = new TaskCondition().setStatusSet(Set.of(TaskStatus.IN_PROGRESS, TaskStatus.SUBMITTED))
.setProgressMessageId(progressMessageId);
return instance.findRunningTask(condition).findFirst().orElse(null);
}
}
|
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);
task.awake();
}
return;
}
Optional<DataArray> embedsOptional = message.optArray("embeds");
if (embedsOptional.isEmpty() || embedsOptional.get().isEmpty()) {
return;
}
DataObject embed = embedsOptional.get().getObject(0);
String title = embed.getString("title", null);
if (CharSequenceUtil.isBlank(title)) {
return;
}
String description = embed.getString("description", null);
String footerText = "";
Optional<DataObject> footer = embed.optObject("footer");
if (footer.isPresent()) {
footerText = footer.get().getString("text", "");
}
int color = embed.getInt("color", 0);
if (color == 16239475) {
log.warn("{} - MJ警告信息: {}\n{}\nfooter: {}", instance.getInstanceId(), title, description, footerText);
} else if (color == 16711680) {
message.put(Constants.MJ_MESSAGE_HANDLED, true);
log.error("{} - MJ异常信息: {}\n{}\nfooter: {}", instance.getInstanceId(), title, description, footerText);
String nonce = getMessageNonce(message);
Task task;
if (CharSequenceUtil.isNotBlank(nonce)) {
task = instance.getRunningTaskByNonce(nonce);
} else {
task = findTaskWhenError(instance, messageType, message);
}
if (task != null) {
task.fail("[" + title + "] " + description);
task.awake();
}
} else {
if ("link".equals(embed.getString("type", "")) || CharSequenceUtil.isBlank(description)) {
return;
}
// 兼容 Invalid link! \ Could not complete 等错误
Task task = findTaskWhenError(instance, messageType, message);
if (task != null) {
message.put(Constants.MJ_MESSAGE_HANDLED, true);
log.warn("{} - MJ可能的异常信息: {}\n{}\nfooter: {}", instance.getInstanceId(), title, description, footerText);
task.fail("[" + title + "] " + description);
task.awake();
}
}
| 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 discordHelper,protected com.github.novicezk.midjourney.loadbalancer.DiscordLoadBalancer discordLoadBalancer
|
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))
.setFinalPromptEn(parseData.getPrompt());
findAndFinishImageTask(instance, condition, parseData.getPrompt(), message);
}
| 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 discordHelper,protected com.github.novicezk.midjourney.loadbalancer.DiscordLoadBalancer discordLoadBalancer
|
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(DataObject message) {
return message.hasKey("content") ? message.getString("content") : "";
}
protected String getMessageNonce(DataObject message) {
return message.hasKey("nonce") ? message.getString("nonce") : "";
}
protected String getInteractionName(DataObject message) {
Optional<DataObject> interaction = message.optObject("interaction");
return interaction.map(dataObject -> dataObject.getString("name", "")).orElse("");
}
protected String getReferenceMessageId(DataObject message) {
Optional<DataObject> reference = message.optObject("message_reference");
return reference.map(dataObject -> dataObject.getString("message_id", "")).orElse("");
}
protected void findAndFinishImageTask(DiscordInstance instance, TaskCondition condition, String finalPrompt, DataObject message) {
String imageUrl = getImageUrl(message);
String messageHash = this.discordHelper.getMessageHash(imageUrl);
condition.setMessageHash(messageHash);
Task task = instance.findRunningTask(condition)
.findFirst().orElseGet(() -> {
condition.setMessageHash(null);
return instance.findRunningTask(condition)
.filter(t -> t.getStartTime() != null)
.min(Comparator.comparing(Task::getStartTime))
.orElse(null);
});
if (task == null) {
return;
}
task.setProperty(Constants.TASK_PROPERTY_FINAL_PROMPT, finalPrompt);
task.setProperty(Constants.TASK_PROPERTY_MESSAGE_HASH, messageHash);
task.setImageUrl(imageUrl);
finishTask(task, message);
task.awake();
}
protected void finishTask(Task task, DataObject message) {
task.setProperty(Constants.TASK_PROPERTY_MESSAGE_ID, message.getString("id"));
task.setProperty(Constants.TASK_PROPERTY_FLAGS, message.getInt("flags", 0));
task.setProperty(Constants.TASK_PROPERTY_MESSAGE_HASH, this.discordHelper.getMessageHash(task.getImageUrl()));
task.success();
}
protected boolean hasImage(DataObject message) {
DataArray attachments = message.optArray("attachments").orElse(DataArray.empty());
return !attachments.isEmpty();
}
protected String getImageUrl(DataObject message) {<FILL_FUNCTION_BODY>}
protected String replaceCdnUrl(String imageUrl) {
if (CharSequenceUtil.isBlank(imageUrl)) {
return imageUrl;
}
String cdn = this.discordHelper.getCdn();
if (CharSequenceUtil.startWith(imageUrl, cdn)) {
return imageUrl;
}
return CharSequenceUtil.replaceFirst(imageUrl, DiscordHelper.DISCORD_CDN_URL, cdn);
}
}
|
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 = "\\*\\*(.*?)\\*\\* - Variations \\(.*?\\) by <@\\d+> \\((.*?)\\)";
@Override
public void handle(DiscordInstance instance, MessageType messageType, DataObject message) {<FILL_FUNCTION_BODY>}
private ContentParseData getParseData(String content) {
ContentParseData parseData = ConvertUtils.parseContent(content, CONTENT_REGEX_1);
if (parseData == null) {
parseData = ConvertUtils.parseContent(content, CONTENT_REGEX_2);
}
if (parseData == null) {
parseData = ConvertUtils.parseContent(content, CONTENT_REGEX_3);
}
return parseData;
}
}
|
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.getPrompt());
findAndFinishImageTask(instance, condition, parseData.getPrompt(), message);
}
| 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 discordHelper,protected com.github.novicezk.midjourney.loadbalancer.DiscordLoadBalancer discordLoadBalancer
|
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 == null) {
return;
}
message.put(Constants.MJ_MESSAGE_HANDLED, true);
task.setProperty(Constants.TASK_PROPERTY_PROGRESS_MESSAGE_ID, message.getString("id"));
// 兼容少数content为空的场景
if (parseData != null) {
task.setProperty(Constants.TASK_PROPERTY_FINAL_PROMPT, parseData.getPrompt());
}
task.setStatus(TaskStatus.IN_PROGRESS);
task.awake();
} else if (MessageType.UPDATE.equals(messageType) && parseData != null) {
// 任务进度
if ("Stopped".equals(parseData.getStatus())) {
return;
}
TaskCondition condition = new TaskCondition().setStatusSet(Set.of(TaskStatus.IN_PROGRESS))
.setProgressMessageId(message.getString("id"));
Task task = instance.findRunningTask(condition).findFirst().orElse(null);
if (task == null) {
return;
}
message.put(Constants.MJ_MESSAGE_HANDLED, true);
task.setProperty(Constants.TASK_PROPERTY_FINAL_PROMPT, parseData.getPrompt());
task.setStatus(TaskStatus.IN_PROGRESS);
task.setProgress(parseData.getStatus());
String imageUrl = getImageUrl(message);
task.setImageUrl(imageUrl);
task.setProperty(Constants.TASK_PROPERTY_MESSAGE_HASH, this.discordHelper.getMessageHash(imageUrl));
task.awake();
}
| 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 discordHelper,protected com.github.novicezk.midjourney.loadbalancer.DiscordLoadBalancer discordLoadBalancer
|
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 = "\\*\\*(.*?)\\*\\* - Image #\\d <@\\d+>";
@Override
public void handle(DiscordInstance instance, MessageType messageType, DataObject message) {<FILL_FUNCTION_BODY>}
private ContentParseData getParseData(String content) {
ContentParseData parseData = ConvertUtils.parseContent(content, CONTENT_REGEX_1);
if (parseData == null) {
parseData = ConvertUtils.parseContent(content, CONTENT_REGEX_2);
}
if (parseData != null) {
return parseData;
}
Matcher matcher = Pattern.compile(CONTENT_REGEX_3).matcher(content);
if (!matcher.find()) {
return null;
}
parseData = new ContentParseData();
parseData.setPrompt(matcher.group(1));
parseData.setStatus("done");
return parseData;
}
}
|
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.getPrompt());
findAndFinishImageTask(instance, condition, parseData.getPrompt(), message);
}
| 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 discordHelper,protected com.github.novicezk.midjourney.loadbalancer.DiscordLoadBalancer discordLoadBalancer
|
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 instance, MessageType messageType, DataObject message) {<FILL_FUNCTION_BODY>}
private ContentParseData getParseData(String content) {
ContentParseData parseData = ConvertUtils.parseContent(content, CONTENT_REGEX_1);
if (parseData == null) {
parseData = ConvertUtils.parseContent(content, CONTENT_REGEX_2);
}
return parseData;
}
}
|
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(parseData.getPrompt());
findAndFinishImageTask(instance, condition, parseData.getPrompt(), message);
}
| 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 discordHelper,protected com.github.novicezk.midjourney.loadbalancer.DiscordLoadBalancer discordLoadBalancer
|
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 boolean sessionClosing = false;
private WebSocketSession webSocketSession = null;
private ResumeData resumeData = null;
public SpringUserWebSocketStarter(String wssServer, String resumeWss, DiscordAccount account, UserMessageListener userMessageListener) {
this.wssServer = wssServer;
this.resumeWss = resumeWss;
this.account = account;
this.userMessageListener = userMessageListener;
}
@Override
public void start() throws Exception {
start(false);
}
private void start(boolean reconnect) {
this.sessionClosing = false;
WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
headers.add("Accept-Encoding", "gzip, deflate, br");
headers.add("Accept-Language", "zh-CN,zh;q=0.9");
headers.add("Cache-Control", "no-cache");
headers.add("Pragma", "no-cache");
headers.add("Sec-Websocket-Extensions", "permessage-deflate; client_max_window_bits");
headers.add("User-Agent", this.account.getUserAgent());
var handler = new SpringWebSocketHandler(this.account, this.userMessageListener, this::onSocketSuccess, this::onSocketFailure);
String gatewayUrl;
if (reconnect) {
gatewayUrl = getGatewayServer(this.resumeData.resumeGatewayUrl()) + "/?encoding=json&v=9&compress=zlib-stream";
handler.setSessionId(this.resumeData.sessionId());
handler.setSequence(this.resumeData.sequence());
handler.setResumeGatewayUrl(this.resumeData.resumeGatewayUrl());
} else {
gatewayUrl = getGatewayServer(null) + "/?encoding=json&v=9&compress=zlib-stream";
}
var webSocketClient = new StandardWebSocketClient();
webSocketClient.getUserProperties().put(Constants.IO_TIMEOUT_MS_PROPERTY, "10000");
var socketSessionFuture = webSocketClient.doHandshake(handler, headers, URI.create(gatewayUrl));
socketSessionFuture.addCallback(new ListenableFutureCallback<>() {
@Override
public void onFailure(@NotNull Throwable e) {
onSocketFailure(SpringWebSocketHandler.CLOSE_CODE_EXCEPTION, e.getMessage());
}
@Override
public void onSuccess(WebSocketSession session) {
SpringUserWebSocketStarter.this.webSocketSession = session;
}
});
}
private void onSocketSuccess(String sessionId, Object sequence, String resumeGatewayUrl) {
this.resumeData = new ResumeData(sessionId, sequence, resumeGatewayUrl);
this.running = true;
notifyWssLock(ReturnCode.SUCCESS, "");
}
private void onSocketFailure(int code, String reason) {
if (this.sessionClosing) {
this.sessionClosing = false;
return;
}
closeSocketSessionWhenIsOpen();
if (!this.running) {
notifyWssLock(code, reason);
return;
}
this.running = false;
if (code >= 4000) {
log.warn("[wss-{}] Can't reconnect! Account disabled. Closed by {}({}).", this.account.getDisplay(), code, reason);
disableAccount();
} else if (code == 2001) {
log.warn("[wss-{}] Closed by {}({}). Try reconnect...", this.account.getDisplay(), code, reason);
tryReconnect();
} else {
log.warn("[wss-{}] Closed by {}({}). Try new connection...", this.account.getDisplay(), code, reason);
tryNewConnect();
}
}
private void tryReconnect() {
try {
tryStart(true);
} catch (Exception e) {
if (e instanceof TimeoutException) {
closeSocketSessionWhenIsOpen();
}
log.warn("[wss-{}] Reconnect fail: {}, Try new connection...", this.account.getDisplay(), e.getMessage());
ThreadUtil.sleep(1000);
tryNewConnect();
}
}
private void tryNewConnect() {
for (int i = 1; i <= CONNECT_RETRY_LIMIT; i++) {
try {
tryStart(false);
return;
} catch (Exception e) {
if (e instanceof TimeoutException) {
closeSocketSessionWhenIsOpen();
}
log.warn("[wss-{}] New connect fail ({}): {}", this.account.getDisplay(), i, e.getMessage());
ThreadUtil.sleep(5000);
}
}
log.error("[wss-{}] Account disabled", this.account.getDisplay());
disableAccount();
}
public void tryStart(boolean reconnect) throws Exception {
start(reconnect);
AsyncLockUtils.LockObject lock = AsyncLockUtils.waitForLock("wss:" + this.account.getId(), Duration.ofSeconds(20));
int code = lock.getProperty("code", Integer.class, 0);
if (code == ReturnCode.SUCCESS) {
log.debug("[wss-{}] {} success.", this.account.getDisplay(), reconnect ? "Reconnect" : "New connect");
return;
}
throw new ValidateException(lock.getProperty("description", String.class));
}
private void notifyWssLock(int code, String reason) {<FILL_FUNCTION_BODY>}
private void disableAccount() {
if (Boolean.FALSE.equals(this.account.isEnable())) {
return;
}
this.account.setEnable(false);
}
private void closeSocketSessionWhenIsOpen() {
try {
if (this.webSocketSession != null && this.webSocketSession.isOpen()) {
this.sessionClosing = true;
this.webSocketSession.close();
}
} catch (IOException e) {
// do nothing
}
}
private String getGatewayServer(String resumeGatewayUrl) {
if (CharSequenceUtil.isNotBlank(resumeGatewayUrl)) {
return CharSequenceUtil.isBlank(this.resumeWss) ? resumeGatewayUrl : this.resumeWss;
}
return this.wssServer;
}
public record ResumeData(String sessionId, Object sequence, String resumeGatewayUrl) {
}
}
|
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;
}
public void onMessage(DataObject raw) {<FILL_FUNCTION_BODY>}
private boolean ignoreAndLogMessage(DataObject data, MessageType messageType) {
String channelId = data.getString("channel_id");
if (!CharSequenceUtil.equals(channelId, this.instance.account().getChannelId())) {
return true;
}
String authorName = data.optObject("author").map(a -> a.getString("username")).orElse("System");
log.debug("{} - {} - {}: {}", this.instance.account().getDisplay(), messageType.name(), authorName, data.opt("content").orElse(""));
return false;
}
}
|
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.messageHandlers) {
if (data.getBoolean(Constants.MJ_MESSAGE_HANDLED, false)) {
return;
}
messageHandler.handle(this.instance, messageType, data);
}
| 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());
case GPT -> new GPTTranslateServiceImpl(this.properties);
default -> new NoTranslateServiceImpl();
};
}
@Bean
TaskStoreService taskStoreService(RedisConnectionFactory redisConnectionFactory) {
ProxyProperties.TaskStore.Type type = this.properties.getTaskStore().getType();
Duration timeout = this.properties.getTaskStore().getTimeout();
return switch (type) {
case IN_MEMORY -> new InMemoryTaskStoreServiceImpl(timeout);
case REDIS -> new RedisTaskStoreServiceImpl(timeout, taskRedisTemplate(redisConnectionFactory));
};
}
@Bean
RedisTemplate<String, Task> taskRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Task> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Task.class));
return redisTemplate;
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public IRule loadBalancerRule() {
String ruleClassName = IRule.class.getPackageName() + "." + this.properties.getAccountChooseRule();
return ReflectUtil.newInstance(ruleClassName);
}
@Bean
List<MessageHandler> messageHandlers() {
return this.applicationContext.getBeansOfType(MessageHandler.class).values().stream().toList();
}
@Bean
DiscordAccountHelper discordAccountHelper(DiscordHelper discordHelper, TaskStoreService taskStoreService, NotifyService notifyService) throws IOException {<FILL_FUNCTION_BODY>}
}
|
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, filename.length() - 5), params);
}
return new DiscordAccountHelper(discordHelper, this.properties, restTemplate(), taskStoreService, notifyService, messageHandlers(), paramsMap);
| 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 measure() {
new ModelMapper().createTypeMap(GiantEntity.class, GiantDto.class);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
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;
}
public boolean applies(MappingContext<S, D> context) {
return a.applies(context) || b.applies(context);
}
@Override
public boolean equals(Object other) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return 37 * (a.hashCode() ^ b.hashCode());
}
@Override
public String toString() {
return String.format("or(%s, %s)", a, 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();
* </pre>
*
* @param elementConverter the converter to map the source element to destination element
* @param <S> the source element type
* @param <D> the destination element type
* @return a Converter
*/
public static <S, D> org.modelmapper.Converter<java.util.Collection<S>, java.util.Collection<D>> map(final Converter<S, D> elementConverter) {
return new org.modelmapper.Converter<java.util.Collection<S>, java.util.Collection<D>>() {
@Override
public java.util.Collection<D> convert(
MappingContext<java.util.Collection<S>, java.util.Collection<D>> context) {
if (context.getSource() == null)
return null;
java.util.Collection<D> destination = MappingContextHelper.createCollection(context);
for (S element : context.getSource()) {
destination.add(elementConverter.convert(element));
}
return destination;
}
};
}
/**
* Provides a helper method to create a collection converter that will get the first element of source collect and convert it.
*
* <pre>
* using(Collection.first().to(Destination.class).map();
* </pre>
*
* @param <S> the source type
* @return a {@code ChainableConverter}
*/
public static <S> ChainableConverter<java.util.Collection<S>, S> first() {<FILL_FUNCTION_BODY>}
private Collection() {
}
}
|
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 convert(MappingContext<java.util.Collection<S>, D> context) {
if (context.getSource() == null || context.getSource().isEmpty())
return null;
MappingContext<S, D> elementContext = context.create(context.getSource().iterator().next(),
context.getDestinationType());
return context.getMappingEngine().map(elementContext);
}
};
}
@Override
public <D> org.modelmapper.Converter<java.util.Collection<S>, D> map(
final org.modelmapper.Converter<S, D> converter) {
return new org.modelmapper.Converter<java.util.Collection<S>, D>() {
@Override
public D convert(MappingContext<java.util.Collection<S>, D> context) {
if (context.getSource() == null || context.getSource().isEmpty())
return null;
MappingContext<S, D> elementContext = context.create(context.getSource().iterator().next(),
context.getDestinationType());
return converter.convert(elementContext);
}
};
}
};
| 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.getSourcePropertyTokens();
destTokens = propertyNameInfo.getDestinationPropertyTokens();
}
/**
* Returns the number of {@code dst} elements that were matched to a source starting at
* {@code dstStartIndex}. {@code src} and {@code dst} elements can be matched in combination.
*/
static int matchTokens(Tokens src, Tokens dst, int dstStartIndex) {
for (int srcStartIndex = 0; srcStartIndex < src.size(); srcStartIndex++) {
TokensIterator srcTokensIterator = TokensIterator.of(src, srcStartIndex);
TokensIterator dstTokensIterator = TokensIterator.of(dst, dstStartIndex);
StringIterator srcStrIterator = StringIterator.of(srcTokensIterator.next());
StringIterator dstStrIterator = StringIterator.of(dstTokensIterator.next());
while (srcStrIterator.hasNext() || srcStrIterator.hasNext()) {
if (!matchToken(srcStrIterator, dstStrIterator))
break;
if (!srcStrIterator.hasNext() && !dstStrIterator.hasNext())
return dstTokensIterator.pos() - dstStartIndex + 1;
if (!srcStrIterator.hasNext() && !srcTokensIterator.hasNext())
break;
if (!dstStrIterator.hasNext() && !dstTokensIterator.hasNext())
break;
if (!srcStrIterator.hasNext() && srcTokensIterator.hasNext())
srcStrIterator = StringIterator.of(srcTokensIterator.next());
if (!dstStrIterator.hasNext() && dstTokensIterator.hasNext())
dstStrIterator = StringIterator.of(dstTokensIterator.next());
}
}
return 0;
}
static boolean matchToken(StringIterator srcStrIterator, StringIterator destStrIterator) {<FILL_FUNCTION_BODY>}
/**
* Returns whether the source class token is an inexact to the {@code destination}.
*/
boolean matchSourceClass(String destination) {
for (String token: propertyNameInfo.getSourceClassTokens())
if (token.equalsIgnoreCase(destination))
return true;
return false;
}
/**
* Returns whether any source property type token is an inexact to the {@code destination}.
*/
boolean matchSourcePropertyType(String destination) {
for (Tokens tokens: propertyNameInfo.getSourcePropertyTypeTokens())
for (String token: tokens)
if (token.equalsIgnoreCase(destination))
return true;
return false;
}
/**
* Returns the numbers of match counts for each {@code sourceTokens} that were matched to{@code destTokens} starting at
* {@code destStartIndex}.
*/
DestTokensMatcher matchSourcePropertyName(Tokens destTokens, int destStartIndex) {
int[] matchedTokens = new int[sourceTokens.size()];
for (int sourceIndex = 0; sourceIndex < sourceTokens.size(); sourceIndex++) {
Tokens srcTokens = sourceTokens.get(sourceIndex);
matchedTokens[sourceIndex] = matchTokens(srcTokens, destTokens, destStartIndex);
}
return new DestTokensMatcher(matchedTokens);
}
static class TokensIterator {
private Tokens tokens;
private int pos;
static TokensIterator of(Tokens tokens, int pos) {
return new TokensIterator(tokens, pos - 1);
}
TokensIterator(Tokens tokens, int pos) {
this.tokens = tokens;
this.pos = pos;
}
public boolean hasNext() {
return pos < tokens.size() - 1;
}
public String next() {
return tokens.token(++pos);
}
public int pos() {
return pos;
}
}
static class StringIterator {
private String text;
private int pos = -1;
static StringIterator of(String text) {
return new StringIterator(text);
}
StringIterator(String text) {
this.text = text;
}
public boolean hasNext() {
return pos < text.length() - 1;
}
public Character next() {
return text.charAt(++pos);
}
}
static class DestTokensMatcher {
int[] counts;
DestTokensMatcher(int[] counts) {
this.counts = counts;
}
boolean match() {
for (int count : counts)
if (count > 0)
return true;
return false;
}
boolean match(int index) {
return counts[index] > 0;
}
int maxMatchTokens() {
int maxIndex = 0;
for (int i = 1; i < counts.length; i++)
if (counts[i] > counts[maxIndex])
maxIndex = i;
return counts[maxIndex];
}
Collection<Integer> matchSources() {
List<Integer> indexes = new ArrayList<Integer>();
for (int i = 0; i < counts.length; i++)
if (counts[i] > 0)
indexes.add(i);
return indexes;
}
}
}
|
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))
return false;
}
return true;
| 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; destTokenIndex < tokens.size(); destTokenIndex++) {
DestTokensMatcher matchedTokens = matchSourcePropertyName(tokens, destTokenIndex);
if (matchedTokens.match())
return true;
if (matchSourcePropertyType(tokens.token(destTokenIndex)) || matchSourceClass(tokens.token(destTokenIndex)))
return true;
}
return false;
}
}
|
if (!matchLastDestTokens())
return false;
for (Tokens destTokens : propertyNameInfo.getDestinationPropertyTokens()) {
for (int destTokenIndex = 0; destTokenIndex < destTokens.size(); destTokenIndex++) {
DestTokensMatcher matchedTokens = matchSourcePropertyName(destTokens, destTokenIndex);
if (matchedTokens.match(sourceTokens.size() - 1))
return true;
}
}
return false;
| 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, NameableType nameableType) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "Javabeans Accessor";
}
};
/**
* Transforms mutator names to their simple property name according to the JavaBeans convention.
* Class and field names are unchanged.
*/
public static final NameTransformer JAVABEANS_MUTATOR = new NameTransformer() {
public String transform(String name, NameableType nameableType) {
if (NameableType.METHOD.equals(nameableType) && name.startsWith("set") && name.length() > 3)
return Strings.decapitalize(name.substring(3));
return name;
}
@Override
public String toString() {
return "Javabeans Mutator";
}
};
/**
* Creates NameTransformer for builder.
* @return a NameTransformer
*/
public static NameTransformer builder() {
return builder("");
}
/**
* Creates NameTransformer for builder.
*
* @param prefix the prefix for the setter of the builder
* @return a NameTransformer
*/
public static NameTransformer builder(String prefix) {
return new BuilderNameTransformer(prefix);
}
/**
* Transforms the names to their simple property name according to the builder convention.
* Class and field names are unchanged.
*/
private static class BuilderNameTransformer implements NameTransformer {
private String prefix;
private BuilderNameTransformer(String prefix) {
this.prefix = prefix;
}
public String transform(String name, NameableType nameableType) {
if (prefix.isEmpty())
return name;
if (name.startsWith(prefix))
return Strings.decapitalize(name.substring(prefix.length()));
return name;
}
@Override
public String toString() {
return "Builder(prefix=" + prefix + ")";
}
}
}
|
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 name;
| 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 "Javabeans Accessor";
}
};
/**
* JavaBeans naming convention for mutators.
*/
public static final NamingConvention JAVABEANS_MUTATOR = new NamingConvention() {
public boolean applies(String propertyName, PropertyType propertyType) {
return PropertyType.FIELD.equals(propertyType)
|| (propertyName.startsWith("set") && propertyName.length() > 3);
}
@Override
public String toString() {
return "Javabeans Mutator";
}
};
/**
* Creates NameTransformer for builder.
* @return a NamingConvention
*/
public static NamingConvention builder() {
return builder("");
}
/**
* Creates NamingConvention for builder.
*
* @param prefix the prefix for the setter of the builder
* @return a NamingConvention
*/
public static NamingConvention builder(String prefix) {
return new BuilderNamingConventions(prefix);
}
/**
* Naming convention for builder.
*/
private static class BuilderNamingConventions implements NamingConvention {
private String prefix;
private BuilderNamingConventions(String prefix) {
this.prefix = prefix;
}
public boolean applies(String propertyName, PropertyType propertyType) {
return PropertyType.METHOD.equals(propertyType) && propertyName.startsWith(prefix);
}
@Override
public String toString() {
return "Builder(prefix=" + prefix + ")";
}
}
/**
* Represents no naming convention. This convention
* {@link NamingConvention#applies(String, PropertyType) applies} to all property names, allowing
* all properties to be eligible for matching.
*/
public static final NamingConvention NONE = new NamingConvention() {
public boolean applies(String propertyName, PropertyType propertyType) {
return true;
}
@Override
public String toString() {
return "None";
}
};
}
|
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);
if (matchedTokens.match()) {
destTokenIndex += matchedTokens.maxMatchTokens();
matchSources.addAll(matchedTokens.matchSources());
} else if (matchSourcePropertyType(destTokens.token(destTokenIndex))
|| matchSourceClass(destTokens.token(destTokenIndex)))
destTokenIndex++;
else
return false;
}
}
return matchSources.size() == sourceTokens.size();
| 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 sTokens = sourceTokens.get(propIndex);
Tokens dTokens = destTokens.get(propIndex);
if (sTokens.size() != dTokens.size())
return false;
for (int tokenIndex = 0; tokenIndex < sTokens.size(); tokenIndex++)
if (!sTokens.token(tokenIndex).equalsIgnoreCase(dTokens.token(tokenIndex)))
return false;
}
return true;
| 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 https://stackoverflow.com/questions/47854086/cglib-creating-class-proxy-in-osgi-results-in-noclassdeffounderror
BridgeClassLoader(ClassLoader primary) {
super(primary);
internalClassSpace = ModelMapper.class.getClassLoader(); // ModelMapper's own ClassLoader must know how to load its internals
additionalClassLoaders = Collections.newSetFromMap(new ConcurrentHashMap<ClassLoader, Boolean>());
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
if (name.startsWith("org.modelmapper.internal.cglib"))
return internalClassSpace.loadClass(name);
for (ClassLoader additionalClassLoader : additionalClassLoaders) {
try {
return additionalClassLoader.loadClass(name);
}
catch (ClassNotFoundException e) {
// Don't mind... Attempt next class loader
}
}
throw new ClassNotFoundException(name);
}
private void addAdditionalClassLoaders(Set<ClassLoader> additionalClassLoaders) {
additionalClassLoaders.remove(this.getParent()); // Make sure that the parent ClassLoader is not part of the collection. Otherwise, a recursion might occur in findClass().
this.additionalClassLoaders.addAll(additionalClassLoaders);
}
}
private static final Map<ClassLoader, WeakReference<BridgeClassLoader>> CACHE = new WeakHashMap<ClassLoader, WeakReference<BridgeClassLoader>>();
static ClassLoader getClassLoader(Class<?> appType) {
Set<Class<?>> allExtendedOrImplementedTypesRecursively = getAllExtendedOrImplementedTypesRecursively(appType);
Set<ClassLoader> allClassLoadersInTheTypeHierarchy = getAllClassLoadersInTheTypeHierarchy(allExtendedOrImplementedTypesRecursively);
synchronized (BridgeClassLoaderFactory.class) {
BridgeClassLoader bridgeClassLoader = null;
WeakReference<BridgeClassLoader> bridgeClassLoaderRef = CACHE.get(appType.getClassLoader());
if (bridgeClassLoaderRef != null) {
bridgeClassLoader = bridgeClassLoaderRef.get();
}
if (bridgeClassLoader == null) {
bridgeClassLoader = new BridgeClassLoader(appType.getClassLoader());
CACHE.put(appType.getClassLoader(), new WeakReference<BridgeClassLoader>(bridgeClassLoader));
}
bridgeClassLoader.addAdditionalClassLoaders(allClassLoadersInTheTypeHierarchy);
return bridgeClassLoader;
}
}
private static Set<ClassLoader> getAllClassLoadersInTheTypeHierarchy(Set<Class<?>> allExtendedOrImplementedTypesRecursively) {
Set<ClassLoader> result = new HashSet<ClassLoader>();
for (Class<?> clazz : allExtendedOrImplementedTypesRecursively) {
if (clazz.getClassLoader() != null) {
result.add(clazz.getClassLoader());
}
}
return result;
}
// Extracted from https://stackoverflow.com/questions/22031207/find-all-classes-and-interfaces-a-class-extends-or-implements-recursively
private static Set<Class<?>> getAllExtendedOrImplementedTypesRecursively(Class<?> clazzArg) {<FILL_FUNCTION_BODY>
|
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(interfaces));
for (Class<?> interfaze : interfaces) {
res.addAll(getAllExtendedOrImplementedTypesRecursively(interfaze));
}
}
// Add the super class
Class<?> superClass = clazz.getSuperclass();
// Interfaces does not have java,lang.Object as superclass, they have null, so break the cycle and return
if (superClass == null) {
break;
}
// Now inspect the superclass
clazz = superClass;
} while (!"java.lang.Object".equals(clazz.getCanonicalName()));
return new HashSet<Class<?>>(res);
| 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));
}
abstract String toString(T subject);
}
public Errors() {
}
/** Returns the formatted message for an exception with the specified messages. */
public static String format(String heading, Collection<ErrorMessage> errorMessages) {<FILL_FUNCTION_BODY>
|
@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());
Throwable cause = errorMessage.getCause();
if (displayCauses && cause != null) {
StringWriter writer = new StringWriter();
cause.printStackTrace(new PrintWriter(writer));
fmt.format("Caused by: %s", writer.getBuffer());
}
fmt.format("%n");
}
if (errorMessages.size() == 1)
fmt.format("1 error");
else
fmt.format("%s errors", errorMessages.size());
return fmt.toString();
| 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;
}
}
static <S, D> Collection<MappingImpl> build(Class<S> sourceType, Class<D> destinationType,
InheritingConfiguration configuration, PropertyMap<S, D> propertyMap) {
return new ExplicitMappingBuilder<S, D>(sourceType, destinationType, configuration)
.build(propertyMap);
}
ExplicitMappingBuilder(Class<S> sourceType, Class<D> destinationType,
InheritingConfiguration configuration) {
this.sourceType = sourceType;
this.destinationType = destinationType;
this.configuration = configuration;
}
public D skip() {
map();
options.skipType = 1;
return destination;
}
public void skip(Object destination) {
map(destination);
options.skipType = 2;
}
public void skip(Object source, Object destination) {
map(source, destination);
options.skipType = 3;
}
public D map() {
saveLastMapping();
getNextMapping();
return destination;
}
public D map(Object subject) {
saveLastMapping();
getNextMapping();
recordSourceValue(subject);
return destination;
}
public void map(Object source, Object destination) {
saveLastMapping();
getNextMapping();
recordSourceValue(source);
}
public <T> T source(String sourcePropertyPath) {
if (sourcePropertyPath == null)
errors.errorNullArgument("sourcePropertyPath");
if (sourceAccessors != null)
saveLastMapping();
String[] propertyNames = DOT_PATTERN.split(sourcePropertyPath);
sourceAccessors = new ArrayList<Accessor>(propertyNames.length);
ValueReader<?> valueReader = configuration.valueAccessStore.getFirstSupportedReader(sourceType);
if (valueReader != null)
for (String propertyName : propertyNames)
sourceAccessors.add(ValueReaderPropertyInfo.create(valueReader, propertyName));
else {
Accessor accessor = null;
for (String propertyName : propertyNames) {
Class<?> propertyType = accessor == null ? sourceType : accessor.getType();
accessor = PropertyInfoRegistry.accessorFor(propertyType, propertyName, configuration);
if (accessor == null) {
errors.errorInvalidSourcePath(sourcePropertyPath, propertyType, propertyName);
return null;
}
sourceAccessors.add(accessor);
}
}
return null;
}
public Object destination(String destPropertyPath) {
if (destPropertyPath == null)
errors.errorNullArgument("destPropertyPath");
String[] propertyNames = DOT_PATTERN.split(destPropertyPath);
destinationMutators = new ArrayList<Mutator>(propertyNames.length);
ValueWriter<?> valueWriter = configuration.valueMutateStore.getFirstSupportedWriter(destinationType);
if (valueWriter != null)
for (String propertyName : propertyNames)
destinationMutators.add(ValueWriterPropertyInfo.create(valueWriter, propertyName));
else {
Mutator mutator = null;
for (String propertyName : propertyNames) {
Class<?> propertyType = mutator == null ? destinationType : mutator.getType();
mutator = PropertyInfoRegistry.mutatorFor(propertyType, propertyName, configuration);
if (mutator == null) {
errors.errorInvalidDestinationPath(destPropertyPath, propertyType, propertyName);
return null;
}
destinationMutators.add(mutator);
}
}
return null;
}
public ConditionExpression<S, D> using(Converter<?, ?> converter) {
saveLastMapping();
if (converter == null)
errors.errorNullArgument("converter");
Assert.state(options.converter == null, "using() can only be called once per mapping.");
options.converter = converter;
return this;
}
public ConditionExpression<S, D> when(Condition<?, ?> condition) {
saveLastMapping();
if (condition == null)
errors.errorNullArgument("condition");
Assert.state(options.condition == null, "when() can only be called once per mapping.");
options.condition = condition;
return this;
}
public ConditionExpression<S, D> with(Provider<?> provider) {
saveLastMapping();
if (provider == null)
errors.errorNullArgument("provider");
Assert.state(options.provider == null, "withProvider() can only be called once per mapping.");
options.provider = provider;
return this;
}
/**
* Builds and returns all property mappings defined in the {@code propertyMap}.
*/
Collection<MappingImpl> build(PropertyMap<S, D> propertyMap) {
try {
PROPERTY_MAP_CONFIGURE.invoke(propertyMap, this);
saveLastMapping();
} catch (IllegalAccessException e) {
errors.errorAccessingConfigure(e);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof ConfigurationException)
throw (ConfigurationException) cause;
else
errors.addMessage(cause, "Failed to configure mappings");
} catch (NullPointerException e) {
if (proxyErrors.hasErrors()) {
throw proxyErrors.toException();
}
throw e;
}
errors.throwConfigurationExceptionIfErrorsExist();
return propertyMappings;
}
/**
* Visits the {@code propertyMap} and captures and validates mappings.
*/
public void visitPropertyMap(PropertyMap<S, D> propertyMap) {<FILL_FUNCTION_BODY>
|
String propertyMapClassName = propertyMap.getClass().getName();
try {
ClassReader cr = new ClassReader(propertyMap.getClass().getClassLoader().getResourceAsStream(
propertyMapClassName.replace('.', '/') + ".class"));
ExplicitMappingVisitor visitor = new ExplicitMappingVisitor(errors, configuration,
propertyMapClassName, destinationType.getName(), propertyMap.getClass().getClassLoader());
cr.accept(visitor, ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);
visitedMappings = visitor.mappings;
} catch (IOException e) {
errors.errorReadingClass(e, propertyMapClassName);
}
errors.throwConfigurationExceptionIfErrorsExist();
createProxies();
| 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<?, ?> converter;
/**
* Creates an implicit mapping.
*/
MappingImpl(List<? extends PropertyInfo> destinationMutators) {
this.destinationMutators = new ArrayList<PropertyInfo>(destinationMutators);
path = Strings.join(destinationMutators);
this.explicit = false;
}
/**
* Creates an explicit mapping.
*/
MappingImpl(List<? extends PropertyInfo> destinationMutators, MappingOptions options) {
this.destinationMutators = new ArrayList<PropertyInfo>(destinationMutators);
path = Strings.join(destinationMutators);
this.skipType = options.skipType;
this.condition = options.condition;
this.provider = options.provider;
this.converter = options.converter;
explicit = true;
}
/**
* Creates a merged mapping.
*/
MappingImpl(MappingImpl copy, List<? extends PropertyInfo> mergedMutators) {
destinationMutators = new ArrayList<PropertyInfo>(copy.destinationMutators.size()
+ mergedMutators.size());
destinationMutators.addAll(mergedMutators);
destinationMutators.addAll(copy.destinationMutators);
path = Strings.join(destinationMutators);
skipType = copy.skipType;
condition = copy.condition;
provider = copy.provider;
converter = copy.converter;
explicit = copy.explicit;
}
@Override
public int compareTo(MappingImpl mapping) {
return path.compareToIgnoreCase(mapping.path);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || !(obj instanceof MappingImpl))
return false;
MappingImpl other = (MappingImpl) obj;
return path.equals(other.path);
}
@Override
public Condition<?, ?> getCondition() {
return condition;
}
@Override
public Converter<?, ?> getConverter() {
return converter;
}
@Override
public List<? extends PropertyInfo> getDestinationProperties() {
return destinationMutators;
}
@Override
public PropertyInfo getLastDestinationProperty() {
return destinationMutators.get(destinationMutators.size() - 1);
}
@Override
public Provider<?> getProvider() {
return provider;
}
@Override
public int hashCode() {
return path.hashCode();
}
@Override
public boolean isSkipped() {
return skipType != 0;
}
@Override
public String getPath() {
return path;
}
@Override
public boolean isExplicit() {
return explicit;
}
MappingOptions getOptions() {<FILL_FUNCTION_BODY>}
}
|
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, PropertyType.GENERIC, name);
this.valueReaderMember = (ValueReader.Member<Object>) valueReaderMember;
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
return null;
}
@Override
public Type getGenericType() {
return type;
}
@Override
@SuppressWarnings("unchecked")
public Object getValue(Object subject) {
return valueReaderMember.get(subject, name);
}
@Override
public TypeInfo<?> getTypeInfo(InheritingConfiguration configuration) {
return TypeInfoRegistry.typeInfoFor(type, configuration);
}
static ValueReaderPropertyInfo fromMember(final ValueReader.Member<?> valueReaderMember, String memberName) {
if (valueReaderMember.getOrigin() != null) {
return new ValueReaderPropertyInfo(valueReaderMember, valueReaderMember.getValueType(), memberName) {
@Override
public TypeInfo<?> getTypeInfo(InheritingConfiguration configuration) {
return TypeInfoRegistry.typeInfoFor(valueReaderMember.getOrigin(),
valueReaderMember.getValueType(), configuration);
}
};
}
return new ValueReaderPropertyInfo(valueReaderMember, valueReaderMember.getValueType(), memberName);
}
@SuppressWarnings("unchecked")
static ValueReaderPropertyInfo create(final ValueReader<?> valueReader, String memberName) {<FILL_FUNCTION_BODY>}
}
|
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, memberName);
}
};
return new ValueReaderPropertyInfo(valueReaderMember, valueReaderMember.getValueType(), memberName);
| 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 = propertyName;
this.configuration = configuration;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof PropertyInfoKey))
return false;
PropertyInfoKey other = (PropertyInfoKey) o;
return initialType.equals(other.initialType) && propertyName.equals(other.propertyName)
&& configuration.equals(other.configuration);
}
@Override
public int hashCode() {
int result = 31 + initialType.hashCode();
result = 31 * result + propertyName.hashCode();
result = 31 * result + configuration.hashCode();
return result;
}
}
/**
* Returns an accessor for the {@code accessorName}, else {@code null} if none exists.
*/
static Accessor accessorFor(Class<?> type, String accessorName, InheritingConfiguration configuration) {
PropertyInfoKey key = new PropertyInfoKey(type, accessorName, configuration);
if (!ACCESSOR_CACHE.containsKey(key) && !FIELD_CACHE.containsKey(key)) {
@SuppressWarnings("unchecked")
Class<Object> uncheckedType = (Class<Object>) type;
for (Entry<String, Accessor> entry : TypeInfoRegistry.typeInfoFor(uncheckedType, configuration).getAccessors().entrySet()) {
if (entry.getValue().getMember() instanceof Method)
accessorFor(type, (Method) entry.getValue().getMember(), configuration, entry.getKey());
else if (entry.getValue().getMember() instanceof Field)
fieldPropertyFor(type, (Field) entry.getValue().getMember(), configuration, entry.getKey());
}
}
if (ACCESSOR_CACHE.containsKey(key))
return ACCESSOR_CACHE.get(key);
return FIELD_CACHE.get(key);
}
/**
* Returns an Accessor for the given accessor method. The method must be externally validated to
* ensure that it accepts zero arguments and does not return void.class.
*/
static synchronized Accessor accessorFor(Class<?> type, Method method,
Configuration configuration, String name) {
PropertyInfoKey key = new PropertyInfoKey(type, name, configuration);
Accessor accessor = ACCESSOR_CACHE.get(key);
if (accessor == null) {
accessor = new MethodAccessor(type, method, name);
ACCESSOR_CACHE.put(key, accessor);
}
return accessor;
}
/**
* Returns a FieldPropertyInfo instance for the given field.
*/
static synchronized FieldPropertyInfo fieldPropertyFor(Class<?> type, Field field,
Configuration configuration, String name) {<FILL_FUNCTION_BODY>
|
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 fieldPropertyInfo;
| 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 boolean canAccessMember(Member member, AccessLevel accessLevel) {
int mod = member.getModifiers();
switch (accessLevel) {
default:
case PUBLIC:
return Modifier.isPublic(mod);
case PROTECTED:
return Modifier.isPublic(mod) || Modifier.isProtected(mod);
case PACKAGE_PRIVATE:
return Modifier.isPublic(mod) || Modifier.isProtected(mod) || !Modifier.isPrivate(mod);
case PRIVATE:
return true;
}
}
static <T> Map<String, Accessor> resolveAccessors(T source, Class<T> type,
InheritingConfiguration configuration) {
ValueReader<T> valueReader = configuration.valueAccessStore.getFirstSupportedReader(type);
if (source != null && valueReader != null)
return resolveAccessorsFromValueReader(source, configuration, valueReader);
else
return resolveProperties(type, true, configuration);
}
static <T> Map<String, Accessor> resolveAccessorsFromValueReader(T source,
InheritingConfiguration configuration, ValueReader<T> valueReader) {
Map<String, Accessor> accessors = new LinkedHashMap<String, Accessor>();
NameTransformer nameTransformer = configuration.getSourceNameTransformer();
for (String memberName : valueReader.memberNames(source)) {
ValueReader.Member<?> member = valueReader.getMember(source, memberName);
if (member != null)
accessors.put(nameTransformer.transform(memberName, NameableType.GENERIC),
PropertyInfoImpl.ValueReaderPropertyInfo.fromMember(member, memberName));
}
return accessors;
}
static <T> Map<String, Mutator> resolveMutators(Class<T> type, InheritingConfiguration configuration) {
ValueWriter<T> valueWriter = configuration.valueMutateStore.getFirstSupportedWriter(type);
if (valueWriter != null && valueWriter.isResolveMembersSupport())
return resolveMutatorsFromValueWriter(type, configuration, valueWriter);
return resolveProperties(type, false, configuration);
}
static <T> Map<String, Mutator> resolveMutatorsFromValueWriter(Class<T> type,
InheritingConfiguration configuration, ValueWriter<T> valueWriter) {
Map<String, Mutator> mutators = new LinkedHashMap<String, Mutator>();
NameTransformer nameTransformer = configuration.getSourceNameTransformer();
for (String memberName : valueWriter.memberNames(type)) {
ValueWriter.Member<?> member = valueWriter.getMember(type, memberName);
if (member != null)
mutators.put(nameTransformer.transform(memberName, NameableType.GENERIC),
PropertyInfoImpl.ValueWriterPropertyInfo.fromMember(member, memberName));
}
return mutators;
}
@SuppressWarnings({ "unchecked" })
private static <M extends AccessibleObject & Member, PI extends PropertyInfo> Map<String, PI> resolveProperties(
Class<?> type, boolean access, Configuration configuration) {
Map<String, PI> properties = new LinkedHashMap<String, PI>();
if (configuration.isFieldMatchingEnabled()) {
properties.putAll(resolveProperties(type, type, PropertyInfoSetResolver.<M, PI>resolveRequest(configuration, access, true)));
}
properties.putAll(resolveProperties(type, type, PropertyInfoSetResolver.<M, PI>resolveRequest(configuration, access, false)));
return properties;
}
/**
* Populates the {@code resolveRequest.propertyInfo} with {@code resolveRequest.propertyResolver}
* resolved property info for properties that are accessible by the
* {@code resolveRequest.accessLevel} and satisfy the {@code resolveRequest.namingConvention}.
* Uses a depth-first search so that child properties of the same name override parents.
*/
private static <M extends AccessibleObject & Member, PI extends PropertyInfo> Map<String, PI> resolveProperties(
Class<?> initialType, Class<?> type, ResolveRequest<M, PI> resolveRequest) {<FILL_FUNCTION_BODY>
|
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 != Enum.class)
properties.putAll(resolveProperties(initialType, superType, resolveRequest));
for (M member : resolveRequest.propertyResolver.membersFor(type)) {
if (canAccessMember(member, resolveRequest.accessLevel)
&& resolveRequest.propertyResolver.isValid(member)
&& resolveRequest.namingConvention.applies(member.getName(), resolveRequest.propertyType)) {
String name = resolveRequest.nameTransformer.transform(member.getName(),
PropertyType.FIELD.equals(resolveRequest.propertyType) ? NameableType.FIELD
: NameableType.METHOD);
PI info = resolveRequest.propertyResolver.propertyInfoFor(initialType, member,
resolveRequest.config, name);
properties.put(name, info);
if (!Modifier.isPublic(member.getModifiers())
|| !Modifier.isPublic(member.getDeclaringClass().getModifiers()))
try {
member.setAccessible(true);
} catch (SecurityException e) {
throw new AssertionError(e);
}
}
}
return properties;
| 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 final Stack<Tokens> destinationPropertyTokens = new Stack<Tokens>();
private final Stack<PropertyInfo> sourceProperties = new Stack<PropertyInfo>();
private final Stack<PropertyInfo> destinationProperties = new Stack<PropertyInfo>();
private final Map<PropertyInfo, Tokens> sourceTypeTokensCache = new HashMap<PropertyInfo, Tokens>();
private final Map<String, Tokens> sourceTokensCache = new HashMap<String, Tokens>();
PropertyNameInfoImpl(Class<?> sourceClass, Configuration configuration) {
this.sourceClass = sourceClass;
this.configuration = configuration;
}
@Override
public List<PropertyInfo> getDestinationProperties() {
return destinationProperties;
}
@Override
public List<Tokens> getDestinationPropertyTokens() {
return destinationPropertyTokens;
}
@Override
public Tokens getSourceClassTokens() {<FILL_FUNCTION_BODY>}
@Override
public List<PropertyInfo> getSourceProperties() {
return sourceProperties;
}
@Override
public List<Tokens> getSourcePropertyTokens() {
return sourcePropertyTokens;
}
@Override
public List<Tokens> getSourcePropertyTypeTokens() {
if (sourcePropertyTypeTokens == null) {
sourcePropertyTypeTokens = new Stack<Tokens>();
for (PropertyInfo sourceProperty : sourceProperties)
pushSourcePropertyType(sourceProperty);
}
return sourcePropertyTypeTokens;
}
@Override
public String toString() {
return new ToStringBuilder(PropertyNameInfoImpl.class).add("sourceProperties", sourceProperties)
.add("destinationProperties", destinationProperties)
.toString();
}
void clearSource() {
sourceProperties.clear();
sourcePropertyTokens.clear();
if (sourcePropertyTypeTokens != null)
sourcePropertyTypeTokens.clear();
}
void popDestination() {
destinationProperties.pop();
destinationPropertyTokens.pop();
}
void popSource() {
sourceProperties.pop();
sourcePropertyTokens.pop();
if (sourcePropertyTypeTokens != null)
sourcePropertyTypeTokens.pop();
}
void pushDestination(String destinationName, Mutator destinationProperty) {
NameableType nameableType = NameableType.forPropertyType(destinationProperty.getPropertyType());
String[] tokens = configuration.getDestinationNameTokenizer().tokenize(
destinationName, nameableType);
destinationPropertyTokens.push(Tokens.of(tokens));
destinationProperties.push(destinationProperty);
}
void pushSource(String sourceName, Accessor sourceProperty) {
NameableType nameableType = NameableType.forPropertyType(sourceProperty.getPropertyType());
if (!sourceTokensCache.containsKey(sourceName)) {
sourceTokensCache.put(sourceName, Tokens.of(configuration.getSourceNameTokenizer()
.tokenize(sourceName, nameableType)));
}
sourcePropertyTokens.push(sourceTokensCache.get(sourceName));
sourceProperties.push(sourceProperty);
pushSourcePropertyType(sourceProperty);
}
private void pushSourcePropertyType(PropertyInfo sourceProperty) {
if (sourcePropertyTypeTokens == null)
return;
if (!sourceTypeTokensCache.containsKey(sourceProperty)) {
String typeName = configuration.getSourceNameTransformer().transform(
sourceProperty.getType().getSimpleName(), NameableType.CLASS);
sourceTypeTokensCache.put(sourceProperty, Tokens.of(configuration.getSourceNameTokenizer()
.tokenize(typeName, NameableType.CLASS)));
}
sourcePropertyTypeTokens.add(sourceTypeTokensCache.get(sourceProperty));
}
}
|
if (sourceClassTokens == null) {
String className = configuration.getSourceNameTransformer().transform(
sourceClass.getSimpleName(), NameableType.CLASS);
sourceClassTokens = Tokens.of(configuration.getSourceNameTokenizer().tokenize(className,
NameableType.CLASS));
}
return sourceClassTokens;
| 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.