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
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webflux-api/src/main/java/org/springdoc/webflux/api/MultipleOpenApiResource.java
MultipleOpenApiResource
afterPropertiesSet
class MultipleOpenApiResource implements InitializingBean { /** * The Grouped open apis. */ private final List<GroupedOpenApi> groupedOpenApis; /** * The Default open api builder. */ private final ObjectFactory<OpenAPIService> defaultOpenAPIBuilder; /** * The Request builder. */ private final AbstractRequestService requestBuilder; /** * The Response builder. */ private final GenericResponseService responseBuilder; /** * The Operation parser. */ private final OperationService operationParser; /** * The Spring doc config properties. */ private final SpringDocConfigProperties springDocConfigProperties; /** * The Spring doc providers. */ private final SpringDocProviders springDocProviders; /** * The Grouped open api resources. */ private Map<String, OpenApiResource> groupedOpenApiResources; /** * The Spring doc customizers. */ private final SpringDocCustomizers springDocCustomizers; /** * Instantiates a new Multiple open api resource. * * @param groupedOpenApis the grouped open apis * @param defaultOpenAPIBuilder the default open api builder * @param requestBuilder the request builder * @param responseBuilder the response builder * @param operationParser the operation parser * @param springDocConfigProperties the spring doc config properties * @param springDocProviders the spring doc providers * @param springDocCustomizers the spring doc customizers */ protected MultipleOpenApiResource(List<GroupedOpenApi> groupedOpenApis, ObjectFactory<OpenAPIService> defaultOpenAPIBuilder, AbstractRequestService requestBuilder, GenericResponseService responseBuilder, OperationService operationParser, SpringDocConfigProperties springDocConfigProperties, SpringDocProviders springDocProviders, SpringDocCustomizers springDocCustomizers) { this.groupedOpenApis = groupedOpenApis; this.defaultOpenAPIBuilder = defaultOpenAPIBuilder; this.requestBuilder = requestBuilder; this.responseBuilder = responseBuilder; this.operationParser = operationParser; this.springDocConfigProperties = springDocConfigProperties; this.springDocProviders = springDocProviders; this.springDocCustomizers = springDocCustomizers; } @Override public void afterPropertiesSet() {<FILL_FUNCTION_BODY>} /** * Build web flux open api resource open api resource. * * @param item the item * @return the open api resource */ private OpenApiResource buildWebFluxOpenApiResource(GroupedOpenApi item) { if (!springDocConfigProperties.isUseManagementPort() && !ACTUATOR_DEFAULT_GROUP.equals(item.getGroup())) return new OpenApiWebfluxResource(item.getGroup(), defaultOpenAPIBuilder, requestBuilder, responseBuilder, operationParser, springDocConfigProperties, springDocProviders, new SpringDocCustomizers(Optional.of(item.getOpenApiCustomizers()), Optional.of(item.getOperationCustomizers()), Optional.of(item.getRouterOperationCustomizers()), Optional.of(item.getOpenApiMethodFilters())) ); else return new OpenApiActuatorResource(item.getGroup(), defaultOpenAPIBuilder, requestBuilder, responseBuilder, operationParser, springDocConfigProperties, springDocProviders, new SpringDocCustomizers(Optional.of(item.getOpenApiCustomizers()), Optional.of(item.getOperationCustomizers()), Optional.of(item.getRouterOperationCustomizers()), Optional.of(item.getOpenApiMethodFilters()))); } /** * Gets open api resource or throw. * * @param group the group * @return the open api resource or throw */ protected OpenApiResource getOpenApiResourceOrThrow(String group) { OpenApiResource openApiResource = groupedOpenApiResources.get(group); if (openApiResource == null) { throw new OpenApiResourceNotFoundException("No OpenAPI resource found for group: " + group); } return openApiResource; } }
this.groupedOpenApis.forEach(groupedOpenApi -> { springDocCustomizers.getGlobalOpenApiCustomizers().ifPresent(groupedOpenApi::addAllOpenApiCustomizer); springDocCustomizers.getGlobalOperationCustomizers().ifPresent(groupedOpenApi::addAllOperationCustomizer); springDocCustomizers.getGlobalOpenApiMethodFilters().ifPresent(groupedOpenApi::addAllOpenApiMethodFilter); } ); this.groupedOpenApiResources = groupedOpenApis.stream() .collect(Collectors.toMap(GroupedOpenApi::getGroup, item -> { GroupConfig groupConfig = new GroupConfig(item.getGroup(), item.getPathsToMatch(), item.getPackagesToScan(), item.getPackagesToExclude(), item.getPathsToExclude(), item.getProducesToMatch(), item.getConsumesToMatch(), item.getHeadersToMatch(), item.getDisplayName()); springDocConfigProperties.addGroupConfig(groupConfig); return buildWebFluxOpenApiResource(item); }, (existingValue, newValue) -> { return existingValue; // choice to keep the existing value } ));
1,052
306
1,358
<no_super_class>
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webflux-api/src/main/java/org/springdoc/webflux/api/OpenApiWebfluxResource.java
OpenApiWebfluxResource
getServerUrl
class OpenApiWebfluxResource extends OpenApiResource { /** * Instantiates a new Open api webflux resource. * * @param groupName the group name * @param openAPIBuilderObjectFactory the open api builder object factory * @param requestBuilder the request builder * @param responseBuilder the response builder * @param operationParser the operation parser * @param springDocConfigProperties the spring doc config properties * @param springDocProviders the spring doc providers * @param springDocCustomizers the spring doc customizers */ public OpenApiWebfluxResource(String groupName, ObjectFactory<OpenAPIService> openAPIBuilderObjectFactory, AbstractRequestService requestBuilder, GenericResponseService responseBuilder, OperationService operationParser, SpringDocConfigProperties springDocConfigProperties, SpringDocProviders springDocProviders, SpringDocCustomizers springDocCustomizers) { super(groupName, openAPIBuilderObjectFactory, requestBuilder, responseBuilder, operationParser, springDocConfigProperties, springDocProviders, springDocCustomizers); } /** * Instantiates a new Open api webflux resource. * * @param openAPIBuilderObjectFactory the open api builder object factory * @param requestBuilder the request builder * @param responseBuilder the response builder * @param operationParser the operation parser * @param springDocConfigProperties the spring doc config properties * @param springDocProviders the spring doc providers * @param springDocCustomizers the spring doc customizers */ @Autowired public OpenApiWebfluxResource(ObjectFactory<OpenAPIService> openAPIBuilderObjectFactory, AbstractRequestService requestBuilder, GenericResponseService responseBuilder, OperationService operationParser, SpringDocConfigProperties springDocConfigProperties, SpringDocProviders springDocProviders, SpringDocCustomizers springDocCustomizers) { super(openAPIBuilderObjectFactory, requestBuilder, responseBuilder, operationParser, springDocConfigProperties, springDocProviders, springDocCustomizers); } /** * Openapi json mono. * * @param serverHttpRequest the server http request * @param apiDocsUrl the api docs url * @param locale the locale * @return the mono * @throws JsonProcessingException the json processing exception */ @Operation(hidden = true) @GetMapping(value = API_DOCS_URL, produces = MediaType.APPLICATION_JSON_VALUE) @Override public Mono<byte[]> openapiJson(ServerHttpRequest serverHttpRequest, @Value(API_DOCS_URL) String apiDocsUrl, Locale locale) throws JsonProcessingException { return super.openapiJson(serverHttpRequest, apiDocsUrl, locale); } /** * Openapi yaml mono. * * @param serverHttpRequest the server http request * @param apiDocsUrl the api docs url * @param locale the locale * @return the mono * @throws JsonProcessingException the json processing exception */ @Operation(hidden = true) @GetMapping(value = DEFAULT_API_DOCS_URL_YAML, produces = APPLICATION_OPENAPI_YAML) @Override public Mono<byte[]> openapiYaml(ServerHttpRequest serverHttpRequest, @Value(DEFAULT_API_DOCS_URL_YAML) String apiDocsUrl, Locale locale) throws JsonProcessingException { return super.openapiYaml(serverHttpRequest, apiDocsUrl, locale); } /** * Gets server url. * * @param serverHttpRequest the server http request * @param apiDocsUrl the api docs url * @return the server url */ @Override protected String getServerUrl(ServerHttpRequest serverHttpRequest, String apiDocsUrl) {<FILL_FUNCTION_BODY>} }
String requestUrl = decode(serverHttpRequest.getURI().toString()); Optional<SpringWebProvider> springWebProviderOptional = springDocProviders.getSpringWebProvider(); String prefix = StringUtils.EMPTY; if (springWebProviderOptional.isPresent()) prefix = springWebProviderOptional.get().findPathPrefix(springDocConfigProperties); return requestUrl.substring(0, requestUrl.length() - apiDocsUrl.length() - prefix.length());
952
121
1,073
<methods>public void <init>(java.lang.String, ObjectFactory<org.springdoc.core.service.OpenAPIService>, org.springdoc.core.service.AbstractRequestService, org.springdoc.core.service.GenericResponseService, org.springdoc.core.service.OperationService, org.springdoc.core.properties.SpringDocConfigProperties, org.springdoc.core.providers.SpringDocProviders, org.springdoc.core.customizers.SpringDocCustomizers) ,public void <init>(ObjectFactory<org.springdoc.core.service.OpenAPIService>, org.springdoc.core.service.AbstractRequestService, org.springdoc.core.service.GenericResponseService, org.springdoc.core.service.OperationService, org.springdoc.core.properties.SpringDocConfigProperties, org.springdoc.core.providers.SpringDocProviders, org.springdoc.core.customizers.SpringDocCustomizers) <variables>
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webflux-api/src/main/java/org/springdoc/webflux/core/configuration/MultipleOpenApiSupportConfiguration.java
SpringDocWebMvcActuatorDifferentConfiguration
multipleOpenApiActuatorResource
class SpringDocWebMvcActuatorDifferentConfiguration { /** * Multiple open api actuator resource multiple open api actuator resource. * * @param groupedOpenApis the grouped open apis * @param defaultOpenAPIBuilder the default open api builder * @param requestBuilder the request builder * @param responseBuilder the response builder * @param operationParser the operation parser * @param springDocConfigProperties the spring doc config properties * @param springDocProviders the spring doc providers * @param springDocCustomizers the spring doc customizers * @return the multiple open api actuator resource */ @Bean @ConditionalOnMissingBean @ConditionalOnProperty(SPRINGDOC_USE_MANAGEMENT_PORT) @Lazy(false) MultipleOpenApiActuatorResource multipleOpenApiActuatorResource(List<GroupedOpenApi> groupedOpenApis, ObjectFactory<OpenAPIService> defaultOpenAPIBuilder, AbstractRequestService requestBuilder, GenericResponseService responseBuilder, OperationService operationParser, SpringDocConfigProperties springDocConfigProperties, SpringDocProviders springDocProviders, SpringDocCustomizers springDocCustomizers) {<FILL_FUNCTION_BODY>} }
return new MultipleOpenApiActuatorResource(groupedOpenApis, defaultOpenAPIBuilder, requestBuilder, responseBuilder, operationParser, springDocConfigProperties, springDocProviders, springDocCustomizers);
315
57
372
<no_super_class>
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webflux-api/src/main/java/org/springdoc/webflux/core/configuration/SpringDocWebFluxConfiguration.java
SpringDocWebFluxActuatorConfiguration
actuatorOpenApiResource
class SpringDocWebFluxActuatorConfiguration { /** * Actuator provider actuator provider. * * @param serverProperties the server properties * @param springDocConfigProperties the spring doc config properties * @param managementServerProperties the management server properties * @param webEndpointProperties the web endpoint properties * @param webFluxEndpointHandlerMapping the web flux endpoint handler mapping * @param controllerEndpointHandlerMapping the controller endpoint handler mapping * @return the actuator provider */ @Bean @ConditionalOnMissingBean @ConditionalOnExpression("${springdoc.show-actuator:false} or ${springdoc.use-management-port:false}") @Lazy(false) ActuatorProvider actuatorProvider(ServerProperties serverProperties, SpringDocConfigProperties springDocConfigProperties, Optional<ManagementServerProperties> managementServerProperties, Optional<WebEndpointProperties> webEndpointProperties, Optional<WebFluxEndpointHandlerMapping> webFluxEndpointHandlerMapping, Optional<ControllerEndpointHandlerMapping> controllerEndpointHandlerMapping) { return new ActuatorWebFluxProvider(serverProperties, springDocConfigProperties, managementServerProperties, webEndpointProperties, webFluxEndpointHandlerMapping, controllerEndpointHandlerMapping); } /** * Actuator open api resource open api actuator resource. * * @param openAPIBuilderObjectFactory the open api builder object factory * @param requestBuilder the request builder * @param responseBuilder the response builder * @param operationParser the operation parser * @param springDocConfigProperties the spring doc config properties * @param springDocProviders the spring doc providers * @return the open api actuator resource */ @Bean @ConditionalOnMissingBean(MultipleOpenApiSupportConfiguration.class) @ConditionalOnExpression("${springdoc.use-management-port:false} and ${springdoc.enable-default-api-docs:true}") @ConditionalOnManagementPort(ManagementPortType.DIFFERENT) @Lazy(false) OpenApiActuatorResource actuatorOpenApiResource(ObjectFactory<OpenAPIService> openAPIBuilderObjectFactory, AbstractRequestService requestBuilder, GenericResponseService responseBuilder, OperationService operationParser, SpringDocConfigProperties springDocConfigProperties, SpringDocProviders springDocProviders, SpringDocCustomizers springDocCustomizers) {<FILL_FUNCTION_BODY>} }
return new OpenApiActuatorResource(openAPIBuilderObjectFactory, requestBuilder, responseBuilder, operationParser, springDocConfigProperties, springDocProviders, springDocCustomizers);
618
47
665
<no_super_class>
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webflux-api/src/main/java/org/springdoc/webflux/core/providers/ActuatorWebFluxProvider.java
ActuatorWebFluxProvider
getMethods
class ActuatorWebFluxProvider extends ActuatorProvider { /** * The Web flux endpoint handler mapping. */ private WebFluxEndpointHandlerMapping webFluxEndpointHandlerMapping; /** * The Controller endpoint handler mapping. */ private ControllerEndpointHandlerMapping controllerEndpointHandlerMapping; /** * Instantiates a new Actuator web flux provider. * * @param serverProperties the server properties * @param springDocConfigProperties the spring doc config properties * @param managementServerProperties the management server properties * @param webEndpointProperties the web endpoint properties * @param webFluxEndpointHandlerMapping the web flux endpoint handler mapping * @param controllerEndpointHandlerMapping the controller endpoint handler mapping */ public ActuatorWebFluxProvider(ServerProperties serverProperties, SpringDocConfigProperties springDocConfigProperties, Optional<ManagementServerProperties> managementServerProperties, Optional<WebEndpointProperties> webEndpointProperties, Optional<WebFluxEndpointHandlerMapping> webFluxEndpointHandlerMapping, Optional<ControllerEndpointHandlerMapping> controllerEndpointHandlerMapping) { super(managementServerProperties, webEndpointProperties, serverProperties, springDocConfigProperties); webFluxEndpointHandlerMapping.ifPresent(webFluxEndpointHandlerMapping1 -> this.webFluxEndpointHandlerMapping = webFluxEndpointHandlerMapping1); controllerEndpointHandlerMapping.ifPresent(controllerEndpointHandlerMapping1 -> this.controllerEndpointHandlerMapping = controllerEndpointHandlerMapping1); } public Map<RequestMappingInfo, HandlerMethod> getMethods() {<FILL_FUNCTION_BODY>} }
Map<RequestMappingInfo, HandlerMethod> mappingInfoHandlerMethodMap = new HashMap<>(); if (webFluxEndpointHandlerMapping == null) webFluxEndpointHandlerMapping = managementApplicationContext.getBean(WebFluxEndpointHandlerMapping.class); mappingInfoHandlerMethodMap.putAll(webFluxEndpointHandlerMapping.getHandlerMethods()); if (controllerEndpointHandlerMapping == null) controllerEndpointHandlerMapping = managementApplicationContext.getBean(ControllerEndpointHandlerMapping.class); mappingInfoHandlerMethodMap.putAll(controllerEndpointHandlerMapping.getHandlerMethods()); return mappingInfoHandlerMethodMap;
389
155
544
<no_super_class>
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webflux-api/src/main/java/org/springdoc/webflux/core/providers/SpringWebFluxProvider.java
SpringWebFluxProvider
getHandlerMethods
class SpringWebFluxProvider extends SpringWebProvider { /** * Finds path prefix. * * @param springDocConfigProperties the spring doc config properties * @return the path prefix */ @Override public String findPathPrefix(SpringDocConfigProperties springDocConfigProperties) { Map<RequestMappingInfo, HandlerMethod> map = getHandlerMethods(); for (Entry<RequestMappingInfo, HandlerMethod> entry : map.entrySet()) { RequestMappingInfo requestMappingInfo = entry.getKey(); Set<String> patterns = getActivePatterns(requestMappingInfo); if (!CollectionUtils.isEmpty(patterns)) { for (String operationPath : patterns) { if (operationPath.endsWith(springDocConfigProperties.getApiDocs().getPath())) return operationPath.replace(springDocConfigProperties.getApiDocs().getPath(), StringUtils.EMPTY); } } } return StringUtils.EMPTY; } /** * Gets active patterns. * * @param requestMapping the request mapping info * @return the active patterns */ public Set<String> getActivePatterns(Object requestMapping) { RequestMappingInfo requestMappingInfo = (RequestMappingInfo) requestMapping; PatternsRequestCondition patternsRequestCondition = requestMappingInfo.getPatternsCondition(); return patternsRequestCondition.getPatterns().stream() .map(PathPattern::getPatternString).collect(Collectors.toSet()); } /** * Gets handler methods. * * @return the handler methods */ @Override public Map getHandlerMethods() {<FILL_FUNCTION_BODY>} }
if (this.handlerMethods == null) { Map<String, RequestMappingHandlerMapping> beansOfTypeRequestMappingHandlerMapping = applicationContext.getBeansOfType(RequestMappingHandlerMapping.class); this.handlerMethods = beansOfTypeRequestMappingHandlerMapping.values().stream() .map(AbstractHandlerMethodMapping::getHandlerMethods) .map(Map::entrySet) .flatMap(Collection::stream) .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (a1, a2) -> a1, LinkedHashMap::new)); } return this.handlerMethods;
416
153
569
<methods>public non-sealed void <init>() ,public abstract java.lang.String findPathPrefix(org.springdoc.core.properties.SpringDocConfigProperties) ,public abstract Set<java.lang.String> getActivePatterns(java.lang.Object) ,public abstract Map#RAW getHandlerMethods() ,public void setApplicationContext(org.springframework.context.ApplicationContext) throws org.springframework.beans.BeansException<variables>protected org.springframework.context.ApplicationContext applicationContext,protected Map#RAW handlerMethods
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webflux-ui/src/main/java/org/springdoc/webflux/ui/SwaggerIndexPageTransformer.java
SwaggerIndexPageTransformer
transform
class SwaggerIndexPageTransformer extends AbstractSwaggerIndexTransformer implements SwaggerIndexTransformer { /** * The Swagger welcome common. */ private final SwaggerWelcomeCommon swaggerWelcomeCommon; /** * Instantiates a new Swagger index transformer. * @param swaggerUiConfig the swagger ui config * @param swaggerUiOAuthProperties the swagger ui o auth properties * @param swaggerUiConfigParameters the swagger ui config parameters * @param swaggerWelcomeCommon the swagger welcome common * @param objectMapperProvider the object mapper provider */ public SwaggerIndexPageTransformer(SwaggerUiConfigProperties swaggerUiConfig, SwaggerUiOAuthProperties swaggerUiOAuthProperties, SwaggerUiConfigParameters swaggerUiConfigParameters, SwaggerWelcomeCommon swaggerWelcomeCommon, ObjectMapperProvider objectMapperProvider) { super(swaggerUiConfig, swaggerUiOAuthProperties, swaggerUiConfigParameters, objectMapperProvider); this.swaggerWelcomeCommon = swaggerWelcomeCommon; } @Override public Mono<Resource> transform(ServerWebExchange serverWebExchange, Resource resource, ResourceTransformerChain resourceTransformerChain) {<FILL_FUNCTION_BODY>} }
if (swaggerUiConfigParameters.getConfigUrl() == null) swaggerWelcomeCommon.buildFromCurrentContextPath(serverWebExchange.getRequest()); final AntPathMatcher antPathMatcher = new AntPathMatcher(); try { boolean isIndexFound = antPathMatcher.match("**/swagger-ui/**/" + SWAGGER_INITIALIZER_JS, resource.getURL().toString()); if (isIndexFound) { String html = defaultTransformations(resource.getInputStream()); return Mono.just(new TransformedResource(resource, html.getBytes(StandardCharsets.UTF_8))); } else { return Mono.just(resource); } } catch (Exception e) { throw new SpringDocUIException("Failed to transform Index", e); }
311
214
525
<methods>public void <init>(org.springdoc.core.properties.SwaggerUiConfigProperties, org.springdoc.core.properties.SwaggerUiOAuthProperties, org.springdoc.core.properties.SwaggerUiConfigParameters, org.springdoc.core.providers.ObjectMapperProvider) <variables>private static final java.lang.String PRESETS,protected com.fasterxml.jackson.databind.ObjectMapper objectMapper,protected org.springdoc.core.properties.SwaggerUiConfigProperties swaggerUiConfig,protected org.springdoc.core.properties.SwaggerUiConfigParameters swaggerUiConfigParameters,protected org.springdoc.core.properties.SwaggerUiOAuthProperties swaggerUiOAuthProperties
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webflux-ui/src/main/java/org/springdoc/webflux/ui/SwaggerResourceResolver.java
SwaggerResourceResolver
resolveResource
class SwaggerResourceResolver extends AbstractSwaggerResourceResolver implements ResourceResolver { /** * Instantiates a new Web jars version resource resolver. * * @param swaggerUiConfigProperties the swagger ui config properties */ public SwaggerResourceResolver(SwaggerUiConfigProperties swaggerUiConfigProperties) { super(swaggerUiConfigProperties); } @Override public Mono<Resource> resolveResource(ServerWebExchange exchange, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) {<FILL_FUNCTION_BODY>} @Override public Mono<String> resolveUrlPath(String resourceUrlPath, List<? extends Resource> locations, ResourceResolverChain chain) { return chain.resolveUrlPath(resourceUrlPath, locations) .switchIfEmpty(Mono.defer(() -> { String webJarResourcePath = findWebJarResourcePath(resourceUrlPath); if (webJarResourcePath != null) { return chain.resolveUrlPath(webJarResourcePath, locations); } else { return Mono.empty(); } })); } }
return chain.resolveResource(exchange, requestPath, locations) .switchIfEmpty(Mono.defer(() -> { String webJarsResourcePath = findWebJarResourcePath(requestPath); if (webJarsResourcePath != null) { return chain.resolveResource(exchange, webJarsResourcePath, locations); } else { return Mono.empty(); } }));
287
110
397
<methods>public void <init>(org.springdoc.core.properties.SwaggerUiConfigProperties) <variables>private final non-sealed org.springdoc.core.properties.SwaggerUiConfigProperties swaggerUiConfigProperties
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webflux-ui/src/main/java/org/springdoc/webflux/ui/SwaggerUiHome.java
SwaggerUiHome
index
class SwaggerUiHome { /** * The Swagger ui path. */ @Value(SWAGGER_UI_PATH) private String swaggerUiPath; /** * The Base path. */ private String basePath = StringUtils.EMPTY; /** * Instantiates a new Swagger ui home. * * @param optionalWebFluxProperties the optional web flux properties */ public SwaggerUiHome(Optional<WebFluxProperties> optionalWebFluxProperties) { optionalWebFluxProperties.ifPresent(webFluxProperties -> this.basePath = StringUtils.defaultIfEmpty(webFluxProperties.getBasePath(), StringUtils.EMPTY)); } /** * Index mono. * * @param response the response * @return the mono */ @GetMapping(DEFAULT_PATH_SEPARATOR) @Operation(hidden = true) public Mono<Void> index(ServerHttpResponse response) {<FILL_FUNCTION_BODY>} }
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(this.basePath + swaggerUiPath); response.setStatusCode(HttpStatus.FOUND); response.getHeaders().setLocation(URI.create(uriBuilder.build().encode().toString())); return response.setComplete();
260
81
341
<no_super_class>
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webflux-ui/src/main/java/org/springdoc/webflux/ui/SwaggerWebFluxConfigurer.java
SwaggerWebFluxConfigurer
addResourceHandlers
class SwaggerWebFluxConfigurer implements WebFluxConfigurer { /** * The Swagger path. */ private final String swaggerPath; /** * The Web jars prefix url. */ private final String webJarsPrefixUrl; /** * The Swagger index transformer. */ private final SwaggerIndexTransformer swaggerIndexTransformer; /** * The Actuator provider. */ private final Optional<ActuatorProvider> actuatorProvider; /** * The Swagger resource resolver. */ private final SwaggerResourceResolver swaggerResourceResolver; /** * Instantiates a new Swagger web flux configurer. * * @param swaggerUiConfigParameters the swagger ui calculated config * @param springDocConfigProperties the spring doc config properties * @param swaggerIndexTransformer the swagger index transformer * @param actuatorProvider the actuator provider * @param swaggerResourceResolver the swagger resource resolver */ public SwaggerWebFluxConfigurer(SwaggerUiConfigParameters swaggerUiConfigParameters, SpringDocConfigProperties springDocConfigProperties, SwaggerIndexTransformer swaggerIndexTransformer, Optional<ActuatorProvider> actuatorProvider, SwaggerResourceResolver swaggerResourceResolver) { this.swaggerPath = swaggerUiConfigParameters.getPath(); this.webJarsPrefixUrl = springDocConfigProperties.getWebjars().getPrefix(); this.swaggerIndexTransformer = swaggerIndexTransformer; this.actuatorProvider = actuatorProvider; this.swaggerResourceResolver = swaggerResourceResolver; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) {<FILL_FUNCTION_BODY>} }
StringBuilder uiRootPath = new StringBuilder(); if (swaggerPath.contains(DEFAULT_PATH_SEPARATOR)) uiRootPath.append(swaggerPath, 0, swaggerPath.lastIndexOf(DEFAULT_PATH_SEPARATOR)); if (actuatorProvider.isPresent() && actuatorProvider.get().isUseManagementPort()) uiRootPath.append(actuatorProvider.get().getBasePath()); registry.addResourceHandler(uiRootPath + webJarsPrefixUrl + ALL_PATTERN) .addResourceLocations(CLASSPATH_RESOURCE_LOCATION + DEFAULT_WEB_JARS_PREFIX_URL + DEFAULT_PATH_SEPARATOR) .resourceChain(false) .addResolver(swaggerResourceResolver) .addTransformer(swaggerIndexTransformer);
443
207
650
<no_super_class>
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webflux-ui/src/main/java/org/springdoc/webflux/ui/SwaggerWelcomeActuator.java
SwaggerWelcomeActuator
calculateOauth2RedirectUrl
class SwaggerWelcomeActuator extends SwaggerWelcomeCommon { /** * The constant SWAGGER_CONFIG_ACTUATOR_URL. */ private static final String SWAGGER_CONFIG_ACTUATOR_URL = DEFAULT_PATH_SEPARATOR + SWAGGER_CONFIG_FILE; /** * The Web endpoint properties. */ private final WebEndpointProperties webEndpointProperties; /** * The Management server properties. */ private final ManagementServerProperties managementServerProperties; /** * Instantiates a new Swagger welcome. * * @param swaggerUiConfig the swagger ui config * @param springDocConfigProperties the spring doc config properties * @param swaggerUiConfigParameters the swagger ui config parameters * @param webEndpointProperties the web endpoint properties * @param managementServerProperties the management server properties */ public SwaggerWelcomeActuator(SwaggerUiConfigProperties swaggerUiConfig , SpringDocConfigProperties springDocConfigProperties, SwaggerUiConfigParameters swaggerUiConfigParameters, WebEndpointProperties webEndpointProperties, ManagementServerProperties managementServerProperties) { super(swaggerUiConfig, springDocConfigProperties, swaggerUiConfigParameters); this.webEndpointProperties = webEndpointProperties; this.managementServerProperties = managementServerProperties; } /** * Redirect to ui mono. * * @param request the request * @param response the response * @return the mono */ @Operation(hidden = true) @GetMapping(DEFAULT_PATH_SEPARATOR) @Override public Mono<Void> redirectToUi(ServerHttpRequest request, ServerHttpResponse response) { return super.redirectToUi(request, response); } /** * Gets swagger ui config. * * @param request the request * @return the swagger ui config */ @Operation(hidden = true) @GetMapping(value = SWAGGER_CONFIG_ACTUATOR_URL, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @Override public Map<String, Object> getSwaggerUiConfig(ServerHttpRequest request) { return super.getSwaggerUiConfig(request); } @Override protected void calculateUiRootPath(StringBuilder... sbUrls) { StringBuilder sbUrl = new StringBuilder(); sbUrl.append(webEndpointProperties.getBasePath()); calculateUiRootCommon(sbUrl, sbUrls); } @Override protected void calculateOauth2RedirectUrl(UriComponentsBuilder uriComponentsBuilder) {<FILL_FUNCTION_BODY>} @Override protected String buildApiDocUrl() { return buildUrl(contextPath + webEndpointProperties.getBasePath(), DEFAULT_API_DOCS_ACTUATOR_URL); } @Override protected String buildUrlWithContextPath(String swaggerUiUrl) { return buildUrl(contextPath + webEndpointProperties.getBasePath(), swaggerUiUrl); } @Override protected String buildSwaggerConfigUrl() { return contextPath + webEndpointProperties.getBasePath() + DEFAULT_PATH_SEPARATOR + DEFAULT_SWAGGER_UI_ACTUATOR_PATH + DEFAULT_PATH_SEPARATOR + SWAGGER_CONFIG_FILE; } }
if (StringUtils.isBlank(swaggerUiConfig.getOauth2RedirectUrl()) || !swaggerUiConfigParameters.isValidUrl(swaggerUiConfig.getOauth2RedirectUrl())) { UriComponentsBuilder oauthPrefix = uriComponentsBuilder.path(managementServerProperties.getBasePath() + swaggerUiConfigParameters.getUiRootPath()).path(webJarsPrefixUrl); swaggerUiConfigParameters.setOauth2RedirectUrl(oauthPrefix.path(getOauth2RedirectUrl()).build().toString()); }
833
143
976
<methods>public void <init>(org.springdoc.core.properties.SwaggerUiConfigProperties, org.springdoc.core.properties.SpringDocConfigProperties, org.springdoc.core.properties.SwaggerUiConfigParameters) <variables>protected java.lang.String webJarsPrefixUrl
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webflux-ui/src/main/java/org/springdoc/webflux/ui/SwaggerWelcomeCommon.java
SwaggerWelcomeCommon
buildFromCurrentContextPath
class SwaggerWelcomeCommon extends AbstractSwaggerWelcome { /** * The Web jars prefix url. */ protected String webJarsPrefixUrl; /** * Instantiates a new Abstract swagger welcome. * @param swaggerUiConfig the swagger ui config * @param springDocConfigProperties the spring doc config properties * @param swaggerUiConfigParameters the swagger ui config parameters */ public SwaggerWelcomeCommon(SwaggerUiConfigProperties swaggerUiConfig, SpringDocConfigProperties springDocConfigProperties, SwaggerUiConfigParameters swaggerUiConfigParameters) { super(swaggerUiConfig, springDocConfigProperties, swaggerUiConfigParameters); this.webJarsPrefixUrl = springDocConfigProperties.getWebjars().getPrefix(); } /** * Redirect to ui mono. * * @param request the request * @param response the response * @return the mono */ protected Mono<Void> redirectToUi(ServerHttpRequest request, ServerHttpResponse response) { this.buildFromCurrentContextPath(request); String sbUrl = this.buildUrl(contextPath, swaggerUiConfigParameters.getUiRootPath() + springDocConfigProperties.getWebjars().getPrefix() + getSwaggerUiUrl()); UriComponentsBuilder uriBuilder = getUriComponentsBuilder(sbUrl); response.setStatusCode(HttpStatus.FOUND); response.getHeaders().setLocation(URI.create(uriBuilder.build().encode().toString())); return response.setComplete(); } /** * Gets swagger ui config. * * @param request the request * @return the swagger ui config */ protected Map<String, Object> getSwaggerUiConfig(ServerHttpRequest request) { this.buildFromCurrentContextPath(request); return swaggerUiConfigParameters.getConfigParameters(); } /** * From current context path string. * * @param request the request * @return the string */ void buildFromCurrentContextPath(ServerHttpRequest request) {<FILL_FUNCTION_BODY>} }
super.init(); contextPath = request.getPath().contextPath().value(); String url = UriComponentsBuilder.fromHttpRequest(request).toUriString(); if (!AntPathMatcher.DEFAULT_PATH_SEPARATOR.equals(request.getPath().toString())) url = url.replace(request.getPath().toString(), ""); buildConfigUrl(UriComponentsBuilder.fromUriString(url));
540
109
649
<methods>public void <init>(org.springdoc.core.properties.SwaggerUiConfigProperties, org.springdoc.core.properties.SpringDocConfigProperties, org.springdoc.core.properties.SwaggerUiConfigParameters) <variables>protected java.lang.String apiDocsUrl,protected java.lang.String contextPath,protected final non-sealed org.springdoc.core.properties.SpringDocConfigProperties springDocConfigProperties,protected java.lang.String swaggerConfigUrl,protected final non-sealed org.springdoc.core.properties.SwaggerUiConfigProperties swaggerUiConfig,protected final non-sealed org.springdoc.core.properties.SwaggerUiConfigParameters swaggerUiConfigParameters
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webflux-ui/src/main/java/org/springdoc/webflux/ui/SwaggerWelcomeWebFlux.java
SwaggerWelcomeWebFlux
calculateOauth2RedirectUrl
class SwaggerWelcomeWebFlux extends SwaggerWelcomeCommon { /** * The Spring web provider. */ private final SpringWebProvider springWebProvider; /** * The Path prefix. */ private String pathPrefix; /** * Instantiates a new Swagger welcome web flux. * * @param swaggerUiConfig the swagger ui config * @param springDocConfigProperties the spring doc config properties * @param swaggerUiConfigParameters the swagger ui config parameters * @param springWebProvider the spring web provider */ public SwaggerWelcomeWebFlux(SwaggerUiConfigProperties swaggerUiConfig, SpringDocConfigProperties springDocConfigProperties, SwaggerUiConfigParameters swaggerUiConfigParameters, SpringWebProvider springWebProvider) { super(swaggerUiConfig, springDocConfigProperties, swaggerUiConfigParameters); this.springWebProvider = springWebProvider; } /** * Redirect to ui mono. * * @param request the request * @param response the response * @return the mono */ @Operation(hidden = true) @GetMapping(SWAGGER_UI_PATH) @Override public Mono<Void> redirectToUi(ServerHttpRequest request, ServerHttpResponse response) { return super.redirectToUi(request, response); } /** * Calculate ui root path. * * @param sbUrls the sb urls */ @Override protected void calculateUiRootPath(StringBuilder... sbUrls) { StringBuilder sbUrl = new StringBuilder(); calculateUiRootCommon(sbUrl, sbUrls); } /** * Calculate oauth 2 redirect url. * * @param uriComponentsBuilder the uri components builder */ @Override protected void calculateOauth2RedirectUrl(UriComponentsBuilder uriComponentsBuilder) {<FILL_FUNCTION_BODY>} /** * Build api doc url string. * * @return the string */ @Override protected String buildApiDocUrl() { return buildUrlWithContextPath(springDocConfigProperties.getApiDocs().getPath()); } @Override protected String buildUrlWithContextPath(String swaggerUiUrl) { if (this.pathPrefix == null) this.pathPrefix = springWebProvider.findPathPrefix(springDocConfigProperties); return buildUrl(this.contextPath + this.pathPrefix, swaggerUiUrl); } /** * Build swagger config url string. * * @return the string */ @Override protected String buildSwaggerConfigUrl() { return this.apiDocsUrl + DEFAULT_PATH_SEPARATOR + SWAGGER_CONFIG_FILE; } }
if (StringUtils.isBlank(swaggerUiConfig.getOauth2RedirectUrl()) || !swaggerUiConfigParameters.isValidUrl(swaggerUiConfig.getOauth2RedirectUrl())) { UriComponentsBuilder oauthPrefix = uriComponentsBuilder.path(contextPath).path(swaggerUiConfigParameters.getUiRootPath()).path(webJarsPrefixUrl); swaggerUiConfigParameters.setOauth2RedirectUrl(oauthPrefix.path(getOauth2RedirectUrl()).build().toString()); }
701
139
840
<methods>public void <init>(org.springdoc.core.properties.SwaggerUiConfigProperties, org.springdoc.core.properties.SpringDocConfigProperties, org.springdoc.core.properties.SwaggerUiConfigParameters) <variables>protected java.lang.String webJarsPrefixUrl
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webmvc-api/src/main/java/org/springdoc/webmvc/api/MultipleOpenApiResource.java
MultipleOpenApiResource
getOpenApiResourceOrThrow
class MultipleOpenApiResource implements InitializingBean { /** * The Grouped open apis. */ private final List<GroupedOpenApi> groupedOpenApis; /** * The Default open api builder. */ private final ObjectFactory<OpenAPIService> defaultOpenAPIBuilder; /** * The Request builder. */ private final AbstractRequestService requestBuilder; /** * The Response builder. */ private final GenericResponseService responseBuilder; /** * The Operation parser. */ private final OperationService operationParser; /** * The Spring doc providers. */ private final SpringDocProviders springDocProviders; /** * The Spring doc config properties. */ private final SpringDocConfigProperties springDocConfigProperties; /** * The Grouped open api resources. */ private Map<String, OpenApiResource> groupedOpenApiResources; /** * The Spring doc customizers. */ private final SpringDocCustomizers springDocCustomizers; /** * Instantiates a new Multiple open api resource. * * @param groupedOpenApis the grouped open apis * @param defaultOpenAPIBuilder the default open api builder * @param requestBuilder the request builder * @param responseBuilder the response builder * @param operationParser the operation parser * @param springDocConfigProperties the spring doc config properties * @param springDocProviders the spring doc providers * @param springDocCustomizers the spring doc customizers */ public MultipleOpenApiResource(List<GroupedOpenApi> groupedOpenApis, ObjectFactory<OpenAPIService> defaultOpenAPIBuilder, AbstractRequestService requestBuilder, GenericResponseService responseBuilder, OperationService operationParser, SpringDocConfigProperties springDocConfigProperties, SpringDocProviders springDocProviders, SpringDocCustomizers springDocCustomizers) { this.groupedOpenApis = groupedOpenApis; this.defaultOpenAPIBuilder = defaultOpenAPIBuilder; this.requestBuilder = requestBuilder; this.responseBuilder = responseBuilder; this.operationParser = operationParser; this.springDocConfigProperties = springDocConfigProperties; this.springDocProviders = springDocProviders; this.springDocCustomizers = springDocCustomizers; } @Override public void afterPropertiesSet() { this.groupedOpenApis.forEach(groupedOpenApi -> { springDocCustomizers.getGlobalOpenApiCustomizers().ifPresent(groupedOpenApi::addAllOpenApiCustomizer); springDocCustomizers.getGlobalOperationCustomizers().ifPresent(groupedOpenApi::addAllOperationCustomizer); springDocCustomizers.getGlobalOpenApiMethodFilters().ifPresent(groupedOpenApi::addAllOpenApiMethodFilter); } ); this.groupedOpenApiResources = groupedOpenApis.stream() .collect(Collectors.toMap(GroupedOpenApi::getGroup, item -> { GroupConfig groupConfig = new GroupConfig(item.getGroup(), item.getPathsToMatch(), item.getPackagesToScan(), item.getPackagesToExclude(), item.getPathsToExclude(), item.getProducesToMatch(), item.getConsumesToMatch(), item.getHeadersToMatch(), item.getDisplayName()); springDocConfigProperties.addGroupConfig(groupConfig); return buildWebMvcOpenApiResource(item); }, (existingValue, newValue) -> { return existingValue; // choice to keep the existing value } )); } /** * Build web mvc open api resource open api resource. * * @param item the item * @return the open api resource */ private OpenApiResource buildWebMvcOpenApiResource(GroupedOpenApi item) { if (!springDocConfigProperties.isUseManagementPort() && !ACTUATOR_DEFAULT_GROUP.equals(item.getGroup())) return new OpenApiWebMvcResource(item.getGroup(), defaultOpenAPIBuilder, requestBuilder, responseBuilder, operationParser, springDocConfigProperties, springDocProviders, new SpringDocCustomizers(Optional.of(item.getOpenApiCustomizers()), Optional.of(item.getOperationCustomizers()), Optional.of(item.getRouterOperationCustomizers()), Optional.of(item.getOpenApiMethodFilters())) ); else return new OpenApiActuatorResource(item.getGroup(), defaultOpenAPIBuilder, requestBuilder, responseBuilder, operationParser, springDocConfigProperties, springDocProviders, new SpringDocCustomizers(Optional.of(item.getOpenApiCustomizers()), Optional.of(item.getOperationCustomizers()), Optional.of(item.getRouterOperationCustomizers()), Optional.of(item.getOpenApiMethodFilters())) ); } /** * Gets open api resource or throw. * * @param group the group * @return the open api resource or throw */ protected OpenApiResource getOpenApiResourceOrThrow(String group) {<FILL_FUNCTION_BODY>} }
OpenApiResource openApiResource = groupedOpenApiResources.get(group); if (openApiResource == null) { throw new OpenApiResourceNotFoundException("No OpenAPI resource found for group: " + group); } return openApiResource;
1,296
67
1,363
<no_super_class>
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webmvc-api/src/main/java/org/springdoc/webmvc/api/OpenApiWebMvcResource.java
OpenApiWebMvcResource
getServerUrl
class OpenApiWebMvcResource extends OpenApiResource { /** * Instantiates a new Open api web mvc resource. * * @param groupName the group name * @param openAPIBuilderObjectFactory the open api builder object factory * @param requestBuilder the request builder * @param responseBuilder the response builder * @param operationParser the operation parser * @param springDocConfigProperties the spring doc config properties * @param springDocProviders the spring doc providers * @param springDocCustomizers the spring doc customizers */ public OpenApiWebMvcResource(String groupName, ObjectFactory<OpenAPIService> openAPIBuilderObjectFactory, AbstractRequestService requestBuilder, GenericResponseService responseBuilder, OperationService operationParser, SpringDocConfigProperties springDocConfigProperties, SpringDocProviders springDocProviders, SpringDocCustomizers springDocCustomizers) { super(groupName, openAPIBuilderObjectFactory, requestBuilder, responseBuilder, operationParser, springDocConfigProperties, springDocProviders,springDocCustomizers); } /** * Instantiates a new Open api web mvc resource. * * @param openAPIBuilderObjectFactory the open api builder object factory * @param requestBuilder the request builder * @param responseBuilder the response builder * @param operationParser the operation parser * @param springDocConfigProperties the spring doc config properties * @param springDocProviders the spring doc providers * @param springDocCustomizers the spring doc customizers */ @Autowired public OpenApiWebMvcResource(ObjectFactory<OpenAPIService> openAPIBuilderObjectFactory, AbstractRequestService requestBuilder, GenericResponseService responseBuilder, OperationService operationParser, SpringDocConfigProperties springDocConfigProperties, SpringDocProviders springDocProviders, SpringDocCustomizers springDocCustomizers) { super(openAPIBuilderObjectFactory, requestBuilder, responseBuilder, operationParser, springDocConfigProperties, springDocProviders, springDocCustomizers); } /** * Openapi json string. * * @param request the request * @param apiDocsUrl the api docs url * @param locale the locale * @return the string * @throws JsonProcessingException the json processing exception */ @Operation(hidden = true) @GetMapping(value = API_DOCS_URL, produces = MediaType.APPLICATION_JSON_VALUE) @Override public byte[] openapiJson(HttpServletRequest request, @Value(API_DOCS_URL) String apiDocsUrl, Locale locale) throws JsonProcessingException { return super.openapiJson(request, apiDocsUrl, locale); } /** * Openapi yaml string. * * @param request the request * @param apiDocsUrl the api docs url * @param locale the locale * @return the string * @throws JsonProcessingException the json processing exception */ @Operation(hidden = true) @GetMapping(value = DEFAULT_API_DOCS_URL_YAML, produces = APPLICATION_OPENAPI_YAML) @Override public byte[] openapiYaml(HttpServletRequest request, @Value(DEFAULT_API_DOCS_URL_YAML) String apiDocsUrl, Locale locale) throws JsonProcessingException { return super.openapiYaml(request, apiDocsUrl, locale); } /** * Gets server url. * * @param request the request * @param apiDocsUrl the api docs url * @return the server url */ @Override protected String getServerUrl(HttpServletRequest request, String apiDocsUrl) {<FILL_FUNCTION_BODY>} }
String requestUrl = decode(request.getRequestURL().toString()); Optional<SpringWebProvider> springWebProviderOptional = springDocProviders.getSpringWebProvider(); String prefix = StringUtils.EMPTY; if (springWebProviderOptional.isPresent()) prefix = springWebProviderOptional.get().findPathPrefix(springDocConfigProperties); return requestUrl.substring(0, requestUrl.length() - apiDocsUrl.length() - prefix.length());
918
120
1,038
<methods>public void <init>(java.lang.String, ObjectFactory<org.springdoc.core.service.OpenAPIService>, org.springdoc.core.service.AbstractRequestService, org.springdoc.core.service.GenericResponseService, org.springdoc.core.service.OperationService, org.springdoc.core.properties.SpringDocConfigProperties, org.springdoc.core.providers.SpringDocProviders, org.springdoc.core.customizers.SpringDocCustomizers) ,public void <init>(ObjectFactory<org.springdoc.core.service.OpenAPIService>, org.springdoc.core.service.AbstractRequestService, org.springdoc.core.service.GenericResponseService, org.springdoc.core.service.OperationService, org.springdoc.core.properties.SpringDocConfigProperties, org.springdoc.core.providers.SpringDocProviders, org.springdoc.core.customizers.SpringDocCustomizers) ,public byte[] openapiJson(jakarta.servlet.http.HttpServletRequest, java.lang.String, java.util.Locale) throws com.fasterxml.jackson.core.JsonProcessingException,public byte[] openapiYaml(jakarta.servlet.http.HttpServletRequest, java.lang.String, java.util.Locale) throws com.fasterxml.jackson.core.JsonProcessingException<variables>
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webmvc-api/src/main/java/org/springdoc/webmvc/core/configuration/MultipleOpenApiSupportConfiguration.java
MultipleOpenApiSupportConfiguration
multipleOpenApiResource
class MultipleOpenApiSupportConfiguration { /** * Multiple open api resource multiple open api resource. * * @param groupedOpenApis the grouped open apis * @param defaultOpenAPIBuilder the default open api builder * @param requestBuilder the request builder * @param responseBuilder the response builder * @param operationParser the operation parser * @param springDocConfigProperties the spring doc config properties * @param springDocProviders the spring doc providers * @param springDocCustomizers the spring doc customizers * @return the multiple open api resource */ @Bean @ConditionalOnMissingBean @ConditionalOnProperty(name = SPRINGDOC_USE_MANAGEMENT_PORT, havingValue = "false", matchIfMissing = true) @Lazy(false) MultipleOpenApiWebMvcResource multipleOpenApiResource(List<GroupedOpenApi> groupedOpenApis, ObjectFactory<OpenAPIService> defaultOpenAPIBuilder, AbstractRequestService requestBuilder, GenericResponseService responseBuilder, OperationService operationParser, SpringDocConfigProperties springDocConfigProperties, SpringDocProviders springDocProviders, SpringDocCustomizers springDocCustomizers) {<FILL_FUNCTION_BODY>} /** * The type Spring doc web mvc actuator different configuration. * @author bnasslashen */ @ConditionalOnClass(WebMvcEndpointHandlerMapping.class) @ConditionalOnManagementPort(ManagementPortType.DIFFERENT) static class SpringDocWebMvcActuatorDifferentConfiguration { /** * Multiple open api actuator resource multiple open api actuator resource. * * @param groupedOpenApis the grouped open apis * @param defaultOpenAPIBuilder the default open api builder * @param requestBuilder the request builder * @param responseBuilder the response builder * @param operationParser the operation parser * @param springDocConfigProperties the spring doc config properties * @param springDocProviders the spring doc providers * @param springDocCustomizers the spring doc customizers * @return the multiple open api actuator resource */ @Bean @ConditionalOnMissingBean @ConditionalOnProperty(SPRINGDOC_USE_MANAGEMENT_PORT) @Lazy(false) MultipleOpenApiActuatorResource multipleOpenApiActuatorResource(List<GroupedOpenApi> groupedOpenApis, ObjectFactory<OpenAPIService> defaultOpenAPIBuilder, AbstractRequestService requestBuilder, GenericResponseService responseBuilder, OperationService operationParser, SpringDocConfigProperties springDocConfigProperties, SpringDocProviders springDocProviders, SpringDocCustomizers springDocCustomizers) { return new MultipleOpenApiActuatorResource(groupedOpenApis, defaultOpenAPIBuilder, requestBuilder, responseBuilder, operationParser, springDocConfigProperties, springDocProviders, springDocCustomizers); } } }
return new MultipleOpenApiWebMvcResource(groupedOpenApis, defaultOpenAPIBuilder, requestBuilder, responseBuilder, operationParser, springDocConfigProperties, springDocProviders, springDocCustomizers);
735
63
798
<no_super_class>
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webmvc-api/src/main/java/org/springdoc/webmvc/core/configuration/SpringDocWebMvcConfiguration.java
SpringDocWebMvcActuatorConfiguration
openApiActuatorResource
class SpringDocWebMvcActuatorConfiguration { /** * Actuator provider actuator provider. * * @param serverProperties the server properties * @param springDocConfigProperties the spring doc config properties * @param managementServerProperties the management server properties * @param webEndpointProperties the web endpoint properties * @param webMvcEndpointHandlerMapping the web mvc endpoint handler mapping * @param controllerEndpointHandlerMapping the controller endpoint handler mapping * @return the actuator provider */ @Bean @ConditionalOnMissingBean @ConditionalOnExpression("${springdoc.show-actuator:false} or ${springdoc.use-management-port:false}") @Lazy(false) ActuatorProvider actuatorProvider(ServerProperties serverProperties, SpringDocConfigProperties springDocConfigProperties, Optional<ManagementServerProperties> managementServerProperties, Optional<WebEndpointProperties> webEndpointProperties, Optional<WebMvcEndpointHandlerMapping> webMvcEndpointHandlerMapping, Optional<ControllerEndpointHandlerMapping> controllerEndpointHandlerMapping) { return new ActuatorWebMvcProvider(serverProperties, springDocConfigProperties, managementServerProperties, webEndpointProperties, webMvcEndpointHandlerMapping, controllerEndpointHandlerMapping); } /** * Open api actuator resource open api actuator resource. * * @param openAPIBuilderObjectFactory the open api builder object factory * @param requestBuilder the request builder * @param responseBuilder the response builder * @param operationParser the operation parser * @param springDocConfigProperties the spring doc config properties * @param springDocProviders the spring doc providers * @param springDocCustomizers the spring doc customizers * @return the open api actuator resource */ @Bean @ConditionalOnMissingBean(MultipleOpenApiSupportConfiguration.class) @ConditionalOnExpression("${springdoc.use-management-port:false} and ${springdoc.enable-default-api-docs:true}") @ConditionalOnManagementPort(ManagementPortType.DIFFERENT) @Lazy(false) OpenApiActuatorResource openApiActuatorResource(ObjectFactory<OpenAPIService> openAPIBuilderObjectFactory, AbstractRequestService requestBuilder, GenericResponseService responseBuilder, OperationService operationParser, SpringDocConfigProperties springDocConfigProperties, SpringDocProviders springDocProviders, SpringDocCustomizers springDocCustomizers) {<FILL_FUNCTION_BODY>} }
return new OpenApiActuatorResource(openAPIBuilderObjectFactory, requestBuilder, responseBuilder, operationParser, springDocConfigProperties, springDocProviders, springDocCustomizers);
634
54
688
<no_super_class>
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webmvc-api/src/main/java/org/springdoc/webmvc/core/providers/ActuatorWebMvcProvider.java
ActuatorWebMvcProvider
getMethods
class ActuatorWebMvcProvider extends ActuatorProvider { /** * The Web mvc endpoint handler mapping. */ private WebMvcEndpointHandlerMapping webMvcEndpointHandlerMapping; /** * The Controller endpoint handler mapping. */ private ControllerEndpointHandlerMapping controllerEndpointHandlerMapping; /** * Instantiates a new Actuator web mvc provider. * * @param serverProperties the server properties * @param springDocConfigProperties the spring doc config properties * @param managementServerProperties the management server properties * @param webEndpointProperties the web endpoint properties * @param webMvcEndpointHandlerMapping the web mvc endpoint handler mapping * @param controllerEndpointHandlerMapping the controller endpoint handler mapping */ public ActuatorWebMvcProvider(ServerProperties serverProperties, SpringDocConfigProperties springDocConfigProperties, Optional<ManagementServerProperties> managementServerProperties, Optional<WebEndpointProperties> webEndpointProperties, Optional<WebMvcEndpointHandlerMapping> webMvcEndpointHandlerMapping, Optional<ControllerEndpointHandlerMapping> controllerEndpointHandlerMapping) { super(managementServerProperties, webEndpointProperties, serverProperties, springDocConfigProperties); webMvcEndpointHandlerMapping.ifPresent(webMvcEndpointHandlerMapping1 -> this.webMvcEndpointHandlerMapping = webMvcEndpointHandlerMapping1); controllerEndpointHandlerMapping.ifPresent(controllerEndpointHandlerMapping1 -> this.controllerEndpointHandlerMapping = controllerEndpointHandlerMapping1); } @Override public Map<RequestMappingInfo, HandlerMethod> getMethods() {<FILL_FUNCTION_BODY>} @Override public String getContextPath() { return StringUtils.defaultIfEmpty(serverProperties.getServlet().getContextPath(), EMPTY); } }
Map<RequestMappingInfo, HandlerMethod> mappingInfoHandlerMethodMap = new HashMap<>(); if (webMvcEndpointHandlerMapping == null) webMvcEndpointHandlerMapping = managementApplicationContext.getBean(WebMvcEndpointHandlerMapping.class); mappingInfoHandlerMethodMap.putAll(webMvcEndpointHandlerMapping.getHandlerMethods()); if (controllerEndpointHandlerMapping == null) controllerEndpointHandlerMapping = managementApplicationContext.getBean(ControllerEndpointHandlerMapping.class); mappingInfoHandlerMethodMap.putAll(controllerEndpointHandlerMapping.getHandlerMethods()); return mappingInfoHandlerMethodMap;
433
155
588
<methods>public void <init>(Optional<org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties>, Optional<org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties>, org.springframework.boot.autoconfigure.web.ServerProperties, org.springdoc.core.properties.SpringDocConfigProperties) ,public java.lang.String getActuatorPath() ,public int getActuatorPort() ,public int getApplicationPort() ,public java.lang.String getBasePath() ,public java.lang.String getContextPath() ,public abstract Map#RAW getMethods() ,public static io.swagger.v3.oas.models.tags.Tag getTag() ,public boolean isRestController(java.lang.String, org.springframework.web.method.HandlerMethod) ,public boolean isUseManagementPort() ,public void onApplicationEvent(org.springframework.boot.web.context.WebServerInitializedEvent) <variables>protected org.springframework.boot.web.server.WebServer actuatorWebServer,protected org.springframework.boot.web.server.WebServer applicationWebServer,protected org.springframework.context.ApplicationContext managementApplicationContext,protected org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties managementServerProperties,protected org.springframework.boot.autoconfigure.web.ServerProperties serverProperties,protected org.springdoc.core.properties.SpringDocConfigProperties springDocConfigProperties,protected org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties webEndpointProperties
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webmvc-api/src/main/java/org/springdoc/webmvc/core/providers/RouterFunctionWebMvcProvider.java
RouterFunctionWebMvcProvider
getRouterFunctionPaths
class RouterFunctionWebMvcProvider implements RouterFunctionProvider, ApplicationContextAware { /** * The Application context. */ private ApplicationContext applicationContext; /** * Gets web mvc router function paths. * * @return the web mvc router function paths */ public Optional<Map<String, AbstractRouterFunctionVisitor>> getRouterFunctionPaths() {<FILL_FUNCTION_BODY>} @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /** * The type Router function visitor. * @author bnasslahsen */ private class RouterFunctionVisitor extends AbstractRouterFunctionVisitor implements RouterFunctions.Visitor, RequestPredicates.Visitor { @Override public void route(RequestPredicate predicate, HandlerFunction<?> handlerFunction) { this.currentRouterFunctionDatas = new ArrayList<>(); predicate.accept(this); commonRoute(); } @Override public void resources(Function<ServerRequest, Optional<Resource>> lookupFunction) { // Not yet needed } @Override public void unknown(RouterFunction<?> routerFunction) { // Not yet needed } @Override public void unknown(RequestPredicate predicate) { // Not yet needed } @Override public void startNested(RequestPredicate predicate) { commonStartNested(); predicate.accept(this); } @Override public void endNested(RequestPredicate predicate) { commonEndNested(); } } }
Map<String, RouterFunction> routerBeans = applicationContext.getBeansOfType(RouterFunction.class); if (CollectionUtils.isEmpty(routerBeans)) return Optional.empty(); Map<String, AbstractRouterFunctionVisitor> routerFunctionVisitorMap = new HashMap<>(); for (Map.Entry<String, RouterFunction> entry : routerBeans.entrySet()) { RouterFunction routerFunction = entry.getValue(); RouterFunctionVisitor routerFunctionVisitor = new RouterFunctionVisitor(); routerFunction.accept(routerFunctionVisitor); routerFunctionVisitorMap.put(entry.getKey(), routerFunctionVisitor); } return Optional.of(routerFunctionVisitorMap);
423
185
608
<no_super_class>
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webmvc-api/src/main/java/org/springdoc/webmvc/core/providers/SpringWebMvcProvider.java
SpringWebMvcProvider
getActivePatterns
class SpringWebMvcProvider extends SpringWebProvider { /** * Finds path prefix. * * @param springDocConfigProperties the spring doc config properties * @return the path prefix */ @Override public String findPathPrefix(SpringDocConfigProperties springDocConfigProperties) { Map<RequestMappingInfo, HandlerMethod> map = getHandlerMethods(); for (Entry<RequestMappingInfo, HandlerMethod> entry : map.entrySet()) { RequestMappingInfo requestMappingInfo = entry.getKey(); Set<String> patterns = getActivePatterns(requestMappingInfo); if (!CollectionUtils.isEmpty(patterns)) { for (String operationPath : patterns) { if (operationPath.endsWith(springDocConfigProperties.getApiDocs().getPath())) return operationPath.replace(springDocConfigProperties.getApiDocs().getPath(), StringUtils.EMPTY); } } } return StringUtils.EMPTY; } /** * Gets active patterns. * * @param requestMapping the request mapping info * @return the active patterns */ public Set<String> getActivePatterns(Object requestMapping) {<FILL_FUNCTION_BODY>} /** * Gets handler methods. * * @return the handler methods */ @Override public Map getHandlerMethods() { if (this.handlerMethods == null) { Map<String, RequestMappingHandlerMapping> beansOfTypeRequestMappingHandlerMapping = applicationContext.getBeansOfType(RequestMappingHandlerMapping.class); this.handlerMethods = beansOfTypeRequestMappingHandlerMapping.values().stream() .map(AbstractHandlerMethodMapping::getHandlerMethods) .map(Map::entrySet) .flatMap(Collection::stream) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a1, a2) -> a1, LinkedHashMap::new)); } return this.handlerMethods; } }
Set<String> patterns = null; RequestMappingInfo requestMappingInfo = (RequestMappingInfo) requestMapping; PatternsRequestCondition patternsRequestCondition = requestMappingInfo.getPatternsCondition(); if (patternsRequestCondition != null) patterns = patternsRequestCondition.getPatterns(); else { PathPatternsRequestCondition pathPatternsRequestCondition = requestMappingInfo.getPathPatternsCondition(); if (pathPatternsRequestCondition != null) patterns = pathPatternsRequestCondition.getPatternValues(); } return patterns;
499
143
642
<methods>public non-sealed void <init>() ,public abstract java.lang.String findPathPrefix(org.springdoc.core.properties.SpringDocConfigProperties) ,public abstract Set<java.lang.String> getActivePatterns(java.lang.Object) ,public abstract Map#RAW getHandlerMethods() ,public void setApplicationContext(org.springframework.context.ApplicationContext) throws org.springframework.beans.BeansException<variables>protected org.springframework.context.ApplicationContext applicationContext,protected Map#RAW handlerMethods
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webmvc-ui/src/main/java/org/springdoc/webmvc/ui/SwaggerIndexPageTransformer.java
SwaggerIndexPageTransformer
transform
class SwaggerIndexPageTransformer extends AbstractSwaggerIndexTransformer implements SwaggerIndexTransformer { /** * The Swagger welcome common. */ private final SwaggerWelcomeCommon swaggerWelcomeCommon; /** * Instantiates a new Swagger index transformer. * @param swaggerUiConfig the swagger ui config * @param swaggerUiOAuthProperties the swagger ui o auth properties * @param swaggerUiConfigParameters the swagger ui config parameters * @param swaggerWelcomeCommon the swagger welcome common * @param objectMapperProvider the object mapper provider */ public SwaggerIndexPageTransformer(SwaggerUiConfigProperties swaggerUiConfig, SwaggerUiOAuthProperties swaggerUiOAuthProperties, SwaggerUiConfigParameters swaggerUiConfigParameters, SwaggerWelcomeCommon swaggerWelcomeCommon, ObjectMapperProvider objectMapperProvider) { super(swaggerUiConfig, swaggerUiOAuthProperties, swaggerUiConfigParameters, objectMapperProvider); this.swaggerWelcomeCommon = swaggerWelcomeCommon; } @Override public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain) throws IOException {<FILL_FUNCTION_BODY>} }
if (swaggerUiConfigParameters.getConfigUrl() == null) swaggerWelcomeCommon.buildFromCurrentContextPath(request); final AntPathMatcher antPathMatcher = new AntPathMatcher(); boolean isIndexFound = antPathMatcher.match("**/swagger-ui/**/" + SWAGGER_INITIALIZER_JS, resource.getURL().toString()); if (isIndexFound) { String html = defaultTransformations(resource.getInputStream()); return new TransformedResource(resource, html.getBytes(StandardCharsets.UTF_8)); } else return resource;
306
158
464
<methods>public void <init>(org.springdoc.core.properties.SwaggerUiConfigProperties, org.springdoc.core.properties.SwaggerUiOAuthProperties, org.springdoc.core.properties.SwaggerUiConfigParameters, org.springdoc.core.providers.ObjectMapperProvider) <variables>private static final java.lang.String PRESETS,protected com.fasterxml.jackson.databind.ObjectMapper objectMapper,protected org.springdoc.core.properties.SwaggerUiConfigProperties swaggerUiConfig,protected org.springdoc.core.properties.SwaggerUiConfigParameters swaggerUiConfigParameters,protected org.springdoc.core.properties.SwaggerUiOAuthProperties swaggerUiOAuthProperties
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webmvc-ui/src/main/java/org/springdoc/webmvc/ui/SwaggerResourceResolver.java
SwaggerResourceResolver
resolveUrlPath
class SwaggerResourceResolver extends AbstractSwaggerResourceResolver implements ResourceResolver { /** * Instantiates a new Web jars version resource resolver. * * @param swaggerUiConfigProperties the swagger ui config properties */ public SwaggerResourceResolver(SwaggerUiConfigProperties swaggerUiConfigProperties) { super(swaggerUiConfigProperties); } @Override public Resource resolveResource(HttpServletRequest request, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) { Resource resolved = chain.resolveResource(request, requestPath, locations); if (resolved == null) { String webJarResourcePath = findWebJarResourcePath(requestPath); if (webJarResourcePath != null) return chain.resolveResource(request, webJarResourcePath, locations); } return resolved; } @Override public String resolveUrlPath(String resourcePath, List<? extends Resource> locations, ResourceResolverChain chain) {<FILL_FUNCTION_BODY>} }
String path = chain.resolveUrlPath(resourcePath, locations); if (path == null) { String webJarResourcePath = findWebJarResourcePath(resourcePath); if (webJarResourcePath != null) return chain.resolveUrlPath(webJarResourcePath, locations); } return path;
255
85
340
<methods>public void <init>(org.springdoc.core.properties.SwaggerUiConfigProperties) <variables>private final non-sealed org.springdoc.core.properties.SwaggerUiConfigProperties swaggerUiConfigProperties
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webmvc-ui/src/main/java/org/springdoc/webmvc/ui/SwaggerUiHome.java
SwaggerUiHome
index
class SwaggerUiHome { @Value(SWAGGER_UI_PATH) private String swaggerUiPath; @Value(MVC_SERVLET_PATH) private String mvcServletPath; /** * Index string. * * @return the string */ @GetMapping(DEFAULT_PATH_SEPARATOR) @Operation(hidden = true) public String index() {<FILL_FUNCTION_BODY>} }
StringBuilder uiRootPath = new StringBuilder(); if (SpringDocUtils.isValidPath(mvcServletPath)) uiRootPath.append(mvcServletPath); return REDIRECT_URL_PREFIX + uiRootPath + swaggerUiPath;
115
71
186
<no_super_class>
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webmvc-ui/src/main/java/org/springdoc/webmvc/ui/SwaggerWebMvcConfigurer.java
SwaggerWebMvcConfigurer
configureDefaultServletHandling
class SwaggerWebMvcConfigurer implements WebMvcConfigurer { /** * The Swagger path. */ private final String swaggerPath; /** * The Swagger index transformer. */ private final SwaggerIndexTransformer swaggerIndexTransformer; /** * The Actuator provider. */ private final Optional<ActuatorProvider> actuatorProvider; /** * The Swagger resource resolver. */ private final SwaggerResourceResolver swaggerResourceResolver; /** * Instantiates a new Swagger web mvc configurer. * * @param swaggerUiConfigParameters the swagger ui calculated config * @param swaggerIndexTransformer the swagger index transformer * @param actuatorProvider the actuator provider * @param swaggerResourceResolver the swagger resource resolver */ public SwaggerWebMvcConfigurer(SwaggerUiConfigParameters swaggerUiConfigParameters, SwaggerIndexTransformer swaggerIndexTransformer, Optional<ActuatorProvider> actuatorProvider, SwaggerResourceResolver swaggerResourceResolver) { this.swaggerPath = swaggerUiConfigParameters.getPath(); this.swaggerIndexTransformer = swaggerIndexTransformer; this.actuatorProvider = actuatorProvider; this.swaggerResourceResolver = swaggerResourceResolver; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { StringBuilder uiRootPath = new StringBuilder(); if (swaggerPath.contains(DEFAULT_PATH_SEPARATOR)) uiRootPath.append(swaggerPath, 0, swaggerPath.lastIndexOf(DEFAULT_PATH_SEPARATOR)); if (actuatorProvider.isPresent() && actuatorProvider.get().isUseManagementPort()) uiRootPath.append(actuatorProvider.get().getBasePath()); registry.addResourceHandler(uiRootPath + SWAGGER_UI_PREFIX + "*/*" + SWAGGER_INITIALIZER_JS) .addResourceLocations(CLASSPATH_RESOURCE_LOCATION + DEFAULT_WEB_JARS_PREFIX_URL + DEFAULT_PATH_SEPARATOR) .setCachePeriod(0) .resourceChain(false) .addResolver(swaggerResourceResolver) .addTransformer(swaggerIndexTransformer); registry.addResourceHandler(uiRootPath + SWAGGER_UI_PREFIX + "*/**") .addResourceLocations(CLASSPATH_RESOURCE_LOCATION + DEFAULT_WEB_JARS_PREFIX_URL + DEFAULT_PATH_SEPARATOR) .resourceChain(false) .addResolver(swaggerResourceResolver) .addTransformer(swaggerIndexTransformer); } @Override public void configurePathMatch(PathMatchConfigurer configurer) { // This implementation is empty to keep compatibility with spring 4 applications. } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { // This implementation is empty to keep compatibility with spring 4 applications. } @Override public void configureAsyncSupport(AsyncSupportConfigurer configurer) { // This implementation is empty to keep compatibility with spring 4 applications. } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {<FILL_FUNCTION_BODY>} @Override public void addFormatters(FormatterRegistry registry) { // This implementation is empty to keep compatibility with spring 4 applications. } @Override public void addInterceptors(InterceptorRegistry registry) { // This implementation is empty to keep compatibility with spring 4 applications. } @Override public void addCorsMappings(CorsRegistry registry) { // This implementation is empty to keep compatibility with spring 4 applications. } @Override public void addViewControllers(ViewControllerRegistry registry) { // This implementation is empty to keep compatibility with spring 4 applications. } @Override public void configureViewResolvers(ViewResolverRegistry registry) { // This implementation is empty to keep compatibility with spring 4 applications. } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { // This implementation is empty to keep compatibility with spring 4 applications. } @Override public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) { // This implementation is empty to keep compatibility with spring 4 applications. } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { // This implementation is empty to keep compatibility with spring 4 applications. } @Override public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { // This implementation is empty to keep compatibility with spring 4 applications. } @Override public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { // This implementation is empty to keep compatibility with spring 4 applications. } @Override public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { // This implementation is empty to keep compatibility with spring 4 applications. } @Override @Nullable public Validator getValidator() { // This implementation is empty to keep compatibility with spring 4 applications. return null; } @Override @Nullable public MessageCodesResolver getMessageCodesResolver() { // This implementation is empty to keep compatibility with spring 4 applications. return null; } }
// This implementation is empty to keep compatibility with spring 4 applications.
1,359
19
1,378
<no_super_class>
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webmvc-ui/src/main/java/org/springdoc/webmvc/ui/SwaggerWelcomeActuator.java
SwaggerWelcomeActuator
buildSwaggerConfigUrl
class SwaggerWelcomeActuator extends SwaggerWelcomeCommon { private static final String SWAGGER_CONFIG_ACTUATOR_URL = DEFAULT_PATH_SEPARATOR + SWAGGER_CONFIG_FILE; /** * The Web endpoint properties. */ private final WebEndpointProperties webEndpointProperties; /** * Instantiates a new Swagger welcome. * @param swaggerUiConfig the swagger ui config * @param springDocConfigProperties the spring doc config properties * @param swaggerUiConfigParameters the swagger ui config parameters * @param webEndpointProperties the web endpoint properties */ public SwaggerWelcomeActuator(SwaggerUiConfigProperties swaggerUiConfig, SpringDocConfigProperties springDocConfigProperties, SwaggerUiConfigParameters swaggerUiConfigParameters, WebEndpointProperties webEndpointProperties) { super(swaggerUiConfig, springDocConfigProperties, swaggerUiConfigParameters); this.webEndpointProperties = webEndpointProperties; } /** * Redirect to ui string. * * @param request the request * @return the string */ @Operation(hidden = true) @GetMapping(DEFAULT_PATH_SEPARATOR) @Override public ResponseEntity<Void> redirectToUi(HttpServletRequest request) { return super.redirectToUi(request); } /** * Openapi yaml map. * * @param request the request * @return the map */ @Operation(hidden = true) @GetMapping(value = SWAGGER_CONFIG_ACTUATOR_URL, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @Override public Map<String, Object> openapiJson(HttpServletRequest request) { return super.openapiJson(request); } @Override protected void calculateUiRootPath(StringBuilder... sbUrls) { StringBuilder sbUrl = new StringBuilder(); sbUrl.append(webEndpointProperties.getBasePath()); calculateUiRootCommon(sbUrl, sbUrls); } @Override protected String buildApiDocUrl() { return buildUrl(contextPath + webEndpointProperties.getBasePath(), DEFAULT_API_DOCS_ACTUATOR_URL); } @Override protected String buildUrlWithContextPath(String swaggerUiUrl) { return buildUrl(contextPath + webEndpointProperties.getBasePath(), swaggerUiUrl); } @Override protected String buildSwaggerConfigUrl() {<FILL_FUNCTION_BODY>} }
return contextPath + webEndpointProperties.getBasePath() + DEFAULT_PATH_SEPARATOR + DEFAULT_SWAGGER_UI_ACTUATOR_PATH + DEFAULT_PATH_SEPARATOR + SWAGGER_CONFIG_FILE;
629
60
689
<methods>public void <init>(org.springdoc.core.properties.SwaggerUiConfigProperties, org.springdoc.core.properties.SpringDocConfigProperties, org.springdoc.core.properties.SwaggerUiConfigParameters) <variables>
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webmvc-ui/src/main/java/org/springdoc/webmvc/ui/SwaggerWelcomeCommon.java
SwaggerWelcomeCommon
redirectToUi
class SwaggerWelcomeCommon extends AbstractSwaggerWelcome { /** * Instantiates a new Abstract swagger welcome. * @param swaggerUiConfig the swagger ui config * @param springDocConfigProperties the spring doc config properties * @param swaggerUiConfigParameters the swagger ui config parameters */ public SwaggerWelcomeCommon(SwaggerUiConfigProperties swaggerUiConfig, SpringDocConfigProperties springDocConfigProperties, SwaggerUiConfigParameters swaggerUiConfigParameters) { super(swaggerUiConfig, springDocConfigProperties, swaggerUiConfigParameters); } /** * Redirect to ui response entity. * * @param request the request * @return the response entity */ protected ResponseEntity<Void> redirectToUi(HttpServletRequest request) {<FILL_FUNCTION_BODY>} /** * Openapi json map. * * @param request the request * @return the map */ protected Map<String, Object> openapiJson(HttpServletRequest request) { buildFromCurrentContextPath(request); return swaggerUiConfigParameters.getConfigParameters(); } @Override protected void calculateOauth2RedirectUrl(UriComponentsBuilder uriComponentsBuilder) { if (StringUtils.isBlank(swaggerUiConfig.getOauth2RedirectUrl()) || !swaggerUiConfigParameters.isValidUrl(swaggerUiConfig.getOauth2RedirectUrl())) swaggerUiConfigParameters.setOauth2RedirectUrl(uriComponentsBuilder .path(swaggerUiConfigParameters.getUiRootPath()) .path(getOauth2RedirectUrl()).build().toString()); } /** * From current context path. * * @param request the request */ void buildFromCurrentContextPath(HttpServletRequest request) { super.init(); contextPath = request.getContextPath(); buildConfigUrl(ServletUriComponentsBuilder.fromCurrentContextPath()); } }
buildFromCurrentContextPath(request); String sbUrl = contextPath + swaggerUiConfigParameters.getUiRootPath() + getSwaggerUiUrl(); UriComponentsBuilder uriBuilder = getUriComponentsBuilder(sbUrl); // forward all queryParams from original request request.getParameterMap().forEach(uriBuilder::queryParam); return ResponseEntity.status(HttpStatus.FOUND) .location(uriBuilder.build().encode().toUri()) .build();
508
126
634
<methods>public void <init>(org.springdoc.core.properties.SwaggerUiConfigProperties, org.springdoc.core.properties.SpringDocConfigProperties, org.springdoc.core.properties.SwaggerUiConfigParameters) <variables>protected java.lang.String apiDocsUrl,protected java.lang.String contextPath,protected final non-sealed org.springdoc.core.properties.SpringDocConfigProperties springDocConfigProperties,protected java.lang.String swaggerConfigUrl,protected final non-sealed org.springdoc.core.properties.SwaggerUiConfigProperties swaggerUiConfig,protected final non-sealed org.springdoc.core.properties.SwaggerUiConfigParameters swaggerUiConfigParameters
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webmvc-ui/src/main/java/org/springdoc/webmvc/ui/SwaggerWelcomeWebMvc.java
SwaggerWelcomeWebMvc
buildUrlWithContextPath
class SwaggerWelcomeWebMvc extends SwaggerWelcomeCommon { /** * The Spring web provider. */ private final SpringWebProvider springWebProvider; /** * The Mvc servlet path. */ // To keep compatibility with spring-boot 1 - WebMvcProperties changed package from spring 4 to spring 5 @Value(MVC_SERVLET_PATH) private String mvcServletPath; /** * The Path prefix. */ private String pathPrefix; /** * Instantiates a new Swagger welcome web mvc. * @param swaggerUiConfig the swagger ui config * @param springDocConfigProperties the spring doc config properties * @param swaggerUiConfigParameters the swagger ui config parameters * @param springWebProvider the spring web provider */ public SwaggerWelcomeWebMvc(SwaggerUiConfigProperties swaggerUiConfig, SpringDocConfigProperties springDocConfigProperties, SwaggerUiConfigParameters swaggerUiConfigParameters, SpringWebProvider springWebProvider) { super(swaggerUiConfig, springDocConfigProperties, swaggerUiConfigParameters); this.springWebProvider = springWebProvider; } /** * Redirect to ui string. * * @param request the request * @return the string */ @Operation(hidden = true) @GetMapping(SWAGGER_UI_PATH) @Override public ResponseEntity<Void> redirectToUi(HttpServletRequest request) { return super.redirectToUi(request); } /** * Calculate ui root path. * * @param sbUrls the sb urls */ @Override protected void calculateUiRootPath(StringBuilder... sbUrls) { StringBuilder sbUrl = new StringBuilder(); if (SpringDocUtils.isValidPath(mvcServletPath)) sbUrl.append(mvcServletPath); calculateUiRootCommon(sbUrl, sbUrls); } /** * Build url string. * * @param contextPath the context path * @param docsUrl the docs url * @return the string */ @Override protected String buildUrl(String contextPath, final String docsUrl) { if (SpringDocUtils.isValidPath(mvcServletPath)) contextPath += mvcServletPath; return super.buildUrl(contextPath, docsUrl); } /** * Build api doc url string. * * @return the string */ @Override protected String buildApiDocUrl() { return buildUrlWithContextPath(springDocConfigProperties.getApiDocs().getPath()); } @Override protected String buildUrlWithContextPath(String swaggerUiUrl) {<FILL_FUNCTION_BODY>} /** * Build swagger config url string. * * @return the string */ @Override protected String buildSwaggerConfigUrl() { return apiDocsUrl + DEFAULT_PATH_SEPARATOR + SWAGGER_CONFIG_FILE; } }
if (this.pathPrefix == null) this.pathPrefix = springWebProvider.findPathPrefix(springDocConfigProperties); return buildUrl(contextPath + pathPrefix, swaggerUiUrl);
767
52
819
<methods>public void <init>(org.springdoc.core.properties.SwaggerUiConfigProperties, org.springdoc.core.properties.SpringDocConfigProperties, org.springdoc.core.properties.SwaggerUiConfigParameters) <variables>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/BusyHandler.java
BusyHandler
commitHandler
class BusyHandler { /** * commit the busy handler for the connection. * * @param conn the SQLite connection * @param busyHandler the busyHandler * @throws SQLException */ private static void commitHandler(Connection conn, BusyHandler busyHandler) throws SQLException {<FILL_FUNCTION_BODY>} /** * Sets a busy handler for the connection. * * @param conn the SQLite connection * @param busyHandler the busyHandler * @throws SQLException */ public static final void setHandler(Connection conn, BusyHandler busyHandler) throws SQLException { commitHandler(conn, busyHandler); } /** * Clears any busy handler registered with the connection. * * @param conn the SQLite connection * @throws SQLException */ public static final void clearHandler(Connection conn) throws SQLException { commitHandler(conn, null); } /** * https://www.sqlite.org/c3ref/busy_handler.html * * @param nbPrevInvok number of times that the busy handler has been invoked previously for the * same locking event * @throws SQLException * @return If the busy callback returns 0, then no additional attempts are made to access the * database and SQLITE_BUSY is returned to the application. If the callback returns * non-zero, then another attempt is made to access the database and the cycle repeats. */ protected abstract int callback(int nbPrevInvok) throws SQLException; }
if (!(conn instanceof SQLiteConnection)) { throw new SQLException("connection must be to an SQLite db"); } if (conn.isClosed()) { throw new SQLException("connection closed"); } SQLiteConnection sqliteConnection = (SQLiteConnection) conn; sqliteConnection.getDatabase().busy_handler(busyHandler);
400
95
495
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/Collation.java
Collation
create
class Collation { private SQLiteConnection conn; private DB db; /** * Registers a given collation with the connection. * * @param conn The connection. * @param name The name of the collation. * @param f The collation to register. */ public static final void create(Connection conn, String name, Collation f) throws SQLException {<FILL_FUNCTION_BODY>} /** * Removes a named collation from the given connection. * * @param conn The connection to remove the collation from. * @param name The name of the collation. * @throws SQLException */ public static final void destroy(Connection conn, String name) throws SQLException { if (conn == null || !(conn instanceof SQLiteConnection)) { throw new SQLException("connection must be to an SQLite db"); } ((SQLiteConnection) conn).getDatabase().destroy_collation(name); } /** * Called by SQLite as a custom collation to compare two strings. * * @param str1 the first string in the comparison * @param str2 the second string in the comparison * @return an integer that is negative, zero, or positive if the first string is less than, * equal to, or greater than the second, respectively */ protected abstract int xCompare(String str1, String str2); }
if (conn == null || !(conn instanceof SQLiteConnection)) { throw new SQLException("connection must be to an SQLite db"); } if (conn.isClosed()) { throw new SQLException("connection closed"); } f.conn = (SQLiteConnection) conn; f.db = f.conn.getDatabase(); if (f.db.create_collation(name, f) != Codes.SQLITE_OK) { throw new SQLException("error creating collation"); }
354
134
488
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/ExtendedCommand.java
ExtendedCommand
parse
class ExtendedCommand { public static interface SQLExtension { public void execute(DB db) throws SQLException; } /** * Parses extended commands of "backup" or "restore" for SQLite database. * * @param sql One of the extended commands:<br> * backup sourceDatabaseName to destinationFileName OR restore targetDatabaseName from * sourceFileName * @return BackupCommand object if the argument is a backup command; RestoreCommand object if * the argument is a restore command; * @throws SQLException */ public static SQLExtension parse(String sql) throws SQLException {<FILL_FUNCTION_BODY>} /** * Remove the quotation mark from string. * * @param s String with quotation mark. * @return String with quotation mark removed. */ public static String removeQuotation(String s) { if (s == null) return s; if ((s.startsWith("\"") && s.endsWith("\"")) || (s.startsWith("'") && s.endsWith("'"))) return s.substring(1, s.length() - 1); else return s; } public static class BackupCommand implements SQLExtension { public final String srcDB; public final String destFile; /** * Constructs a BackupCommand instance that backup the database to a target file. * * @param srcDB Source database name. * @param destFile Target file name. */ public BackupCommand(String srcDB, String destFile) { this.srcDB = srcDB; this.destFile = destFile; } private static Pattern backupCmd = Pattern.compile( "backup(\\s+(\"[^\"]*\"|'[^\']*\'|\\S+))?\\s+to\\s+(\"[^\"]*\"|'[^\']*\'|\\S+)", Pattern.CASE_INSENSITIVE); /** * Parses SQLite database backup command and creates a BackupCommand object. * * @param sql SQLite database backup command. * @return BackupCommand object. * @throws SQLException */ public static BackupCommand parse(String sql) throws SQLException { if (sql != null) { Matcher m = backupCmd.matcher(sql); if (m.matches()) { String dbName = removeQuotation(m.group(2)); String dest = removeQuotation(m.group(3)); if (dbName == null || dbName.length() == 0) dbName = "main"; return new BackupCommand(dbName, dest); } } throw new SQLException("syntax error: " + sql); } public void execute(DB db) throws SQLException { int rc = db.backup(srcDB, destFile, null); if (rc != SQLiteErrorCode.SQLITE_OK.code) { throw DB.newSQLException(rc, "Backup failed"); } } } public static class RestoreCommand implements SQLExtension { public final String targetDB; public final String srcFile; private static Pattern restoreCmd = Pattern.compile( "restore(\\s+(\"[^\"]*\"|'[^\']*\'|\\S+))?\\s+from\\s+(\"[^\"]*\"|'[^\']*\'|\\S+)", Pattern.CASE_INSENSITIVE); /** * Constructs a RestoreCommand instance that restores the database from a given source file. * * @param targetDB Target database name * @param srcFile Source file name */ public RestoreCommand(String targetDB, String srcFile) { this.targetDB = targetDB; this.srcFile = srcFile; } /** * Parses SQLite database restore command and creates a RestoreCommand object. * * @param sql SQLite restore backup command * @return RestoreCommand object. * @throws SQLException */ public static RestoreCommand parse(String sql) throws SQLException { if (sql != null) { Matcher m = restoreCmd.matcher(sql); if (m.matches()) { String dbName = removeQuotation(m.group(2)); String dest = removeQuotation(m.group(3)); if (dbName == null || dbName.length() == 0) dbName = "main"; return new RestoreCommand(dbName, dest); } } throw new SQLException("syntax error: " + sql); } /** @see org.sqlite.ExtendedCommand.SQLExtension#execute(org.sqlite.core.DB) */ public void execute(DB db) throws SQLException { int rc = db.restore(targetDB, srcFile, null); if (rc != SQLiteErrorCode.SQLITE_OK.code) { throw DB.newSQLException(rc, "Restore failed"); } } } }
if (sql == null) return null; if (sql.length() > 5 && sql.substring(0, 6).toLowerCase().equals("backup")) return BackupCommand.parse(sql); else if (sql.length() > 6 && sql.substring(0, 7).toLowerCase().equals("restore")) return RestoreCommand.parse(sql); return null;
1,322
102
1,424
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/JDBC.java
JDBC
createConnection
class JDBC implements Driver { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(JDBC.class); public static final String PREFIX = "jdbc:sqlite:"; static { try { DriverManager.registerDriver(new JDBC()); } catch (SQLException e) { logger.error("Could not register driver", e); } } /** @see java.sql.Driver#getMajorVersion() */ public int getMajorVersion() { return SQLiteJDBCLoader.getMajorVersion(); } /** @see java.sql.Driver#getMinorVersion() */ public int getMinorVersion() { return SQLiteJDBCLoader.getMinorVersion(); } /** @see java.sql.Driver#jdbcCompliant() */ public boolean jdbcCompliant() { return false; } public Logger getParentLogger() throws SQLFeatureNotSupportedException { // TODO return null; } /** @see java.sql.Driver#acceptsURL(java.lang.String) */ public boolean acceptsURL(String url) { return isValidURL(url); } /** * Validates a URL * * @param url * @return true if the URL is valid, false otherwise */ public static boolean isValidURL(String url) { return url != null && url.toLowerCase().startsWith(PREFIX); } /** @see java.sql.Driver#getPropertyInfo(java.lang.String, java.util.Properties) */ public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return SQLiteConfig.getDriverPropertyInfo(); } /** @see java.sql.Driver#connect(java.lang.String, java.util.Properties) */ public Connection connect(String url, Properties info) throws SQLException { return createConnection(url, info); } /** * Gets the location to the database from a given URL. * * @param url The URL to extract the location from. * @return The location to the database. */ static String extractAddress(String url) { return url.substring(PREFIX.length()); } /** * Creates a new database connection to a given URL. * * @param url the URL * @param prop the properties * @return a Connection object that represents a connection to the URL * @throws SQLException * @see java.sql.Driver#connect(java.lang.String, java.util.Properties) */ public static SQLiteConnection createConnection(String url, Properties prop) throws SQLException {<FILL_FUNCTION_BODY>} }
if (!isValidURL(url)) return null; url = url.trim(); return new JDBC4Connection(url, extractAddress(url), prop);
707
44
751
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/ProgressHandler.java
ProgressHandler
setHandler
class ProgressHandler { /** * Sets a progress handler for the connection. * * @param conn the SQLite connection * @param vmCalls the approximate number of virtual machine instructions that are evaluated * between successive invocations of the progressHandler * @param progressHandler the progressHandler * @throws SQLException */ public static final void setHandler( Connection conn, int vmCalls, ProgressHandler progressHandler) throws SQLException {<FILL_FUNCTION_BODY>} /** * Clears any progress handler registered with the connection. * * @param conn the SQLite connection * @throws SQLException */ public static final void clearHandler(Connection conn) throws SQLException { SQLiteConnection sqliteConnection = (SQLiteConnection) conn; sqliteConnection.getDatabase().clear_progress_handler(); } protected abstract int progress() throws SQLException; }
if (!(conn instanceof SQLiteConnection)) { throw new SQLException("connection must be to an SQLite db"); } if (conn.isClosed()) { throw new SQLException("connection closed"); } SQLiteConnection sqliteConnection = (SQLiteConnection) conn; sqliteConnection.getDatabase().register_progress_handler(vmCalls, progressHandler);
228
96
324
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/SQLiteConnectionConfig.java
SQLiteConnectionConfig
fromPragmaTable
class SQLiteConnectionConfig implements Cloneable { private SQLiteConfig.DateClass dateClass = SQLiteConfig.DateClass.INTEGER; private SQLiteConfig.DatePrecision datePrecision = SQLiteConfig.DatePrecision.MILLISECONDS; // Calendar.SECOND or Calendar.MILLISECOND private String dateStringFormat = DEFAULT_DATE_STRING_FORMAT; private FastDateFormat dateFormat = FastDateFormat.getInstance(dateStringFormat); private int transactionIsolation = Connection.TRANSACTION_SERIALIZABLE; private SQLiteConfig.TransactionMode transactionMode = SQLiteConfig.TransactionMode.DEFERRED; private boolean autoCommit = true; public static SQLiteConnectionConfig fromPragmaTable(Properties pragmaTable) {<FILL_FUNCTION_BODY>} public SQLiteConnectionConfig( SQLiteConfig.DateClass dateClass, SQLiteConfig.DatePrecision datePrecision, String dateStringFormat, int transactionIsolation, SQLiteConfig.TransactionMode transactionMode, boolean autoCommit) { setDateClass(dateClass); setDatePrecision(datePrecision); setDateStringFormat(dateStringFormat); setTransactionIsolation(transactionIsolation); setTransactionMode(transactionMode); setAutoCommit(autoCommit); } public SQLiteConnectionConfig copyConfig() { return new SQLiteConnectionConfig( dateClass, datePrecision, dateStringFormat, transactionIsolation, transactionMode, autoCommit); } public long getDateMultiplier() { return (datePrecision == SQLiteConfig.DatePrecision.MILLISECONDS) ? 1L : 1000L; } public SQLiteConfig.DateClass getDateClass() { return dateClass; } public void setDateClass(SQLiteConfig.DateClass dateClass) { this.dateClass = dateClass; } public SQLiteConfig.DatePrecision getDatePrecision() { return datePrecision; } public void setDatePrecision(SQLiteConfig.DatePrecision datePrecision) { this.datePrecision = datePrecision; } public String getDateStringFormat() { return dateStringFormat; } public void setDateStringFormat(String dateStringFormat) { this.dateStringFormat = dateStringFormat; this.dateFormat = FastDateFormat.getInstance(dateStringFormat); } public FastDateFormat getDateFormat() { return dateFormat; } public boolean isAutoCommit() { return autoCommit; } public void setAutoCommit(boolean autoCommit) { this.autoCommit = autoCommit; } public int getTransactionIsolation() { return transactionIsolation; } public void setTransactionIsolation(int transactionIsolation) { this.transactionIsolation = transactionIsolation; } public SQLiteConfig.TransactionMode getTransactionMode() { return transactionMode; } @SuppressWarnings("deprecation") public void setTransactionMode(SQLiteConfig.TransactionMode transactionMode) { this.transactionMode = transactionMode; } private static final Map<SQLiteConfig.TransactionMode, String> beginCommandMap = new EnumMap<SQLiteConfig.TransactionMode, String>(SQLiteConfig.TransactionMode.class); static { beginCommandMap.put(SQLiteConfig.TransactionMode.DEFERRED, "begin;"); beginCommandMap.put(SQLiteConfig.TransactionMode.IMMEDIATE, "begin immediate;"); beginCommandMap.put(SQLiteConfig.TransactionMode.EXCLUSIVE, "begin exclusive;"); } String transactionPrefix() { return beginCommandMap.get(transactionMode); } }
return new SQLiteConnectionConfig( SQLiteConfig.DateClass.getDateClass( pragmaTable.getProperty( SQLiteConfig.Pragma.DATE_CLASS.pragmaName, SQLiteConfig.DateClass.INTEGER.name())), SQLiteConfig.DatePrecision.getPrecision( pragmaTable.getProperty( SQLiteConfig.Pragma.DATE_PRECISION.pragmaName, SQLiteConfig.DatePrecision.MILLISECONDS.name())), pragmaTable.getProperty( SQLiteConfig.Pragma.DATE_STRING_FORMAT.pragmaName, DEFAULT_DATE_STRING_FORMAT), Connection.TRANSACTION_SERIALIZABLE, SQLiteConfig.TransactionMode.getMode( pragmaTable.getProperty( SQLiteConfig.Pragma.TRANSACTION_MODE.pragmaName, SQLiteConfig.TransactionMode.DEFERRED.name())), true);
974
238
1,212
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/core/CoreDatabaseMetaData.java
CoreDatabaseMetaData
close
class CoreDatabaseMetaData implements DatabaseMetaData { protected SQLiteConnection conn; protected PreparedStatement getTables = null, getTableTypes = null, getTypeInfo = null, getCatalogs = null, getSchemas = null, getUDTs = null, getColumnsTblName = null, getSuperTypes = null, getSuperTables = null, getTablePrivileges = null, getIndexInfo = null, getProcedures = null, getProcedureColumns = null, getAttributes = null, getBestRowIdentifier = null, getVersionColumns = null, getColumnPrivileges = null; /** * Constructor that applies the Connection object. * * @param conn Connection object. */ protected CoreDatabaseMetaData(SQLiteConnection conn) { this.conn = conn; } /** * @deprecated Not exactly sure what this function does, as it is not implementing any * interface, and is not used anywhere in the code. Deprecated since 3.43.0.0. */ @Deprecated public abstract ResultSet getGeneratedKeys() throws SQLException; /** @throws SQLException */ protected void checkOpen() throws SQLException { if (conn == null) { throw new SQLException("connection closed"); } } /** @throws SQLException */ public synchronized void close() throws SQLException {<FILL_FUNCTION_BODY>} /** * Adds SQL string quotes to the given string. * * @param tableName The string to quote. * @return The quoted string. */ protected static String quote(String tableName) { if (tableName == null) { return "null"; } else { return String.format("'%s'", tableName); } } /** * Applies SQL escapes for special characters in a given string. * * @param val The string to escape. * @return The SQL escaped string. */ protected String escape(final String val) { // TODO: this function is ugly, pass this work off to SQLite, then we // don't have to worry about Unicode 4, other characters needing // escaping, etc. int len = val.length(); StringBuilder buf = new StringBuilder(len); for (int i = 0; i < len; i++) { if (val.charAt(i) == '\'') { buf.append('\''); } buf.append(val.charAt(i)); } return buf.toString(); } // inner classes /** Pattern used to extract column order for an unnamed primary key. */ protected static final Pattern PK_UNNAMED_PATTERN = Pattern.compile( ".*\\sPRIMARY\\s+KEY\\s+\\((.*?,+.*?)\\).*", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); /** Pattern used to extract a named primary key. */ protected static final Pattern PK_NAMED_PATTERN = Pattern.compile( ".*\\sCONSTRAINT\\s+(.*?)\\s+PRIMARY\\s+KEY\\s+\\((.*?)\\).*", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); /** @see java.lang.Object#finalize() */ protected void finalize() throws Throwable { close(); } }
if (conn == null) { return; } try { if (getTables != null) { getTables.close(); } if (getTableTypes != null) { getTableTypes.close(); } if (getTypeInfo != null) { getTypeInfo.close(); } if (getCatalogs != null) { getCatalogs.close(); } if (getSchemas != null) { getSchemas.close(); } if (getUDTs != null) { getUDTs.close(); } if (getColumnsTblName != null) { getColumnsTblName.close(); } if (getSuperTypes != null) { getSuperTypes.close(); } if (getSuperTables != null) { getSuperTables.close(); } if (getTablePrivileges != null) { getTablePrivileges.close(); } if (getIndexInfo != null) { getIndexInfo.close(); } if (getProcedures != null) { getProcedures.close(); } if (getProcedureColumns != null) { getProcedureColumns.close(); } if (getAttributes != null) { getAttributes.close(); } if (getBestRowIdentifier != null) { getBestRowIdentifier.close(); } if (getVersionColumns != null) { getVersionColumns.close(); } if (getColumnPrivileges != null) { getColumnPrivileges.close(); } getTables = null; getTableTypes = null; getTypeInfo = null; getCatalogs = null; getSchemas = null; getUDTs = null; getColumnsTblName = null; getSuperTypes = null; getSuperTables = null; getTablePrivileges = null; getIndexInfo = null; getProcedures = null; getProcedureColumns = null; getAttributes = null; getBestRowIdentifier = null; getVersionColumns = null; getColumnPrivileges = null; } finally { conn = null; }
900
605
1,505
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/core/CorePreparedStatement.java
CorePreparedStatement
executeLargeBatch
class CorePreparedStatement extends JDBC4Statement { protected int columnCount; protected int paramCount; protected int batchQueryCount; /** * Constructs a prepared statement on a provided connection. * * @param conn Connection on which to create the prepared statement. * @param sql The SQL script to prepare. * @throws SQLException */ protected CorePreparedStatement(SQLiteConnection conn, String sql) throws SQLException { super(conn); this.sql = sql; DB db = conn.getDatabase(); db.prepare(this); rs.colsMeta = pointer.safeRun(DB::column_names); columnCount = pointer.safeRunInt(DB::column_count); paramCount = pointer.safeRunInt(DB::bind_parameter_count); batchQueryCount = 0; batch = null; batchPos = 0; } /** @see org.sqlite.jdbc3.JDBC3Statement#executeBatch() */ @Override public int[] executeBatch() throws SQLException { return Arrays.stream(executeLargeBatch()).mapToInt(l -> (int) l).toArray(); } /** @see org.sqlite.jdbc3.JDBC3Statement#executeLargeBatch() */ @Override public long[] executeLargeBatch() throws SQLException {<FILL_FUNCTION_BODY>} /** @see org.sqlite.jdbc3.JDBC3Statement#clearBatch() () */ @Override public void clearBatch() throws SQLException { super.clearBatch(); batchQueryCount = 0; } // PARAMETER FUNCTIONS ////////////////////////////////////////// /** * Assigns the object value to the element at the specific position of array batch. * * @param pos * @param value * @throws SQLException */ protected void batch(int pos, Object value) throws SQLException { checkOpen(); if (batch == null) { batch = new Object[paramCount]; } batch[batchPos + pos - 1] = value; } /** Store the date in the user's preferred format (text, int, or real) */ protected void setDateByMilliseconds(int pos, Long value, Calendar calendar) throws SQLException { SQLiteConnectionConfig config = conn.getConnectionConfig(); switch (config.getDateClass()) { case TEXT: batch( pos, FastDateFormat.getInstance( config.getDateStringFormat(), calendar.getTimeZone()) .format(new Date(value))); break; case REAL: // long to Julian date batch(pos, new Double((value / 86400000.0) + 2440587.5)); break; default: // INTEGER: batch(pos, new Long(value / config.getDateMultiplier())); } } }
if (batchQueryCount == 0) { return new long[] {}; } if (this.conn instanceof JDBC3Connection) { ((JDBC3Connection) this.conn).tryEnforceTransactionMode(); } return this.withConnectionTimeout( () -> { try { return conn.getDatabase() .executeBatch( pointer, batchQueryCount, batch, conn.getAutoCommit()); } finally { clearBatch(); } });
752
129
881
<methods>public void <init>(org.sqlite.SQLiteConnection) ,public void close() throws SQLException,public void closeOnCompletion() throws SQLException,public boolean isCloseOnCompletion() throws SQLException,public boolean isClosed() ,public boolean isPoolable() throws SQLException,public boolean isWrapperFor(Class<?>) ,public void setPoolable(boolean) throws SQLException,public T unwrap(Class<T>) throws java.lang.ClassCastException<variables>boolean closeOnCompletion,private boolean closed
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/core/CoreResultSet.java
CoreResultSet
findColumnIndexInCache
class CoreResultSet implements Codes { protected final CoreStatement stmt; /** If the result set does not have any rows. */ public boolean emptyResultSet = false; /** If the result set is open. Doesn't mean it has results. */ public boolean open = false; /** Maximum number of rows as set by a Statement */ public long maxRows; /** if null, the RS is closed() */ public String[] cols = null; /** same as cols, but used by Meta interface */ public String[] colsMeta = null; protected boolean[][] meta = null; /** 0 means no limit, must check against maxRows */ protected int limitRows; /** number of current row, starts at 1 (0 is for before loading data) */ protected int row = 0; protected boolean pastLastRow = false; /** last column accessed, for wasNull(). -1 if none */ protected int lastCol; public boolean closeStmt; protected Map<String, Integer> columnNameToIndex = null; /** * Default constructor for a given statement. * * @param stmt The statement. */ protected CoreResultSet(CoreStatement stmt) { this.stmt = stmt; } // INTERNAL FUNCTIONS /////////////////////////////////////////// protected DB getDatabase() { return stmt.getDatabase(); } protected SQLiteConnectionConfig getConnectionConfig() { return stmt.getConnectionConfig(); } /** * Checks the status of the result set. * * @return True if has results and can iterate them; false otherwise. */ public boolean isOpen() { return open; } /** @throws SQLException if ResultSet is not open. */ protected void checkOpen() throws SQLException { if (!open) { throw new SQLException("ResultSet closed"); } } /** * Takes col in [1,x] form, returns in [0,x-1] form * * @param col * @return * @throws SQLException */ public int checkCol(int col) throws SQLException { if (colsMeta == null) { throw new SQLException("SQLite JDBC: inconsistent internal state"); } if (col < 1 || col > colsMeta.length) { throw new SQLException("column " + col + " out of bounds [1," + colsMeta.length + "]"); } return --col; } /** * Takes col in [1,x] form, marks it as last accessed and returns [0,x-1] * * @param col * @return * @throws SQLException */ protected int markCol(int col) throws SQLException { checkCol(col); lastCol = col; return --col; } /** @throws SQLException */ public void checkMeta() throws SQLException { checkCol(1); if (meta == null) { meta = stmt.pointer.safeRun(DB::column_metadata); } } public void close() throws SQLException { cols = null; colsMeta = null; meta = null; limitRows = 0; row = 0; pastLastRow = false; lastCol = -1; columnNameToIndex = null; emptyResultSet = false; if (stmt.pointer.isClosed() || (!open && !closeStmt)) { return; } DB db = stmt.getDatabase(); synchronized (db) { if (!stmt.pointer.isClosed()) { stmt.pointer.safeRunInt(DB::reset); if (closeStmt) { closeStmt = false; // break recursive call ((Statement) stmt).close(); } } } open = false; } protected Integer findColumnIndexInCache(String col) {<FILL_FUNCTION_BODY>} protected int addColumnIndexInCache(String col, int index) { if (columnNameToIndex == null) { columnNameToIndex = new HashMap<String, Integer>(cols.length); } columnNameToIndex.put(col, index); return index; } }
if (columnNameToIndex == null) { return null; } return columnNameToIndex.get(col);
1,108
35
1,143
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/core/CoreStatement.java
CoreStatement
exec
class CoreStatement implements Codes { public final SQLiteConnection conn; protected final CoreResultSet rs; public SafeStmtPtr pointer; protected String sql = null; protected int batchPos; protected Object[] batch = null; protected boolean resultsWaiting = false; private Statement generatedKeysStat = null; private ResultSet generatedKeysRs = null; // pattern for matching insert statements of the general format starting with INSERT or REPLACE. // CTEs used prior to the insert or replace keyword are also be permitted. private static final Pattern INSERT_PATTERN = Pattern.compile( "^\\s*(?:with\\s+.+\\(.+?\\))*\\s*(?:insert|replace)\\s*", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); protected CoreStatement(SQLiteConnection c) { conn = c; rs = new JDBC4ResultSet(this); } public DB getDatabase() { return conn.getDatabase(); } public SQLiteConnectionConfig getConnectionConfig() { return conn.getConnectionConfig(); } /** @throws SQLException If the database is not opened. */ protected final void checkOpen() throws SQLException { if (pointer.isClosed()) throw new SQLException("statement is not executing"); } /** * @return True if the database is opened; false otherwise. * @throws SQLException */ boolean isOpen() throws SQLException { return !pointer.isClosed(); } /** * Calls sqlite3_step() and sets up results. Expects a clean stmt. * * @return True if the ResultSet has at least one row; false otherwise. * @throws SQLException If the given SQL statement is null or no database is open. */ protected boolean exec() throws SQLException {<FILL_FUNCTION_BODY>} /** * Executes SQL statement and throws SQLExceptions if the given SQL statement is null or no * database is open. * * @param sql SQL statement. * @return True if the ResultSet has at least one row; false otherwise. * @throws SQLException If the given SQL statement is null or no database is open. */ protected boolean exec(String sql) throws SQLException { if (sql == null) throw new SQLException("SQLiteJDBC internal error: sql==null"); if (rs.isOpen()) throw new SQLException("SQLite JDBC internal error: rs.isOpen() on exec."); if (this.conn instanceof JDBC3Connection) { ((JDBC3Connection) this.conn).tryEnforceTransactionMode(); } boolean rc = false; boolean success = false; try { rc = conn.getDatabase().execute(sql, conn.getAutoCommit()); success = true; } finally { notifyFirstStatementExecuted(); resultsWaiting = rc; if (!success && pointer != null) { pointer.close(); } } return pointer.safeRunInt(DB::column_count) != 0; } protected void internalClose() throws SQLException { if (this.pointer != null && !this.pointer.isClosed()) { if (conn.isClosed()) throw DB.newSQLException(SQLITE_ERROR, "Connection is closed"); rs.close(); batch = null; batchPos = 0; int resp = this.pointer.close(); if (resp != SQLITE_OK && resp != SQLITE_MISUSE) conn.getDatabase().throwex(resp); } } protected void notifyFirstStatementExecuted() { conn.setFirstStatementExecuted(true); } public abstract ResultSet executeQuery(String sql, boolean closeStmt) throws SQLException; protected void checkIndex(int index) throws SQLException { if (batch == null) { throw new SQLException("No parameter has been set yet"); } if (index < 1 || index > batch.length) { throw new SQLException("Parameter index is invalid"); } } protected void clearGeneratedKeys() throws SQLException { if (generatedKeysRs != null && !generatedKeysRs.isClosed()) { generatedKeysRs.close(); } generatedKeysRs = null; if (generatedKeysStat != null && !generatedKeysStat.isClosed()) { generatedKeysStat.close(); } generatedKeysStat = null; } /** * SQLite's last_insert_rowid() function is DB-specific. However, in this implementation we * ensure the Generated Key result set is statement-specific by executing the query immediately * after an insert operation is performed. The caller is simply responsible for calling * updateGeneratedKeys on the statement object right after execute in a synchronized(connection) * block. */ public void updateGeneratedKeys() throws SQLException { clearGeneratedKeys(); if (sql != null && INSERT_PATTERN.matcher(sql).find()) { generatedKeysStat = conn.createStatement(); generatedKeysRs = generatedKeysStat.executeQuery("SELECT last_insert_rowid();"); } } /** * This implementation uses SQLite's last_insert_rowid function to obtain the row ID. It cannot * provide multiple values when inserting multiple rows. Suggestion is to use a <a * href=https://www.sqlite.org/lang_returning.html>RETURNING</a> clause instead. * * @see java.sql.Statement#getGeneratedKeys() */ public ResultSet getGeneratedKeys() throws SQLException { // getGeneratedKeys is required to return an EmptyResult set if the statement // did not generate any keys. Thus, if the generateKeysResultSet is NULL, spin // up a new result set without any contents by issuing a query with a false where condition if (generatedKeysRs == null) { generatedKeysStat = conn.createStatement(); generatedKeysRs = generatedKeysStat.executeQuery("SELECT 1 WHERE 1 = 2;"); } return generatedKeysRs; } }
if (sql == null) throw new SQLException("SQLiteJDBC internal error: sql==null"); if (rs.isOpen()) throw new SQLException("SQLite JDBC internal error: rs.isOpen() on exec."); if (this.conn instanceof JDBC3Connection) { ((JDBC3Connection) this.conn).tryEnforceTransactionMode(); } boolean success = false; boolean rc = false; try { rc = conn.getDatabase().execute(this, null); success = true; } finally { notifyFirstStatementExecuted(); resultsWaiting = rc; if (!success) { this.pointer.close(); } } return pointer.safeRunInt(DB::column_count) != 0;
1,566
202
1,768
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/core/SafeStmtPtr.java
SafeStmtPtr
equals
class SafeStmtPtr { // store a reference to the DB, to lock it before any safe function is called. This avoids // deadlocking by locking the DB. All calls with the raw pointer are synchronized with the DB // anyways, so making a separate lock would be pointless private final DB db; private final long ptr; private volatile boolean closed = false; // to return on subsequent calls to close() after this ptr has been closed private int closedRC; // to throw on subsequent calls to close after this ptr has been closed, if the close function // threw an exception private SQLException closeException; /** * Construct a new Safe Pointer Wrapper to ensure a pointer is properly handled * * @param db the database that made this pointer. Always locked before any safe run function is * executed to avoid deadlocks * @param ptr the raw pointer */ public SafeStmtPtr(DB db, long ptr) { this.db = db; this.ptr = ptr; } /** * Check whether this pointer has been closed * * @return whether this pointer has been closed */ public boolean isClosed() { return closed; } /** * Close this pointer * * @return the return code of the close callback function * @throws SQLException if the close callback throws an SQLException, or the pointer is locked * elsewhere */ public int close() throws SQLException { synchronized (db) { return internalClose(); } } private int internalClose() throws SQLException { try { // if this is already closed, return or throw the previous result if (closed) { if (closeException != null) throw closeException; return closedRC; } closedRC = db.finalize(this, ptr); return closedRC; } catch (SQLException ex) { this.closeException = ex; throw ex; } finally { this.closed = true; } } /** * Run a callback with the wrapped pointer safely. * * @param run the function to run * @return the return of the passed in function * @throws SQLException if the pointer is utilized elsewhere */ public <E extends Throwable> int safeRunInt(SafePtrIntFunction<E> run) throws SQLException, E { synchronized (db) { this.ensureOpen(); return run.run(db, ptr); } } /** * Run a callback with the wrapped pointer safely. * * @param run the function to run * @return the return of the passed in function * @throws SQLException if the pointer is utilized elsewhere */ public <E extends Throwable> long safeRunLong(SafePtrLongFunction<E> run) throws SQLException, E { synchronized (db) { this.ensureOpen(); return run.run(db, ptr); } } /** * Run a callback with the wrapped pointer safely. * * @param run the function to run * @return the return of the passed in function * @throws SQLException if the pointer is utilized elsewhere */ public <E extends Throwable> double safeRunDouble(SafePtrDoubleFunction<E> run) throws SQLException, E { synchronized (db) { this.ensureOpen(); return run.run(db, ptr); } } /** * Run a callback with the wrapped pointer safely. * * @param run the function to run * @return the return code of the function * @throws SQLException if the pointer is utilized elsewhere */ public <T, E extends Throwable> T safeRun(SafePtrFunction<T, E> run) throws SQLException, E { synchronized (db) { this.ensureOpen(); return run.run(db, ptr); } } /** * Run a callback with the wrapped pointer safely. * * @param run the function to run * @throws SQLException if the pointer is utilized elsewhere */ public <E extends Throwable> void safeRunConsume(SafePtrConsumer<E> run) throws SQLException, E { synchronized (db) { this.ensureOpen(); run.run(db, ptr); } } private void ensureOpen() throws SQLException { if (this.closed) { throw new SQLException("stmt pointer is closed"); } } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Long.hashCode(ptr); } @FunctionalInterface public interface SafePtrIntFunction<E extends Throwable> { int run(DB db, long ptr) throws E; } @FunctionalInterface public interface SafePtrLongFunction<E extends Throwable> { long run(DB db, long ptr) throws E; } @FunctionalInterface public interface SafePtrDoubleFunction<E extends Throwable> { double run(DB db, long ptr) throws E; } @FunctionalInterface public interface SafePtrFunction<T, E extends Throwable> { T run(DB db, long ptr) throws E; } @FunctionalInterface public interface SafePtrConsumer<E extends Throwable> { void run(DB db, long ptr) throws E; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SafeStmtPtr that = (SafeStmtPtr) o; return ptr == that.ptr;
1,411
61
1,472
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/date/ExceptionUtils.java
ExceptionUtils
rethrow
class ExceptionUtils { /** * Throw a checked exception without adding the exception to the throws clause of the calling * method. This method prevents throws clause pollution and reduces the clutter of "Caused by" * exceptions in the stacktrace. * * <p>The use of this technique may be controversial, but exceedingly useful to library * developers. <code> * public int propagateExample { // note that there is no throws clause * try { * return invocation(); // throws IOException * } catch (Exception e) { * return ExceptionUtils.rethrow(e); // propagates a checked exception * } * } * </code> * * <p>This is an alternative to the more conservative approach of wrapping the checked exception * in a RuntimeException: <code> * public int wrapExample { // note that there is no throws clause * try { * return invocation(); // throws IOException * } catch (Error e) { * throw e; * } catch (RuntimeException e) { * throw e; // wraps a checked exception * } catch (Exception e) { * throw new UndeclaredThrowableException(e); // wraps a checked exception * } * } * </code> * * <p>One downside to using this approach is that the java compiler will not allow invoking code * to specify a checked exception in a catch clause unless there is some code path within the * try block that has invoked a method declared with that checked exception. If the invoking * site wishes to catch the shaded checked exception, it must either invoke the shaded code * through a method re-declaring the desired checked exception, or catch Exception and use the * instanceof operator. Either of these techniques are required when interacting with non-java * jvm code such as Jython, Scala, or Groovy, since these languages do not consider any * exceptions as checked. * * @since 3.5 * @see {{@link #wrapAndThrow(Throwable)} * @param throwable The throwable to rethrow. * @return R Never actually returns, this generic type matches any type which the calling site * requires. "Returning" the results of this method, as done in the propagateExample above, * will satisfy the java compiler requirement that all code paths return a value. * @throws throwable */ public static <R> R rethrow(Throwable throwable) {<FILL_FUNCTION_BODY>} /** * Claim a Throwable is another Exception type using type erasure. This hides a checked * exception from the java compiler, allowing a checked exception to be thrown without having * the exception in the method's throw clause. */ @SuppressWarnings("unchecked") private static <R, T extends Throwable> R typeErasure(Throwable throwable) throws T { throw (T) throwable; } }
// claim that the typeErasure invocation throws a RuntimeException return ExceptionUtils.<R, RuntimeException>typeErasure(throwable);
757
37
794
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/date/FastDateParser.java
Strategy
getStrategy
class Strategy { /** * Is this field a number? The default implementation returns false. * * @return true, if field is a number */ boolean isNumber() { return false; } /** * Set the Calendar with the parsed field. * * <p>The default implementation does nothing. * * @param parser The parser calling this strategy * @param cal The <code>Calendar</code> to set * @param value The parsed field to translate and set in cal */ void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {} /** * Generate a <code>Pattern</code> regular expression to the <code>StringBuilder</code> * which will accept this field * * @param parser The parser calling this strategy * @param regex The <code>StringBuilder</code> to append to * @return true, if this field will set the calendar; false, if this field is a constant * value */ abstract boolean addRegex(FastDateParser parser, StringBuilder regex); } /** A <code>Pattern</code> to parse the user supplied SimpleDateFormat pattern */ private static final Pattern formatPattern = Pattern.compile( "D+|E+|F+|G+|H+|K+|M+|S+|W+|X+|Z+|a+|d+|h+|k+|m+|s+|w+|y+|z+|''|'[^']++(''[^']*+)*+'|[^'A-Za-z]++"); /** * Obtain a Strategy given a field from a SimpleDateFormat pattern * * @param formatField A sub-sequence of the SimpleDateFormat pattern * @param definingCalendar The calendar to obtain the short and long values * @return The Strategy that will handle parsing for the field */ private Strategy getStrategy(final String formatField, final Calendar definingCalendar) {<FILL_FUNCTION_BODY>
switch (formatField.charAt(0)) { case '\'': if (formatField.length() > 2) { return new CopyQuotedStrategy( formatField.substring(1, formatField.length() - 1)); } // $FALL-THROUGH$ default: return new CopyQuotedStrategy(formatField); case 'D': return DAY_OF_YEAR_STRATEGY; case 'E': return getLocaleSpecificStrategy(Calendar.DAY_OF_WEEK, definingCalendar); case 'F': return DAY_OF_WEEK_IN_MONTH_STRATEGY; case 'G': return getLocaleSpecificStrategy(Calendar.ERA, definingCalendar); case 'H': // Hour in day (0-23) return HOUR_OF_DAY_STRATEGY; case 'K': // Hour in am/pm (0-11) return HOUR_STRATEGY; case 'M': return formatField.length() >= 3 ? getLocaleSpecificStrategy(Calendar.MONTH, definingCalendar) : NUMBER_MONTH_STRATEGY; case 'S': return MILLISECOND_STRATEGY; case 'W': return WEEK_OF_MONTH_STRATEGY; case 'a': return getLocaleSpecificStrategy(Calendar.AM_PM, definingCalendar); case 'd': return DAY_OF_MONTH_STRATEGY; case 'h': // Hour in am/pm (1-12), i.e. midday/midnight is 12, not 0 return HOUR12_STRATEGY; case 'k': // Hour in day (1-24), i.e. midnight is 24, not 0 return HOUR24_OF_DAY_STRATEGY; case 'm': return MINUTE_STRATEGY; case 's': return SECOND_STRATEGY; case 'w': return WEEK_OF_YEAR_STRATEGY; case 'y': return formatField.length() > 2 ? LITERAL_YEAR_STRATEGY : ABBREVIATED_YEAR_STRATEGY; case 'X': return ISO8601TimeZoneStrategy.getStrategy(formatField.length()); case 'Z': if (formatField.equals("ZZ")) { return ISO_8601_STRATEGY; } // $FALL-THROUGH$ case 'z': return getLocaleSpecificStrategy(Calendar.ZONE_OFFSET, definingCalendar); }
499
706
1,205
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/date/FastDatePrinter.java
TimeZoneDisplayKey
equals
class TimeZoneDisplayKey { private final TimeZone mTimeZone; private final int mStyle; private final Locale mLocale; /** * Constructs an instance of {@code TimeZoneDisplayKey} with the specified properties. * * @param timeZone the time zone * @param daylight adjust the style for daylight saving time if {@code true} * @param style the timezone style * @param locale the timezone locale */ TimeZoneDisplayKey( final TimeZone timeZone, final boolean daylight, final int style, final Locale locale) { mTimeZone = timeZone; if (daylight) { mStyle = style | 0x80000000; } else { mStyle = style; } mLocale = locale; } /** {@inheritDoc} */ @Override public int hashCode() { return (mStyle * 31 + mLocale.hashCode()) * 31 + mTimeZone.hashCode(); } /** {@inheritDoc} */ @Override public boolean equals(final Object obj) {<FILL_FUNCTION_BODY>} }
if (this == obj) { return true; } if (obj instanceof TimeZoneDisplayKey) { final TimeZoneDisplayKey other = (TimeZoneDisplayKey) obj; return mTimeZone.equals(other.mTimeZone) && mStyle == other.mStyle && mLocale.equals(other.mLocale); } return false;
305
97
402
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/javax/SQLitePooledConnection.java
SQLitePooledConnection
getConnection
class SQLitePooledConnection extends JDBC4PooledConnection { protected SQLiteConnection physicalConn; protected volatile Connection handleConn; protected List<ConnectionEventListener> listeners = new ArrayList<ConnectionEventListener>(); /** * Constructor. * * @param physicalConn The physical Connection. */ protected SQLitePooledConnection(SQLiteConnection physicalConn) { this.physicalConn = physicalConn; } public SQLiteConnection getPhysicalConn() { return physicalConn; } /** @see javax.sql.PooledConnection#close() */ public void close() throws SQLException { if (handleConn != null) { listeners.clear(); handleConn.close(); } if (physicalConn != null) { try { physicalConn.close(); } finally { physicalConn = null; } } } /** @see javax.sql.PooledConnection#getConnection() */ public Connection getConnection() throws SQLException {<FILL_FUNCTION_BODY>} /** * @see javax.sql.PooledConnection#addConnectionEventListener(javax.sql.ConnectionEventListener) */ public void addConnectionEventListener(ConnectionEventListener listener) { listeners.add(listener); } /** * @see * javax.sql.PooledConnection#removeConnectionEventListener(javax.sql.ConnectionEventListener) */ public void removeConnectionEventListener(ConnectionEventListener listener) { listeners.remove(listener); } public List<ConnectionEventListener> getListeners() { return listeners; } }
if (handleConn != null) handleConn.close(); handleConn = (Connection) Proxy.newProxyInstance( getClass().getClassLoader(), new Class[] {Connection.class}, new InvocationHandler() { boolean isClosed; public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { String name = method.getName(); if ("close".equals(name)) { ConnectionEvent event = new ConnectionEvent( SQLitePooledConnection.this); for (int i = listeners.size() - 1; i >= 0; i--) { listeners.get(i).connectionClosed(event); } if (!physicalConn.getAutoCommit()) { physicalConn.rollback(); } physicalConn.setAutoCommit(true); isClosed = true; return null; // don't close physical connection } else if ("isClosed".equals(name)) { if (!isClosed) isClosed = ((Boolean) method.invoke( physicalConn, args)) .booleanValue(); return isClosed; } if (isClosed) { throw new SQLException("Connection is closed"); } return method.invoke(physicalConn, args); } catch (SQLException e) { if ("database connection closed" .equals(e.getMessage())) { ConnectionEvent event = new ConnectionEvent( SQLitePooledConnection.this, e); for (int i = listeners.size() - 1; i >= 0; i--) { listeners.get(i).connectionErrorOccurred(event); } } throw e; } catch (InvocationTargetException ex) { throw ex.getCause(); } } }); return handleConn;
423
508
931
<methods>public non-sealed void <init>() ,public void addStatementEventListener(javax.sql.StatementEventListener) ,public void removeStatementEventListener(javax.sql.StatementEventListener) <variables>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/jdbc4/JDBC4Connection.java
JDBC4Connection
unwrap
class JDBC4Connection extends JDBC3Connection { public JDBC4Connection(String url, String fileName, Properties prop) throws SQLException { super(url, fileName, prop); } public Statement createStatement(int rst, int rsc, int rsh) throws SQLException { checkOpen(); checkCursor(rst, rsc, rsh); return new JDBC4Statement(this); } public PreparedStatement prepareStatement(String sql, int rst, int rsc, int rsh) throws SQLException { checkOpen(); checkCursor(rst, rsc, rsh); return new JDBC4PreparedStatement(this, sql); } // JDBC 4 /** @see java.sql.Connection#isClosed() */ public boolean isClosed() throws SQLException { return super.isClosed(); } public <T> T unwrap(Class<T> iface) throws ClassCastException {<FILL_FUNCTION_BODY>} public boolean isWrapperFor(Class<?> iface) { return iface.isInstance(this); } public Clob createClob() throws SQLException { // TODO Support this throw new SQLFeatureNotSupportedException(); } public Blob createBlob() throws SQLException { // TODO Support this throw new SQLFeatureNotSupportedException(); } public NClob createNClob() throws SQLException { // TODO Support this throw new SQLFeatureNotSupportedException(); } public SQLXML createSQLXML() throws SQLException { // TODO Support this throw new SQLFeatureNotSupportedException(); } public boolean isValid(int timeout) throws SQLException { if (isClosed()) { return false; } Statement statement = createStatement(); try { return statement.execute("select 1"); } finally { statement.close(); } } public void setClientInfo(String name, String value) throws SQLClientInfoException { // TODO Auto-generated method stub } public void setClientInfo(Properties properties) throws SQLClientInfoException { // TODO Auto-generated method stub } public String getClientInfo(String name) throws SQLException { // TODO Auto-generated method stub return null; } public Properties getClientInfo() throws SQLException { // TODO Auto-generated method stub return null; } public Array createArrayOf(String typeName, Object[] elements) throws SQLException { // TODO Auto-generated method stub return null; } }
// caller should invoke isWrapperFor prior to unwrap return iface.cast(this);
677
27
704
<methods>public void clearWarnings() throws SQLException,public Statement createStatement() throws SQLException,public Statement createStatement(int, int) throws SQLException,public abstract Statement createStatement(int, int, int) throws SQLException,public Struct createStruct(java.lang.String, java.lang.Object[]) throws SQLException,public java.lang.String getCatalog() throws SQLException,public int getHoldability() throws SQLException,public Map<java.lang.String,Class<?>> getTypeMap() throws SQLException,public SQLWarning getWarnings() throws SQLException,public boolean isReadOnly() ,public java.lang.String nativeSQL(java.lang.String) ,public CallableStatement prepareCall(java.lang.String) throws SQLException,public CallableStatement prepareCall(java.lang.String, int, int) throws SQLException,public CallableStatement prepareCall(java.lang.String, int, int, int) throws SQLException,public PreparedStatement prepareStatement(java.lang.String) throws SQLException,public PreparedStatement prepareStatement(java.lang.String, int) throws SQLException,public PreparedStatement prepareStatement(java.lang.String, int[]) throws SQLException,public PreparedStatement prepareStatement(java.lang.String, java.lang.String[]) throws SQLException,public PreparedStatement prepareStatement(java.lang.String, int, int) throws SQLException,public abstract PreparedStatement prepareStatement(java.lang.String, int, int, int) throws SQLException,public void releaseSavepoint(Savepoint) throws SQLException,public void rollback(Savepoint) throws SQLException,public void setCatalog(java.lang.String) throws SQLException,public void setHoldability(int) throws SQLException,public void setReadOnly(boolean) throws SQLException,public Savepoint setSavepoint() throws SQLException,public Savepoint setSavepoint(java.lang.String) throws SQLException,public void setTypeMap(Map#RAW) throws SQLException,public void tryEnforceTransactionMode() throws SQLException<variables>private boolean readOnly,private final java.util.concurrent.atomic.AtomicInteger savePoint,private Map<java.lang.String,Class<?>> typeMap
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/jdbc4/JDBC4Statement.java
JDBC4Statement
isCloseOnCompletion
class JDBC4Statement extends JDBC3Statement implements Statement { public JDBC4Statement(SQLiteConnection conn) { super(conn); } // JDBC 4 public <T> T unwrap(Class<T> iface) throws ClassCastException { return iface.cast(this); } public boolean isWrapperFor(Class<?> iface) { return iface.isInstance(this); } private boolean closed = false; @Override public void close() throws SQLException { super.close(); closed = true; // isClosed() should only return true when close() happened } public boolean isClosed() { return closed; } boolean closeOnCompletion; public void closeOnCompletion() throws SQLException { if (closed) throw new SQLException("statement is closed"); closeOnCompletion = true; } public boolean isCloseOnCompletion() throws SQLException {<FILL_FUNCTION_BODY>} public void setPoolable(boolean poolable) throws SQLException { // TODO Auto-generated method stub } public boolean isPoolable() throws SQLException { // TODO Auto-generated method stub return false; } }
if (closed) throw new SQLException("statement is closed"); return closeOnCompletion;
325
26
351
<methods>public void addBatch(java.lang.String) throws SQLException,public void cancel() throws SQLException,public void clearBatch() throws SQLException,public void clearWarnings() throws SQLException,public void close() throws SQLException,public boolean execute(java.lang.String) throws SQLException,public boolean execute(java.lang.String, int) throws SQLException,public boolean execute(java.lang.String, int[]) throws SQLException,public boolean execute(java.lang.String, java.lang.String[]) throws SQLException,public int[] executeBatch() throws SQLException,public long[] executeLargeBatch() throws SQLException,public long executeLargeUpdate(java.lang.String) throws SQLException,public long executeLargeUpdate(java.lang.String, int) throws SQLException,public long executeLargeUpdate(java.lang.String, int[]) throws SQLException,public long executeLargeUpdate(java.lang.String, java.lang.String[]) throws SQLException,public ResultSet executeQuery(java.lang.String, boolean) throws SQLException,public ResultSet executeQuery(java.lang.String) throws SQLException,public int executeUpdate(java.lang.String) throws SQLException,public int executeUpdate(java.lang.String, int) throws SQLException,public int executeUpdate(java.lang.String, int[]) throws SQLException,public int executeUpdate(java.lang.String, java.lang.String[]) throws SQLException,public Connection getConnection() throws SQLException,public int getFetchDirection() throws SQLException,public int getFetchSize() throws SQLException,public long getLargeMaxRows() throws SQLException,public long getLargeUpdateCount() throws SQLException,public int getMaxFieldSize() throws SQLException,public int getMaxRows() throws SQLException,public boolean getMoreResults() throws SQLException,public boolean getMoreResults(int) throws SQLException,public int getQueryTimeout() throws SQLException,public ResultSet getResultSet() throws SQLException,public int getResultSetConcurrency() throws SQLException,public int getResultSetHoldability() throws SQLException,public int getResultSetType() throws SQLException,public int getUpdateCount() throws SQLException,public SQLWarning getWarnings() throws SQLException,public void setCursorName(java.lang.String) ,public void setEscapeProcessing(boolean) ,public void setFetchDirection(int) throws SQLException,public void setFetchSize(int) throws SQLException,public void setLargeMaxRows(long) throws SQLException,public void setMaxFieldSize(int) throws SQLException,public void setMaxRows(int) throws SQLException,public void setQueryTimeout(int) throws SQLException<variables>protected boolean exhaustedResults,private int queryTimeout,protected long updateCount
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/util/LibraryLoaderUtil.java
LibraryLoaderUtil
getNativeLibResourcePath
class LibraryLoaderUtil { public static final String NATIVE_LIB_BASE_NAME = "sqlitejdbc"; /** * Get the OS-specific resource directory within the jar, where the relevant sqlitejdbc native * library is located. */ public static String getNativeLibResourcePath() {<FILL_FUNCTION_BODY>} /** Get the OS-specific name of the sqlitejdbc native library. */ public static String getNativeLibName() { return System.mapLibraryName(NATIVE_LIB_BASE_NAME); } public static boolean hasNativeLib(String path, String libraryName) { return SQLiteJDBCLoader.class.getResource(path + "/" + libraryName) != null; } }
String packagePath = SQLiteJDBCLoader.class.getPackage().getName().replace(".", "/"); return String.format( "/%s/native/%s", packagePath, OSInfo.getNativeLibFolderPathForCurrentOS());
193
62
255
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/util/ProcessRunner.java
ProcessRunner
getProcessOutput
class ProcessRunner { String runAndWaitFor(String command) throws IOException, InterruptedException { Process p = Runtime.getRuntime().exec(command); p.waitFor(); return getProcessOutput(p); } String runAndWaitFor(String command, long timeout, TimeUnit unit) throws IOException, InterruptedException { Process p = Runtime.getRuntime().exec(command); p.waitFor(timeout, unit); return getProcessOutput(p); } static String getProcessOutput(Process process) throws IOException {<FILL_FUNCTION_BODY>} }
try (InputStream in = process.getInputStream()) { int readLen; ByteArrayOutputStream b = new ByteArrayOutputStream(); byte[] buf = new byte[32]; while ((readLen = in.read(buf, 0, buf.length)) >= 0) { b.write(buf, 0, readLen); } return b.toString(); }
152
97
249
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/util/QueryUtils.java
QueryUtils
valuesQuery
class QueryUtils { /** * Build a SQLite query using the VALUES clause to return arbitrary values. * * @param columns list of column names * @param valuesList values to return as rows * @return SQL query as string */ public static String valuesQuery(List<String> columns, List<List<Object>> valuesList) {<FILL_FUNCTION_BODY>} }
valuesList.forEach( (list) -> { if (list.size() != columns.size()) throw new IllegalArgumentException( "values and columns must have the same size"); }); return "with cte(" + String.join(",", columns) + ") as (values " + valuesList.stream() .map( (values) -> "(" + values.stream() .map( (o -> { if (o instanceof String) return "'" + o + "'"; if (o == null) return "null"; return o.toString(); })) .collect(Collectors.joining(",")) + ")") .collect(Collectors.joining(",")) + ") select * from cte";
100
216
316
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/util/ResourceFinder.java
ResourceFinder
find
class ResourceFinder { /** * Gets the {@link URL} of the file resource * * @param referenceClass the base class for finding resources files. This method will search the * package containing the given referenceClass. * @param resourceFileName the resource file name relative to the package of the referenceClass * @return the URL of the file resource */ public static URL find(Class<?> referenceClass, String resourceFileName) { return find(referenceClass.getClassLoader(), referenceClass.getPackage(), resourceFileName); } /** * Finds the {@link URL} of the resource * * @param basePackage the base package to find the resource * @param resourceFileName the resource file name relative to the package folder * @return the URL of the specified resource */ public static URL find(ClassLoader classLoader, Package basePackage, String resourceFileName) { return find(classLoader, basePackage.getName(), resourceFileName); } /** * Finds the {@link URL} of the resource * * @param packageName the base package name to find the resource * @param resourceFileName the resource file name relative to the package folder * @return the URL of the specified resource */ public static URL find(ClassLoader classLoader, String packageName, String resourceFileName) {<FILL_FUNCTION_BODY>} @SuppressWarnings("unused") private static String packagePath(Class<?> referenceClass) { return packagePath(referenceClass.getPackage()); } /** * @param basePackage Package object * @return Package path String in the unix-like format. */ private static String packagePath(Package basePackage) { return packagePath(basePackage.getName()); } /** * @param packageName Package name string * @return Package path String in the unix-like format. */ private static String packagePath(String packageName) { String packageAsPath = packageName.replaceAll("\\.", "/"); return packageAsPath.endsWith("/") ? packageAsPath : packageAsPath + "/"; } }
String packagePath = packagePath(packageName); String resourcePath = packagePath + resourceFileName; if (!resourcePath.startsWith("/")) resourcePath = "/" + resourcePath; return classLoader.getResource(resourcePath);
527
61
588
<no_super_class>
xerial_sqlite-jdbc
sqlite-jdbc/src/main/java/org/sqlite/util/StringUtils.java
StringUtils
join
class StringUtils { public static String join(List<String> list, String separator) {<FILL_FUNCTION_BODY>} }
StringBuilder sb = new StringBuilder(); boolean first = true; for (String item : list) { if (first) first = false; else sb.append(separator); sb.append(item); } return sb.toString();
37
69
106
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/StartApplication.java
StartApplication
mavenVersionResolver
class StartApplication { public static void main(String[] args) { SpringApplication.run(StartApplication.class, args); } @Bean public HomeController homeController() { return new HomeController(); } @Bean public StartInitializrMetadataUpdateStrategy initializrMetadataUpdateStrategy( RestTemplateBuilder restTemplateBuilder, ObjectMapper objectMapper) { return new StartInitializrMetadataUpdateStrategy(restTemplateBuilder.build(), objectMapper); } @Bean public CacheableMavenVersionResolver mavenVersionResolver(StartConfigurationProperties properties) throws IOException {<FILL_FUNCTION_BODY>} @Bean public SimpleDockerServiceResolver dockerServiceResolver() { return new SimpleDockerServiceResolver(); } }
Path location; if (StringUtils.hasText(properties.getMavenVersionResolver().getCacheDirectory())) { location = Path.of(properties.getMavenVersionResolver().getCacheDirectory()); } else { location = Files.createTempDirectory("version-resolver-cache-"); } return new CacheableMavenVersionResolver(MavenVersionResolver.withCacheLocation(location));
186
104
290
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/container/ServiceConnections.java
ServiceConnections
addServiceConnection
class ServiceConnections { private static final String GENERIC_CONTAINER_CLASS_NAME = "org.testcontainers.containers.GenericContainer"; private final Map<String, ServiceConnection> connectionsById = new HashMap<>(); public void addServiceConnection(ServiceConnection serviceConnection) {<FILL_FUNCTION_BODY>} public Stream<ServiceConnection> values() { return this.connectionsById.values().stream().sorted(Comparator.comparing(ServiceConnection::id)); } public record ServiceConnection(String id, DockerService dockerService, String containerClassName, boolean containerClassNameGeneric, String connectionName) { public static ServiceConnection ofGenericContainer(String id, DockerService dockerService, String connectionName) { return new ServiceConnection(id, dockerService, GENERIC_CONTAINER_CLASS_NAME, true, connectionName); } public static ServiceConnection ofContainer(String id, DockerService dockerService, String containerClassName) { return ofContainer(id, dockerService, containerClassName, true); } public static ServiceConnection ofContainer(String id, DockerService dockerService, String containerClassName, boolean containerClassNameGeneric) { return new ServiceConnection(id, dockerService, containerClassName, containerClassNameGeneric, null); } public boolean isGenericContainer() { return this.containerClassName.equals(GENERIC_CONTAINER_CLASS_NAME); } } }
String id = serviceConnection.id(); if (this.connectionsById.containsKey(id)) { throw new IllegalArgumentException("Connection with id '" + id + "' already registered"); } this.connectionsById.put(id, serviceConnection);
369
66
435
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/container/SimpleDockerServiceResolver.java
SimpleDockerServiceResolver
elasticsearch
class SimpleDockerServiceResolver implements DockerServiceResolver { private final Map<String, DockerService> dockerServices; public SimpleDockerServiceResolver() { this.dockerServices = new HashMap<>(); this.dockerServices.put("activeMQ", activeMQ()); this.dockerServices.put("activeMQClassic", activeMQClassic()); this.dockerServices.put("artemis", artemis()); this.dockerServices.put("cassandra", cassandra()); this.dockerServices.put("elasticsearch", elasticsearch()); this.dockerServices.put("kafka", kafka()); this.dockerServices.put("mariaDb", mariaDb()); this.dockerServices.put("mongoDb", mongoDb()); this.dockerServices.put("mysql", mysql()); this.dockerServices.put("neo4j", neo4j()); this.dockerServices.put("oracleFree", oracleFree()); this.dockerServices.put("oracleXe", oracleXe()); this.dockerServices.put("pgvector", pgvector()); this.dockerServices.put("postgres", postgres()); this.dockerServices.put("pulsar", pulsar()); this.dockerServices.put("rabbit", rabbit()); this.dockerServices.put("redis", redis()); this.dockerServices.put("sqlServer", sqlServer()); this.dockerServices.put("zipkin", zipkin()); } private static DockerService activeMQ() { return DockerService.withImageAndTag("symptoma/activemq") .website("https://hub.docker.com/r/symptoma/activemq") .ports(61616) .build(); } private static DockerService activeMQClassic() { return DockerService.withImageAndTag("apache/activemq-classic") .website("https://hub.docker.com/r/apache/activemq-classic") .ports(61616) .build(); } private static DockerService artemis() { return DockerService.withImageAndTag("apache/activemq-artemis") .website("https://hub.docker.com/r/apache/activemq-artemis") .ports(61616) .build(); } private static DockerService cassandra() { return DockerService.withImageAndTag("cassandra") .website("https://hub.docker.com/_/cassandra") .ports(9042) .build(); } private static DockerService elasticsearch() {<FILL_FUNCTION_BODY>} private static DockerService kafka() { return DockerService.withImageAndTag("confluentinc/cp-kafka") .website("https://hub.docker.com/r/confluentinc/cp-kafka") .ports(9092) .build(); } private static DockerService mariaDb() { return DockerService.withImageAndTag("mariadb").website("https://hub.docker.com/_/mariadb").ports(3306).build(); } private static DockerService mongoDb() { return DockerService.withImageAndTag("mongo").website("https://hub.docker.com/_/mongo").ports(27017).build(); } private static DockerService mysql() { return DockerService.withImageAndTag("mysql").website("https://hub.docker.com/_/mysql").ports(3306).build(); } private static DockerService neo4j() { return DockerService.withImageAndTag("neo4j").website("https://hub.docker.com/_/neo4j").ports(7687).build(); } private static DockerService oracleFree() { return DockerService.withImageAndTag("gvenzl/oracle-free") .website("https://hub.docker.com/r/gvenzl/oracle-free") .ports(1521) .build(); } private static DockerService oracleXe() { return DockerService.withImageAndTag("gvenzl/oracle-xe") .website("https://hub.docker.com/r/gvenzl/oracle-xe") .ports(1521) .build(); } private static DockerService pgvector() { return DockerService.withImageAndTag("pgvector/pgvector:pg16") .website("https://hub.docker.com/r/pgvector/pgvector") .ports(5432) .build(); } private static DockerService postgres() { return DockerService.withImageAndTag("postgres") .website("https://hub.docker.com/_/postgres") .ports(5432) .build(); } private static DockerService pulsar() { return DockerService.withImageAndTag("apachepulsar/pulsar") .website("https://hub.docker.com/r/apachepulsar/pulsar") .command("bin/pulsar standalone") .ports(8080, 6650) .build(); } private static DockerService rabbit() { return DockerService.withImageAndTag("rabbitmq") .website("https://hub.docker.com/_/rabbitmq") .ports(5672) .build(); } private static DockerService redis() { return DockerService.withImageAndTag("redis").website("https://hub.docker.com/_/redis").ports(6379).build(); } private static DockerService sqlServer() { return DockerService.withImageAndTag("mcr.microsoft.com/mssql/server") .website("https://mcr.microsoft.com/en-us/product/mssql/server/about/") .ports(1433) .build(); } private static DockerService zipkin() { return DockerService.withImageAndTag("openzipkin/zipkin") .website("https://hub.docker.com/r/openzipkin/zipkin/") .ports(9411) .build(); } @Override public DockerService resolve(String id) { return this.dockerServices.get(id); } }
// They don't provide a 'latest' tag return DockerService.withImageAndTag("docker.elastic.co/elasticsearch/elasticsearch:7.17.10") .website("https://www.docker.elastic.co/r/elasticsearch") .ports(9200, 9300) .build();
1,664
90
1,754
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/build/gradle/GradleBuildSystemHelpDocumentCustomizer.java
GradleBuildSystemHelpDocumentCustomizer
customize
class GradleBuildSystemHelpDocumentCustomizer implements HelpDocumentCustomizer { private final Version springBootVersion; GradleBuildSystemHelpDocumentCustomizer(ProjectDescription description) { this.springBootVersion = description.getPlatformVersion(); } @Override public void customize(HelpDocument document) {<FILL_FUNCTION_BODY>} }
document.gettingStarted() .addAdditionalLink("https://scans.gradle.com#gradle", "Gradle Build Scans – insights for your project's build"); document.gettingStarted().addReferenceDocLink("https://docs.gradle.org", "Official Gradle documentation"); document.gettingStarted() .addReferenceDocLink( String.format("https://docs.spring.io/spring-boot/docs/%s/gradle-plugin/reference/html/", this.springBootVersion), "Spring Boot Gradle Plugin Reference Guide"); document.gettingStarted() .addReferenceDocLink(String.format( "https://docs.spring.io/spring-boot/docs/%s/gradle-plugin/reference/html/#build-image", this.springBootVersion), "Create an OCI image");
87
221
308
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/build/gradle/ManagedDependenciesDependencyManagementPluginVersionResolver.java
ManagedDependenciesDependencyManagementPluginVersionResolver
resolveDependencyManagementPluginVersion
class ManagedDependenciesDependencyManagementPluginVersionResolver implements DependencyManagementPluginVersionResolver { private final MavenVersionResolver versionResolver; private final Function<ProjectDescription, String> fallback; public ManagedDependenciesDependencyManagementPluginVersionResolver(MavenVersionResolver versionResolver, Function<ProjectDescription, String> fallback) { this.versionResolver = versionResolver; this.fallback = fallback; } @Override public String resolveDependencyManagementPluginVersion(ProjectDescription description) {<FILL_FUNCTION_BODY>} }
String pluginVersion = this.versionResolver .resolveDependencies("org.springframework.boot", "spring-boot-dependencies", description.getPlatformVersion().toString()) .get("io.spring.gradle:dependency-management-plugin"); return (pluginVersion != null) ? pluginVersion : this.fallback.apply(description);
138
85
223
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/build/maven/AnnotationProcessorExclusionBuildCustomizer.java
AnnotationProcessorExclusionBuildCustomizer
customize
class AnnotationProcessorExclusionBuildCustomizer implements BuildCustomizer<MavenBuild> { private static final List<String> KNOWN_ANNOTATION_PROCESSORS = Collections .singletonList("configuration-processor"); private final InitializrMetadata metadata; AnnotationProcessorExclusionBuildCustomizer(InitializrMetadata metadata) { this.metadata = metadata; } @Override public void customize(MavenBuild build) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return 5; } private boolean isAnnotationProcessor(String id) { Dependency dependency = this.metadata.getDependencies().get(id); return (dependency != null) && Dependency.SCOPE_ANNOTATION_PROCESSOR.equals(dependency.getScope()); } }
if (!build.plugins().has("org.springframework.boot", "spring-boot-maven-plugin")) { return; } List<io.spring.initializr.generator.buildsystem.Dependency> dependencies = build.dependencies() .ids() .filter(this::isAnnotationProcessor) .filter((id) -> !KNOWN_ANNOTATION_PROCESSORS.contains(id)) .map((id) -> build.dependencies().get(id)) .toList(); if (!dependencies.isEmpty()) { build.plugins() .add("org.springframework.boot", "spring-boot-maven-plugin", (plugin) -> plugin .configuration((configuration) -> configuration.configure("excludes", (excludes) -> { for (io.spring.initializr.generator.buildsystem.Dependency dependency : dependencies) { excludes.add("exclude", (exclude) -> { exclude.add("groupId", dependency.getGroupId()); exclude.add("artifactId", dependency.getArtifactId()); }); } }))); }
206
283
489
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/build/maven/MavenBuildSystemHelpDocumentCustomizer.java
MavenBuildSystemHelpDocumentCustomizer
customize
class MavenBuildSystemHelpDocumentCustomizer implements HelpDocumentCustomizer { private final Version springBootVersion; MavenBuildSystemHelpDocumentCustomizer(ProjectDescription description) { this.springBootVersion = description.getPlatformVersion(); } @Override public void customize(HelpDocument document) {<FILL_FUNCTION_BODY>} private String generateReferenceGuideUrl() { String baseUrlFormat = "https://docs.spring.io/spring-boot/docs/%s/maven-plugin/reference/html/"; return String.format(baseUrlFormat, this.springBootVersion); } }
document.gettingStarted() .addReferenceDocLink("https://maven.apache.org/guides/index.html", "Official Apache Maven documentation"); String referenceGuideUrl = generateReferenceGuideUrl(); document.gettingStarted().addReferenceDocLink(referenceGuideUrl, "Spring Boot Maven Plugin Reference Guide"); String buildImageSection = referenceGuideUrl + "#build-image"; document.gettingStarted().addReferenceDocLink(buildImageSection, "Create an OCI image");
151
133
284
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/code/kotlin/KotlinCoroutinesCustomizer.java
KotlinCoroutinesCustomizer
customize
class KotlinCoroutinesCustomizer { private final BuildMetadataResolver buildResolver; private final ProjectDescription description; private final MavenVersionResolver versionResolver; public KotlinCoroutinesCustomizer(InitializrMetadata metadata, ProjectDescription description, MavenVersionResolver versionResolver) { this.buildResolver = new BuildMetadataResolver(metadata); this.description = description; this.versionResolver = versionResolver; } public void customize(Build build) { if (hasReactiveFacet(build)) { build.dependencies() .add("kotlinx-coroutines-reactor", Dependency.withCoordinates("org.jetbrains.kotlinx", "kotlinx-coroutines-reactor")); } } public void customize(HelpDocument document, Build build) {<FILL_FUNCTION_BODY>} private boolean hasReactiveFacet(Build build) { return this.buildResolver.hasFacet(build, "reactive"); } }
if (hasReactiveFacet(build)) { Map<String, String> resolve = this.versionResolver.resolveDependencies("org.springframework.boot", "spring-boot-dependencies", this.description.getPlatformVersion().toString()); String frameworkVersion = resolve.get("org.springframework:spring-core"); String versionToUse = (frameworkVersion != null) ? frameworkVersion : "current"; String href = String.format( "https://docs.spring.io/spring/docs/%s/spring-framework-reference/languages.html#coroutines", versionToUse); document.gettingStarted() .addReferenceDocLink(href, "Coroutines section of the Spring Framework Documentation"); }
256
186
442
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/code/kotlin/ManagedDependenciesKotlinVersionResolver.java
ManagedDependenciesKotlinVersionResolver
resolveKotlinVersion
class ManagedDependenciesKotlinVersionResolver implements KotlinVersionResolver { private final MavenVersionResolver versionResolver; private final Function<ProjectDescription, String> fallback; public ManagedDependenciesKotlinVersionResolver(MavenVersionResolver versionResolver, Function<ProjectDescription, String> fallback) { this.versionResolver = versionResolver; this.fallback = fallback; } @Override public String resolveKotlinVersion(ProjectDescription description) {<FILL_FUNCTION_BODY>} }
String kotlinVersion = this.versionResolver .resolveDependencies("org.springframework.boot", "spring-boot-dependencies", description.getPlatformVersion().toString()) .get("org.jetbrains.kotlin:kotlin-reflect"); return (kotlinVersion != null) ? kotlinVersion : this.fallback.apply(description);
132
95
227
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/code/kotlin/ReactorKotlinExtensionsCustomizer.java
ReactorKotlinExtensionsCustomizer
customize
class ReactorKotlinExtensionsCustomizer implements BuildCustomizer<Build> { private final BuildMetadataResolver buildResolver; ReactorKotlinExtensionsCustomizer(InitializrMetadata metadata) { this.buildResolver = new BuildMetadataResolver(metadata); } @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} }
if (this.buildResolver.hasFacet(build, "reactive")) { build.dependencies() .add("reactor-kotlin-extensions", Dependency.withCoordinates("io.projectreactor.kotlin", "reactor-kotlin-extensions")); }
93
77
170
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/activemq/ActiveMQProjectGenerationConfiguration.java
ActiveMQProjectGenerationConfiguration
activeMQClassicServiceConnectionsCustomizer
class ActiveMQProjectGenerationConfiguration { private static final String TESTCONTAINERS_CLASS_NAME = "org.testcontainers.activemq.ActiveMQContainer"; @Bean @ConditionalOnPlatformVersion("[3.2.0-M1,3.3.0-M2)") @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer activeMQServiceConnectionsCustomizer(DockerServiceResolver serviceResolver) { return (serviceConnections) -> serviceResolver.doWith("activeMQ", (service) -> serviceConnections .addServiceConnection(ServiceConnection.ofGenericContainer("activeMQ", service, "symptoma/activemq"))); } @Bean @ConditionalOnPlatformVersion("3.3.0-M2") @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer activeMQClassicServiceConnectionsCustomizer(DockerServiceResolver serviceResolver) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnPlatformVersion("[3.2.0-M1,3.3.0-M2)") @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer activeMQComposeFileCustomizer(DockerServiceResolver serviceResolver) { return (composeFile) -> serviceResolver.doWith("activeMQ", (service) -> composeFile.services().add("activemq", service)); } @Bean @ConditionalOnPlatformVersion("3.3.0-M2") @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer activeMQClassicComposeFileCustomizer(DockerServiceResolver serviceResolver) { return (composeFile) -> serviceResolver.doWith("activeMQClassic", (service) -> composeFile.services().add("activemq", service)); } }
return (serviceConnections) -> serviceResolver.doWith("activeMQClassic", (service) -> serviceConnections.addServiceConnection( ServiceConnection.ofContainer("activemq", service, TESTCONTAINERS_CLASS_NAME, false)));
466
68
534
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/activemq/ArtemisProjectGenerationConfiguration.java
ArtemisProjectGenerationConfiguration
artemisServiceConnectionsCustomizer
class ArtemisProjectGenerationConfiguration { private static final String TESTCONTAINERS_CLASS_NAME = "org.testcontainers.activemq.ArtemisContainer"; @Bean @ConditionalOnPlatformVersion("3.3.0-M2") @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer artemisServiceConnectionsCustomizer(DockerServiceResolver serviceResolver) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnPlatformVersion("3.3.0-M2") @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer artemisComposeFileCustomizer(DockerServiceResolver serviceResolver) { return (composeFile) -> serviceResolver.doWith("artemis", (service) -> composeFile.services().add("artemis", service)); } }
return (serviceConnections) -> serviceResolver.doWith("artemis", (service) -> serviceConnections .addServiceConnection(ServiceConnection.ofContainer("artemis", service, TESTCONTAINERS_CLASS_NAME, false)));
218
63
281
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/cassandra/CassandraProjectGenerationConfiguration.java
CassandraProjectGenerationConfiguration
cassandraComposeFileCustomizer
class CassandraProjectGenerationConfiguration { private static final String TESTCONTAINERS_CLASS_NAME = "org.testcontainers.containers.CassandraContainer"; @Bean @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer cassandraServiceConnectionsCustomizer(Build build, DockerServiceResolver serviceResolver) { return (serviceConnections) -> { if (isCassandraEnabled(build)) { serviceResolver.doWith("cassandra", (service) -> serviceConnections.addServiceConnection( ServiceConnection.ofContainer("cassandra", service, TESTCONTAINERS_CLASS_NAME))); } }; } @Bean @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer cassandraComposeFileCustomizer(Build build, DockerServiceResolver serviceResolver) {<FILL_FUNCTION_BODY>} private boolean isCassandraEnabled(Build build) { return build.dependencies().has("data-cassandra") || build.dependencies().has("data-cassandra-reactive"); } }
return (composeFile) -> { if (isCassandraEnabled(build)) { serviceResolver.doWith("cassandra", (service) -> composeFile.services() .add("cassandra", service.andThen((builder) -> builder.environment("CASSANDRA_DC", "dc1") .environment("CASSANDRA_ENDPOINT_SNITCH", "GossipingPropertyFileSnitch")))); } };
277
119
396
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/dgs/DgsCodegenGroovyDslGradleBuildCustomizer.java
DgsCodegenGroovyDslGradleBuildCustomizer
customize
class DgsCodegenGroovyDslGradleBuildCustomizer implements BuildCustomizer<GradleBuild> { private final String pluginVersion; private final String packageName; DgsCodegenGroovyDslGradleBuildCustomizer(String pluginVersion, String packageName) { this.pluginVersion = pluginVersion; this.packageName = packageName; } @Override public void customize(GradleBuild build) {<FILL_FUNCTION_BODY>} }
build.plugins().add("com.netflix.dgs.codegen", (plugin) -> plugin.setVersion(this.pluginVersion)); build.snippets().add((writer) -> { writer.println("generateJava {"); writer.indented(() -> { writer.println("schemaPaths = [\"${projectDir}/src/main/resources/graphql-client\"]"); writer.println("packageName = '" + this.packageName + ".codegen'"); writer.println("generateClient = true"); }); writer.println("}"); });
125
158
283
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/dgs/DgsCodegenHelpDocumentCustomizer.java
DgsCodegenHelpDocumentCustomizer
customize
class DgsCodegenHelpDocumentCustomizer implements HelpDocumentCustomizer { private final BuildSystem buildSystem; DgsCodegenHelpDocumentCustomizer(ProjectDescription description) { this.buildSystem = description.getBuildSystem(); } @Override public void customize(HelpDocument document) {<FILL_FUNCTION_BODY>} }
Map<String, Object> model = new HashMap<>(); if (MavenBuildSystem.ID.equals(this.buildSystem.id())) { model.put("dsgCodegenOptionsLink", "https://github.com/deweyjose/graphqlcodegen"); } else if (GradleBuildSystem.ID.equals(this.buildSystem.id())) { model.put("dsgCodegenOptionsLink", "https://netflix.github.io/dgs/generating-code-from-schema/#configuring-code-generation"); } document.addSection("dgscodegen", model);
88
168
256
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/dgs/DgsCodegenKotlinDslGradleBuildCustomizer.java
DgsCodegenKotlinDslGradleBuildCustomizer
customize
class DgsCodegenKotlinDslGradleBuildCustomizer implements BuildCustomizer<GradleBuild> { private final String pluginVersion; private final String packageName; DgsCodegenKotlinDslGradleBuildCustomizer(String pluginVersion, String packageName) { this.pluginVersion = pluginVersion; this.packageName = packageName; } @Override public void customize(GradleBuild build) {<FILL_FUNCTION_BODY>} }
build.plugins().add("com.netflix.dgs.codegen", (plugin) -> plugin.setVersion(this.pluginVersion)); build.snippets().add((writer) -> { writer.println("tasks.generateJava {"); writer.indented(() -> { writer.println("schemaPaths.add(\"${projectDir}/src/main/resources/graphql-client\")"); writer.println("packageName = \"" + this.packageName + ".codegen\""); writer.println("generateClient = true"); }); writer.println("}"); });
123
163
286
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/dgs/DgsCodegenMavenBuildCustomizer.java
DgsCodegenMavenBuildCustomizer
customize
class DgsCodegenMavenBuildCustomizer implements BuildCustomizer<MavenBuild> { private final String pluginVersion; private final String packageName; public DgsCodegenMavenBuildCustomizer(String pluginVersion, String packageName) { this.pluginVersion = pluginVersion; this.packageName = packageName; } @Override public void customize(MavenBuild build) {<FILL_FUNCTION_BODY>} }
build.plugins() .add("io.github.deweyjose", "graphqlcodegen-maven-plugin", (plugin) -> plugin.version(this.pluginVersion) .execution("dgs-codegen", (execution) -> execution.goal("generate") .configuration((configuration) -> configuration .add("schemaPaths", (schemaPaths) -> schemaPaths.add("param", "src/main/resources/graphql-client")) .add("packageName", this.packageName + ".codegen") .add("addGeneratedAnnotation", "true")))); build.plugins() .add("org.codehaus.mojo", "build-helper-maven-plugin", (plugin) -> plugin.execution("add-dgs-source", (execution) -> execution.goal("add-source") .phase("generate-sources") .configuration((configuration) -> configuration.add("sources", (sources) -> sources.add("source", "${project.build.directory}/generated-sources")))));
113
276
389
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/dgs/DgsCodegenVersionResolver.java
DgsCodegenVersionResolver
resolve
class DgsCodegenVersionResolver { static String resolve(InitializrMetadata metadata, Version platformVersion, BuildSystem build) {<FILL_FUNCTION_BODY>} }
if (GradleBuildSystem.ID.equals(build.id())) { return metadata.getDependencies().get("dgs-codegen").resolve(platformVersion).getVersion(); } else if (MavenBuildSystem.ID.equals(build.id())) { // https://github.com/deweyjose/graphqlcodegen/releases return "1.50"; } throw new IllegalArgumentException("Could not resolve DGS Codegen version for build system " + build.id());
47
131
178
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/dockercompose/DockerComposeProjectGenerationConfiguration.java
DockerComposeProjectGenerationConfiguration
dockerComposeFile
class DockerComposeProjectGenerationConfiguration { @Bean ComposeFile dockerComposeFile(ObjectProvider<ComposeFileCustomizer> composeFileCustomizers) {<FILL_FUNCTION_BODY>} @Bean ComposeProjectContributor dockerComposeProjectContributor(ComposeFile composeFile, IndentingWriterFactory indentingWriterFactory) { return new ComposeProjectContributor(composeFile, indentingWriterFactory); } @Bean ComposeHelpDocumentCustomizer dockerComposeHelpDocumentCustomizer(ComposeFile composeFile) { return new ComposeHelpDocumentCustomizer(composeFile); } }
ComposeFile composeFile = new ComposeFile(); composeFileCustomizers.orderedStream().forEach((customizer) -> customizer.customize(composeFile)); return composeFile;
166
54
220
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/elasticsearch/ElasticsearchProjectGenerationConfiguration.java
ElasticsearchProjectGenerationConfiguration
elasticsearchComposeFileCustomizer
class ElasticsearchProjectGenerationConfiguration { private static String TESTCONTAINERS_CLASS_NAME = "org.testcontainers.elasticsearch.ElasticsearchContainer"; @Bean @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer elasticsearchServiceConnectionsCustomizer(DockerServiceResolver serviceResolver) { return (serviceConnections) -> serviceResolver.doWith("elasticsearch", (service) -> serviceConnections.addServiceConnection( ServiceConnection.ofContainer("elasticsearch", service, TESTCONTAINERS_CLASS_NAME, false))); } @Bean @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer elasticsearchComposeFileCustomizer(DockerServiceResolver serviceResolver) {<FILL_FUNCTION_BODY>} }
return (composeFile) -> serviceResolver.doWith("elasticsearch", (service) -> composeFile.services() .add("elasticsearch", service.andThen((builder) -> builder.environment("ELASTIC_PASSWORD", "secret") .environment("xpack.security.enabled", "false") .environment("discovery.type", "single-node"))));
200
101
301
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/flyway/FlywayBuildCustomizer.java
FlywayBuildCustomizer
customize
class FlywayBuildCustomizer implements BuildCustomizer<Build> { private static final VersionRange SPRING_BOOT_3_2_M1_OR_LATER = VersionParser.DEFAULT.parseRange("3.2.0-M1"); private static final VersionRange SPRING_BOOT_3_3_M3_OR_LATER = VersionParser.DEFAULT.parseRange("3.3.0-M3"); private final boolean isSpringBoot32OrLater; private final boolean isSpringBoot33OrLater; FlywayBuildCustomizer(ProjectDescription projectDescription) { this.isSpringBoot32OrLater = SPRING_BOOT_3_2_M1_OR_LATER.match(projectDescription.getPlatformVersion()); this.isSpringBoot33OrLater = SPRING_BOOT_3_3_M3_OR_LATER.match(projectDescription.getPlatformVersion()); } @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} }
DependencyContainer dependencies = build.dependencies(); if ((dependencies.has("mysql") || dependencies.has("mariadb"))) { dependencies.add("flyway-mysql", "org.flywaydb", "flyway-mysql", DependencyScope.COMPILE); } if (dependencies.has("sqlserver")) { dependencies.add("flyway-sqlserver", "org.flywaydb", "flyway-sqlserver", DependencyScope.COMPILE); } if (this.isSpringBoot32OrLater) { if (dependencies.has("oracle")) { dependencies.add("flyway-oracle", "org.flywaydb", "flyway-database-oracle", DependencyScope.COMPILE); } } if (this.isSpringBoot33OrLater) { if (dependencies.has("db2")) { dependencies.add("flyway-database-db2", "org.flywaydb", "flyway-database-db2", DependencyScope.COMPILE); } if (dependencies.has("derby")) { dependencies.add("flyway-database-derby", "org.flywaydb", "flyway-database-derby", DependencyScope.COMPILE); } if (dependencies.has("hsql")) { dependencies.add("flyway-database-hsqldb", "org.flywaydb", "flyway-database-hsqldb", DependencyScope.COMPILE); } if (dependencies.has("postgresql")) { dependencies.add("flyway-database-postgresql", "org.flywaydb", "flyway-database-postgresql", DependencyScope.COMPILE); } }
265
459
724
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/graalvm/GraalVmGradleBuildCustomizer.java
GraalVmGradleBuildCustomizer
customize
class GraalVmGradleBuildCustomizer implements BuildCustomizer<GradleBuild> { private final String nbtVersion; protected GraalVmGradleBuildCustomizer(String nbtVersion) { this.nbtVersion = nbtVersion; } @Override public final void customize(GradleBuild build) {<FILL_FUNCTION_BODY>} protected void customizeSpringBootPlugin(GradleBuild build) { } }
if (this.nbtVersion != null) { build.plugins().add("org.graalvm.buildtools.native", (plugin) -> plugin.setVersion(this.nbtVersion)); } // Spring Boot plugin customizeSpringBootPlugin(build);
115
74
189
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/graalvm/GraalVmHelpDocumentCustomizer.java
GraalVmHelpDocumentCustomizer
customize
class GraalVmHelpDocumentCustomizer implements HelpDocumentCustomizer { private final InitializrMetadata metadata; private final ProjectDescription description; private final Build build; private final Version platformVersion; GraalVmHelpDocumentCustomizer(InitializrMetadata metadata, ProjectDescription description, Build build) { this.metadata = metadata; this.description = description; this.build = build; this.platformVersion = description.getPlatformVersion(); } @Override public void customize(HelpDocument document) {<FILL_FUNCTION_BODY>} private String createRunImageCommand() { StringBuilder sb = new StringBuilder("docker run --rm"); boolean hasWeb = buildDependencies().anyMatch((dependency) -> dependency.getFacets().contains("web")); if (hasWeb) { sb.append(" -p 8080:8080"); } sb.append(" ").append(this.description.getArtifactId()).append(":").append(this.description.getVersion()); return sb.toString(); } private Stream<Dependency> buildDependencies() { return this.build.dependencies() .ids() .map((id) -> this.metadata.getDependencies().get(id)) .filter(Objects::nonNull); } }
document.gettingStarted() .addReferenceDocLink(String.format( "https://docs.spring.io/spring-boot/docs/%s/reference/html/native-image.html#native-image", this.platformVersion), "GraalVM Native Image Support"); boolean mavenBuild = this.build instanceof MavenBuild; String url = String.format("https://docs.spring.io/spring-boot/docs/%s/%s/reference/htmlsingle/#aot", this.platformVersion, (mavenBuild) ? "maven-plugin" : "gradle-plugin"); document.gettingStarted().addAdditionalLink(url, "Configure AOT settings in Build Plugin"); Map<String, Object> model = new HashMap<>(); // Cloud native buildpacks model.put("cnbBuildImageCommand", mavenBuild ? "./mvnw spring-boot:build-image -Pnative" : "./gradlew bootBuildImage"); model.put("cnbRunImageCommand", createRunImageCommand()); // Native buildtools plugin model.put("nbtBuildImageCommand", mavenBuild ? "./mvnw native:compile -Pnative" : "./gradlew nativeCompile"); model.put("nbtRunImageCommand", String.format("%s/%s", mavenBuild ? "target" : "build/native/nativeCompile", this.build.getSettings().getArtifact())); // Tests execution model.put("testsExecutionCommand", mavenBuild ? "./mvnw test -PnativeTest" : "./gradlew nativeTest"); document.addSection("graalvm", model);
330
418
748
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/graalvm/GraalVmProjectGenerationConfiguration.java
HibernateConfiguration
determineHibernateVersion
class HibernateConfiguration { private final Version platformVersion; HibernateConfiguration(ProjectDescription description) { this.platformVersion = description.getPlatformVersion(); } @Bean @ConditionalOnBuildSystem(MavenBuildSystem.ID) HibernatePluginMavenBuildCustomizer hibernatePluginMavenBuildCustomizer() { return new HibernatePluginMavenBuildCustomizer(); } @Bean @ConditionalOnBuildSystem(value = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_GROOVY) HibernatePluginGroovyDslGradleBuildCustomizer hibernatePluginGroovyDslGradleBuildCustomizer( MavenVersionResolver versionResolver) { return new HibernatePluginGroovyDslGradleBuildCustomizer(determineHibernateVersion(versionResolver)); } @Bean @ConditionalOnBuildSystem(value = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_KOTLIN) HibernatePluginKotlinDslGradleBuildCustomizer hibernatePluginKotlinDslGradleBuildCustomizer( MavenVersionResolver versionResolver) { return new HibernatePluginKotlinDslGradleBuildCustomizer(determineHibernateVersion(versionResolver)); } private Version determineHibernateVersion(MavenVersionResolver versionResolver) {<FILL_FUNCTION_BODY>} }
Map<String, String> resolve = versionResolver.resolveDependencies("org.springframework.boot", "spring-boot-dependencies", this.platformVersion.toString()); String hibernateVersion = resolve.get("org.hibernate.orm" + ":hibernate-core"); if (hibernateVersion == null) { throw new IllegalStateException( "Failed to determine Hibernate version for Spring Boot " + this.platformVersion); } return Version.parse(hibernateVersion);
372
125
497
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/graalvm/HibernatePluginGroovyDslGradleBuildCustomizer.java
HibernatePluginGroovyDslGradleBuildCustomizer
customize
class HibernatePluginGroovyDslGradleBuildCustomizer implements BuildCustomizer<GradleBuild> { private final Version hibernateVersion; HibernatePluginGroovyDslGradleBuildCustomizer(Version hibernateVersion) { this.hibernateVersion = hibernateVersion; } @Override public void customize(GradleBuild build) {<FILL_FUNCTION_BODY>} }
build.plugins().add("org.hibernate.orm", (plugin) -> plugin.setVersion(this.hibernateVersion.toString())); build.snippets().add((writer) -> { writer.println("hibernate {"); writer.indented(() -> { writer.println("enhancement {"); writer.indented(() -> writer.println("enableAssociationManagement = true")); writer.println("}"); }); writer.println("}"); });
108
133
241
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/graalvm/HibernatePluginKotlinDslGradleBuildCustomizer.java
HibernatePluginKotlinDslGradleBuildCustomizer
customize
class HibernatePluginKotlinDslGradleBuildCustomizer implements BuildCustomizer<GradleBuild> { private final Version hibernateVersion; HibernatePluginKotlinDslGradleBuildCustomizer(Version hibernateVersion) { this.hibernateVersion = hibernateVersion; } @Override public void customize(GradleBuild build) {<FILL_FUNCTION_BODY>} }
build.plugins().add("org.hibernate.orm", (plugin) -> plugin.setVersion(this.hibernateVersion.toString())); build.snippets().add((writer) -> { writer.println("hibernate {"); writer.indented(() -> { writer.println("enhancement {"); writer.indented(() -> writer.println("enableAssociationManagement.set(true)")); writer.println("}"); }); writer.println("}"); });
106
136
242
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/graalvm/HibernatePluginMavenBuildCustomizer.java
HibernatePluginMavenBuildCustomizer
customize
class HibernatePluginMavenBuildCustomizer implements BuildCustomizer<MavenBuild> { @Override public void customize(MavenBuild build) {<FILL_FUNCTION_BODY>} }
build.plugins() .add("org.hibernate.orm.tooling", "hibernate-enhance-maven-plugin", (plugin) -> plugin.version("${hibernate.version}") .execution("enhance", (execution) -> execution.goal("enhance") .configuration((configuration) -> configuration.add("enableLazyInitialization", "true") .add("enableDirtyTracking", "true") .add("enableAssociationManagement", "true"))));
51
129
180
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/graalvm/NativeBuildtoolsVersionResolver.java
NativeBuildtoolsVersionResolver
resolve
class NativeBuildtoolsVersionResolver { static String resolve(MavenVersionResolver versionResolver, Version platformVersion) {<FILL_FUNCTION_BODY>} }
Map<String, String> resolve = versionResolver.resolvePlugins("org.springframework.boot", "spring-boot-dependencies", platformVersion.toString()); return resolve.get("org.graalvm.buildtools:native-maven-plugin");
42
65
107
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/graphql/SpringGraphQlBuildCustomizer.java
SpringGraphQlBuildCustomizer
customize
class SpringGraphQlBuildCustomizer implements BuildCustomizer<Build> { private final BuildMetadataResolver buildResolver; SpringGraphQlBuildCustomizer(InitializrMetadata metadata) { this.buildResolver = new BuildMetadataResolver(metadata); } @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} }
build.dependencies() .add("spring-graphql-test", Dependency.withCoordinates("org.springframework.graphql", "spring-graphql-test") .scope(DependencyScope.TEST_COMPILE)); if (!this.buildResolver.hasFacet(build, "reactive")) { build.dependencies() .add("spring-webflux", Dependency.withCoordinates("org.springframework", "spring-webflux") .scope(DependencyScope.TEST_COMPILE)); }
90
135
225
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/hilla/HillaMavenBuildCustomizer.java
HillaMavenBuildCustomizer
customize
class HillaMavenBuildCustomizer implements BuildCustomizer<MavenBuild> { @Override public void customize(MavenBuild build) {<FILL_FUNCTION_BODY>} }
build.plugins() .add("dev.hilla", "hilla-maven-plugin", (plugin) -> plugin.version("${hilla.version}") .execution("frontend", (execution) -> execution.goal("prepare-frontend"))); build.profiles() .id("production") .plugins() .add("dev.hilla", "hilla-maven-plugin", (plugin) -> plugin.version("${hilla.version}") .execution("frontend", (execution) -> execution.goal("build-frontend") .phase("compile") .configuration((configuration) -> configuration.add("productionMode", "true"))));
49
178
227
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/lombok/LombokGradleBuildCustomizer.java
LombokGradleBuildCustomizer
customize
class LombokGradleBuildCustomizer implements BuildCustomizer<GradleBuild> { private final InitializrMetadata metadata; public LombokGradleBuildCustomizer(InitializrMetadata metadata) { this.metadata = metadata; } @Override public void customize(GradleBuild build) {<FILL_FUNCTION_BODY>} }
Dependency lombok = this.metadata.getDependencies().get("lombok"); build.dependencies() .add("lombok-compileOnly", lombok.getGroupId(), lombok.getArtifactId(), DependencyScope.COMPILE_ONLY);
89
74
163
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/mariadb/MariaDbProjectGenerationConfiguration.java
MariaDbProjectGenerationConfiguration
mariaDbComposeFileCustomizer
class MariaDbProjectGenerationConfiguration { private static final String TESTCONTAINERS_CLASS_NAME = "org.testcontainers.containers.MariaDBContainer"; @Bean @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer mariaDbServiceConnectionsCustomizer(DockerServiceResolver serviceResolver) { return (serviceConnections) -> serviceResolver.doWith("mariaDb", (service) -> serviceConnections .addServiceConnection(ServiceConnection.ofContainer("mariaDb", service, TESTCONTAINERS_CLASS_NAME))); } @Bean @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer mariaDbComposeFileCustomizer(DockerServiceResolver serviceResolver) {<FILL_FUNCTION_BODY>} }
return (composeFile) -> serviceResolver.doWith("mariaDb", (service) -> composeFile.services() .add("mariadb", service.andThen((builder) -> builder.environment("MARIADB_ROOT_PASSWORD", "verysecret") .environment("MARIADB_USER", "myuser") .environment("MARIADB_PASSWORD", "secret") .environment("MARIADB_DATABASE", "mydatabase"))));
199
128
327
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/mongodb/MongoDbProjectGenerationConfiguration.java
MongoDbProjectGenerationConfiguration
mongoDbServiceConnectionsCustomizer
class MongoDbProjectGenerationConfiguration { private static final String TESTCONTAINERS_CLASS_NAME = "org.testcontainers.containers.MongoDBContainer"; @Bean @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer mongoDbServiceConnectionsCustomizer(Build build, DockerServiceResolver serviceResolver) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer mongoDbComposeFileCustomizer(Build build, DockerServiceResolver serviceResolver) { return (composeFile) -> { if (isMongoEnabled(build)) { serviceResolver.doWith("mongoDb", (service) -> composeFile.services() .add("mongodb", service.andThen((builder) -> builder.environment("MONGO_INITDB_ROOT_USERNAME", "root") .environment("MONGO_INITDB_ROOT_PASSWORD", "secret") .environment("MONGO_INITDB_DATABASE", "mydatabase")))); } }; } private boolean isMongoEnabled(Build build) { return build.dependencies().has("data-mongodb") || build.dependencies().has("data-mongodb-reactive"); } }
return (serviceConnections) -> { if (isMongoEnabled(build)) { serviceResolver.doWith("mongoDb", (service) -> serviceConnections.addServiceConnection( ServiceConnection.ofContainer("mongoDb", service, TESTCONTAINERS_CLASS_NAME, false))); } };
332
86
418
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/mybatis/MyBatisTestBuildCustomizer.java
MyBatisTestBuildCustomizer
customize
class MyBatisTestBuildCustomizer implements BuildCustomizer<Build> { @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} }
Dependency mybatis = build.dependencies().get("mybatis"); build.dependencies() .add("mybatis-test", Dependency.withCoordinates(mybatis.getGroupId(), mybatis.getArtifactId() + "-test") .version(mybatis.getVersion()) .scope(DependencyScope.TEST_COMPILE));
46
97
143
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/mysql/MysqlProjectGenerationConfiguration.java
MysqlProjectGenerationConfiguration
mysqlComposeFileCustomizer
class MysqlProjectGenerationConfiguration { private static String TESTCONTAINERS_CLASS_NAME = "org.testcontainers.containers.MySQLContainer"; @Bean @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer mysqlServiceConnectionsCustomizer(DockerServiceResolver serviceResolver) { return (serviceConnections) -> serviceResolver.doWith("mysql", (service) -> serviceConnections .addServiceConnection(ServiceConnection.ofContainer("mysql", service, TESTCONTAINERS_CLASS_NAME))); } @Bean @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer mysqlComposeFileCustomizer(DockerServiceResolver serviceResolver) {<FILL_FUNCTION_BODY>} }
return (composeFile) -> serviceResolver.doWith("mysql", (service) -> composeFile.services() .add("mysql", service.andThen((builder) -> builder.environment("MYSQL_ROOT_PASSWORD", "verysecret") .environment("MYSQL_USER", "myuser") .environment("MYSQL_PASSWORD", "secret") .environment("MYSQL_DATABASE", "mydatabase"))));
190
115
305
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/neo4j/Neo4jProjectGenerationConfiguration.java
Neo4jProjectGenerationConfiguration
neo4jServiceConnectionsCustomizer
class Neo4jProjectGenerationConfiguration { private static final String TESTCONTAINERS_CLASS_NAME = "org.testcontainers.containers.Neo4jContainer"; @Bean @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer neo4jServiceConnectionsCustomizer(Build build, DockerServiceResolver serviceResolver) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer neo4jComposeFileCustomizer(Build build, DockerServiceResolver serviceResolver) { return (composeFile) -> { if (isNeo4jEnabled(build)) { serviceResolver.doWith("neo4j", (service) -> composeFile.services() .add("neo4j", service.andThen((builder) -> builder.environment("NEO4J_AUTH", "neo4j/notverysecret")))); } }; } private boolean isNeo4jEnabled(Build build) { return build.dependencies().has("data-neo4j") || build.dependencies().has("spring-ai-vectordb-neo4j"); } }
return (serviceConnections) -> { if (isNeo4jEnabled(build)) { serviceResolver.doWith("neo4j", (service) -> serviceConnections .addServiceConnection(ServiceConnection.ofContainer("neo4j", service, TESTCONTAINERS_CLASS_NAME))); } };
308
87
395
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/observability/Observability2xHelpDocumentCustomizer.java
Observability2xHelpDocumentCustomizer
customize
class Observability2xHelpDocumentCustomizer implements HelpDocumentCustomizer { private final Build build; public Observability2xHelpDocumentCustomizer(Build build) { this.build = build; } @Override public void customize(HelpDocument document) {<FILL_FUNCTION_BODY>} }
if (this.build.dependencies().has("distributed-tracing")) { document.gettingStarted() .addReferenceDocLink( "https://docs.spring.io/spring-cloud-sleuth/docs/current/reference/htmlsingle/spring-cloud-sleuth.html", "Spring Cloud Sleuth Reference Guide"); }
78
94
172
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/observability/ObservabilityDistributedTracingBuildCustomizer.java
ObservabilityDistributedTracingBuildCustomizer
customize
class ObservabilityDistributedTracingBuildCustomizer implements BuildCustomizer<Build> { @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} }
// Zipkin without distributed tracing make no sense if (build.dependencies().has("zipkin") && !build.dependencies().has("distributed-tracing")) { build.dependencies().add("distributed-tracing"); } if (build.dependencies().has("wavefront") && build.dependencies().has("distributed-tracing")) { build.dependencies() .add("wavefront-tracing-reporter", Dependency.withCoordinates("io.micrometer", "micrometer-tracing-reporter-wavefront") .scope(DependencyScope.RUNTIME)); }
47
160
207
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/observability/ObservabilityHelpDocumentCustomizer.java
ObservabilityHelpDocumentCustomizer
customize
class ObservabilityHelpDocumentCustomizer implements HelpDocumentCustomizer { private final Version platformVersion; private final Build build; public ObservabilityHelpDocumentCustomizer(ProjectDescription description, Build build) { this.platformVersion = description.getPlatformVersion(); this.build = build; } @Override public void customize(HelpDocument document) {<FILL_FUNCTION_BODY>} }
if (this.build.dependencies().has("distributed-tracing")) { document.gettingStarted() .addReferenceDocLink("https://micrometer.io/docs/tracing", "Distributed Tracing Reference Guide"); document.gettingStarted() .addReferenceDocLink(String.format( "https://docs.spring.io/spring-boot/docs/%s/reference/html/actuator.html#actuator.micrometer-tracing.getting-started", this.platformVersion), "Getting Started with Distributed Tracing"); }
99
153
252
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/observability/WavefrontHelpDocumentCustomizer.java
WavefrontHelpDocumentCustomizer
customize
class WavefrontHelpDocumentCustomizer implements HelpDocumentCustomizer { private final Build build; private final String referenceLink; WavefrontHelpDocumentCustomizer(String referenceLink, Build build) { this.referenceLink = referenceLink; this.build = build; } @Override public void customize(HelpDocument document) {<FILL_FUNCTION_BODY>} }
document.gettingStarted().addReferenceDocLink(this.referenceLink, "Wavefront for Spring Boot documentation"); StringBuilder sb = new StringBuilder(); sb.append(String.format("## Observability with Wavefront%n%n")); sb.append(String .format("If you don't have a Wavefront account, the starter will create a freemium account for you.%n")); sb.append(String.format("The URL to access the Wavefront Service dashboard is logged on startup.%n")); if (this.build.dependencies().has("web") || this.build.dependencies().has("webflux")) { sb.append( String.format("%nYou can also access your dashboard using the `/actuator/wavefront` endpoint.%n")); } if (!this.build.dependencies().has("distributed-tracing")) { sb.append(String.format( "%nFinally, you can opt-in for distributed tracing by adding the 'Distributed Tracing' entry.%n")); } document.addSection((writer) -> writer.print(sb));
98
291
389
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/oracle/OracleProjectGenerationConfiguration.java
OracleProjectGenerationConfiguration
oracleServiceConnectionsCustomizer
class OracleProjectGenerationConfiguration { @Bean @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer oracleServiceConnectionsCustomizer(DockerServiceResolver serviceResolver, ProjectDescription projectDescription) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer oracleComposeFileCustomizer(DockerServiceResolver serviceResolver, ProjectDescription projectDescription) { OracleContainer oracleContainer = OracleContainer.forVersion(projectDescription.getPlatformVersion()); return (composeFile) -> serviceResolver.doWith(oracleContainer.serviceId, (service) -> composeFile.services() .add("oracle", service.andThen((builder) -> builder.environment("ORACLE_PASSWORD", "secret")))); } private enum OracleContainer { FREE("oracleFree", "org.testcontainers.oracle.OracleContainer"), XE("oracleXe", "org.testcontainers.containers.OracleContainer"); private static final VersionRange SPRING_BOOT_3_2_0_OR_LATER = VersionParser.DEFAULT.parseRange("3.2.0"); private final String serviceId; private final String testcontainersClassName; OracleContainer(String serviceId, String testcontainersClassName) { this.serviceId = serviceId; this.testcontainersClassName = testcontainersClassName; } static OracleContainer forVersion(Version version) { return SPRING_BOOT_3_2_0_OR_LATER.match(version) ? FREE : XE; } } }
OracleContainer oracleContainer = OracleContainer.forVersion(projectDescription.getPlatformVersion()); return (serviceConnections) -> serviceResolver.doWith(oracleContainer.serviceId, (service) -> serviceConnections.addServiceConnection(ServiceConnection .ofContainer(oracleContainer.serviceId, service, oracleContainer.testcontainersClassName, false)));
424
89
513
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/picocli/PicocliCodegenBuildCustomizer.java
PicocliCodegenBuildCustomizer
customize
class PicocliCodegenBuildCustomizer implements BuildCustomizer<Build> { @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} }
if (build.dependencies().has("native")) { VersionReference picocliVersion = build.dependencies().get("picocli").getVersion(); Dependency picocliCodegen = Dependency.withCoordinates("info.picocli", "picocli-codegen") .scope(DependencyScope.ANNOTATION_PROCESSOR) .version(picocliVersion) .build(); build.dependencies().add("picocli-codegen", picocliCodegen); }
47
134
181
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/postgresql/PgVectorProjectGenerationConfiguration.java
PgVectorProjectGenerationConfiguration
pgvectorComposeFileCustomizer
class PgVectorProjectGenerationConfiguration { private static final String TESTCONTAINERS_CLASS_NAME = "org.testcontainers.containers.PostgreSQLContainer"; private static final VersionRange TESTCONTAINERS_1_19_7_OR_LATER = VersionParser.DEFAULT.parseRange("1.19.7"); private final MavenVersionResolver versionResolver; private final ProjectDescription description; PgVectorProjectGenerationConfiguration(MavenVersionResolver versionResolver, ProjectDescription description) { this.versionResolver = versionResolver; this.description = description; } @Bean @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer pgvectorServiceConnectionsCustomizer(DockerServiceResolver serviceResolver) { Map<String, String> resolve = this.versionResolver.resolveDependencies("org.springframework.boot", "spring-boot-dependencies", this.description.getPlatformVersion().toString()); String testcontainersVersion = resolve.get("org.testcontainers:testcontainers"); return (serviceConnections) -> { if (TESTCONTAINERS_1_19_7_OR_LATER.match(Version.parse(testcontainersVersion))) { serviceResolver.doWith("pgvector", (service) -> serviceConnections.addServiceConnection( ServiceConnection.ofContainer("pgvector", service, TESTCONTAINERS_CLASS_NAME))); } }; } @Bean @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer pgvectorComposeFileCustomizer(DockerServiceResolver serviceResolver) {<FILL_FUNCTION_BODY>} }
return (composeFile) -> serviceResolver.doWith("pgvector", (service) -> composeFile.services() .add("pgvector", service.andThen((builder) -> builder.environment("POSTGRES_USER", "myuser") .environment("POSTGRES_DB", "mydatabase") .environment("POSTGRES_PASSWORD", "secret") .label("org.springframework.boot.service-connection", "postgres"))));
413
119
532
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/postgresql/PostgresqlProjectGenerationConfiguration.java
PostgresqlProjectGenerationConfiguration
postgresqlComposeFileCustomizer
class PostgresqlProjectGenerationConfiguration { private static final String TESTCONTAINERS_CLASS_NAME = "org.testcontainers.containers.PostgreSQLContainer"; @Bean @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer postgresqlServiceConnectionsCustomizer(DockerServiceResolver serviceResolver) { return (serviceConnections) -> serviceResolver.doWith("postgres", (service) -> serviceConnections .addServiceConnection(ServiceConnection.ofContainer("postgres", service, TESTCONTAINERS_CLASS_NAME))); } @Bean @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer postgresqlComposeFileCustomizer(DockerServiceResolver serviceResolver) {<FILL_FUNCTION_BODY>} }
return (composeFile) -> serviceResolver.doWith("postgres", (service) -> composeFile.services() .add("postgres", service.andThen((builder) -> builder.environment("POSTGRES_USER", "myuser") .environment("POSTGRES_DB", "mydatabase") .environment("POSTGRES_PASSWORD", "secret"))));
195
100
295
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/reactor/ReactorTestBuildCustomizer.java
ReactorTestBuildCustomizer
customize
class ReactorTestBuildCustomizer implements BuildCustomizer<Build> { private final BuildMetadataResolver buildResolver; public ReactorTestBuildCustomizer(InitializrMetadata metadata) { this.buildResolver = new BuildMetadataResolver(metadata); } @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} }
if (this.buildResolver.hasFacet(build, "reactive")) { build.dependencies() .add("reactor-test", Dependency.withCoordinates("io.projectreactor", "reactor-test") .scope(DependencyScope.TEST_COMPILE)); }
87
78
165
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/redis/RedisProjectGenerationConfiguration.java
RedisProjectGenerationConfiguration
redisServiceConnectionsCustomizer
class RedisProjectGenerationConfiguration { @Bean @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer redisServiceConnectionsCustomizer(Build build, DockerServiceResolver serviceResolver) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer redisComposeFileCustomizer(Build build, DockerServiceResolver serviceResolver) { return (composeFile) -> { if (isRedisEnabled(build)) { serviceResolver.doWith("redis", (service) -> composeFile.services().add("redis", service)); } }; } private boolean isRedisEnabled(Build build) { return (build.dependencies().has("data-redis") || build.dependencies().has("data-redis-reactive")); } }
return (serviceConnections) -> { if (isRedisEnabled(build)) { serviceResolver.doWith("redis", (service) -> serviceConnections .addServiceConnection(ServiceConnection.ofGenericContainer("redis", service, "redis"))); } };
219
76
295
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/solace/SolaceBinderBuildCustomizer.java
SolaceBinderBuildCustomizer
resolveBom
class SolaceBinderBuildCustomizer implements BuildCustomizer<Build> { private static final String BOM_ID = "solace-spring-cloud"; private final BillOfMaterials bom; SolaceBinderBuildCustomizer(InitializrMetadata metadata, ProjectDescription description) { this.bom = resolveBom(metadata, description); } private static BillOfMaterials resolveBom(InitializrMetadata metadata, ProjectDescription description) {<FILL_FUNCTION_BODY>} @Override public void customize(Build build) { if (this.bom != null) { build.properties().version(this.bom.getVersionProperty(), this.bom.getVersion()); build.boms().add(BOM_ID); build.dependencies() .add("solace-binder", Dependency.withCoordinates("com.solace.spring.cloud", "spring-cloud-starter-stream-solace")); // The low-level API is likely not going to be used in such arrangement build.dependencies().remove("solace"); } } }
try { return metadata.getConfiguration().getEnv().getBoms().get(BOM_ID).resolve(description.getPlatformVersion()); } catch (InvalidInitializrMetadataException ex) { return null; }
276
63
339
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springamqp/SpringAmqpProjectGenerationConfiguration.java
SpringAmqpProjectGenerationConfiguration
rabbitComposeFileCustomizer
class SpringAmqpProjectGenerationConfiguration { private static String TESTCONTAINERS_CLASS_NAME = "org.testcontainers.containers.RabbitMQContainer"; @Bean SpringRabbitTestBuildCustomizer springAmqpTestBuildCustomizer() { return new SpringRabbitTestBuildCustomizer(); } @Bean @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer rabbitServiceConnectionsCustomizer(DockerServiceResolver serviceResolver) { return (serviceConnections) -> serviceResolver.doWith("rabbit", (service) -> serviceConnections .addServiceConnection(ServiceConnection.ofContainer("rabbit", service, TESTCONTAINERS_CLASS_NAME, false))); } @Bean @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer rabbitComposeFileCustomizer(DockerServiceResolver serviceResolver) {<FILL_FUNCTION_BODY>} }
return (composeFile) -> serviceResolver.doWith("rabbit", (service) -> composeFile.services() .add("rabbitmq", service.andThen((builder) -> builder.environment("RABBITMQ_DEFAULT_USER", "myuser") .environment("RABBITMQ_DEFAULT_PASS", "secret") .ports(5672))));
240
104
344
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springazure/SpringAzureModuleRegistry.java
SpringAzureModuleRegistry
createSpringBootRegistry
class SpringAzureModuleRegistry { static Iterable<ImplicitDependency> createSpringBootRegistry() {<FILL_FUNCTION_BODY>} private static Iterable<ImplicitDependency> create(ImplicitDependency.Builder... dependencies) { return Arrays.stream(dependencies).map(Builder::build).collect(Collectors.toList()); } private static ImplicitDependency.Builder onDependencies(String... dependencyIds) { return new Builder() .match((build) -> build.dependencies() .items() .anyMatch((dependency) -> dependency.getGroupId().equals("com.azure.spring"))) .matchAllDependencyIds(dependencyIds); } private static Consumer<Build> addDependency(String id) { return addDependency(id, DependencyScope.COMPILE); } private static Consumer<Build> addDependency(String id, DependencyScope scope) { return (build) -> build.dependencies().add(id, Dependency.withCoordinates("com.azure.spring", id).scope(scope)); } private static Consumer<HelpDocument> addReferenceLink(String id, String description) { return (helpDocument) -> { String href = String.format("https://aka.ms/spring/docs/%s", id); helpDocument.gettingStarted().addReferenceDocLink(href, description); }; } }
return create( onDependencies("actuator").customizeBuild(addDependency("spring-cloud-azure-starter-actuator")) .customizeHelpDocument(addReferenceLink("actuator", "Azure Actuator")), onDependencies("integration", "azure-storage") .customizeBuild(addDependency("spring-cloud-azure-starter-integration-storage-queue")) .customizeHelpDocument( addReferenceLink("spring-integration/storage-queue", "Azure Integration Storage Queue")), onDependencies("mysql", "azure-support") .customizeBuild(addDependency("spring-cloud-azure-starter-jdbc-mysql")) .customizeHelpDocument((helpDocument) -> helpDocument.gettingStarted() .addReferenceDocLink("https://aka.ms/spring/msdocs/mysql", "Azure MySQL support")), onDependencies("postgresql", "azure-support") .customizeBuild(addDependency("spring-cloud-azure-starter-jdbc-postgresql")) .customizeHelpDocument((helpDocument) -> helpDocument.gettingStarted() .addReferenceDocLink("https://aka.ms/spring/msdocs/postgresql", "Azure PostgreSQL support")));
350
325
675
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springboot/PaketoBuilderBuildCustomizer.java
PaketoBuilderBuildCustomizer
customize
class PaketoBuilderBuildCustomizer<B extends Build> implements BuildCustomizer<B> { static final String BASE_IMAGE_BUILDER = "paketobuildpacks/builder-jammy-base:latest"; static final String TINY_IMAGE_BUILDER = "paketobuildpacks/builder-jammy-tiny:latest"; @Override public void customize(B build) {<FILL_FUNCTION_BODY>} /** * Customize the build with the specified image builder. * @param build the build to customize * @param imageBuilder the image builder to use */ protected abstract void customize(B build, String imageBuilder); }
String builder = (build.dependencies().has("native")) ? TINY_IMAGE_BUILDER : BASE_IMAGE_BUILDER; customize(build, builder);
177
50
227
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springboot/PaketoBuilderGroovyDslGradleBuildCustomizer.java
PaketoBuilderGroovyDslGradleBuildCustomizer
customize
class PaketoBuilderGroovyDslGradleBuildCustomizer extends PaketoBuilderBuildCustomizer<GradleBuild> { @Override protected void customize(GradleBuild build, String imageBuilder) {<FILL_FUNCTION_BODY>} }
build.tasks().customize("bootBuildImage", (task) -> task.attribute("builder", "'" + imageBuilder + "'"));
64
37
101
<methods>public void customize(GradleBuild) <variables>static final java.lang.String BASE_IMAGE_BUILDER,static final java.lang.String TINY_IMAGE_BUILDER