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
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/groovy/GroovyProjectGenerationDefaultContributorsConfiguration.java
GroovyProjectGenerationDefaultContributorsConfiguration
junitJupiterTestMethodContributor
class GroovyProjectGenerationDefaultContributorsConfiguration { private static final VersionRange GROOVY4 = VersionParser.DEFAULT.parseRange("3.0.0-M2"); @Bean MainApplicationTypeCustomizer<GroovyTypeDeclaration> mainMethodContributor() { return (typeDeclaration) -> typeDeclaration.addMethodDeclaration(GroovyMethodDeclaration.method("main") .modifiers(Modifier.PUBLIC | Modifier.STATIC) .returning("void") .parameters(Parameter.of("args", String[].class)) .body(CodeBlock.ofStatement("$T.run($L, args)", "org.springframework.boot.SpringApplication", typeDeclaration.getName()))); } @Bean TestApplicationTypeCustomizer<GroovyTypeDeclaration> junitJupiterTestMethodContributor() {<FILL_FUNCTION_BODY>} @Bean BuildCustomizer<Build> groovyDependenciesConfigurer(ProjectDescription description) { return new GroovyDependenciesConfigurer(GROOVY4.match(description.getPlatformVersion())); } /** * Groovy source code contributions for projects using war packaging. */ @Configuration @ConditionalOnPackaging(WarPackaging.ID) static class WarPackagingConfiguration { @Bean ServletInitializerCustomizer<GroovyTypeDeclaration> javaServletInitializerCustomizer( ProjectDescription description) { return (typeDeclaration) -> { GroovyMethodDeclaration configure = GroovyMethodDeclaration.method("configure") .modifiers(Modifier.PROTECTED) .returning("org.springframework.boot.builder.SpringApplicationBuilder") .parameters( Parameter.of("application", "org.springframework.boot.builder.SpringApplicationBuilder")) .body(CodeBlock.ofStatement("application.sources($L)", description.getApplicationName())); configure.annotations().add(ClassName.of(Override.class)); typeDeclaration.addMethodDeclaration(configure); }; } } /** * Configuration for Groovy projects built with Maven. */ @Configuration @ConditionalOnBuildSystem(MavenBuildSystem.ID) static class GroovyMavenProjectConfiguration { @Bean GroovyMavenBuildCustomizer groovyBuildCustomizer() { return new GroovyMavenBuildCustomizer(); } } }
return (typeDeclaration) -> { GroovyMethodDeclaration method = GroovyMethodDeclaration.method("contextLoads") .returning("void") .body(CodeBlock.of("")); method.annotations().add(ClassName.of("org.junit.jupiter.api.Test")); typeDeclaration.addMethodDeclaration(method); };
618
96
714
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/java/JavaProjectGenerationConfiguration.java
JavaProjectGenerationConfiguration
mainJavaSourceCodeProjectContributor
class JavaProjectGenerationConfiguration { private final ProjectDescription description; private final IndentingWriterFactory indentingWriterFactory; public JavaProjectGenerationConfiguration(ProjectDescription description, IndentingWriterFactory indentingWriterFactory) { this.description = description; this.indentingWriterFactory = indentingWriterFactory; } @Bean public MainSourceCodeProjectContributor<JavaTypeDeclaration, JavaCompilationUnit, JavaSourceCode> mainJavaSourceCodeProjectContributor( ObjectProvider<MainApplicationTypeCustomizer<?>> mainApplicationTypeCustomizers, ObjectProvider<MainCompilationUnitCustomizer<?, ?>> mainCompilationUnitCustomizers, ObjectProvider<MainSourceCodeCustomizer<?, ?, ?>> mainSourceCodeCustomizers) {<FILL_FUNCTION_BODY>} @Bean public TestSourceCodeProjectContributor<JavaTypeDeclaration, JavaCompilationUnit, JavaSourceCode> testJavaSourceCodeProjectContributor( ObjectProvider<TestApplicationTypeCustomizer<?>> testApplicationTypeCustomizers, ObjectProvider<TestSourceCodeCustomizer<?, ?, ?>> testSourceCodeCustomizers) { return new TestSourceCodeProjectContributor<>(this.description, JavaSourceCode::new, new JavaSourceCodeWriter(this.indentingWriterFactory), testApplicationTypeCustomizers, testSourceCodeCustomizers); } }
return new MainSourceCodeProjectContributor<>(this.description, JavaSourceCode::new, new JavaSourceCodeWriter(this.indentingWriterFactory), mainApplicationTypeCustomizers, mainCompilationUnitCustomizers, mainSourceCodeCustomizers);
338
64
402
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/java/JavaProjectGenerationDefaultContributorsConfiguration.java
JavaProjectGenerationDefaultContributorsConfiguration
mainMethodContributor
class JavaProjectGenerationDefaultContributorsConfiguration { @Bean MainApplicationTypeCustomizer<JavaTypeDeclaration> mainMethodContributor() {<FILL_FUNCTION_BODY>} @Bean TestApplicationTypeCustomizer<JavaTypeDeclaration> junitJupiterTestMethodContributor() { return (typeDeclaration) -> { JavaMethodDeclaration method = JavaMethodDeclaration.method("contextLoads") .returning("void") .body(CodeBlock.of("")); method.annotations().add(ClassName.of("org.junit.jupiter.api.Test")); typeDeclaration.addMethodDeclaration(method); }; } /** * Java source code contributions for projects using war packaging. */ @Configuration @ConditionalOnPackaging(WarPackaging.ID) static class WarPackagingConfiguration { @Bean ServletInitializerCustomizer<JavaTypeDeclaration> javaServletInitializerCustomizer( ProjectDescription description) { return (typeDeclaration) -> { typeDeclaration.modifiers(Modifier.PUBLIC); JavaMethodDeclaration configure = JavaMethodDeclaration.method("configure") .modifiers(Modifier.PROTECTED) .returning("org.springframework.boot.builder.SpringApplicationBuilder") .parameters( Parameter.of("application", "org.springframework.boot.builder.SpringApplicationBuilder")) .body(CodeBlock.ofStatement("return application.sources($L.class)", description.getApplicationName())); configure.annotations().add(ClassName.of(Override.class)); typeDeclaration.addMethodDeclaration(configure); }; } } }
return (typeDeclaration) -> { typeDeclaration.modifiers(Modifier.PUBLIC); typeDeclaration.addMethodDeclaration(JavaMethodDeclaration.method("main") .modifiers(Modifier.PUBLIC | Modifier.STATIC) .returning("void") .parameters(Parameter.of("args", String[].class)) .body(CodeBlock.ofStatement("$T.run($L.class, args)", "org.springframework.boot.SpringApplication", typeDeclaration.getName()))); };
418
136
554
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/kotlin/GroovyDslKotlinGradleBuildCustomizer.java
GroovyDslKotlinGradleBuildCustomizer
compilerArgsAsString
class GroovyDslKotlinGradleBuildCustomizer extends KotlinGradleBuildCustomizer { GroovyDslKotlinGradleBuildCustomizer(KotlinProjectSettings kotlinProjectSettings) { super(kotlinProjectSettings); } @Override protected void customizeKotlinOptions(KotlinProjectSettings settings, GradleTask.Builder compile) { compile.nested("kotlinOptions", (kotlinOptions) -> { kotlinOptions.append("freeCompilerArgs", compilerArgsAsString(settings.getCompilerArgs())); kotlinOptions.attribute("jvmTarget", "'" + settings.getJvmTarget() + "'"); }); } private String compilerArgsAsString(List<String> compilerArgs) {<FILL_FUNCTION_BODY>} }
if (compilerArgs.size() == 1) { return "'" + compilerArgs.get(0) + "'"; } String values = compilerArgs.stream().map((arg) -> "'" + arg + "'").collect(Collectors.joining(", ")); return "[%s]".formatted(values);
208
82
290
<methods>public void customize(io.spring.initializr.generator.buildsystem.gradle.GradleBuild) <variables>private final non-sealed io.spring.initializr.generator.spring.code.kotlin.KotlinProjectSettings settings
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/kotlin/KotlinDslKotlinGradleBuildCustomizer.java
KotlinDslKotlinGradleBuildCustomizer
customizeKotlinOptions
class KotlinDslKotlinGradleBuildCustomizer extends KotlinGradleBuildCustomizer { KotlinDslKotlinGradleBuildCustomizer(KotlinProjectSettings kotlinProjectSettings) { super(kotlinProjectSettings); } @Override protected void customizeKotlinOptions(KotlinProjectSettings settings, GradleTask.Builder compile) {<FILL_FUNCTION_BODY>} private String compilerArgsAsString(List<String> compilerArgs) { if (compilerArgs.size() == 1) { return "\"" + compilerArgs.get(0) + "\""; } String values = compilerArgs.stream().map((arg) -> "\"" + arg + "\"").collect(Collectors.joining(", ")); return "listOf(%s)".formatted(values); } }
compile.nested("kotlinOptions", (kotlinOptions) -> { kotlinOptions.append("freeCompilerArgs", compilerArgsAsString(settings.getCompilerArgs())); kotlinOptions.attribute("jvmTarget", "\"" + settings.getJvmTarget() + "\""); });
214
81
295
<methods>public void customize(io.spring.initializr.generator.buildsystem.gradle.GradleBuild) <variables>private final non-sealed io.spring.initializr.generator.spring.code.kotlin.KotlinProjectSettings settings
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/kotlin/KotlinGradleBuildCustomizer.java
KotlinGradleBuildCustomizer
customize
class KotlinGradleBuildCustomizer implements BuildCustomizer<GradleBuild> { private final KotlinProjectSettings settings; KotlinGradleBuildCustomizer(KotlinProjectSettings kotlinProjectSettings) { this.settings = kotlinProjectSettings; } @Override public void customize(GradleBuild build) {<FILL_FUNCTION_BODY>} protected abstract void customizeKotlinOptions(KotlinProjectSettings settings, GradleTask.Builder compile); }
build.plugins().add("org.jetbrains.kotlin.jvm", (plugin) -> plugin.setVersion(this.settings.getVersion())); build.plugins() .add("org.jetbrains.kotlin.plugin.spring", (plugin) -> plugin.setVersion(this.settings.getVersion())); build.tasks() .customizeWithType("org.jetbrains.kotlin.gradle.tasks.KotlinCompile", (compile) -> customizeKotlinOptions(this.settings, compile));
125
141
266
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/kotlin/KotlinJacksonBuildCustomizer.java
KotlinJacksonBuildCustomizer
customize
class KotlinJacksonBuildCustomizer implements BuildCustomizer<Build> { private final BuildMetadataResolver buildMetadataResolver; private final ProjectDescription description; public KotlinJacksonBuildCustomizer(InitializrMetadata metadata, ProjectDescription description) { this.buildMetadataResolver = new BuildMetadataResolver(metadata); this.description = description; } @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} }
boolean isKotlin = ClassUtils.isAssignableValue(KotlinLanguage.class, this.description.getLanguage()); if (this.buildMetadataResolver.hasFacet(build, "json") && isKotlin) { build.dependencies() .add("jackson-module-kotlin", "com.fasterxml.jackson.module", "jackson-module-kotlin", DependencyScope.COMPILE); }
113
118
231
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/kotlin/KotlinJpaGradleBuildCustomizer.java
KotlinJpaGradleBuildCustomizer
customize
class KotlinJpaGradleBuildCustomizer implements BuildCustomizer<GradleBuild> { private final BuildMetadataResolver buildMetadataResolver; private final KotlinProjectSettings settings; public KotlinJpaGradleBuildCustomizer(InitializrMetadata metadata, KotlinProjectSettings settings) { this.buildMetadataResolver = new BuildMetadataResolver(metadata); this.settings = settings; } @Override public void customize(GradleBuild build) {<FILL_FUNCTION_BODY>} }
if (this.buildMetadataResolver.hasFacet(build, "jpa")) { build.plugins() .add("org.jetbrains.kotlin.plugin.jpa", (plugin) -> plugin.setVersion(this.settings.getVersion())); }
127
71
198
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/kotlin/KotlinJpaMavenBuildCustomizer.java
KotlinJpaMavenBuildCustomizer
customize
class KotlinJpaMavenBuildCustomizer implements BuildCustomizer<MavenBuild> { private final BuildMetadataResolver buildMetadataResolver; public KotlinJpaMavenBuildCustomizer(InitializrMetadata metadata) { this.buildMetadataResolver = new BuildMetadataResolver(metadata); } @Override public void customize(MavenBuild build) {<FILL_FUNCTION_BODY>} }
if (this.buildMetadataResolver.hasFacet(build, "jpa")) { build.plugins().add("org.jetbrains.kotlin", "kotlin-maven-plugin", (kotlinPlugin) -> { kotlinPlugin.configuration((configuration) -> configuration.configure("compilerPlugins", (compilerPlugins) -> compilerPlugins.add("plugin", "jpa"))); kotlinPlugin.dependency("org.jetbrains.kotlin", "kotlin-maven-noarg", "${kotlin.version}"); }); }
101
154
255
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/kotlin/KotlinMavenBuildCustomizer.java
KotlinMavenBuildCustomizer
customize
class KotlinMavenBuildCustomizer implements BuildCustomizer<MavenBuild> { private static final VersionRange KOTLIN_ONE_EIGHT_OR_LATER = new VersionRange(Version.parse("1.8.0")); private final KotlinProjectSettings settings; KotlinMavenBuildCustomizer(KotlinProjectSettings kotlinProjectSettings) { this.settings = kotlinProjectSettings; } @Override public void customize(MavenBuild build) {<FILL_FUNCTION_BODY>} }
build.properties().version("kotlin.version", this.settings.getVersion()); build.settings() .sourceDirectory("${project.basedir}/src/main/kotlin") .testSourceDirectory("${project.basedir}/src/test/kotlin"); build.plugins().add("org.jetbrains.kotlin", "kotlin-maven-plugin", (kotlinMavenPlugin) -> { kotlinMavenPlugin.configuration((configuration) -> { configuration.configure("args", (args) -> this.settings.getCompilerArgs().forEach((arg) -> args.add("arg", arg))); configuration.configure("compilerPlugins", (compilerPlugins) -> compilerPlugins.add("plugin", "spring")); }); kotlinMavenPlugin.dependency("org.jetbrains.kotlin", "kotlin-maven-allopen", "${kotlin.version}"); }); String artifactId = KotlinMavenBuildCustomizer.KOTLIN_ONE_EIGHT_OR_LATER .match(Version.parse(this.settings.getVersion())) ? "kotlin-stdlib" : "kotlin-stdlib-jdk8"; build.dependencies() .add("kotlin-stdlib", Dependency.withCoordinates("org.jetbrains.kotlin", artifactId).scope(DependencyScope.COMPILE));
135
369
504
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/kotlin/KotlinMavenFullBuildCustomizer.java
KotlinMavenFullBuildCustomizer
customize
class KotlinMavenFullBuildCustomizer implements BuildCustomizer<MavenBuild> { private final KotlinProjectSettings settings; KotlinMavenFullBuildCustomizer(KotlinProjectSettings kotlinProjectSettings) { this.settings = kotlinProjectSettings; } @Override public void customize(MavenBuild build) {<FILL_FUNCTION_BODY>} }
build.properties().version("kotlin.version", this.settings.getVersion()); build.settings() .sourceDirectory("${project.basedir}/src/main/kotlin") .testSourceDirectory("${project.basedir}/src/test/kotlin"); build.plugins().add("org.jetbrains.kotlin", "kotlin-maven-plugin", (kotlinMavenPlugin) -> { kotlinMavenPlugin.version("${kotlin.version}"); kotlinMavenPlugin.configuration((configuration) -> { configuration.configure("args", (args) -> this.settings.getCompilerArgs().forEach((arg) -> args.add("arg", arg))); configuration.configure("compilerPlugins", (compilerPlugins) -> compilerPlugins.add("plugin", "spring")); configuration.add("jvmTarget", this.settings.getJvmTarget()); }); kotlinMavenPlugin.execution("compile", (compile) -> compile.phase("compile").goal("compile")); kotlinMavenPlugin.execution("test-compile", (compile) -> compile.phase("test-compile").goal("test-compile")); kotlinMavenPlugin.dependency("org.jetbrains.kotlin", "kotlin-maven-allopen", "${kotlin.version}"); });
101
361
462
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/kotlin/KotlinProjectGenerationConfiguration.java
KotlinProjectGenerationConfiguration
kotlinGradlePluginGitIgnoreCustomizer
class KotlinProjectGenerationConfiguration { private final ProjectDescription description; private final IndentingWriterFactory indentingWriterFactory; public KotlinProjectGenerationConfiguration(ProjectDescription description, IndentingWriterFactory indentingWriterFactory) { this.description = description; this.indentingWriterFactory = indentingWriterFactory; } @Bean public MainSourceCodeProjectContributor<KotlinTypeDeclaration, KotlinCompilationUnit, KotlinSourceCode> mainKotlinSourceCodeProjectContributor( ObjectProvider<MainApplicationTypeCustomizer<?>> mainApplicationTypeCustomizers, ObjectProvider<MainCompilationUnitCustomizer<?, ?>> mainCompilationUnitCustomizers, ObjectProvider<MainSourceCodeCustomizer<?, ?, ?>> mainSourceCodeCustomizers) { return new MainSourceCodeProjectContributor<>(this.description, KotlinSourceCode::new, new KotlinSourceCodeWriter(this.indentingWriterFactory), mainApplicationTypeCustomizers, mainCompilationUnitCustomizers, mainSourceCodeCustomizers); } @Bean public TestSourceCodeProjectContributor<KotlinTypeDeclaration, KotlinCompilationUnit, KotlinSourceCode> testKotlinSourceCodeProjectContributor( ObjectProvider<TestApplicationTypeCustomizer<?>> testApplicationTypeCustomizers, ObjectProvider<TestSourceCodeCustomizer<?, ?, ?>> testSourceCodeCustomizers) { return new TestSourceCodeProjectContributor<>(this.description, KotlinSourceCode::new, new KotlinSourceCodeWriter(this.indentingWriterFactory), testApplicationTypeCustomizers, testSourceCodeCustomizers); } @Bean @ConditionalOnBuildSystem(GradleBuildSystem.ID) public GitIgnoreCustomizer kotlinGradlePluginGitIgnoreCustomizer() {<FILL_FUNCTION_BODY>} @Bean public KotlinProjectSettings kotlinProjectSettings(ObjectProvider<KotlinVersionResolver> kotlinVersionResolver, InitializrMetadata metadata) { String kotlinVersion = kotlinVersionResolver .getIfAvailable(() -> new InitializrMetadataKotlinVersionResolver(metadata)) .resolveKotlinVersion(this.description); return new SimpleKotlinProjectSettings(kotlinVersion, this.description.getLanguage().jvmVersion()); } @Bean public KotlinJacksonBuildCustomizer kotlinJacksonBuildCustomizer(InitializrMetadata metadata) { return new KotlinJacksonBuildCustomizer(metadata, this.description); } }
return (gitIgnore) -> { GitIgnore.GitIgnoreSection section = gitIgnore.addSectionIfAbsent("Kotlin"); section.add(".kotlin"); };
637
53
690
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/kotlin/KotlinProjectGenerationDefaultContributorsConfiguration.java
KotlinProjectGenerationDefaultContributorsConfiguration
junitJupiterTestMethodContributor
class KotlinProjectGenerationDefaultContributorsConfiguration { @Bean TestApplicationTypeCustomizer<KotlinTypeDeclaration> junitJupiterTestMethodContributor() {<FILL_FUNCTION_BODY>} @Bean BuildCustomizer<Build> kotlinDependenciesConfigurer() { return new KotlinDependenciesConfigurer(); } @Bean @ConditionalOnBuildSystem(GradleBuildSystem.ID) KotlinJpaGradleBuildCustomizer kotlinJpaGradleBuildCustomizer(InitializrMetadata metadata, KotlinProjectSettings settings) { return new KotlinJpaGradleBuildCustomizer(metadata, settings); } @Bean @ConditionalOnBuildSystem(MavenBuildSystem.ID) KotlinJpaMavenBuildCustomizer kotlinJpaMavenBuildCustomizer(InitializrMetadata metadata) { return new KotlinJpaMavenBuildCustomizer(metadata); } /** * Configuration for Kotlin projects using Spring Boot 2.0 and later. */ @Configuration @ConditionalOnPlatformVersion("2.0.0.M1") static class SpringBoot2AndLaterKotlinProjectGenerationConfiguration { @Bean @ConditionalOnBuildSystem(MavenBuildSystem.ID) KotlinMavenBuildCustomizer kotlinBuildCustomizer(KotlinProjectSettings kotlinProjectSettings) { return new KotlinMavenBuildCustomizer(kotlinProjectSettings); } @Bean MainCompilationUnitCustomizer<KotlinTypeDeclaration, KotlinCompilationUnit> mainFunctionContributor( ProjectDescription description) { return (compilationUnit) -> compilationUnit.addTopLevelFunction(KotlinFunctionDeclaration.function("main") .parameters(Parameter.of("args", "Array<String>")) .body(CodeBlock.ofStatement("$T<$L>(*args)", "org.springframework.boot.runApplication", description.getApplicationName()))); } } /** * Kotlin source code contributions for projects using war packaging. */ @Configuration @ConditionalOnPackaging(WarPackaging.ID) static class WarPackagingConfiguration { @Bean ServletInitializerCustomizer<KotlinTypeDeclaration> javaServletInitializerCustomizer( ProjectDescription description) { return (typeDeclaration) -> { KotlinFunctionDeclaration configure = KotlinFunctionDeclaration.function("configure") .modifiers(KotlinModifier.OVERRIDE) .returning("org.springframework.boot.builder.SpringApplicationBuilder") .parameters( Parameter.of("application", "org.springframework.boot.builder.SpringApplicationBuilder")) .body(CodeBlock.ofStatement("return application.sources($L::class.java)", description.getApplicationName())); typeDeclaration.addFunctionDeclaration(configure); }; } } /** * Configuration for Kotlin projects built with Gradle (Groovy DSL). * * @author Andy Wilkinson */ @Configuration @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_GROOVY) static class KotlinGradleProjectConfiguration { @Bean KotlinGradleBuildCustomizer kotlinBuildCustomizer(KotlinProjectSettings kotlinProjectSettings) { return new GroovyDslKotlinGradleBuildCustomizer(kotlinProjectSettings); } } /** * Configuration for Kotlin projects built with Gradle (Kotlin DSL). * * @author Jean-Baptiste Nizet */ @Configuration @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_KOTLIN) static class KotlinGradleKtsProjectConfiguration { @Bean KotlinDslKotlinGradleBuildCustomizer kotlinBuildCustomizer(KotlinProjectSettings kotlinProjectSettings) { return new KotlinDslKotlinGradleBuildCustomizer(kotlinProjectSettings); } } }
return (typeDeclaration) -> { KotlinFunctionDeclaration function = KotlinFunctionDeclaration.function("contextLoads") .body(CodeBlock.of("")); function.annotations().add(ClassName.of("org.junit.jupiter.api.Test")); typeDeclaration.addFunctionDeclaration(function); };
1,056
86
1,142
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/container/docker/compose/ComposeHelpDocumentCustomizer.java
ComposeHelpDocumentCustomizer
customize
class ComposeHelpDocumentCustomizer implements HelpDocumentCustomizer { private final ComposeFile composeFile; public ComposeHelpDocumentCustomizer(ComposeFile composeFile) { this.composeFile = composeFile; } @Override public void customize(HelpDocument document) {<FILL_FUNCTION_BODY>} }
Map<String, Object> model = new HashMap<>(); if (this.composeFile.services().isEmpty()) { document.getWarnings() .addItem( "No Docker Compose services found. As of now, the application won't start! Please add at least one service to the `compose.yaml` file."); } else { model.put("services", this.composeFile.services() .values() .sorted(Comparator.comparing(ComposeService::getName)) .toList()); } document.addSection("documentation/docker-compose", model);
86
166
252
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/container/docker/compose/ComposeProjectContributor.java
ComposeProjectContributor
writeComposeFile
class ComposeProjectContributor implements ProjectContributor { private final ComposeFile composeFile; private final IndentingWriterFactory indentingWriterFactory; private final ComposeFileWriter composeFileWriter; public ComposeProjectContributor(ComposeFile composeFile, IndentingWriterFactory indentingWriterFactory) { this.composeFile = composeFile; this.indentingWriterFactory = indentingWriterFactory; this.composeFileWriter = new ComposeFileWriter(); } @Override public void contribute(Path projectRoot) throws IOException { Path file = Files.createFile(projectRoot.resolve("compose.yaml")); writeComposeFile(Files.newBufferedWriter(file)); } void writeComposeFile(Writer out) throws IOException {<FILL_FUNCTION_BODY>} }
try (IndentingWriter writer = this.indentingWriterFactory.createIndentingWriter("yaml", out)) { this.composeFileWriter.writeTo(writer, this.composeFile); }
212
56
268
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/documentation/GettingStartedSection.java
GettingStartedSection
resolveSubSections
class GettingStartedSection extends PreDefinedSection { private final BulletedSection<Link> referenceDocs; private final BulletedSection<Link> guides; private final BulletedSection<Link> additionalLinks; GettingStartedSection(MustacheTemplateRenderer templateRenderer) { super("Getting Started"); this.referenceDocs = new BulletedSection<>(templateRenderer, "documentation/reference-documentation"); this.guides = new BulletedSection<>(templateRenderer, "documentation/guides"); this.additionalLinks = new BulletedSection<>(templateRenderer, "documentation/additional-links"); } @Override public boolean isEmpty() { return referenceDocs().isEmpty() && guides().isEmpty() && additionalLinks().isEmpty() && super.isEmpty(); } @Override protected List<Section> resolveSubSections(List<Section> sections) {<FILL_FUNCTION_BODY>} public GettingStartedSection addReferenceDocLink(String href, String description) { this.referenceDocs.addItem(new Link(href, description)); return this; } public BulletedSection<Link> referenceDocs() { return this.referenceDocs; } public GettingStartedSection addGuideLink(String href, String description) { this.guides.addItem(new Link(href, description)); return this; } public BulletedSection<Link> guides() { return this.guides; } public GettingStartedSection addAdditionalLink(String href, String description) { this.additionalLinks.addItem(new Link(href, description)); return this; } public BulletedSection<Link> additionalLinks() { return this.additionalLinks; } /** * Internal representation of a link. */ public static class Link { private final String href; private final String description; Link(String href, String description) { this.href = href; this.description = description; } public String getHref() { return this.href; } public String getDescription() { return this.description; } } }
List<Section> allSections = new ArrayList<>(); allSections.add(this.referenceDocs); allSections.add(this.guides); allSections.add(this.additionalLinks); allSections.addAll(sections); return allSections;
549
82
631
<methods>public void <init>(java.lang.String) ,public io.spring.initializr.generator.spring.documentation.PreDefinedSection addSection(io.spring.initializr.generator.io.text.Section) ,public boolean isEmpty() ,public void write(java.io.PrintWriter) throws java.io.IOException<variables>private final List<io.spring.initializr.generator.io.text.Section> subSections,private final non-sealed java.lang.String title
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/documentation/HelpDocument.java
HelpDocument
write
class HelpDocument { private final MustacheTemplateRenderer templateRenderer; private final BulletedSection<String> warnings; private final GettingStartedSection gettingStarted; private final PreDefinedSection nextSteps; private final LinkedList<Section> sections = new LinkedList<>(); public HelpDocument(MustacheTemplateRenderer templateRenderer) { this.templateRenderer = templateRenderer; this.warnings = new BulletedSection<>(templateRenderer, "documentation/warnings"); this.gettingStarted = new GettingStartedSection(templateRenderer); this.nextSteps = new PreDefinedSection("Next Steps"); } /** * Return a section that can be used to inform the user that something happened when * building this project. * @return a warnings section rendered as bullet points */ public BulletedSection<String> getWarnings() { return this.warnings; } public GettingStartedSection gettingStarted() { return this.gettingStarted; } public PreDefinedSection nextSteps() { return this.nextSteps; } public HelpDocument addSection(Section section) { this.sections.add(section); return this; } /** * Add a section rendered by the specified mustache template and model. * @param templateName the name of the mustache template to render * @param model the model that should be used for the rendering * @return this document */ public HelpDocument addSection(String templateName, Map<String, Object> model) { return addSection(new MustacheSection(this.templateRenderer, templateName, model)); } public List<Section> getSections() { return Collections.unmodifiableList(this.sections); } public void write(PrintWriter writer) throws IOException {<FILL_FUNCTION_BODY>} public boolean isEmpty() { return getWarnings().isEmpty() && gettingStarted().isEmpty() && this.sections.isEmpty() && nextSteps().isEmpty(); } }
List<Section> allSections = new ArrayList<>(); allSections.add(this.warnings); allSections.add(this.gettingStarted); allSections.addAll(this.sections); allSections.add(this.nextSteps); for (Section section : allSections) { section.write(writer); }
499
101
600
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/documentation/HelpDocumentProjectContributor.java
HelpDocumentProjectContributor
contribute
class HelpDocumentProjectContributor implements ProjectContributor { private final HelpDocument helpDocument; public HelpDocumentProjectContributor(HelpDocument helpDocument) { this.helpDocument = helpDocument; } @Override public void contribute(Path projectRoot) throws IOException {<FILL_FUNCTION_BODY>} }
if (this.helpDocument.isEmpty()) { return; } Path file = Files.createFile(projectRoot.resolve("HELP.md")); try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(file))) { this.helpDocument.write(writer); }
82
80
162
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/documentation/HelpDocumentProjectGenerationConfiguration.java
HelpDocumentProjectGenerationConfiguration
helpDocument
class HelpDocumentProjectGenerationConfiguration { @Bean public HelpDocument helpDocument(ObjectProvider<MustacheTemplateRenderer> templateRenderer, ObjectProvider<HelpDocumentCustomizer> helpDocumentCustomizers) {<FILL_FUNCTION_BODY>} @Bean public HelpDocumentProjectContributor helpDocumentProjectContributor(HelpDocument helpDocument) { return new HelpDocumentProjectContributor(helpDocument); } }
HelpDocument helpDocument = new HelpDocument( templateRenderer.getIfAvailable(() -> new MustacheTemplateRenderer("classpath:/templates"))); helpDocumentCustomizers.orderedStream().forEach((customizer) -> customizer.customize(helpDocument)); return helpDocument;
104
73
177
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/documentation/PreDefinedSection.java
PreDefinedSection
write
class PreDefinedSection implements Section { private final String title; private final List<Section> subSections = new ArrayList<>(); public PreDefinedSection(String title) { this.title = title; } public PreDefinedSection addSection(Section section) { this.subSections.add(section); return this; } @Override public void write(PrintWriter writer) throws IOException {<FILL_FUNCTION_BODY>} public boolean isEmpty() { return this.subSections.isEmpty(); } /** * Resolve the sections to render based on the current registered sections. * @param sections the registered sections * @return the sections to render */ protected List<Section> resolveSubSections(List<Section> sections) { return sections; } }
if (!isEmpty()) { writer.println("# " + this.title); writer.println(""); for (Section section : resolveSubSections(this.subSections)) { section.write(writer); } }
206
65
271
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/documentation/RequestedDependenciesHelpDocumentCustomizer.java
RequestedDependenciesHelpDocumentCustomizer
indexLinks
class RequestedDependenciesHelpDocumentCustomizer implements HelpDocumentCustomizer { private final ProjectDescription description; private final InitializrMetadata metadata; private final String platformVersion; public RequestedDependenciesHelpDocumentCustomizer(ProjectDescription description, InitializrMetadata metadata) { this.description = description; this.metadata = metadata; this.platformVersion = (description.getPlatformVersion() != null) ? description.getPlatformVersion().toString() : metadata.getBootVersions().getDefault().getId(); } @Override public void customize(HelpDocument document) { this.description.getRequestedDependencies().forEach((id, dependency) -> { Dependency dependencyMetadata = this.metadata.getDependencies().get(id); if (dependencyMetadata != null) { handleDependency(document, dependencyMetadata); } }); } @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE; } private void handleDependency(HelpDocument document, Dependency dependency) { GettingStartedSection gettingStartedSection = document.gettingStarted(); MultiValueMap<GuideType, Link> indexedLinks = indexLinks(dependency); registerLinks(indexedLinks.get(GuideType.REFERENCE), defaultLinkDescription(dependency), gettingStartedSection::referenceDocs); registerLinks(indexedLinks.get(GuideType.GUIDE), defaultLinkDescription(dependency), gettingStartedSection::guides); registerLinks(indexedLinks.get(GuideType.OTHER), (links) -> null, gettingStartedSection::additionalLinks); } private void registerLinks(List<Link> links, Function<List<Link>, String> defaultDescription, Supplier<BulletedSection<GettingStartedSection.Link>> section) { if (ObjectUtils.isEmpty(links)) { return; } links.forEach((link) -> { if (link.getHref() != null) { String description = (link.getDescription() != null) ? link.getDescription() : defaultDescription.apply(links); if (description != null) { String url = link.getHref().replace("{bootVersion}", this.platformVersion); section.get().addItem(new GettingStartedSection.Link(url, description)); } } }); } private Function<List<Link>, String> defaultLinkDescription(Dependency dependency) { return (links) -> (links.size() == 1) ? dependency.getName() : null; } private MultiValueMap<GuideType, Link> indexLinks(Dependency dependency) {<FILL_FUNCTION_BODY>} private enum GuideType { REFERENCE, GUIDE, OTHER } }
MultiValueMap<GuideType, Link> links = new LinkedMultiValueMap<>(); dependency.getLinks().forEach((link) -> { if ("reference".equals(link.getRel())) { links.add(GuideType.REFERENCE, link); } else if ("guide".equals(link.getRel())) { links.add(GuideType.GUIDE, link); } else { links.add(GuideType.OTHER, link); } }); return links;
718
141
859
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/properties/ApplicationProperties.java
ApplicationProperties
writeTo
class ApplicationProperties { private final Map<String, Object> properties = new HashMap<>(); /** * Adds a new property. * @param key the key of the property * @param value the value of the property */ public void add(String key, long value) { add(key, (Object) value); } /** * Adds a new property. * @param key the key of the property * @param value the value of the property */ public void add(String key, boolean value) { add(key, (Object) value); } /** * Adds a new property. * @param key the key of the property * @param value the value of the property */ public void add(String key, double value) { add(key, (Object) value); } /** * Adds a new property. * @param key the key of the property * @param value the value of the property */ public void add(String key, String value) { add(key, (Object) value); } void writeTo(PrintWriter writer) {<FILL_FUNCTION_BODY>} private void add(String key, Object value) { Assert.state(!this.properties.containsKey(key), () -> "Property '%s' already exists".formatted(key)); this.properties.put(key, value); } }
for (Map.Entry<String, Object> entry : this.properties.entrySet()) { writer.printf("%s=%s%n", entry.getKey(), entry.getValue()); }
359
51
410
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/properties/ApplicationPropertiesContributor.java
ApplicationPropertiesContributor
contribute
class ApplicationPropertiesContributor implements ProjectContributor { private static final String FILE = "src/main/resources/application.properties"; private final ApplicationProperties properties; public ApplicationPropertiesContributor(ApplicationProperties properties) { this.properties = properties; } @Override public void contribute(Path projectRoot) throws IOException {<FILL_FUNCTION_BODY>} }
Path output = projectRoot.resolve(FILE); if (!Files.exists(output)) { Files.createDirectories(output.getParent()); Files.createFile(output); } try (PrintWriter writer = new PrintWriter(Files.newOutputStream(output, StandardOpenOption.APPEND), false, StandardCharsets.UTF_8)) { this.properties.writeTo(writer); }
95
109
204
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/properties/ApplicationPropertiesProjectGenerationConfiguration.java
ApplicationPropertiesProjectGenerationConfiguration
applicationProperties
class ApplicationPropertiesProjectGenerationConfiguration { @Bean ApplicationProperties applicationProperties(ObjectProvider<ApplicationPropertiesCustomizer> customizers) {<FILL_FUNCTION_BODY>} @Bean ApplicationPropertiesContributor applicationPropertiesContributor(ApplicationProperties applicationProperties) { return new ApplicationPropertiesContributor(applicationProperties); } }
ApplicationProperties properties = new ApplicationProperties(); customizers.orderedStream().forEach((customizer) -> customizer.customize(properties)); return properties;
85
43
128
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/scm/git/GitIgnore.java
GitIgnoreSection
write
class GitIgnoreSection implements Section { private final String name; private final LinkedList<String> items; public GitIgnoreSection(String name) { this.name = name; this.items = new LinkedList<>(); } public void add(String... items) { this.items.addAll(Arrays.asList(items)); } public LinkedList<String> getItems() { return this.items; } @Override public void write(PrintWriter writer) {<FILL_FUNCTION_BODY>} }
if (!this.items.isEmpty()) { if (this.name != null) { writer.println(); writer.println(String.format("### %s ###", this.name)); } this.items.forEach(writer::println); }
148
72
220
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/scm/git/GitIgnoreContributor.java
GitIgnoreContributor
contribute
class GitIgnoreContributor implements ProjectContributor { private final GitIgnore gitIgnore; public GitIgnoreContributor(GitIgnore gitIgnore) { this.gitIgnore = gitIgnore; } @Override public void contribute(Path projectRoot) throws IOException {<FILL_FUNCTION_BODY>} }
if (this.gitIgnore.isEmpty()) { return; } Path file = Files.createFile(projectRoot.resolve(".gitignore")); try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(file))) { this.gitIgnore.write(writer); }
81
78
159
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/scm/git/GitProjectGenerationConfiguration.java
GitProjectGenerationConfiguration
createGitIgnore
class GitProjectGenerationConfiguration { @Bean public GitIgnoreContributor gitIgnoreContributor(GitIgnore gitIgnore) { return new GitIgnoreContributor(gitIgnore); } @Bean public GitIgnore gitIgnore(ObjectProvider<GitIgnoreCustomizer> gitIgnoreCustomizers) { GitIgnore gitIgnore = createGitIgnore(); gitIgnoreCustomizers.orderedStream().forEach((customizer) -> customizer.customize(gitIgnore)); return gitIgnore; } @Bean @ConditionalOnBuildSystem(MavenBuildSystem.ID) public GitIgnoreCustomizer mavenGitIgnoreCustomizer() { return (gitIgnore) -> { gitIgnore.getGeneral() .add("target/", "!.mvn/wrapper/maven-wrapper.jar", "!**/src/main/**/target/", "!**/src/test/**/target/"); gitIgnore.getNetBeans().add("build/", "!**/src/main/**/build/", "!**/src/test/**/build/"); }; } @Bean @ConditionalOnBuildSystem(GradleBuildSystem.ID) public GitIgnoreCustomizer gradleGitIgnoreCustomizer() { return (gitIgnore) -> { gitIgnore.getGeneral() .add(".gradle", "build/", "!gradle/wrapper/gradle-wrapper.jar", "!**/src/main/**/build/", "!**/src/test/**/build/"); gitIgnore.getIntellijIdea().add("out/", "!**/src/main/**/out/", "!**/src/test/**/out/"); gitIgnore.getSts().add("bin/", "!**/src/main/**/bin/", "!**/src/test/**/bin/"); }; } private GitIgnore createGitIgnore() {<FILL_FUNCTION_BODY>} }
GitIgnore gitIgnore = new GitIgnore(); gitIgnore.getSts() .add(".apt_generated", ".classpath", ".factorypath", ".project", ".settings", ".springBeans", ".sts4-cache"); gitIgnore.getIntellijIdea().add(".idea", "*.iws", "*.iml", "*.ipr"); gitIgnore.getNetBeans().add("/nbproject/private/", "/nbbuild/", "/dist/", "/nbdist/", "/.nb-gradle/"); gitIgnore.getVscode().add(".vscode/"); return gitIgnore;
482
160
642
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/util/LambdaSafe.java
Callbacks
invoke
class Callbacks<C, A> extends LambdaSafeCallback<C, A, Callbacks<C, A>> { private final Collection<? extends C> callbackInstances; private Callbacks(Class<C> callbackType, Collection<? extends C> callbackInstances, A argument, Object[] additionalArguments) { super(callbackType, argument, additionalArguments); this.callbackInstances = callbackInstances; } /** * Invoke the callback instances where the callback method returns void. * @param invoker the invoker used to invoke the callback */ public void invoke(Consumer<C> invoker) {<FILL_FUNCTION_BODY>} /** * Invoke the callback instances where the callback method returns a result. * @param invoker the invoker used to invoke the callback * @param <R> the result type * @return the results of the invocation (may be an empty stream if no callbacks * could be called) */ public <R> Stream<R> invokeAnd(Function<C, R> invoker) { Function<C, InvocationResult<R>> mapper = (callbackInstance) -> invoke(callbackInstance, () -> invoker.apply(callbackInstance)); return this.callbackInstances.stream() .map(mapper) .filter(InvocationResult::hasResult) .map(InvocationResult::get); } }
this.callbackInstances.forEach((callbackInstance) -> invoke(callbackInstance, () -> { invoker.accept(callbackInstance); return null; }));
358
48
406
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/Build.java
Build
determineBuildItemResolver
class Build { private final PropertyContainer properties; private final DependencyContainer dependencies; private final BomContainer boms; private final MavenRepositoryContainer repositories; private final MavenRepositoryContainer pluginRepositories; protected Build(BuildItemResolver buildItemResolver) { BuildItemResolver resolver = determineBuildItemResolver(buildItemResolver); this.properties = new PropertyContainer(); this.dependencies = new DependencyContainer(resolver::resolveDependency); this.boms = new BomContainer(resolver::resolveBom); this.repositories = new MavenRepositoryContainer(resolver::resolveRepository); this.pluginRepositories = new MavenRepositoryContainer(resolver::resolveRepository); } protected static BuildItemResolver determineBuildItemResolver(BuildItemResolver buildItemResolver) {<FILL_FUNCTION_BODY>} /** * Return a builder to configure the general settings of this build. * @return a builder for {@link BuildSettings}. */ public abstract BuildSettings.Builder<?> settings(); /** * Return the settings of this build. * @return a {@link BuildSettings} */ public abstract BuildSettings getSettings(); /** * Return the {@linkplain PropertyContainer property container} to use to configure * properties. * @return the {@link PropertyContainer} */ public PropertyContainer properties() { return this.properties; } /** * Return the {@linkplain DependencyContainer dependency container} to use to * configure dependencies. * @return the {@link DependencyContainer} */ public DependencyContainer dependencies() { return this.dependencies; } /** * Return the {@linkplain BomContainer bom container} to use to configure Bill of * Materials. * @return the {@link BomContainer} */ public BomContainer boms() { return this.boms; } /** * Return the {@linkplain MavenRepositoryContainer repository container} to use to * configure repositories. * @return the {@link MavenRepositoryContainer} for repositories */ public MavenRepositoryContainer repositories() { return this.repositories; } /** * Return the {@linkplain MavenRepositoryContainer repository container} to use to * configure plugin repositories. * @return the {@link MavenRepositoryContainer} for plugin repositories */ public MavenRepositoryContainer pluginRepositories() { return this.pluginRepositories; } }
if (buildItemResolver != null) { return buildItemResolver; } return new SimpleBuildItemResolver((id) -> null, (id) -> null, (id) -> id.equals("maven-central") ? MavenRepository.MAVEN_CENTRAL : null);
621
79
700
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/BuildItemContainer.java
BuildItemContainer
add
class BuildItemContainer<I, V> { private final Map<I, V> items; private final Function<I, V> itemResolver; protected BuildItemContainer(Map<I, V> items, Function<I, V> itemResolver) { this.items = items; this.itemResolver = itemResolver; } /** * Specify if this container is empty. * @return {@code true} if no item is registered */ public boolean isEmpty() { return this.items.isEmpty(); } /** * Specify if this container has an item with the specified id. * @param id the id of an item * @return {@code true} if an item with the specified {@code id} is registered */ public boolean has(I id) { return this.items.containsKey(id); } /** * Return a {@link Stream} of registered identifiers. * @return a stream of ids */ public Stream<I> ids() { return this.items.keySet().stream(); } /** * Return a {@link Stream} of registered items. * @return a stream of items */ public Stream<V> items() { return this.items.values().stream(); } /** * Return the item with the specified {@code id} or {@code null} if no such item * exists. * @param id the id of an item * @return the item or {@code null} */ public V get(I id) { return this.items.get(id); } /** * Lookup the item with the specified {@code id} and register it to this container. * @param id the id of an item */ public void add(I id) {<FILL_FUNCTION_BODY>} /** * Register the specified {@code item} with the specified {@code id}. * @param id the id of the item * @param item the item to register */ public void add(I id, V item) { this.items.put(id, item); } /** * Remove the item with the specified {@code id}. * @param id the id of the item to remove * @return {@code true} if such an item was registered, {@code false} otherwise */ public boolean remove(I id) { return this.items.remove(id) != null; } }
V item = this.itemResolver.apply(id); if (item == null) { throw new IllegalArgumentException("No such value with id '" + id + "'"); } add(id, item);
601
58
659
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/Dependency.java
Exclusion
equals
class Exclusion { private final String groupId; private final String artifactId; public Exclusion(String groupId, String artifactId) { Assert.hasText(groupId, "GroupId must not be null"); Assert.hasText(groupId, "ArtifactId must not be null"); this.groupId = groupId; this.artifactId = artifactId; } public String getGroupId() { return this.groupId; } public String getArtifactId() { return this.artifactId; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(this.groupId, this.artifactId); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Exclusion exclusion = (Exclusion) o; return this.groupId.equals(exclusion.groupId) && this.artifactId.equals(exclusion.artifactId);
200
87
287
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/DependencyComparator.java
DependencyComparator
compare
class DependencyComparator implements Comparator<Dependency> { /** * A default stateless instance. */ public static final DependencyComparator INSTANCE = new DependencyComparator(); @Override public int compare(Dependency o1, Dependency o2) {<FILL_FUNCTION_BODY>} private boolean isSpringBootDependency(Dependency dependency) { return dependency.getGroupId().startsWith("org.springframework.boot"); } }
if (isSpringBootDependency(o1) && isSpringBootDependency(o2)) { return o1.getArtifactId().compareTo(o2.getArtifactId()); } if (isSpringBootDependency(o1)) { return -1; } if (isSpringBootDependency(o2)) { return 1; } int group = o1.getGroupId().compareTo(o2.getGroupId()); if (group != 0) { return group; } return o1.getArtifactId().compareTo(o2.getArtifactId());
123
160
283
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/MavenRepository.java
MavenRepository
equals
class MavenRepository { /** * Maven Central. */ public static final MavenRepository MAVEN_CENTRAL = MavenRepository .withIdAndUrl("maven-central", "https://repo.maven.apache.org/maven2") .name("Maven Central") .onlyReleases() .build(); private final String id; private final String name; private final String url; private final boolean releasesEnabled; private final boolean snapshotsEnabled; protected MavenRepository(Builder builder) { this.id = builder.id; this.name = builder.name; this.url = builder.url; this.releasesEnabled = builder.releasesEnabled; this.snapshotsEnabled = builder.snapshotsEnabled; } /** * Initialize a new repository {@link Builder} with the specified id and url. The name * of the repository is initialized with the id. * @param id the identifier of the repository * @param url the url of the repository * @return a new builder */ public static Builder withIdAndUrl(String id, String url) { return new Builder(id, url); } /** * Return the identifier of the repository. * @return the repository ID */ public String getId() { return this.id; } /** * Return the name of the repository. * @return the repository name */ public String getName() { return this.name; } /** * Return the url of the repository. * @return the repository url */ public String getUrl() { return this.url; } /** * Return whether releases are enabled on the repository. * @return {@code true} to enable releases, {@code false} otherwise */ public boolean isReleasesEnabled() { return this.releasesEnabled; } /** * Return whether snapshots are enabled on the repository. * @return {@code true} to enable snapshots, {@code false} otherwise */ public boolean isSnapshotsEnabled() { return this.snapshotsEnabled; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(this.id, this.name, this.url, this.releasesEnabled, this.snapshotsEnabled); } public static class Builder { private String id; private String name; private String url; private boolean releasesEnabled = true; private boolean snapshotsEnabled; public Builder(String id, String url) { this.id = id; this.name = id; this.url = url; } /** * Set the id of the repository. * @param id the identifier * @return this for method chaining */ public Builder id(String id) { this.id = id; return this; } /** * Set the name of the repository. * @param name the name * @return this for method chaining */ public Builder name(String name) { this.name = name; return this; } /** * Set the url of the repository. * @param url the url * @return this for method chaining */ public Builder url(String url) { this.url = url; return this; } /** * Specify whether releases are enabled. * @param releasesEnabled whether releases are served by the repository * @return this for method chaining */ public Builder releasesEnabled(boolean releasesEnabled) { this.releasesEnabled = releasesEnabled; return this; } /** * Specify whether snapshots are enabled. * @param snapshotsEnabled whether snapshots are served by the repository * @return this for method chaining */ public Builder snapshotsEnabled(boolean snapshotsEnabled) { this.snapshotsEnabled = snapshotsEnabled; return this; } /** * Specify that the repository should only be used for releases. * @return this for method chaining */ public Builder onlyReleases() { return releasesEnabled(true).snapshotsEnabled(false); } /** * Specify that the repository should only be used for snapshots. * @return this for method chaining */ public Builder onlySnapshots() { return snapshotsEnabled(true).releasesEnabled(false); } /** * Build a {@link MavenRepository} with the current state of this builder. * @return a {@link MavenRepository} */ public MavenRepository build() { return new MavenRepository(this); } } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MavenRepository that = (MavenRepository) o; return this.releasesEnabled == that.releasesEnabled && this.snapshotsEnabled == that.snapshotsEnabled && Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name) && Objects.equals(this.url, that.url);
1,204
134
1,338
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/gradle/GradleBuildSettings.java
Builder
mapPlugin
class Builder extends BuildSettings.Builder<Builder> { private String sourceCompatibility; private final List<PluginMapping> pluginMappings = new ArrayList<>(); /** * Set the java version compatibility to use when compiling Java source. * @param sourceCompatibility java version compatibility * @return this for method chaining */ public Builder sourceCompatibility(String sourceCompatibility) { this.sourceCompatibility = sourceCompatibility; return self(); } /** * Map the plugin with the specified id to the specified {@link Dependency}. This * is mandatory when a plugin does not have an appropriate plugin marker artifact. * @param id the id of a plugin * @param pluginDependency the dependency for that plugin * @return this for method chaining */ public Builder mapPlugin(String id, Dependency pluginDependency) {<FILL_FUNCTION_BODY>} /** * Build a {@link GradleBuildSettings} with the current state of this builder. * @return a {@link GradleBuildSettings} */ public GradleBuildSettings build() { return new GradleBuildSettings(this); } }
if (pluginDependency.getVersion() == null || pluginDependency.getVersion().isProperty()) { throw new IllegalArgumentException("Mapping for plugin '" + id + "' must have a version"); } this.pluginMappings.add(new PluginMapping(id, pluginDependency)); return this;
290
75
365
<methods>public java.lang.String getArtifact() ,public java.lang.String getGroup() ,public java.lang.String getVersion() <variables>private final non-sealed java.lang.String artifact,private final non-sealed java.lang.String group,private final non-sealed java.lang.String version
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/gradle/GradleBuildSystemFactory.java
GradleBuildSystemFactory
createBuildSystem
class GradleBuildSystemFactory implements BuildSystemFactory { @Override public BuildSystem createBuildSystem(String id) { return createBuildSystem(id, null); } @Override public BuildSystem createBuildSystem(String id, String dialect) {<FILL_FUNCTION_BODY>} }
if (GradleBuildSystem.ID.equals(id)) { if (dialect == null) { return new GradleBuildSystem(); } if (dialect.equals(GradleBuildSystem.DIALECT_GROOVY) || dialect.equals(GradleBuildSystem.DIALECT_KOTLIN)) { return new GradleBuildSystem(dialect); } } return null;
75
110
185
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/gradle/GradleConfigurationContainer.java
GradleConfigurationContainer
remove
class GradleConfigurationContainer { private final Set<String> configurations = new LinkedHashSet<>(); private final Map<String, GradleConfiguration.Builder> configurationCustomizations = new LinkedHashMap<>(); /** * Specify if this container is empty. * @return {@code true} if no custom configuration is registered or no configuration * is customized */ public boolean isEmpty() { return this.configurations.isEmpty() && this.configurationCustomizations.isEmpty(); } /** * Specify if this container has a configuration with the specified {@code name}. * @param name the name of a configuration * @return {@code true} if a configuration with the specified {@code name} exists */ public boolean has(String name) { return this.configurations.contains(name) || this.configurationCustomizations.containsKey(name); } /** * Return the configuration names that should be registered. * @return the configuration names */ public Stream<String> names() { return this.configurations.stream(); } /** * Return the configuration that should be customized. * @return the configuration customizations */ public Stream<GradleConfiguration> customizations() { return this.configurationCustomizations.values().stream().map(Builder::build); } /** * Register a {@code configuration} with the specified name. * @param name the name of a configuration */ public void add(String name) { this.configurations.add(name); } /** * Customize an existing {@code configuration} with the specified {@code name}. If the * configuration has already been customized, the consumer can be used to further tune * the existing configuration customization. * @param name the name of the configuration to customize * @param configuration a {@link Consumer} to customize the * {@link GradleConfiguration} */ public void customize(String name, Consumer<Builder> configuration) { Builder builder = this.configurationCustomizations.computeIfAbsent(name, Builder::new); configuration.accept(builder); } /** * Remove the configuration with the specified {@code name}. * @param name the name of a configuration to register or customization * @return {@code true} if such a configuration was registered, {@code false} * otherwise */ public boolean remove(String name) {<FILL_FUNCTION_BODY>} }
if (this.configurations.remove(name)) { return true; } return this.configurationCustomizations.remove(name) != null;
590
43
633
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/gradle/GradleDependency.java
Builder
initialize
class Builder extends Dependency.Builder<Builder> { private String configuration; protected Builder(String groupId, String artifactId) { super(groupId, artifactId); } /** * Specify the configuration to use for the dependency. Overrides the * {@linkplain DependencyScope scope}. * @param configuration the name of the configuration to use * @return this for method chaining */ public Builder configuration(String configuration) { this.configuration = configuration; return self(); } @Override protected Builder initialize(Dependency dependency) {<FILL_FUNCTION_BODY>} @Override public GradleDependency build() { return new GradleDependency(this); } }
super.initialize(dependency); if (dependency instanceof GradleDependency) { configuration(((GradleDependency) dependency).getConfiguration()); } return self();
192
47
239
<methods>public static Builder<?> from(io.spring.initializr.generator.buildsystem.Dependency) ,public java.lang.String getArtifactId() ,public java.lang.String getClassifier() ,public Set<io.spring.initializr.generator.buildsystem.Dependency.Exclusion> getExclusions() ,public java.lang.String getGroupId() ,public io.spring.initializr.generator.buildsystem.DependencyScope getScope() ,public java.lang.String getType() ,public io.spring.initializr.generator.version.VersionReference getVersion() ,public static Builder<?> withCoordinates(java.lang.String, java.lang.String) <variables>private final non-sealed java.lang.String artifactId,private final non-sealed java.lang.String classifier,private final non-sealed Set<io.spring.initializr.generator.buildsystem.Dependency.Exclusion> exclusions,private final non-sealed java.lang.String groupId,private final non-sealed io.spring.initializr.generator.buildsystem.DependencyScope scope,private final non-sealed java.lang.String type,private final non-sealed io.spring.initializr.generator.version.VersionReference version
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/gradle/GradlePluginContainer.java
GradlePluginContainer
add
class GradlePluginContainer { private final Map<String, GradlePlugin> plugins = new LinkedHashMap<>(); /** * Specify if this container is empty. * @return {@code true} if no {@link GradlePlugin} is added */ public boolean isEmpty() { return this.plugins.isEmpty(); } /** * Specify if this container has a plugin with the specified id. * @param id the identifier of a gradle plugin * @return {@code true} if a plugin with the specified {@code id} exists */ public boolean has(String id) { return this.plugins.containsKey(id); } /** * Returns a {@link Stream} of registered {@link GradlePlugin}s. * @return a stream of {@link GradlePlugin}s */ public Stream<GradlePlugin> values() { return this.plugins.values().stream(); } /** * Add a {@link GradlePlugin} to the standard {@code plugins} block with the specified * id. Does nothing if the plugin has already been added. * @param id the id of the plugin * @see #add(String, Consumer) */ public void add(String id) { addPlugin(id, StandardGradlePlugin::new); } /** * Add a {@link GradlePlugin} to the standard {@code plugins} block with the specified * id and {@link Consumer} to customize the object. If the plugin has already been * added, the consumer can be used to further tune the existing plugin configuration. * @param id the id of the plugin * @param plugin a {@link Consumer} to customize the {@link GradlePlugin} */ public void add(String id, Consumer<StandardGradlePlugin> plugin) {<FILL_FUNCTION_BODY>} /** * Apply a {@link GradlePlugin} with the specified id. Does nothing if the plugin has * already been applied. * @param id the id of the plugin */ public void apply(String id) { addPlugin(id, (pluginId) -> new GradlePlugin(pluginId, true)); } private GradlePlugin addPlugin(String id, Function<String, GradlePlugin> pluginId) { return this.plugins.computeIfAbsent(id, pluginId); } /** * Remove the plugin with the specified {@code id}. * @param id the id of the plugin to remove * @return {@code true} if such a plugin was registered, {@code false} otherwise */ public boolean remove(String id) { return this.plugins.remove(id) != null; } }
GradlePlugin gradlePlugin = addPlugin(id, StandardGradlePlugin::new); if (gradlePlugin instanceof StandardGradlePlugin) { plugin.accept((StandardGradlePlugin) gradlePlugin); }
652
57
709
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/gradle/GradleSettingsWriter.java
GradleSettingsWriter
writeResolutionStrategy
class GradleSettingsWriter { /** * Write a {@linkplain GradleBuild settings.gradle} using the specified * {@linkplain IndentingWriter writer}. * @param writer the writer to use * @param build the gradle build to write */ public final void writeTo(IndentingWriter writer, GradleBuild build) { writePluginManagement(writer, build); writer.println("rootProject.name = " + wrapWithQuotes(build.getSettings().getArtifact())); } private void writePluginManagement(IndentingWriter writer, GradleBuild build) { if (build.pluginRepositories().isEmpty() && build.getSettings().getPluginMappings().isEmpty()) { return; } writer.println("pluginManagement {"); writer.indented(() -> { writeRepositories(writer, build); writeResolutionStrategy(writer, build); }); writer.println("}"); } private void writeRepositories(IndentingWriter writer, GradleBuild build) { if (build.pluginRepositories().isEmpty()) { return; } writer.println("repositories {"); writer.indented(() -> { build.pluginRepositories().items().map(this::repositoryAsString).forEach(writer::println); writer.println("gradlePluginPortal()"); }); writer.println("}"); } private void writeResolutionStrategy(IndentingWriter writer, GradleBuild build) {<FILL_FUNCTION_BODY>} private void writePluginMapping(IndentingWriter writer, PluginMapping pluginMapping) { writer.println("if (requested.id.id == " + wrapWithQuotes(pluginMapping.getId()) + ") {"); Dependency dependency = pluginMapping.getDependency(); String module = String.format("%s:%s:%s", dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion().getValue()); writer.indented(() -> writer.println("useModule(" + wrapWithQuotes(module) + ")")); writer.println("}"); } private String repositoryAsString(MavenRepository repository) { if (MavenRepository.MAVEN_CENTRAL.equals(repository)) { return "mavenCentral()"; } return "maven { " + urlAssignment(repository.getUrl()) + " }"; } protected abstract String wrapWithQuotes(String value); protected abstract String urlAssignment(String url); }
if (build.getSettings().getPluginMappings().isEmpty()) { return; } writer.println("resolutionStrategy {"); writer.indented(() -> { writer.println("eachPlugin {"); writer.indented(() -> build.getSettings() .getPluginMappings() .forEach((pluginMapping) -> writePluginMapping(writer, pluginMapping))); writer.println("}"); }); writer.println("}");
640
123
763
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/gradle/GradleTask.java
Attribute
toString
class Attribute { private final String name; private final String value; private final Type type; private Attribute(String name, String value, Type type) { this.name = name; this.value = value; this.type = type; } /** * Create an attribute that {@linkplain Type#SET sets} the specified value. * @param name the name of the attribute * @param value the value to set * @return an attribute */ public static Attribute set(String name, String value) { return new Attribute(name, value, Type.SET); } /** * Create an attribute that {@linkplain Type#APPEND appends} the specified value. * @param name the name of the attribute * @param value the value to append * @return an attribute */ public static Attribute append(String name, String value) { return new Attribute(name, value, Type.APPEND); } /** * Return the name of the attribute. * @return the name */ public String getName() { return this.name; } /** * Return the value of the attribute to set or to append. * @return the value */ public String getValue() { return this.value; } /** * Return the {@link Type} of the attribute. * @return the type */ public Type getType() { return this.type; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Attribute attribute = (Attribute) o; return Objects.equals(this.name, attribute.name) && Objects.equals(this.value, attribute.value) && this.type == attribute.type; } @Override public int hashCode() { return Objects.hash(this.name, this.value, this.type); } @Override public String toString() {<FILL_FUNCTION_BODY>} public enum Type { /** * Set the value of the attribute. */ SET, /** * Append the value to the attribute. */ APPEND; } }
return this.name + ((this.type == Type.SET) ? " = " : " += ") + this.value;
619
32
651
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/maven/MavenBuildSettings.java
Builder
licenses
class Builder extends BuildSettings.Builder<Builder> { private MavenParent parent; private String packaging; private String name; private String description; private List<MavenLicense> licenses = new ArrayList<>(); private List<MavenDeveloper> developers = new ArrayList<>(); private final MavenScm.Builder scm = new MavenScm.Builder(); private String defaultGoal; private String finalName; private String sourceDirectory; private String testSourceDirectory; public Builder() { } /** * Set the coordinates of the project. * @param groupId the group ID of the project * @param artifactId the artifact ID of the project * @return this for method chaining */ public Builder coordinates(String groupId, String artifactId) { return group(groupId).artifact(artifactId); } /** * Set the coordinates of the parent, to be resolved against the repository. * @param groupId the groupID of the parent * @param artifactId the artifactID of the parent * @param version the version of the parent * @return this for method chaining * @see #parent(String, String, String, String) */ public Builder parent(String groupId, String artifactId, String version) { return parent(groupId, artifactId, version, ""); } /** * Set the coordinates of the parent and its relative path. The relative path can * be set to {@code null} to let Maven search the parent using local file search, * for instance {@code pom.xml} in the parent directory. It can also be set to an * empty string to specify that it should be resolved against the repository. * @param groupId the groupID of the parent * @param artifactId the artifactID of the parent * @param version the version of the parent * @param relativePath the relative path * @return this for method chaining */ public Builder parent(String groupId, String artifactId, String version, String relativePath) { this.parent = new MavenParent(groupId, artifactId, version, relativePath); return self(); } /** * Set the packaging of the project. * @param packaging the packaging * @return this for method chaining * @see Packaging */ public Builder packaging(String packaging) { this.packaging = packaging; return self(); } /** * Set the name of the project. * @param name the name of the project * @return this for method chaining */ public Builder name(String name) { this.name = name; return self(); } /** * Set a human readable description of the project. * @param description the description of the project * @return this for method chaining */ public Builder description(String description) { this.description = description; return self(); } /** * Set the licenses of the project. * @param licenses the licenses associated with the project * @return this for method chaining */ public Builder licenses(MavenLicense... licenses) {<FILL_FUNCTION_BODY>} /** * Set the developers of the project. * @param developers the developers associated with the project * @return this for method chaining */ public Builder developers(MavenDeveloper... developers) { this.developers = (developers != null) ? Arrays.asList(developers) : new ArrayList<>(); return self(); } /** * Customize the {@code scm} section using the specified consumer. * @param scm a consumer of the current version control section * @return this for method chaining */ public Builder scm(Consumer<MavenScm.Builder> scm) { scm.accept(this.scm); return self(); } /** * Set the name of the bundled project when it is finally built. * @param finalName the final name of the artifact * @return this for method chaining */ public Builder finalName(String finalName) { this.finalName = finalName; return self(); } /** * Set the default goal or phase to execute if none is given. * @param defaultGoal the default goal or {@code null} to use the default * @return this for method chaining */ public Builder defaultGoal(String defaultGoal) { this.defaultGoal = defaultGoal; return self(); } /** * Set the the location of main source code. Can use Maven properties such as * {@code ${basedir}}. * @param sourceDirectory the location of main source code or {@code null} to use * the default * @return this for method chaining */ public Builder sourceDirectory(String sourceDirectory) { this.sourceDirectory = sourceDirectory; return self(); } /** * Set the the location of test source code. Can use Maven properties such as * {@code ${basedir}}. * @param testSourceDirectory the location of test source code or {@code null} to * use the default * @return this for method chaining */ public Builder testSourceDirectory(String testSourceDirectory) { this.testSourceDirectory = testSourceDirectory; return self(); } @Override public MavenBuildSettings build() { return new MavenBuildSettings(this); } }
this.licenses = (licenses != null) ? Arrays.asList(licenses) : new ArrayList<>(); return self();
1,393
37
1,430
<methods>public java.lang.String getArtifact() ,public java.lang.String getGroup() ,public java.lang.String getVersion() <variables>private final non-sealed java.lang.String artifact,private final non-sealed java.lang.String group,private final non-sealed java.lang.String version
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/maven/MavenBuildSystemFactory.java
MavenBuildSystemFactory
createBuildSystem
class MavenBuildSystemFactory implements BuildSystemFactory { @Override public MavenBuildSystem createBuildSystem(String id) {<FILL_FUNCTION_BODY>} }
if (MavenBuildSystem.ID.equals(id)) { return new MavenBuildSystem(); } return null;
45
36
81
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/maven/MavenDependency.java
Builder
initialize
class Builder extends Dependency.Builder<Builder> { private boolean optional; protected Builder(String groupId, String artifactId) { super(groupId, artifactId); } /** * Specify if the dependency is {@code optional}. * @param optional whether the dependency is optional * @return this for method chaining */ public Builder optional(boolean optional) { this.optional = optional; return self(); } @Override protected Builder initialize(Dependency dependency) {<FILL_FUNCTION_BODY>} @Override public MavenDependency build() { return new MavenDependency(this); } }
super.initialize(dependency); if (dependency instanceof MavenDependency) { optional(((MavenDependency) dependency).isOptional()); } return self();
174
47
221
<methods>public static Builder<?> from(io.spring.initializr.generator.buildsystem.Dependency) ,public java.lang.String getArtifactId() ,public java.lang.String getClassifier() ,public Set<io.spring.initializr.generator.buildsystem.Dependency.Exclusion> getExclusions() ,public java.lang.String getGroupId() ,public io.spring.initializr.generator.buildsystem.DependencyScope getScope() ,public java.lang.String getType() ,public io.spring.initializr.generator.version.VersionReference getVersion() ,public static Builder<?> withCoordinates(java.lang.String, java.lang.String) <variables>private final non-sealed java.lang.String artifactId,private final non-sealed java.lang.String classifier,private final non-sealed Set<io.spring.initializr.generator.buildsystem.Dependency.Exclusion> exclusions,private final non-sealed java.lang.String groupId,private final non-sealed io.spring.initializr.generator.buildsystem.DependencyScope scope,private final non-sealed java.lang.String type,private final non-sealed io.spring.initializr.generator.version.VersionReference version
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/maven/MavenDistributionManagement.java
DeploymentRepository
isEmpty
class DeploymentRepository { private final String id; private final String name; private final String url; private final String layout; private final Boolean uniqueVersion; DeploymentRepository(Builder builder) { this.id = builder.id; this.name = builder.name; this.url = builder.url; this.layout = builder.layout; this.uniqueVersion = builder.uniqueVersion; } public boolean isEmpty() {<FILL_FUNCTION_BODY>} /** * Return the identifier of the repository. * @return the repository ID */ public String getId() { return this.id; } /** * Return the name of the repository. * @return the repository name */ public String getName() { return this.name; } /** * Return the url of the repository to use to upload artifacts. * @return the repository url */ public String getUrl() { return this.url; } /** * Return the repository layout. Can be {@code default} or {@code legacy}. * @return the repository layout */ public String getLayout() { return this.layout; } /** * Return whether to assign snapshots a unique version comprised of the timestamp * and build number, or to use the same version each time. * @return {@code true} to assign each snapshot a unique version */ public Boolean getUniqueVersion() { return this.uniqueVersion; } public static class Builder { private String id; private String name; private String url; private String layout; private Boolean uniqueVersion; /** * Set the id of the repository. * @param id the identifier * @return this for method chaining */ public Builder id(String id) { this.id = id; return this; } /** * Set the name of the repository. * @param name the name * @return this for method chaining */ public Builder name(String name) { this.name = name; return this; } /** * Set the url of the repository to use to upload artifacts. Specify both the * location and the transport protocol used to transfer a built artifact to * the repository. * @param url the url * @return this for method chaining */ public Builder url(String url) { this.url = url; return this; } /** * Set the repository layout, can be {@code default} or {@code legacy}. * @param layout the layout * @return this for method chaining */ public Builder layout(String layout) { this.layout = layout; return this; } /** * Set whether snapshots should be assigned a unique version comprised of the * timestamp and build number. * @param uniqueVersion {@code true} to use unique version for snapshots * @return this for method chaining */ public Builder uniqueVersion(Boolean uniqueVersion) { this.uniqueVersion = uniqueVersion; return this; } /** * Build a {@link DeploymentRepository} with the current state of this * builder. * @return a {@link DeploymentRepository} */ public DeploymentRepository build() { return new DeploymentRepository(this); } } }
return this.id == null && this.name == null && this.url == null && this.layout == null && this.uniqueVersion == null;
887
39
926
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/maven/MavenPlugin.java
ExecutionBuilder
build
class ExecutionBuilder { private final String id; private String phase; private final List<String> goals = new ArrayList<>(); private ConfigurationBuilder configurationCustomization = null; public ExecutionBuilder(String id) { this.id = id; } Execution build() {<FILL_FUNCTION_BODY>} /** * Set the {@code phase} of the build lifecycle that goals will execute in. * @param phase the phase to use * @return this for method chaining */ public ExecutionBuilder phase(String phase) { this.phase = phase; return this; } /** * Add a goal to invoke for this execution. * @param goal the goal to invoke * @return this for method chaining */ public ExecutionBuilder goal(String goal) { this.goals.add(goal); return this; } /** * Customize the {@code configuration} of the execution using the specified * consumer. * @param configuration a consumer of the current configuration * @return this for method chaining */ public ExecutionBuilder configuration(Consumer<ConfigurationBuilder> configuration) { if (this.configurationCustomization == null) { this.configurationCustomization = new ConfigurationBuilder(); } configuration.accept(this.configurationCustomization); return this; } }
return new Execution(this.id, this.phase, this.goals, (this.configurationCustomization == null) ? null : this.configurationCustomization.build());
356
45
401
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/maven/MavenProfileActivation.java
Builder
os
class Builder { private Boolean activeByDefault; private String jdk; private Os os; private Property property; private String fileExists; private String fileMissing; protected Builder() { } /** * Specify if the profile should be enabled if no profile is active. * @param activeByDefault whether to enable the profile is no profile is active * @return this for method chaining */ public Builder activeByDefault(Boolean activeByDefault) { this.activeByDefault = activeByDefault; return this; } /** * Specify the JDK(s) to match to enable the profile. Can be a JDK value or an * OSGi range. * @param jdk the jdk (or JDKs range) to match * @return this for method chaining */ public Builder jdk(String jdk) { this.jdk = jdk; return this; } /** * Specify the OS to match to enable the profile. * @param name the name of the OS * @param family the family os OS * @param arch the cpu architecture * @param version the version of the OS * @return this for method chaining */ public Builder os(String name, String family, String arch, String version) {<FILL_FUNCTION_BODY>} /** * Specify the property to match to enable the profile. * @param name the name of the property * @param value the value of the property * @return this for method chaining */ public Builder property(String name, String value) { if (name == null) { this.property = null; } else { this.property = new Property(name, value); } return this; } /** * Specify the file that should exist to enable the profile. * @param existingFile the file that should exist * @return this for method chaining */ public Builder fileExists(String existingFile) { this.fileExists = existingFile; return this; } /** * Specify the file that should be missing to enable the profile. * @param missingFile the file that should be missing * @return this for method chaining */ public Builder fileMissing(String missingFile) { this.fileMissing = missingFile; return this; } /** * Create a {@link MavenProfileActivation} with the current state of this builder. * @return a {@link MavenProfileActivation}. */ public MavenProfileActivation build() { return new MavenProfileActivation(this); } }
if (name == null && family == null && arch == null && version == null) { this.os = null; } else { this.os = new Os(name, family, arch, version); } return this;
686
64
750
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/buildsystem/maven/MavenScm.java
MavenScm
isEmpty
class MavenScm { private final String connection; private final String developerConnection; private final String tag; private final String url; MavenScm(Builder builder) { this.connection = builder.connection; this.developerConnection = builder.developerConnection; this.tag = builder.tag; this.url = builder.url; } public boolean isEmpty() {<FILL_FUNCTION_BODY>} /** * Return the source control management system URL that describes the repository and * how to connect to the repository. * @return the source control management system URL */ public String getConnection() { return this.connection; } /** * * Just like <code>connection</code>, but for developers, i.e. this scm connection * will not be read only. * @return the source control management system URL for developers */ public String getDeveloperConnection() { return this.developerConnection; } /** * The tag of current code. By default, it's set to HEAD during development. * @return the tag of current code */ public String getTag() { return this.tag; } /** * The URL to the project's browsable SCM repository. * @return the URL to the project's browsable SCM repository */ public String getUrl() { return this.url; } public static class Builder { private String connection; private String developerConnection; private String tag; private String url; /** * Specify the source control management system URL that describes the repository * and how to connect to the repository. * @param connection the source control management system URL * @return this for method chaining */ public Builder connection(String connection) { this.connection = connection; return this; } /** * Specify the source control management system URL for developers that describes * the repository and how to connect to the repository. * @param developerConnection the source control management system URL for * developers * @return this for method chaining */ public Builder developerConnection(String developerConnection) { this.developerConnection = developerConnection; return this; } /** * Specify the tag of current code. By default, it's set to HEAD during * development. * @param tag the tag of current code * @return this for method chaining */ public Builder tag(String tag) { this.tag = tag; return this; } /** * Specify the URL to the project's browsable SCM repository. * @param url the URL to the project's browsable SCM repository * @return this for method chaining */ public Builder url(String url) { this.url = url; return this; } public MavenScm build() { return new MavenScm(this); } } }
return this.connection == null && this.developerConnection == null && this.tag == null && this.url == null;
760
32
792
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/condition/OnBuildSystemCondition.java
OnBuildSystemCondition
matches
class OnBuildSystemCondition extends ProjectGenerationCondition { @Override protected boolean matches(ProjectDescription description, ConditionContext context, AnnotatedTypeMetadata metadata) {<FILL_FUNCTION_BODY>} }
MultiValueMap<String, Object> attributes = metadata .getAllAnnotationAttributes(ConditionalOnBuildSystem.class.getName()); String buildSystemId = (String) attributes.getFirst("value"); String dialect = (String) attributes.getFirst("dialect"); BuildSystem buildSystem = description.getBuildSystem(); if (buildSystem.id().equals(buildSystemId)) { if (StringUtils.hasText(dialect)) { return dialect.equals(buildSystem.dialect()); } return true; } return false;
56
144
200
<methods>public non-sealed void <init>() ,public boolean matches(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata) <variables>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/condition/OnLanguageCondition.java
OnLanguageCondition
matches
class OnLanguageCondition extends ProjectGenerationCondition { @Override protected boolean matches(ProjectDescription description, ConditionContext context, AnnotatedTypeMetadata metadata) {<FILL_FUNCTION_BODY>} }
if (description.getLanguage() == null) { return false; } String languageId = (String) metadata.getAllAnnotationAttributes(ConditionalOnLanguage.class.getName()) .getFirst("value"); Language language = Language.forId(languageId, null); return description.getLanguage().id().equals(language.id());
55
89
144
<methods>public non-sealed void <init>() ,public boolean matches(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata) <variables>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/condition/OnPackagingCondition.java
OnPackagingCondition
matches
class OnPackagingCondition extends ProjectGenerationCondition { @Override protected boolean matches(ProjectDescription description, ConditionContext context, AnnotatedTypeMetadata metadata) {<FILL_FUNCTION_BODY>} }
if (description.getPackaging() == null) { return false; } String packagingId = (String) metadata.getAllAnnotationAttributes(ConditionalOnPackaging.class.getName()) .getFirst("value"); Packaging packaging = Packaging.forId(packagingId); return description.getPackaging().id().equals(packaging.id());
56
94
150
<methods>public non-sealed void <init>() ,public boolean matches(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata) <variables>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/condition/OnPlatformVersionCondition.java
OnPlatformVersionCondition
matches
class OnPlatformVersionCondition extends ProjectGenerationCondition { @Override protected boolean matches(ProjectDescription description, ConditionContext context, AnnotatedTypeMetadata metadata) {<FILL_FUNCTION_BODY>} }
Version platformVersion = description.getPlatformVersion(); if (platformVersion == null) { return false; } return Arrays.stream( (String[]) metadata.getAnnotationAttributes(ConditionalOnPlatformVersion.class.getName()).get("value")) .anyMatch((range) -> VersionParser.DEFAULT.parseRange(range).match(platformVersion));
56
94
150
<methods>public non-sealed void <init>() ,public boolean matches(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata) <variables>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/container/docker/compose/ComposeFileWriter.java
ComposeFileWriter
writerServicePorts
class ComposeFileWriter { /** * Write a {@linkplain ComposeFile compose.yaml} using the specified * {@linkplain IndentingWriter writer}. * @param writer the writer to use * @param compose the compose file to write */ public void writeTo(IndentingWriter writer, ComposeFile compose) { writer.println("services:"); compose.services() .values() .sorted(Comparator.comparing(ComposeService::getName)) .forEach((service) -> writeService(writer, service)); } private void writeService(IndentingWriter writer, ComposeService service) { writer.indented(() -> { writer.println(service.getName() + ":"); writer.indented(() -> { writer.println("image: '%s:%s'".formatted(service.getImage(), service.getImageTag())); writerServiceEnvironment(writer, service.getEnvironment()); writerServiceLabels(writer, service.getLabels()); writerServicePorts(writer, service.getPorts()); writeServiceCommand(writer, service.getCommand()); }); }); } private void writerServiceEnvironment(IndentingWriter writer, Map<String, String> environment) { if (environment.isEmpty()) { return; } writer.println("environment:"); writer.indented(() -> { for (Map.Entry<String, String> env : environment.entrySet()) { writer.println("- '%s=%s'".formatted(env.getKey(), env.getValue())); } }); } private void writerServicePorts(IndentingWriter writer, Set<Integer> ports) {<FILL_FUNCTION_BODY>} private void writeServiceCommand(IndentingWriter writer, String command) { if (!StringUtils.hasText(command)) { return; } writer.println("command: '%s'".formatted(command)); } private void writerServiceLabels(IndentingWriter writer, Map<String, String> labels) { if (labels.isEmpty()) { return; } writer.println("labels:"); writer.indented(() -> { for (Map.Entry<String, String> label : labels.entrySet()) { writer.println("- \"%s=%s\"".formatted(label.getKey(), label.getValue())); } }); } }
if (ports.isEmpty()) { return; } writer.println("ports:"); writer.indented(() -> { for (Integer port : ports) { writer.println("- '%d'".formatted(port)); } });
628
73
701
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/container/docker/compose/ComposeService.java
Builder
imageAndTag
class Builder { private final String name; private String image; private String imageTag = "latest"; private String imageWebsite; private final Map<String, String> environment = new TreeMap<>(); private final Set<Integer> ports = new TreeSet<>(); private String command; private final Map<String, String> labels = new TreeMap<>(); protected Builder(String name) { this.name = name; } public Builder imageAndTag(String imageAndTag) {<FILL_FUNCTION_BODY>} public Builder image(String image) { this.image = image; return this; } public Builder imageTag(String imageTag) { this.imageTag = imageTag; return this; } public Builder imageWebsite(String imageWebsite) { this.imageWebsite = imageWebsite; return this; } public Builder environment(String key, String value) { this.environment.put(key, value); return this; } public Builder environment(Map<String, String> environment) { this.environment.putAll(environment); return this; } public Builder ports(Collection<Integer> ports) { this.ports.addAll(ports); return this; } public Builder ports(int... ports) { return ports(Arrays.stream(ports).boxed().toList()); } public Builder command(String command) { this.command = command; return this; } public Builder label(String key, String value) { this.labels.put(key, value); return this; } public Builder labels(Map<String, String> label) { this.labels.putAll(label); return this; } /** * Builds the {@link ComposeService} instance. * @return the built instance */ public ComposeService build() { return new ComposeService(this); } }
String[] split = imageAndTag.split(":", 2); String tag = (split.length == 1) ? "latest" : split[1]; return image(split[0]).imageTag(tag);
525
56
581
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/io/IndentingWriter.java
IndentingWriter
write
class IndentingWriter extends Writer { private final Writer out; private final Function<Integer, String> indentStrategy; private int level = 0; private String indent = ""; private boolean prependIndent = false; /** * Create a new instance with the specified {@linkplain Writer writer} using a default * indent strategy of 4 spaces. * @param out the writer to use */ public IndentingWriter(Writer out) { this(out, new SimpleIndentStrategy(" ")); } /** * Create a new instance with the specified {@linkplain Writer writer} and indent * strategy. * @param out the writer to use * @param indentStrategy a function that provides the ident to use based on a * indentation level */ public IndentingWriter(Writer out, Function<Integer, String> indentStrategy) { this.out = out; this.indentStrategy = indentStrategy; } /** * Write the specified text. * @param string the content to write */ public void print(String string) { write(string.toCharArray(), 0, string.length()); } /** * Write the specified text and append a new line. * @param string the content to write */ public void println(String string) { write(string.toCharArray(), 0, string.length()); println(); } /** * Write a new line. */ public void println() { String separator = System.lineSeparator(); try { this.out.write(separator.toCharArray(), 0, separator.length()); } catch (IOException ex) { throw new IllegalStateException(ex); } this.prependIndent = true; } /** * Increase the indentation level and execute the {@link Runnable}. Decrease the * indentation level on completion. * @param runnable the code to execute withing an extra indentation level */ public void indented(Runnable runnable) { indent(); runnable.run(); outdent(); } /** * Increase the indentation level. */ private void indent() { this.level++; refreshIndent(); } /** * Decrease the indentation level. */ private void outdent() { this.level--; refreshIndent(); } private void refreshIndent() { this.indent = this.indentStrategy.apply(this.level); } @Override public void write(char[] chars, int offset, int length) {<FILL_FUNCTION_BODY>} @Override public void flush() throws IOException { this.out.flush(); } @Override public void close() throws IOException { this.out.close(); } }
try { if (this.prependIndent) { this.out.write(this.indent.toCharArray(), 0, this.indent.length()); this.prependIndent = false; } this.out.write(chars, offset, length); } catch (IOException ex) { throw new IllegalStateException(ex); }
748
100
848
<methods>public java.io.Writer append(java.lang.CharSequence) throws java.io.IOException,public java.io.Writer append(char) throws java.io.IOException,public java.io.Writer append(java.lang.CharSequence, int, int) throws java.io.IOException,public abstract void close() throws java.io.IOException,public abstract void flush() throws java.io.IOException,public static java.io.Writer nullWriter() ,public void write(int) throws java.io.IOException,public void write(char[]) throws java.io.IOException,public void write(java.lang.String) throws java.io.IOException,public abstract void write(char[], int, int) throws java.io.IOException,public void write(java.lang.String, int, int) throws java.io.IOException<variables>private static final int WRITE_BUFFER_SIZE,protected java.lang.Object lock,private char[] writeBuffer
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/io/IndentingWriterFactory.java
IndentingWriterFactory
create
class IndentingWriterFactory { private final Function<Integer, String> defaultIndentingStrategy; private final Map<String, Function<Integer, String>> indentingStrategies; private IndentingWriterFactory(Builder builder) { this.defaultIndentingStrategy = builder.defaultIndentingStrategy; this.indentingStrategies = new HashMap<>(builder.indentingStrategies); } /** * Create an {@link IndentingWriter} for the specified content and output. * @param contentId the identifier of the content * @param out the output to use * @return a configured {@link IndentingWriter} */ public IndentingWriter createIndentingWriter(String contentId, Writer out) { Function<Integer, String> indentingStrategy = this.indentingStrategies.getOrDefault(contentId, this.defaultIndentingStrategy); return new IndentingWriter(out, indentingStrategy); } /** * Create an {@link IndentingWriterFactory} with a default indentation strategy of 4 * spaces. * @return an {@link IndentingWriterFactory} with default settings */ public static IndentingWriterFactory withDefaultSettings() { return create(new SimpleIndentStrategy(" ")); } /** * Create a {@link IndentingWriterFactory} with a single indenting strategy. * @param defaultIndentingStrategy the default indenting strategy to use * @return an {@link IndentingWriterFactory} */ public static IndentingWriterFactory create(Function<Integer, String> defaultIndentingStrategy) { return new IndentingWriterFactory(new Builder(defaultIndentingStrategy)); } /** * Create a {@link IndentingWriterFactory}. * @param defaultIndentingStrategy the default indenting strategy to use * @param factory a consumer of the builder to apply further customizations * @return an {@link IndentingWriterFactory} */ public static IndentingWriterFactory create(Function<Integer, String> defaultIndentingStrategy, Consumer<Builder> factory) {<FILL_FUNCTION_BODY>} /** * Settings customizer for {@link IndentingWriterFactory}. */ public static final class Builder { private final Function<Integer, String> defaultIndentingStrategy; private final Map<String, Function<Integer, String>> indentingStrategies = new HashMap<>(); private Builder(Function<Integer, String> defaultIndentingStrategy) { this.defaultIndentingStrategy = defaultIndentingStrategy; } /** * Register an indenting strategy for the specified content. * @param contentId the identifier of the content to configure * @param indentingStrategy the indent strategy for that particular content * @return this for method chaining * @see #createIndentingWriter(String, Writer) */ public Builder indentingStrategy(String contentId, Function<Integer, String> indentingStrategy) { this.indentingStrategies.put(contentId, indentingStrategy); return this; } } }
Builder factoryBuilder = new Builder(defaultIndentingStrategy); factory.accept(factoryBuilder); return new IndentingWriterFactory(factoryBuilder);
782
42
824
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/io/SimpleIndentStrategy.java
SimpleIndentStrategy
apply
class SimpleIndentStrategy implements Function<Integer, String> { private final String indent; /** * Create a new instance with the indent style to apply. * @param indent the indent to apply for each indent level */ public SimpleIndentStrategy(String indent) { Assert.notNull(indent, "Indent must be provided"); this.indent = indent; } @Override public String apply(Integer level) {<FILL_FUNCTION_BODY>} }
if (level < 0) { throw new IllegalArgumentException("Indent level must not be negative, got" + level); } return String.valueOf(this.indent).repeat(level);
128
52
180
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/io/template/MustacheTemplateRenderer.java
MustacheTemplateRenderer
getTemplate
class MustacheTemplateRenderer implements TemplateRenderer { private final Compiler mustache; private final Function<String, String> keyGenerator; private final Cache templateCache; /** * Create a new instance with the resource prefix and the {@link Cache} to use. * @param resourcePrefix the resource prefix to apply to locate a template based on * its name * @param templateCache the cache to use for compiled templates (can be {@code null} * to not use caching) */ public MustacheTemplateRenderer(String resourcePrefix, Cache templateCache) { String prefix = (resourcePrefix.endsWith("/") ? resourcePrefix : resourcePrefix + "/"); this.mustache = Mustache.compiler().withLoader(mustacheTemplateLoader(prefix)).escapeHTML(false); this.keyGenerator = (name) -> String.format("%s%s", prefix, name); this.templateCache = templateCache; } /** * Create a new instance with the resource prefix to use. * @param resourcePrefix the resource prefix to apply to locate a template based on * its name * @see #MustacheTemplateRenderer(String, Cache) */ public MustacheTemplateRenderer(String resourcePrefix) { this(resourcePrefix, null); } private static TemplateLoader mustacheTemplateLoader(String prefix) { ResourceLoader resourceLoader = new DefaultResourceLoader(); return (name) -> { String location = prefix + name + ".mustache"; return new InputStreamReader(resourceLoader.getResource(location).getInputStream(), StandardCharsets.UTF_8); }; } @Override public String render(String templateName, Map<String, ?> model) { Template template = getTemplate(templateName); return template.execute(model); } private Template getTemplate(String name) {<FILL_FUNCTION_BODY>} private Template loadTemplate(String name) throws Exception { Reader template = this.mustache.loader.getTemplate(name); return this.mustache.compile(template); } }
try { if (this.templateCache != null) { try { return this.templateCache.get(this.keyGenerator.apply(name), () -> loadTemplate(name)); } catch (ValueRetrievalException ex) { throw ex.getCause(); } } return loadTemplate(name); } catch (Throwable ex) { throw new IllegalStateException("Cannot load template " + name, ex); }
499
127
626
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/io/text/BulletedSection.java
BulletedSection
write
class BulletedSection<T> implements Section { private final TemplateRenderer templateRenderer; private final String templateName; private final String itemName; private final List<T> items = new ArrayList<>(); /** * Create a new instance adding items in the model with the {@code items} key. * @param templateRenderer the {@linkplain TemplateRenderer template renderer} to use * @param templateName the name of the template */ public BulletedSection(TemplateRenderer templateRenderer, String templateName) { this(templateRenderer, templateName, "items"); } /** * Create a new instance. * @param templateRenderer the {@linkplain TemplateRenderer template renderer} to use * @param templateName the name of the template * @param itemName the key of the items in the model */ public BulletedSection(TemplateRenderer templateRenderer, String templateName, String itemName) { this.templateRenderer = templateRenderer; this.templateName = templateName; this.itemName = itemName; } /** * Add an item to the list. * @param item the item to add * @return this for method chaining */ public BulletedSection<T> addItem(T item) { this.items.add(item); return this; } /** * Specify whether this section is empty. * @return {@code true} if no item is registered */ public boolean isEmpty() { return this.items.isEmpty(); } /** * Return an immutable list of the registered items. * @return the registered items */ public List<T> getItems() { return Collections.unmodifiableList(this.items); } @Override public void write(PrintWriter writer) throws IOException {<FILL_FUNCTION_BODY>} }
if (!isEmpty()) { Map<String, Object> model = new HashMap<>(); model.put(this.itemName, this.items); writer.println(this.templateRenderer.render(this.templateName, model)); }
452
66
518
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/language/Annotation.java
AnnotationWriter
generateAttributeValuesCode
class AnnotationWriter { private final IndentingWriter writer; private final FormattingOptions formattingOptions; AnnotationWriter(IndentingWriter writer, FormattingOptions formattingOptions) { this.writer = writer; this.formattingOptions = formattingOptions; } void write(Annotation annotation) { generateAnnotationCode(annotation).write(this.writer, this.formattingOptions); } private CodeBlock generateAnnotationCode(Annotation annotation) { CodeBlock.Builder code = CodeBlock.builder(); code.add("@$T", annotation.className); if (annotation.attributes.size() == 1 && annotation.attributes.get(0).getName().equals("value")) { code.add("($L)", generateAttributeValuesCode(annotation.attributes.get(0))); } else if (!annotation.attributes.isEmpty()) { CodeBlock attributes = annotation.attributes.stream() .map(this::generateAttributeCode) .collect(CodeBlock.joining(", ")); code.add("($L)", attributes); } return code.build(); } private CodeBlock generateAttributeCode(Attribute attribute) { return CodeBlock.of("$L = $L", attribute.name, generateAttributeValuesCode(attribute)); } private CodeBlock generateAttributeValuesCode(Attribute attribute) {<FILL_FUNCTION_BODY>} private CodeBlock generateValueCode(AttributeType attributeType, Object value) { Class<?> valueType = ClassUtils.resolvePrimitiveIfNecessary(value.getClass()); // CodeBlock can be anything if (value instanceof CodeBlock codeBlock) { return codeBlock; } return switch (attributeType) { case PRIMITIVE -> { if (valueType == Character.class) { yield CodeBlock.of("'$L'", value); } else { yield CodeBlock.of("$L", value); } } case STRING -> CodeBlock.of("$S", value); case CLASS -> { ClassName className = (value instanceof Class clazz) ? ClassName.of(clazz) : (ClassName) value; yield this.formattingOptions.classReference(className); } case ENUM -> { Enum<?> enumValue = (Enum<?>) value; yield CodeBlock.of("$T.$L", enumValue.getClass(), enumValue.name()); } case ANNOTATION -> generateAnnotationCode((Annotation) value); case CODE -> (CodeBlock) value; }; } }
CodeBlock[] values = attribute.values.stream() .map((value) -> generateValueCode(attribute.type, value)) .toArray(CodeBlock[]::new); return (values.length == 1) ? values[0] : this.formattingOptions.arrayOf(values);
666
75
741
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/language/AnnotationContainer.java
AnnotationContainer
add
class AnnotationContainer { private final Map<ClassName, Builder> annotations; public AnnotationContainer() { this(new LinkedHashMap<>()); } private AnnotationContainer(Map<ClassName, Builder> annotations) { this.annotations = annotations; } /** * Specify if this container is empty. * @return {@code true} if no annotation is registered */ public boolean isEmpty() { return this.annotations.isEmpty(); } /** * Specify if this container has a an annotation with the specified {@link ClassName}. * @param className the class name of an annotation * @return {@code true} if the annotation with the specified class name exists */ public boolean has(ClassName className) { return this.annotations.containsKey(className); } /** * Return the {@link Annotation annotations}. * @return the annotations */ public Stream<Annotation> values() { return this.annotations.values().stream().map(Builder::build); } /** * Add a single {@link Annotation} with the specified class name and {@link Consumer} * to customize it. If the annotation has already been added, the consumer can be used * to further tune attributes * @param className the class name of an annotation * @param annotation a {@link Consumer} to customize the {@link Annotation} */ public void add(ClassName className, Consumer<Builder> annotation) {<FILL_FUNCTION_BODY>} /** * Add a single {@link Annotation} with the specified class name. Does nothing If the * annotation has already been added. * @param className the class name of an annotation */ public void add(ClassName className) { add(className, null); } /** * Remove the annotation with the specified {@link ClassName}. * @param className the class name of the annotation * @return {@code true} if such an annotation exists, {@code false} otherwise */ public boolean remove(ClassName className) { return this.annotations.remove(className) != null; } public AnnotationContainer deepCopy() { Map<ClassName, Builder> copy = new LinkedHashMap<>(); this.annotations.forEach((className, builder) -> copy.put(className, new Builder(builder))); return new AnnotationContainer(copy); } }
Builder builder = this.annotations.computeIfAbsent(className, (key) -> new Builder(className)); if (annotation != null) { annotation.accept(builder); }
590
53
643
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/language/ClassName.java
ClassName
equals
class ClassName { private static final List<String> PRIMITIVE_NAMES = List.of("boolean", "byte", "short", "int", "long", "char", "float", "double", "void"); private final String packageName; private final String simpleName; private final ClassName enclosingType; private String canonicalName; private ClassName(String packageName, String simpleName, ClassName enclosingType) { this.packageName = packageName; this.simpleName = simpleName; this.enclosingType = enclosingType; } /** * Create a {@link ClassName} based on the specified fully qualified name. The format * of the class name must follow {@linkplain Class#getName()}, in particular inner * classes should be separated by a {@code $}. * @param fqName the fully qualified name of the class * @return a class name */ public static ClassName of(String fqName) { Assert.notNull(fqName, "'className' must not be null"); if (!isValidClassName(fqName)) { throw new IllegalStateException("Invalid class name '" + fqName + "'"); } if (!fqName.contains("$")) { return createClassName(fqName); } String[] elements = fqName.split("(?<!\\$)\\$(?!\\$)"); ClassName className = createClassName(elements[0]); for (int i = 1; i < elements.length; i++) { className = new ClassName(className.getPackageName(), elements[i], className); } return className; } /** * Create a {@link ClassName} based on the specified {@link Class}. * @param type the class to wrap * @return a class name */ public static ClassName of(Class<?> type) { return of(type.getName()); } /** * Return the fully qualified name. * @return the reflection target name */ public String getName() { ClassName enclosingType = getEnclosingType(); String simpleName = getSimpleName(); return (enclosingType != null) ? (enclosingType.getName() + '$' + simpleName) : addPackageIfNecessary(simpleName); } /** * Return the package name. * @return the package name */ public String getPackageName() { return this.packageName; } /** * Return the {@linkplain Class#getSimpleName() simple name}. * @return the simple name */ public String getSimpleName() { return this.simpleName; } /** * Return the enclosing class name, or {@code null} if this instance does not have an * enclosing type. * @return the enclosing type, if any */ public ClassName getEnclosingType() { return this.enclosingType; } /** * Return the {@linkplain Class#getCanonicalName() canonical name}. * @return the canonical name */ public String getCanonicalName() { if (this.canonicalName == null) { StringBuilder names = new StringBuilder(); buildName(this, names); this.canonicalName = addPackageIfNecessary(names.toString()); } return this.canonicalName; } private boolean isPrimitive() { return isPrimitive(getSimpleName()); } private static boolean isPrimitive(String name) { return PRIMITIVE_NAMES.stream().anyMatch(name::startsWith); } private String addPackageIfNecessary(String part) { if (this.packageName.isEmpty() || this.packageName.equals("java.lang") && isPrimitive()) { return part; } return this.packageName + '.' + part; } private static boolean isValidClassName(String className) { for (String s : className.split("\\.", -1)) { String candidate = s.replace("[", "").replace("]", ""); if (!SourceVersion.isIdentifier(candidate)) { return false; } } return true; } private static ClassName createClassName(String className) { int i = className.lastIndexOf('.'); if (i != -1) { return new ClassName(className.substring(0, i), className.substring(i + 1), null); } else { String packageName = (isPrimitive(className)) ? "java.lang" : ""; return new ClassName(packageName, className, null); } } private static void buildName(ClassName className, StringBuilder sb) { if (className == null) { return; } String typeName = (className.getEnclosingType() != null) ? "." + className.getSimpleName() : className.getSimpleName(); sb.insert(0, typeName); buildName(className.getEnclosingType(), sb); } @Override public boolean equals(@Nullable Object other) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(getCanonicalName()); } @Override public String toString() { return getCanonicalName(); } }
if (this == other) { return true; } if (!(other instanceof ClassName className)) { return false; } return getCanonicalName().equals(className.getCanonicalName());
1,349
57
1,406
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/language/CodeBlock.java
CodeBlockJoiner
merge
class CodeBlockJoiner { private final String delimiter; private final CodeBlock.Builder builder; private boolean first = true; CodeBlockJoiner(String delimiter, CodeBlock.Builder builder) { this.delimiter = delimiter; this.builder = builder; } CodeBlockJoiner add(CodeBlock codeBlock) { if (!this.first) { this.builder.add(this.delimiter); } this.first = false; this.builder.add(codeBlock); return this; } CodeBlock.CodeBlockJoiner merge(CodeBlockJoiner other) {<FILL_FUNCTION_BODY>} CodeBlock join() { return this.builder.build(); } }
CodeBlock otherBlock = other.builder.build(); if (!otherBlock.parts.isEmpty()) { add(otherBlock); } return this;
207
45
252
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/language/SourceStructure.java
SourceStructure
resolveSourceFile
class SourceStructure { private final Path rootDirectory; private final String sourceFileExtension; private final Path sourcesDirectory; private final Path resourcesDirectory; public SourceStructure(Path rootDirectory, Language language) { this.rootDirectory = rootDirectory; this.sourceFileExtension = language.sourceFileExtension(); this.sourcesDirectory = rootDirectory.resolve(language.id()); this.resourcesDirectory = rootDirectory.resolve("resources"); } /** * Return the root {@link Path directory} of this structure. Can be used to access * additional resources. * @return the root directory */ public Path getRootDirectory() { return this.rootDirectory; } /** * Return the sources {@link Path directory} of this structure. * @return the sources directory */ public Path getSourcesDirectory() { return this.sourcesDirectory; } /** * Return the resources {@link Path directory} of this structure. * @return the resources directory */ public Path getResourcesDirectory() { return this.resourcesDirectory; } /** * Resolve a source file. * @param packageName the name of the package * @param fileName the name of the file (without its extension) * @return the {@link Path file} to use to store a {@code CompilationUnit} with the * specified package and name * @see #getSourcesDirectory() */ public Path resolveSourceFile(String packageName, String fileName) {<FILL_FUNCTION_BODY>} /** * Create a source file, creating its package structure if necessary. * @param packageName the name of the package * @param fileName the name of the file (without its extension) * @return the {@link Path file} to use to store a {@code CompilationUnit} with the * specified package and name * @throws IOException if an error occurred while trying to create the directory * structure or the file itself * @see #getSourcesDirectory() */ public Path createSourceFile(String packageName, String fileName) throws IOException { Path sourceFile = resolveSourceFile(packageName, fileName); createFile(sourceFile); return sourceFile; } /** * Resolve a resource file defined in the specified package. * @param packageName the name of the package * @param file the name of the file (including its extension) * @return the {@link Path file} to use to store a resource with the specified package * @see #getResourcesDirectory() */ public Path resolveResourceFile(String packageName, String file) { return resolvePackage(this.resourcesDirectory, packageName).resolve(file); } /** * Create a resource file, creating its package structure if necessary. * @param packageName the name of the package * @param file the name of the file (including its extension) * @return the {@link Path file} to use to store a resource with the specified package * @throws IOException if an error occurred while trying to create the directory * structure or the file itself * @see #getResourcesDirectory() */ public Path createResourceFile(String packageName, String file) throws IOException { Path resourceFile = resolveResourceFile(packageName, file); createFile(resourceFile); return resourceFile; } private void createFile(Path file) throws IOException { Files.createDirectories(file.getParent()); Files.createFile(file); } private static Path resolvePackage(Path directory, String packageName) { return directory.resolve(packageName.replace('.', '/')); } }
String file = fileName + "." + this.sourceFileExtension; return resolvePackage(this.sourcesDirectory, packageName).resolve(file);
890
38
928
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/language/groovy/GroovyLanguageFactory.java
GroovyLanguageFactory
createLanguage
class GroovyLanguageFactory implements LanguageFactory { @Override public Language createLanguage(String id, String jvmVersion) {<FILL_FUNCTION_BODY>} }
if (GroovyLanguage.ID.equals(id)) { return new GroovyLanguage(jvmVersion); } return null;
45
41
86
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/language/java/JavaLanguageFactory.java
JavaLanguageFactory
createLanguage
class JavaLanguageFactory implements LanguageFactory { @Override public Language createLanguage(String id, String jvmVersion) {<FILL_FUNCTION_BODY>} }
if (JavaLanguage.ID.equals(id)) { return new JavaLanguage(jvmVersion); } return null;
43
36
79
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/language/kotlin/KotlinLanguageFactory.java
KotlinLanguageFactory
createLanguage
class KotlinLanguageFactory implements LanguageFactory { @Override public Language createLanguage(String id, String jvmVersion) {<FILL_FUNCTION_BODY>} }
if (KotlinLanguage.ID.equals(id)) { return new KotlinLanguage(jvmVersion); } return null;
45
40
85
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/packaging/jar/JarPackagingFactory.java
JarPackagingFactory
createPackaging
class JarPackagingFactory implements PackagingFactory { @Override public Packaging createPackaging(String id) {<FILL_FUNCTION_BODY>} }
if (JarPackaging.ID.equals(id)) { return new JarPackaging(); } return null;
42
35
77
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/packaging/war/WarPackagingFactory.java
WarPackagingFactory
createPackaging
class WarPackagingFactory implements PackagingFactory { @Override public Packaging createPackaging(String id) {<FILL_FUNCTION_BODY>} }
if (WarPackaging.ID.equals(id)) { return new WarPackaging(); } return null;
42
34
76
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/project/DefaultProjectAssetGenerator.java
DefaultProjectAssetGenerator
generate
class DefaultProjectAssetGenerator implements ProjectAssetGenerator<Path> { private final ProjectDirectoryFactory projectDirectoryFactory; /** * Create a new instance with the {@link ProjectDirectoryFactory} to use. * @param projectDirectoryFactory the project directory factory to use */ public DefaultProjectAssetGenerator(ProjectDirectoryFactory projectDirectoryFactory) { this.projectDirectoryFactory = projectDirectoryFactory; } /** * Create a new instance without an explicit {@link ProjectDirectoryFactory}. A bean * of that type is expected to be available in the context. */ public DefaultProjectAssetGenerator() { this(null); } @Override public Path generate(ProjectGenerationContext context) throws IOException {<FILL_FUNCTION_BODY>} private ProjectDirectoryFactory resolveProjectDirectoryFactory(ProjectGenerationContext context) { return (this.projectDirectoryFactory != null) ? this.projectDirectoryFactory : context.getBean(ProjectDirectoryFactory.class); } private Path initializerProjectDirectory(Path rootDir, ProjectDescription description) throws IOException { Path projectDirectory = resolveProjectDirectory(rootDir, description); Files.createDirectories(projectDirectory); return projectDirectory; } private Path resolveProjectDirectory(Path rootDir, ProjectDescription description) { if (description.getBaseDirectory() != null) { return rootDir.resolve(description.getBaseDirectory()); } return rootDir; } }
ProjectDescription description = context.getBean(ProjectDescription.class); Path projectRoot = resolveProjectDirectoryFactory(context).createProjectDirectory(description); Path projectDirectory = initializerProjectDirectory(projectRoot, description); List<ProjectContributor> contributors = context.getBeanProvider(ProjectContributor.class) .orderedStream() .toList(); for (ProjectContributor contributor : contributors) { contributor.contribute(projectDirectory); } return projectRoot;
351
132
483
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/project/MutableProjectDescription.java
MutableProjectDescription
getPackageName
class MutableProjectDescription implements ProjectDescription { private Version platformVersion; private BuildSystem buildSystem; private Packaging packaging; private Language language; private final Map<String, Dependency> requestedDependencies = new LinkedHashMap<>(); private String groupId; private String artifactId; private String version; private String name; private String description; private String applicationName; private String packageName; private String baseDirectory; public MutableProjectDescription() { } /** * Create a new instance with the state of the specified {@code source}. * @param source the source description to initialize this instance with */ protected MutableProjectDescription(MutableProjectDescription source) { this.platformVersion = source.getPlatformVersion(); this.buildSystem = source.getBuildSystem(); this.packaging = source.getPackaging(); this.language = source.getLanguage(); this.requestedDependencies.putAll(source.getRequestedDependencies()); this.groupId = source.getGroupId(); this.artifactId = source.getArtifactId(); this.version = source.getVersion(); this.name = source.getName(); this.description = source.getDescription(); this.applicationName = source.getApplicationName(); this.packageName = source.getPackageName(); this.baseDirectory = source.getBaseDirectory(); } @Override public MutableProjectDescription createCopy() { return new MutableProjectDescription(this); } @Override public Version getPlatformVersion() { return this.platformVersion; } public void setPlatformVersion(Version platformVersion) { this.platformVersion = platformVersion; } @Override public BuildSystem getBuildSystem() { return this.buildSystem; } public void setBuildSystem(BuildSystem buildSystem) { this.buildSystem = buildSystem; } @Override public Packaging getPackaging() { return this.packaging; } public void setPackaging(Packaging packaging) { this.packaging = packaging; } @Override public Language getLanguage() { return this.language; } public void setLanguage(Language language) { this.language = language; } public Dependency addDependency(String id, Dependency dependency) { return this.requestedDependencies.put(id, dependency); } public Dependency addDependency(String id, Dependency.Builder<?> builder) { return addDependency(id, builder.build()); } public Dependency removeDependency(String id) { return this.requestedDependencies.remove(id); } @Override public Map<String, Dependency> getRequestedDependencies() { return Collections.unmodifiableMap(this.requestedDependencies); } @Override public String getGroupId() { return this.groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } @Override public String getArtifactId() { return this.artifactId; } public void setArtifactId(String artifactId) { this.artifactId = artifactId; } @Override public String getVersion() { return this.version; } public void setVersion(String version) { this.version = version; } @Override public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Override public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } @Override public String getApplicationName() { return this.applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } @Override public String getPackageName() {<FILL_FUNCTION_BODY>} public void setPackageName(String packageName) { this.packageName = packageName; } @Override public String getBaseDirectory() { return this.baseDirectory; } public void setBaseDirectory(String baseDirectory) { this.baseDirectory = baseDirectory; } }
if (StringUtils.hasText(this.packageName)) { return this.packageName; } if (StringUtils.hasText(this.groupId) && StringUtils.hasText(this.artifactId)) { return this.groupId + "." + this.artifactId; } return null;
1,059
78
1,137
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/project/ProjectGenerator.java
ProjectGenerator
resolve
class ProjectGenerator { private final Consumer<ProjectGenerationContext> contextConsumer; private final Supplier<? extends ProjectGenerationContext> contextFactory; /** * Create an instance with a customizer for the project generator application context * and a factory for the {@link ProjectGenerationContext}. * @param contextConsumer a consumer of the project generation context after * contributors and the {@link ProjectDescription} have been registered but before it * is refreshed * @param contextFactory the factory to use to create {@link ProjectGenerationContext} * instances */ public ProjectGenerator(Consumer<ProjectGenerationContext> contextConsumer, Supplier<? extends ProjectGenerationContext> contextFactory) { this.contextConsumer = contextConsumer; this.contextFactory = contextFactory; } /** * Create an instance with a customizer for the {@link ProjectGenerationContext} and a * default factory for the {@link ProjectGenerationContext} that disables bean * definition overriding. * @param contextConsumer a consumer of the project generation context after * contributors and the {@link ProjectDescription} have been registered but before it * is refreshed * @see GenericApplicationContext#setAllowBeanDefinitionOverriding(boolean) */ public ProjectGenerator(Consumer<ProjectGenerationContext> contextConsumer) { this(contextConsumer, defaultContextFactory()); } private static Supplier<ProjectGenerationContext> defaultContextFactory() { return () -> { ProjectGenerationContext context = new ProjectGenerationContext(); context.setAllowBeanDefinitionOverriding(false); return context; }; } /** * Generate project assets using the specified {@link ProjectAssetGenerator} for the * specified {@link ProjectDescription}. * <p> * Create a dedicated {@link ProjectGenerationContext} using the supplied * {@link #ProjectGenerator(Consumer, Supplier) contextFactory} and then apply the * following: * <ul> * <li>Register a {@link ProjectDescription} bean based on the given * {@code description} post-processed by available * {@link ProjectDescriptionCustomizer} beans.</li> * <li>Process all registered {@link ProjectGenerationConfiguration} classes.</li> * <li>Apply the {@link #ProjectGenerator(Consumer, Supplier) contextConsumer} to * further customize the context before it is refreshed.</li> * </ul> * @param description the description of the project to generate * @param projectAssetGenerator the {@link ProjectAssetGenerator} to invoke * @param <T> the type that gathers the project assets * @return the generated content * @throws ProjectGenerationException if an error occurs while generating the project */ public <T> T generate(ProjectDescription description, ProjectAssetGenerator<T> projectAssetGenerator) throws ProjectGenerationException { try (ProjectGenerationContext context = this.contextFactory.get()) { registerProjectDescription(context, description); registerProjectContributors(context, description); this.contextConsumer.accept(context); context.refresh(); try { return projectAssetGenerator.generate(context); } catch (IOException ex) { throw new ProjectGenerationException("Failed to generate project", ex); } } } /** * Return the {@link ProjectGenerationConfiguration} class names that should be * considered. By default this method will load candidates using * {@link SpringFactoriesLoader} with {@link ProjectGenerationConfiguration}. * @param description the description of the project to generate * @return a list of candidate configurations */ @SuppressWarnings("deprecation") protected List<String> getCandidateProjectGenerationConfigurations(ProjectDescription description) { return SpringFactoriesLoader.loadFactoryNames(ProjectGenerationConfiguration.class, getClass().getClassLoader()); } private void registerProjectDescription(ProjectGenerationContext context, ProjectDescription description) { context.registerBean(ProjectDescription.class, resolve(description, context)); } private void registerProjectContributors(ProjectGenerationContext context, ProjectDescription description) { getCandidateProjectGenerationConfigurations(description).forEach((configurationClassName) -> { GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClassName(configurationClassName); context.registerBeanDefinition(configurationClassName, beanDefinition); }); } private Supplier<ProjectDescription> resolve(ProjectDescription description, ProjectGenerationContext context) {<FILL_FUNCTION_BODY>} }
return () -> { if (description instanceof MutableProjectDescription mutableDescription) { ProjectDescriptionDiffFactory diffFactory = context.getBeanProvider(ProjectDescriptionDiffFactory.class) .getIfAvailable(DefaultProjectDescriptionDiffFactory::new); // Create the diff here so that it takes a copy of the description // immediately ProjectDescriptionDiff diff = diffFactory.create(mutableDescription); context.registerBean(ProjectDescriptionDiff.class, () -> diff); context.getBeanProvider(ProjectDescriptionCustomizer.class) .orderedStream() .forEach((customizer) -> customizer.customize(mutableDescription)); } return description; };
1,136
170
1,306
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/project/contributor/MultipleResourcesProjectContributor.java
MultipleResourcesProjectContributor
contribute
class MultipleResourcesProjectContributor implements ProjectContributor { private final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); private final String rootResource; private final Predicate<String> executable; /** * Create a new instance with the {@code rootResource} to use to locate resources to * copy to the project structure. * @param rootResource the root resource path * @see PathMatchingResourcePatternResolver#getResources(String) */ public MultipleResourcesProjectContributor(String rootResource) { this(rootResource, (filename) -> false); } public MultipleResourcesProjectContributor(String rootResource, Predicate<String> executable) { this.rootResource = StringUtils.trimTrailingCharacter(rootResource, '/'); this.executable = executable; } @Override public void contribute(Path projectRoot) throws IOException {<FILL_FUNCTION_BODY>} private String extractFileName(URI root, URI resource) { String candidate = resource.toString().substring(root.toString().length()); return StringUtils.trimLeadingCharacter(candidate, '/'); } }
Resource root = this.resolver.getResource(this.rootResource); Resource[] resources = this.resolver.getResources(this.rootResource + "/**"); for (Resource resource : resources) { if (resource.isReadable()) { String filename = extractFileName(root.getURI(), resource.getURI()); Path output = projectRoot.resolve(filename); if (!Files.exists(output)) { Files.createDirectories(output.getParent()); Files.createFile(output); } FileCopyUtils.copy(resource.getInputStream(), Files.newOutputStream(output)); // TODO Set executable using NIO output.toFile().setExecutable(this.executable.test(filename)); } }
284
192
476
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/project/contributor/SingleResourceProjectContributor.java
SingleResourceProjectContributor
contribute
class SingleResourceProjectContributor implements ProjectContributor { private final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); private final String relativePath; private final String resourcePattern; /** * Create a new instance. * @param relativePath the {@linkplain Path#resolve(String) relative path} in the * generated structure. * @param resourcePattern the pattern to use to locate the resource to copy to the * project structure * @see PathMatchingResourcePatternResolver#getResource(String) */ public SingleResourceProjectContributor(String relativePath, String resourcePattern) { this.relativePath = relativePath; this.resourcePattern = resourcePattern; } @Override public void contribute(Path projectRoot) throws IOException {<FILL_FUNCTION_BODY>} }
Path output = projectRoot.resolve(this.relativePath); if (!Files.exists(output)) { Files.createDirectories(output.getParent()); Files.createFile(output); } Resource resource = this.resolver.getResource(this.resourcePattern); FileCopyUtils.copy(resource.getInputStream(), Files.newOutputStream(output, StandardOpenOption.APPEND));
205
104
309
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/version/VersionParser.java
VersionParser
parseRange
class VersionParser { /** * The default {@link VersionParser}. */ public static final VersionParser DEFAULT = new VersionParser(Collections.emptyList()); private static final Pattern VERSION_REGEX = Pattern .compile("^(\\d+)\\.(\\d+|x)\\.(\\d+|x)(?:([.|-])([^0-9]+)(\\d+)?)?$"); private static final Pattern RANGE_REGEX = Pattern.compile("([(\\[])(.*),(.*)([)\\]])"); private final List<Version> latestVersions; public VersionParser(List<Version> latestVersions) { this.latestVersions = latestVersions; } /** * Parse the string representation of a {@link Version}. Throws an * {@link InvalidVersionException} if the version could not be parsed. * @param text the version text * @return a Version instance for the specified version text * @throws InvalidVersionException if the version text could not be parsed * @see #safeParse(java.lang.String) */ public Version parse(String text) { Assert.notNull(text, "Text must not be null"); Matcher matcher = VERSION_REGEX.matcher(text.trim()); if (!matcher.matches()) { throw new InvalidVersionException("Could not determine version based on '" + text + "': version format " + "is Major.Minor.Patch and an optional Qualifier " + "(e.g. 1.0.5.RELEASE)"); } Integer major = Integer.valueOf(matcher.group(1)); String minor = matcher.group(2); String patch = matcher.group(3); Qualifier qualifier = parseQualifier(matcher); if ("x".equals(minor) || "x".equals(patch)) { Integer minorInt = ("x".equals(minor) ? null : Integer.parseInt(minor)); Version latest = findLatestVersion(major, minorInt, qualifier); if (latest == null) { return new Version(major, ("x".equals(minor) ? 999 : Integer.parseInt(minor)), ("x".equals(patch) ? 999 : Integer.parseInt(patch)), qualifier); } return new Version(major, latest.getMinor(), latest.getPatch(), latest.getQualifier()); } else { return new Version(major, Integer.parseInt(minor), Integer.parseInt(patch), qualifier); } } private Qualifier parseQualifier(Matcher matcher) { String qualifierSeparator = matcher.group(4); String qualifierId = matcher.group(5); if (StringUtils.hasText(qualifierSeparator) && StringUtils.hasText(qualifierId)) { String versionString = matcher.group(6); return new Qualifier(qualifierId, (versionString != null) ? Integer.valueOf(versionString) : null, qualifierSeparator); } return null; } /** * Parse safely the specified string representation of a {@link Version}. * <p> * Return {@code null} if the text represents an invalid version. * @param text the version text * @return a Version instance for the specified version text * @see #parse(java.lang.String) */ public Version safeParse(String text) { try { return parse(text); } catch (InvalidVersionException ex) { return null; } } /** * Parse the string representation of a {@link VersionRange}. Throws an * {@link InvalidVersionException} if the range could not be parsed. * @param text the range text * @return a VersionRange instance for the specified range text * @throws InvalidVersionException if the range text could not be parsed */ public VersionRange parseRange(String text) {<FILL_FUNCTION_BODY>} private Version findLatestVersion(Integer major, Integer minor, Version.Qualifier qualifier) { List<Version> matches = this.latestVersions.stream().filter((it) -> { if (major != null && !major.equals(it.getMajor())) { return false; } if (minor != null && !minor.equals(it.getMinor())) { return false; } if (qualifier != null && !qualifier.equals(it.getQualifier())) { return false; } return true; }).toList(); return (matches.size() != 1) ? null : matches.get(0); } }
Assert.notNull(text, "Text must not be null"); Matcher matcher = RANGE_REGEX.matcher(text.trim()); if (!matcher.matches()) { // Try to read it as simple string Version version = parse(text); return new VersionRange(version, true, null, true); } boolean lowerInclusive = matcher.group(1).equals("["); Version lowerVersion = parse(matcher.group(2)); Version higherVersion = parse(matcher.group(3)); boolean higherInclusive = matcher.group(4).equals("]"); return new VersionRange(lowerVersion, lowerInclusive, higherVersion, higherInclusive);
1,188
181
1,369
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/version/VersionProperty.java
VersionProperty
toCamelCaseFormat
class VersionProperty implements Serializable, Comparable<VersionProperty> { private static final List<Character> SUPPORTED_CHARS = Arrays.asList('.', '-'); private final String property; private final boolean internal; private VersionProperty(String property, boolean internal) { this.property = validateFormat(property); this.internal = internal; } /** * Create a {@link VersionProperty}. * @param property the name of the property * @param internal whether the property is internal and can be tuned according to the * build system * @return a version property */ public static VersionProperty of(String property, boolean internal) { return new VersionProperty(property, internal); } /** * Create an internal {@link VersionProperty}. * @param property the name of the property * @return a version property whose format can be tuned according to the build system */ public static VersionProperty of(String property) { return of(property, true); } /** * Specify if the property is internally defined and can be tuned according to the * build system. * @return {@code true} if the property is defined within the scope of this project */ public boolean isInternal() { return this.internal; } /** * Return a camel cased representation of this instance. * @return the property in camel case format */ public String toCamelCaseFormat() {<FILL_FUNCTION_BODY>} public String toStandardFormat() { return this.property; } private static String validateFormat(String property) { for (char c : property.toCharArray()) { if (Character.isUpperCase(c)) { throw new IllegalArgumentException("Invalid property '" + property + "', must not contain upper case"); } if (!Character.isLetterOrDigit(c) && !SUPPORTED_CHARS.contains(c)) { throw new IllegalArgumentException("Unsupported character '" + c + "' for '" + property + "'"); } } return property; } @Override public int compareTo(VersionProperty o) { return this.property.compareTo(o.property); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } VersionProperty that = (VersionProperty) o; return this.internal == that.internal && this.property.equals(that.property); } @Override public int hashCode() { return Objects.hash(this.property, this.internal); } @Override public String toString() { return this.property; } }
String[] tokens = this.property.split("[-.]"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < tokens.length; i++) { String part = tokens[i]; if (i > 0) { part = StringUtils.capitalize(part); } sb.append(part); } return sb.toString();
687
101
788
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/version/VersionRange.java
VersionRange
toRangeString
class VersionRange { private final Version lowerVersion; private final boolean lowerInclusive; private final Version higherVersion; private final boolean higherInclusive; protected VersionRange(Version lowerVersion, boolean lowerInclusive, Version higherVersion, boolean higherInclusive) { this.lowerVersion = lowerVersion; this.lowerInclusive = lowerInclusive; this.higherVersion = higherVersion; this.higherInclusive = higherInclusive; } public VersionRange(Version startingVersion) { this(startingVersion, true, null, false); } /** * Specify if the {@link Version} matches this range. Returns {@code true} if the * version is contained within this range, {@code false} otherwise. * @param version the version to check * @return {@code true} if the version matches */ public boolean match(Version version) { Assert.notNull(version, "Version must not be null"); int lower = this.lowerVersion.compareTo(version); if (lower > 0) { return false; } else if (!this.lowerInclusive && lower == 0) { return false; } if (this.higherVersion != null) { int higher = this.higherVersion.compareTo(version); if (higher < 0) { return false; } else if (!this.higherInclusive && higher == 0) { return false; } } return true; } /** * Format this version range to the specified {@link Format}. * @param format the version format to use * @return a version range whose boundaries are compliant with the specified format. */ public VersionRange format(Format format) { Version lower = this.lowerVersion.format(format); Version higher = (this.higherVersion != null) ? this.higherVersion.format(format) : null; return new VersionRange(lower, this.lowerInclusive, higher, this.higherInclusive); } public Version getLowerVersion() { return this.lowerVersion; } public boolean isLowerInclusive() { return this.lowerInclusive; } public Version getHigherVersion() { return this.higherVersion; } public boolean isHigherInclusive() { return this.higherInclusive; } public String toRangeString() {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } VersionRange other = (VersionRange) obj; if (this.higherInclusive != other.higherInclusive) { return false; } if (this.higherVersion == null) { if (other.higherVersion != null) { return false; } } else if (!this.higherVersion.equals(other.higherVersion)) { return false; } if (this.lowerInclusive != other.lowerInclusive) { return false; } if (this.lowerVersion == null) { if (other.lowerVersion != null) { return false; } } else if (!this.lowerVersion.equals(other.lowerVersion)) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.higherInclusive ? 1231 : 1237); result = prime * result + ((this.higherVersion == null) ? 0 : this.higherVersion.hashCode()); result = prime * result + (this.lowerInclusive ? 1231 : 1237); result = prime * result + ((this.lowerVersion == null) ? 0 : this.lowerVersion.hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (this.lowerVersion != null) { sb.append(this.lowerInclusive ? ">=" : ">").append(this.lowerVersion); } if (this.higherVersion != null) { sb.append(" and ").append(this.higherInclusive ? "<=" : "<").append(this.higherVersion); } return sb.toString(); } }
StringBuilder sb = new StringBuilder(); if (this.lowerVersion == null && this.higherVersion == null) { return ""; } if (this.higherVersion != null) { sb.append(this.lowerInclusive ? "[" : "(") .append(this.lowerVersion) .append(",") .append(this.higherVersion) .append(this.higherInclusive ? "]" : ")"); } else { sb.append(this.lowerVersion); } return sb.toString();
1,164
147
1,311
<no_super_class>
spring-io_initializr
initializr/initializr-generator/src/main/java/io/spring/initializr/generator/version/VersionReference.java
VersionReference
equals
class VersionReference { private final VersionProperty property; private final String value; private VersionReference(VersionProperty property, String value) { this.property = property; this.value = value; } public static VersionReference ofProperty(VersionProperty property) { return new VersionReference(property, null); } public static VersionReference ofProperty(String internalProperty) { return ofProperty(VersionProperty.of(internalProperty)); } public static VersionReference ofValue(String value) { return new VersionReference(null, value); } /** * Specify if this reference defines a property. * @return {@code true} if this version is backed by a property */ public boolean isProperty() { return this.property != null; } /** * Return the {@link VersionProperty} or {@code null} if this reference is not a * property. * @return the version property or {@code null} */ public VersionProperty getProperty() { return this.property; } /** * Return the version of {@code null} if this reference is backed by a property. * @return the version or {@code null} */ public String getValue() { return this.value; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(this.property, this.value); } @Override public String toString() { return (this.property != null) ? "${" + this.property.toStandardFormat() + "}" : this.value; } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } VersionReference that = (VersionReference) o; return Objects.equals(this.property, that.property) && Objects.equals(this.value, that.value);
407
90
497
<no_super_class>
spring-io_initializr
initializr/initializr-metadata/src/main/java/io/spring/initializr/metadata/DependenciesCapability.java
DependenciesCapability
index
class DependenciesCapability extends ServiceCapability<List<DependencyGroup>> { final List<DependencyGroup> content = new ArrayList<>(); @JsonIgnore private final Map<String, Dependency> indexedDependencies = new LinkedHashMap<>(); public DependenciesCapability() { super("dependencies", ServiceCapabilityType.HIERARCHICAL_MULTI_SELECT, "Project dependencies", "dependency identifiers (comma-separated)"); } @Override public List<DependencyGroup> getContent() { return this.content; } /** * Return the {@link Dependency} with the specified id or {@code null} if no such * dependency exists. * @param id the ID of the dependency * @return the dependency or {@code null} */ public Dependency get(String id) { return this.indexedDependencies.get(id); } /** * Return all dependencies as a flat collection. * @return all dependencies */ public Collection<Dependency> getAll() { return Collections .unmodifiableCollection(this.indexedDependencies.values().stream().distinct().collect(Collectors.toList())); } public void validate() { index(); } public void updateCompatibilityRange(VersionParser versionParser) { this.indexedDependencies.values().forEach((it) -> it.updateCompatibilityRange(versionParser)); } @Override public void merge(List<DependencyGroup> otherContent) { otherContent.forEach((group) -> { if (this.content.stream() .noneMatch((it) -> group.getName() != null && group.getName().equals(it.getName()))) { this.content.add(group); } }); index(); } private void index() {<FILL_FUNCTION_BODY>} private void indexDependency(String id, Dependency dependency) { Dependency existing = this.indexedDependencies.get(id); if (existing != null) { throw new IllegalArgumentException("Could not register " + dependency + " another dependency " + "has also the '" + id + "' id " + existing); } this.indexedDependencies.put(id, dependency); } }
this.indexedDependencies.clear(); this.content.forEach((group) -> group.content.forEach((dependency) -> { // Apply defaults if (dependency.getCompatibilityRange() == null && group.getCompatibilityRange() != null) { dependency.setCompatibilityRange(group.getCompatibilityRange()); } if (dependency.getBom() == null && group.getBom() != null) { dependency.setBom(group.getBom()); } if (dependency.getRepository() == null && group.getRepository() != null) { dependency.setRepository(group.getRepository()); } dependency.resolve(); indexDependency(dependency.getId(), dependency); for (String alias : dependency.getAliases()) { indexDependency(alias, dependency); } }));
568
220
788
<methods>public abstract List<io.spring.initializr.metadata.DependencyGroup> getContent() ,public java.lang.String getDescription() ,public java.lang.String getId() ,public java.lang.String getTitle() ,public io.spring.initializr.metadata.ServiceCapabilityType getType() ,public abstract void merge(List<io.spring.initializr.metadata.DependencyGroup>) ,public void merge(ServiceCapability<List<io.spring.initializr.metadata.DependencyGroup>>) ,public void setDescription(java.lang.String) ,public void setTitle(java.lang.String) <variables>private java.lang.String description,private final non-sealed java.lang.String id,private java.lang.String title,private final non-sealed io.spring.initializr.metadata.ServiceCapabilityType type
spring-io_initializr
initializr/initializr-metadata/src/main/java/io/spring/initializr/metadata/InitializrConfiguration.java
Platform
updateCompatibilityRange
class Platform { /** * Compatibility range of supported platform versions. Requesting metadata or * project generation with a platform version that does not match this range is * not supported. */ private String compatibilityRange; @JsonIgnore private VersionRange range; /** * Compatibility range of platform versions using the first version format. */ private String v1FormatCompatibilityRange; @JsonIgnore private VersionRange v1FormatRange; /** * Compatibility range of platform versions using the second version format. */ private String v2FormatCompatibilityRange; @JsonIgnore private VersionRange v2FormatRange; public void updateCompatibilityRange(VersionParser versionParser) {<FILL_FUNCTION_BODY>} private void merge(Platform other) { this.compatibilityRange = other.compatibilityRange; this.range = other.range; this.v1FormatCompatibilityRange = other.v1FormatCompatibilityRange; this.v1FormatRange = other.v1FormatRange; this.v2FormatCompatibilityRange = other.v2FormatCompatibilityRange; this.v2FormatRange = other.v2FormatRange; } /** * Specify whether the specified {@linkplain Version platform version} is * supported. * @param platformVersion the platform version to check * @return {@code true} if this version is supported, {@code false} otherwise */ public boolean isCompatibleVersion(Version platformVersion) { return (this.range == null || this.range.match(platformVersion)); } public String determineCompatibilityRangeRequirement() { return this.range.toString(); } /** * Format the expected {@link Version platform version}. * @param platformVersion a platform version * @return a platform version in the suitable format */ public Version formatPlatformVersion(Version platformVersion) { Format format = getExpectedVersionFormat(platformVersion); return platformVersion.format(format); } private Format getExpectedVersionFormat(Version version) { if (this.v2FormatRange != null && this.v2FormatRange.match(version)) { return Format.V2; } if (this.v1FormatRange != null && this.v1FormatRange.match(version)) { return Format.V1; } return version.getFormat(); } public String getCompatibilityRange() { return this.compatibilityRange; } public void setCompatibilityRange(String compatibilityRange) { this.compatibilityRange = compatibilityRange; } public String getV1FormatCompatibilityRange() { return this.v1FormatCompatibilityRange; } public void setV1FormatCompatibilityRange(String v1FormatCompatibilityRange) { this.v1FormatCompatibilityRange = v1FormatCompatibilityRange; } public String getV2FormatCompatibilityRange() { return this.v2FormatCompatibilityRange; } public void setV2FormatCompatibilityRange(String v2FormatCompatibilityRange) { this.v2FormatCompatibilityRange = v2FormatCompatibilityRange; } }
this.range = (this.compatibilityRange != null) ? versionParser.parseRange(this.compatibilityRange) : null; this.v1FormatRange = (this.v1FormatCompatibilityRange != null) ? versionParser.parseRange(this.v1FormatCompatibilityRange) : null; this.v2FormatRange = (this.v2FormatCompatibilityRange != null) ? versionParser.parseRange(this.v2FormatCompatibilityRange) : null;
807
123
930
<no_super_class>
spring-io_initializr
initializr/initializr-metadata/src/main/java/io/spring/initializr/metadata/InitializrMetadataBuilder.java
InitializrMetadataBuilder
build
class InitializrMetadataBuilder { private final List<InitializrMetadataCustomizer> customizers = new ArrayList<>(); private final InitializrConfiguration configuration; private InitializrMetadataBuilder(InitializrConfiguration configuration) { this.configuration = configuration; } /** * Add a {@link InitializrProperties} to be merged with other content. Merges the * settings only and not the configuration. * @param properties the properties to use * @return this instance * @see #withInitializrProperties(InitializrProperties, boolean) */ public InitializrMetadataBuilder withInitializrProperties(InitializrProperties properties) { return withInitializrProperties(properties, false); } /** * Add a {@link InitializrProperties} to be merged with other content. * @param properties the settings to merge onto this instance * @param mergeConfiguration specify if service configuration should be merged as well * @return this instance */ public InitializrMetadataBuilder withInitializrProperties(InitializrProperties properties, boolean mergeConfiguration) { if (mergeConfiguration) { this.configuration.merge(properties); } return withCustomizer(new InitializerPropertiesCustomizer(properties)); } /** * Add a {@link InitializrMetadata} to be merged with other content. * @param resource a resource to a json document describing the metadata to include * @return this instance */ public InitializrMetadataBuilder withInitializrMetadata(Resource resource) { return withCustomizer(new ResourceInitializrMetadataCustomizer(resource)); } /** * Add a {@link InitializrMetadataCustomizer}. customizers are invoked in their order * of addition. * @param customizer the customizer to add * @return this instance * @see InitializrMetadataCustomizer */ public InitializrMetadataBuilder withCustomizer(InitializrMetadataCustomizer customizer) { this.customizers.add(customizer); return this; } /** * Build a {@link InitializrMetadata} based on the state of this builder. * @return a new {@link InitializrMetadata} instance */ public InitializrMetadata build() {<FILL_FUNCTION_BODY>} /** * Creates an empty instance based on the specified {@link InitializrConfiguration}. * @param configuration the configuration * @return a new {@link InitializrMetadata} instance */ protected InitializrMetadata createInstance(InitializrConfiguration configuration) { return new InitializrMetadata(configuration); } /** * Apply defaults to capabilities that have no value. * @param metadata the initializr metadata */ protected void applyDefaults(InitializrMetadata metadata) { if (!StringUtils.hasText(metadata.getName().getContent())) { metadata.getName().setContent("demo"); } if (!StringUtils.hasText(metadata.getDescription().getContent())) { metadata.getDescription().setContent("Demo project for Spring Boot"); } if (!StringUtils.hasText(metadata.getGroupId().getContent())) { metadata.getGroupId().setContent("com.example"); } if (!StringUtils.hasText(metadata.getVersion().getContent())) { metadata.getVersion().setContent("0.0.1-SNAPSHOT"); } } /** * Create a builder instance from the specified {@link InitializrProperties}. * Initialize the configuration to use. * @param configuration the configuration to use * @return a new {@link InitializrMetadataBuilder} instance * @see #withInitializrProperties(InitializrProperties) */ public static InitializrMetadataBuilder fromInitializrProperties(InitializrProperties configuration) { return new InitializrMetadataBuilder(configuration).withInitializrProperties(configuration); } /** * Create an empty builder instance with a default {@link InitializrConfiguration}. * @return a new {@link InitializrMetadataBuilder} instance */ public static InitializrMetadataBuilder create() { return new InitializrMetadataBuilder(new InitializrConfiguration()); } private static class InitializerPropertiesCustomizer implements InitializrMetadataCustomizer { private final InitializrProperties properties; InitializerPropertiesCustomizer(InitializrProperties properties) { this.properties = properties; } @Override public void customize(InitializrMetadata metadata) { metadata.getDependencies().merge(this.properties.getDependencies()); metadata.getTypes().merge(this.properties.getTypes()); metadata.getBootVersions().merge(this.properties.getBootVersions()); metadata.getPackagings().merge(this.properties.getPackagings()); metadata.getJavaVersions().merge(this.properties.getJavaVersions()); metadata.getLanguages().merge(this.properties.getLanguages()); this.properties.getGroupId().apply(metadata.getGroupId()); this.properties.getArtifactId().apply(metadata.getArtifactId()); this.properties.getVersion().apply(metadata.getVersion()); this.properties.getName().apply(metadata.getName()); this.properties.getDescription().apply(metadata.getDescription()); this.properties.getPackageName().apply(metadata.getPackageName()); } } private static class ResourceInitializrMetadataCustomizer implements InitializrMetadataCustomizer { private static final Log logger = LogFactory.getLog(ResourceInitializrMetadataCustomizer.class); private static final Charset UTF_8 = StandardCharsets.UTF_8; private final Resource resource; ResourceInitializrMetadataCustomizer(Resource resource) { this.resource = resource; } @Override public void customize(InitializrMetadata metadata) { logger.info("Loading initializr metadata from " + this.resource); try (InputStream in = this.resource.getInputStream()) { String content = StreamUtils.copyToString(in, UTF_8); ObjectMapper objectMapper = new ObjectMapper(); InitializrMetadata anotherMetadata = objectMapper.readValue(content, InitializrMetadata.class); metadata.merge(anotherMetadata); } catch (Exception ex) { throw new IllegalStateException("Cannot merge", ex); } } } }
InitializrConfiguration config = (this.configuration != null) ? this.configuration : new InitializrConfiguration(); InitializrMetadata metadata = createInstance(config); for (InitializrMetadataCustomizer customizer : this.customizers) { customizer.customize(metadata); } applyDefaults(metadata); metadata.validate(); return metadata;
1,580
102
1,682
<no_super_class>
spring-io_initializr
initializr/initializr-metadata/src/main/java/io/spring/initializr/metadata/InitializrProperties.java
SimpleElement
apply
class SimpleElement { /** * Element title. */ private String title; /** * Element description. */ private String description; /** * Element default value. */ private String value; private SimpleElement(String value) { this.value = value; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getValue() { return this.value; } public void setValue(String value) { this.value = value; } public void apply(TextCapability capability) {<FILL_FUNCTION_BODY>} }
if (StringUtils.hasText(this.title)) { capability.setTitle(this.title); } if (StringUtils.hasText(this.description)) { capability.setDescription(this.description); } if (StringUtils.hasText(this.value)) { capability.setContent(this.value); }
239
96
335
<methods>public non-sealed void <init>() ,public java.lang.String cleanPackageName(java.lang.String, java.lang.String) ,public java.lang.String generateApplicationName(java.lang.String) ,public io.spring.initializr.metadata.InitializrConfiguration.Env getEnv() ,public void merge(io.spring.initializr.metadata.InitializrConfiguration) ,public void validate() <variables>private final io.spring.initializr.metadata.InitializrConfiguration.Env env
spring-io_initializr
initializr/initializr-metadata/src/main/java/io/spring/initializr/metadata/Link.java
Link
resolve
class Link { private static final Pattern VARIABLE_REGEX = Pattern.compile("\\{(\\w+)\\}"); /** * The relation of the link. */ private String rel; /** * The URI the link is pointing to. */ private String href; /** * Specify if the URI is templated. */ @JsonInclude(JsonInclude.Include.NON_DEFAULT) private boolean templated; @JsonIgnore private final Set<String> templateVariables = new LinkedHashSet<>(); /** * A description of the link. */ @JsonInclude(JsonInclude.Include.NON_NULL) private String description; public Link() { } private Link(String rel, String href) { this(rel, href, null); } private Link(String rel, String href, String description) { this.rel = rel; this.href = href; this.description = description; } private Link(String rel, String href, boolean templated) { this(rel, href); this.templated = templated; } public String getRel() { return this.rel; } public void setRel(String rel) { this.rel = rel; } public boolean isTemplated() { return this.templated; } public void setTemplated(boolean templated) { this.templated = templated; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getHref() { return this.href; } public Set<String> getTemplateVariables() { return Collections.unmodifiableSet(this.templateVariables); } public void setHref(String href) { this.href = href; } public void resolve() {<FILL_FUNCTION_BODY>} /** * Expand the link using the specified parameters. * @param parameters the parameters value * @return an URI where all variables have been expanded */ public URI expand(Map<String, String> parameters) { AtomicReference<String> result = new AtomicReference<>(this.href); this.templateVariables.forEach((var) -> { Object value = parameters.get(var); if (value == null) { throw new IllegalArgumentException( "Could not expand " + this.href + ", missing value for '" + var + "'"); } result.set(result.get().replace("{" + var + "}", value.toString())); }); try { return new URI(result.get()); } catch (URISyntaxException ex) { throw new IllegalStateException("Invalid URL", ex); } } public static Link create(String rel, String href) { return new Link(rel, href); } public static Link create(String rel, String href, String description) { return new Link(rel, href, description); } public static Link create(String rel, String href, boolean templated) { return new Link(rel, href, templated); } }
if (this.rel == null) { throw new InvalidInitializrMetadataException("Invalid link " + this + ": rel attribute is mandatory"); } if (this.href == null) { throw new InvalidInitializrMetadataException("Invalid link " + this + ": href attribute is mandatory"); } Matcher matcher = VARIABLE_REGEX.matcher(this.href); while (matcher.find()) { String variable = matcher.group(1); this.templateVariables.add(variable); } this.templated = !this.templateVariables.isEmpty();
813
158
971
<no_super_class>
spring-io_initializr
initializr/initializr-metadata/src/main/java/io/spring/initializr/metadata/Repository.java
Repository
equals
class Repository { private String name; private URL url; private boolean releasesEnabled = true; private boolean snapshotsEnabled; public Repository() { } public Repository(String name, URL url) { this(name, url, true, false); } public Repository(String name, URL url, boolean releasesEnabled, boolean snapshotsEnabled) { this.name = name; this.url = url; this.releasesEnabled = releasesEnabled; this.snapshotsEnabled = snapshotsEnabled; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public URL getUrl() { return this.url; } public void setUrl(URL url) { this.url = url; } public boolean isReleasesEnabled() { return this.releasesEnabled; } public void setReleasesEnabled(boolean releasesEnabled) { this.releasesEnabled = releasesEnabled; } public boolean isSnapshotsEnabled() { return this.snapshotsEnabled; } public void setSnapshotsEnabled(boolean snapshotsEnabled) { this.snapshotsEnabled = snapshotsEnabled; } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); result = prime * result + (this.releasesEnabled ? 1231 : 1237); result = prime * result + (this.snapshotsEnabled ? 1231 : 1237); result = prime * result + ((this.url == null) ? 0 : this.url.hashCode()); return result; } @Override public String toString() { return new StringJoiner(", ", Repository.class.getSimpleName() + "[", "]").add("name='" + this.name + "'") .add("url=" + this.url) .add("releasesEnabled=" + this.releasesEnabled) .add("snapshotsEnabled=" + this.snapshotsEnabled) .toString(); } }
if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Repository other = (Repository) obj; if (this.name == null) { if (other.name != null) { return false; } } else if (!this.name.equals(other.name)) { return false; } if (this.releasesEnabled != other.releasesEnabled) { return false; } if (this.snapshotsEnabled != other.snapshotsEnabled) { return false; } if (this.url == null) { if (other.url != null) { return false; } } else if (!this.url.equals(other.url)) { return false; } return true;
584
244
828
<no_super_class>
spring-io_initializr
initializr/initializr-metadata/src/main/java/io/spring/initializr/metadata/ServiceCapability.java
ServiceCapability
merge
class ServiceCapability<T> implements Cloneable { private final String id; private final ServiceCapabilityType type; /** * A title of the capability, used as a header text or label. */ private String title; /** * A description of the capability, used in help usage or UI tooltips. */ private String description; protected ServiceCapability(String id, ServiceCapabilityType type, String title, String description) { this.id = id; this.type = type; this.title = title; this.description = description; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getId() { return this.id; } public ServiceCapabilityType getType() { return this.type; } /** * Return the "content" of this capability. The structure of the content vastly * depends on the {@link ServiceCapability type} of the capability. * @return the content */ public abstract T getContent(); /** * Merge the content of this instance with the specified content. * @param otherContent the content to merge * @see #merge(io.spring.initializr.metadata.ServiceCapability) */ public abstract void merge(T otherContent); /** * Merge this capability with the specified argument. The service capabilities should * match (i.e have the same {@code id} and {@code type}). Sub-classes may merge * additional content. * @param other the content to merge */ public void merge(ServiceCapability<T> other) {<FILL_FUNCTION_BODY>} }
Assert.notNull(other, "Other must not be null"); Assert.isTrue(this.id.equals(other.id), "Ids must be equals"); Assert.isTrue(this.type.equals(other.type), "Types must be equals"); if (StringUtils.hasText(other.title)) { this.title = other.title; } if (StringUtils.hasText(other.description)) { this.description = other.description; } merge(other.getContent());
471
134
605
<no_super_class>
spring-io_initializr
initializr/initializr-metadata/src/main/java/io/spring/initializr/metadata/SingleSelectCapability.java
SingleSelectCapability
merge
class SingleSelectCapability extends ServiceCapability<List<DefaultMetadataElement>> implements Defaultable<DefaultMetadataElement> { private final List<DefaultMetadataElement> content = new ArrayList<>(); private final ReadWriteLock contentLock = new ReentrantReadWriteLock(); @JsonCreator SingleSelectCapability(@JsonProperty("id") String id) { this(id, null, null); } public SingleSelectCapability(String id, String title, String description) { super(id, ServiceCapabilityType.SINGLE_SELECT, title, description); } @Override public List<DefaultMetadataElement> getContent() { return Collections.unmodifiableList(withReadableContent(ArrayList::new)); } public void addContent(DefaultMetadataElement element) { withWritableContent((content) -> content.add(element)); } public void setContent(List<DefaultMetadataElement> newContent) { withWritableContent((content) -> { content.clear(); content.addAll(newContent); }); } /** * Return the default element of this capability. */ @Override public DefaultMetadataElement getDefault() { return withReadableContent( (content) -> content.stream().filter(DefaultMetadataElement::isDefault).findFirst().orElse(null)); } /** * Return the element with the specified id or {@code null} if no such element exists. * @param id the ID of the element to find * @return the element or {@code null} */ public DefaultMetadataElement get(String id) { return withReadableContent( (content) -> content.stream().filter((it) -> id.equals(it.getId())).findFirst().orElse(null)); } @Override public void merge(List<DefaultMetadataElement> otherContent) {<FILL_FUNCTION_BODY>} private <T> T withReadableContent(Function<List<DefaultMetadataElement>, T> consumer) { this.contentLock.readLock().lock(); try { return consumer.apply(this.content); } finally { this.contentLock.readLock().unlock(); } } private void withWritableContent(Consumer<List<DefaultMetadataElement>> consumer) { this.contentLock.writeLock().lock(); try { consumer.accept(this.content); } finally { this.contentLock.writeLock().unlock(); } } }
withWritableContent((content) -> otherContent.forEach((it) -> { if (get(it.getId()) == null) { this.content.add(it); } }));
632
58
690
<methods>public abstract List<io.spring.initializr.metadata.DefaultMetadataElement> getContent() ,public java.lang.String getDescription() ,public java.lang.String getId() ,public java.lang.String getTitle() ,public io.spring.initializr.metadata.ServiceCapabilityType getType() ,public abstract void merge(List<io.spring.initializr.metadata.DefaultMetadataElement>) ,public void merge(ServiceCapability<List<io.spring.initializr.metadata.DefaultMetadataElement>>) ,public void setDescription(java.lang.String) ,public void setTitle(java.lang.String) <variables>private java.lang.String description,private final non-sealed java.lang.String id,private java.lang.String title,private final non-sealed io.spring.initializr.metadata.ServiceCapabilityType type
spring-io_initializr
initializr/initializr-metadata/src/main/java/io/spring/initializr/metadata/TextCapability.java
TextCapability
merge
class TextCapability extends ServiceCapability<String> { private String content; @JsonCreator TextCapability(@JsonProperty("id") String id) { this(id, null, null); } TextCapability(String id, String title, String description) { super(id, ServiceCapabilityType.TEXT, title, description); } @Override public String getContent() { return this.content; } public void setContent(String content) { this.content = content; } @Override public void merge(String otherContent) {<FILL_FUNCTION_BODY>} }
if (otherContent != null) { this.content = otherContent; }
159
26
185
<methods>public abstract java.lang.String getContent() ,public java.lang.String getDescription() ,public java.lang.String getId() ,public java.lang.String getTitle() ,public io.spring.initializr.metadata.ServiceCapabilityType getType() ,public abstract void merge(java.lang.String) ,public void merge(ServiceCapability<java.lang.String>) ,public void setDescription(java.lang.String) ,public void setTitle(java.lang.String) <variables>private java.lang.String description,private final non-sealed java.lang.String id,private java.lang.String title,private final non-sealed io.spring.initializr.metadata.ServiceCapabilityType type
spring-io_initializr
initializr/initializr-metadata/src/main/java/io/spring/initializr/metadata/Type.java
Type
setAction
class Type extends DefaultMetadataElement implements Describable { private String description; private String action; private final Map<String, String> tags = new LinkedHashMap<>(); public void setAction(String action) {<FILL_FUNCTION_BODY>} @Override public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getAction() { return this.action; } public Map<String, String> getTags() { return this.tags; } }
String actionToUse = action; if (!actionToUse.startsWith("/")) { actionToUse = "/" + actionToUse; } this.action = actionToUse;
148
53
201
<methods>public void <init>() ,public void <init>(java.lang.String, java.lang.String, boolean) ,public void <init>(java.lang.String, boolean) ,public static io.spring.initializr.metadata.DefaultMetadataElement create(java.lang.String, boolean) ,public static io.spring.initializr.metadata.DefaultMetadataElement create(java.lang.String, java.lang.String, boolean) ,public boolean isDefault() ,public void setDefault(boolean) <variables>private boolean defaultValue
spring-io_initializr
initializr/initializr-metadata/src/main/java/io/spring/initializr/metadata/TypeCapability.java
TypeCapability
merge
class TypeCapability extends ServiceCapability<List<Type>> implements Defaultable<Type> { private final List<Type> content = new ArrayList<>(); public TypeCapability() { super("type", ServiceCapabilityType.ACTION, "Type", "project type"); } @Override public List<Type> getContent() { return this.content; } /** * Return the {@link Type} with the specified id or {@code null} if no such type * exists. * @param id the ID to find * @return the Type or {@code null} */ public Type get(String id) { return this.content.stream().filter((it) -> id.equals(it.getId())).findFirst().orElse(null); } /** * Return the default {@link Type}. */ @Override public Type getDefault() { return this.content.stream().filter(DefaultMetadataElement::isDefault).findFirst().orElse(null); } @Override public void merge(List<Type> otherContent) {<FILL_FUNCTION_BODY>} }
otherContent.forEach((it) -> { if (get(it.getId()) == null) { this.content.add(it); } });
276
46
322
<methods>public abstract List<io.spring.initializr.metadata.Type> getContent() ,public java.lang.String getDescription() ,public java.lang.String getId() ,public java.lang.String getTitle() ,public io.spring.initializr.metadata.ServiceCapabilityType getType() ,public abstract void merge(List<io.spring.initializr.metadata.Type>) ,public void merge(ServiceCapability<List<io.spring.initializr.metadata.Type>>) ,public void setDescription(java.lang.String) ,public void setTitle(java.lang.String) <variables>private java.lang.String description,private final non-sealed java.lang.String id,private java.lang.String title,private final non-sealed io.spring.initializr.metadata.ServiceCapabilityType type
spring-io_initializr
initializr/initializr-metadata/src/main/java/io/spring/initializr/metadata/support/MetadataBuildItemMapper.java
MetadataBuildItemMapper
toBom
class MetadataBuildItemMapper { private MetadataBuildItemMapper() { } /** * Return an {@link Build} dependency from a {@link Dependency dependency metadata}. * @param dependency a dependency metadata * @return an equivalent build dependency */ public static io.spring.initializr.generator.buildsystem.Dependency toDependency(Dependency dependency) { if (dependency == null) { return null; } VersionReference versionReference = (dependency.getVersion() != null) ? VersionReference.ofValue(dependency.getVersion()) : null; return io.spring.initializr.generator.buildsystem.Dependency .withCoordinates(dependency.getGroupId(), dependency.getArtifactId()) .version(versionReference) .scope(toDependencyScope(dependency.getScope())) .classifier(dependency.getClassifier()) .type(dependency.getType()) .build(); } private static DependencyScope toDependencyScope(String scope) { return switch (scope) { case Dependency.SCOPE_ANNOTATION_PROCESSOR -> DependencyScope.ANNOTATION_PROCESSOR; case Dependency.SCOPE_COMPILE -> DependencyScope.COMPILE; case Dependency.SCOPE_RUNTIME -> DependencyScope.RUNTIME; case Dependency.SCOPE_COMPILE_ONLY -> DependencyScope.COMPILE_ONLY; case Dependency.SCOPE_PROVIDED -> DependencyScope.PROVIDED_RUNTIME; case Dependency.SCOPE_TEST -> DependencyScope.TEST_COMPILE; default -> null; }; } /** * Return a {@link Build} bom from a {@link BillOfMaterials bom metadata}. * @param bom a metadata bom * @return an equivalent build bom */ public static io.spring.initializr.generator.buildsystem.BillOfMaterials toBom(BillOfMaterials bom) {<FILL_FUNCTION_BODY>} /** * Return a {@link Build} repository from a {@link Repository repository metadata}. * @param id the repository id * @param repository a repository metadata * @return an equivalent build repository */ public static io.spring.initializr.generator.buildsystem.MavenRepository toRepository(String id, Repository repository) { if (repository == null) { return null; } return io.spring.initializr.generator.buildsystem.MavenRepository .withIdAndUrl(id, repository.getUrl().toExternalForm()) .name(repository.getName()) .releasesEnabled(repository.isReleasesEnabled()) .snapshotsEnabled(repository.isSnapshotsEnabled()) .build(); } }
if (bom == null) { return null; } VersionReference version = (bom.getVersionProperty() != null) ? VersionReference.ofProperty(bom.getVersionProperty()) : VersionReference.ofValue(bom.getVersion()); return io.spring.initializr.generator.buildsystem.BillOfMaterials .withCoordinates(bom.getGroupId(), bom.getArtifactId()) .version(version) .order(bom.getOrder()) .build();
711
135
846
<no_super_class>
spring-io_initializr
initializr/initializr-metadata/src/main/java/io/spring/initializr/metadata/support/MetadataBuildItemResolver.java
MetadataBuildItemResolver
resolveDependency
class MetadataBuildItemResolver implements BuildItemResolver { private final InitializrMetadata metadata; private final Version platformVersion; /** * Creates an instance for the specified {@link InitializrMetadata} and {@link Version * platform version}. * @param metadata the metadata to use * @param platformVersion the platform version to consider */ public MetadataBuildItemResolver(InitializrMetadata metadata, Version platformVersion) { this.metadata = metadata; this.platformVersion = platformVersion; } @Override public Dependency resolveDependency(String id) {<FILL_FUNCTION_BODY>} @Override public BillOfMaterials resolveBom(String id) { io.spring.initializr.metadata.BillOfMaterials bom = this.metadata.getConfiguration().getEnv().getBoms().get(id); if (bom != null) { return MetadataBuildItemMapper.toBom(bom.resolve(this.platformVersion)); } return null; } @Override public MavenRepository resolveRepository(String id) { if (id.equals(MavenRepository.MAVEN_CENTRAL.getId())) { return MavenRepository.MAVEN_CENTRAL; } return MetadataBuildItemMapper.toRepository(id, this.metadata.getConfiguration().getEnv().getRepositories().get(id)); } }
io.spring.initializr.metadata.Dependency dependency = this.metadata.getDependencies().get(id); if (dependency != null) { return MetadataBuildItemMapper.toDependency(dependency.resolve(this.platformVersion)); } return null;
352
70
422
<no_super_class>
spring-io_initializr
initializr/initializr-version-resolver/src/main/java/io/spring/initializr/versionresolver/DefaultMavenVersionResolver.java
DefaultMavenVersionResolver
resolveBom
class DefaultMavenVersionResolver implements MavenVersionResolver { private static final Log logger = LogFactory.getLog(DefaultMavenVersionResolver.class); private static final RemoteRepository mavenCentral = new RemoteRepository.Builder("central", "default", "https://repo1.maven.org/maven2") .build(); private static final RemoteRepository springMilestones = new RemoteRepository.Builder("spring-milestones", "default", "https://repo.spring.io/milestone") .build(); private static final RemoteRepository springSnapshots = new RemoteRepository.Builder("spring-snapshots", "default", "https://repo.spring.io/snapshot") .build(); private static final List<RemoteRepository> repositories = Arrays.asList(mavenCentral, springMilestones, springSnapshots); private final Object monitor = new Object(); private final RepositorySystemSession repositorySystemSession; private final RemoteRepositoryManager remoteRepositoryManager; private final RepositorySystem repositorySystem; DefaultMavenVersionResolver(Path cacheLocation) { ServiceLocator serviceLocator = createServiceLocator(); DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); session.setArtifactDescriptorPolicy(new SimpleArtifactDescriptorPolicy(false, false)); LocalRepository localRepository = new LocalRepository(cacheLocation.toFile()); this.repositorySystem = serviceLocator.getService(RepositorySystem.class); session.setLocalRepositoryManager(this.repositorySystem.newLocalRepositoryManager(session, localRepository)); session.setUserProperties(System.getProperties()); session.setReadOnly(); this.repositorySystemSession = session; this.remoteRepositoryManager = serviceLocator.getService(RemoteRepositoryManager.class); } @Override public Map<String, String> resolveDependencies(String groupId, String artifactId, String version) { ArtifactDescriptorResult bom = resolveBom(groupId, artifactId, version); Map<String, String> managedVersions = new HashMap<>(); bom.getManagedDependencies() .stream() .map(Dependency::getArtifact) .forEach((artifact) -> managedVersions.putIfAbsent(artifact.getGroupId() + ":" + artifact.getArtifactId(), artifact.getVersion())); return managedVersions; } @Override public Map<String, String> resolvePlugins(String groupId, String artifactId, String version) { Model model = buildEffectiveModel(groupId, artifactId, version); Map<String, String> managedPluginVersions = new HashMap<>(); model.getBuild() .getPluginManagement() .getPlugins() .forEach((plugin) -> managedPluginVersions.putIfAbsent(plugin.getGroupId() + ":" + plugin.getArtifactId(), plugin.getVersion())); return managedPluginVersions; } private ArtifactDescriptorResult resolveBom(String groupId, String artifactId, String version) {<FILL_FUNCTION_BODY>} private Model buildEffectiveModel(String groupId, String artifactId, String version) { try { ArtifactResult bom = resolvePom(groupId, artifactId, version); RequestTrace requestTrace = new RequestTrace(null); ModelResolver modelResolver = new ProjectModelResolver(this.repositorySystemSession, requestTrace, this.repositorySystem, this.remoteRepositoryManager, repositories, ProjectBuildingRequest.RepositoryMerging.POM_DOMINANT, null); DefaultModelBuildingRequest modelBuildingRequest = new DefaultModelBuildingRequest(); modelBuildingRequest.setSystemProperties(System.getProperties()); modelBuildingRequest.setPomFile(bom.getArtifact().getFile()); modelBuildingRequest.setModelResolver(modelResolver); DefaultModelBuilder modelBuilder = new DefaultModelBuilderFactory().newInstance(); return modelBuilder.build(modelBuildingRequest).getEffectiveModel(); } catch (ModelBuildingException ex) { Model model = ex.getModel(); if (model != null) { logger.warn("Model for '" + groupId + ":" + artifactId + ":" + version + "' is incomplete: " + ex.getProblems()); return model; } throw new IllegalStateException( "Model for '" + groupId + ":" + artifactId + ":" + version + "' could not be built", ex); } } private ArtifactResult resolvePom(String groupId, String artifactId, String version) { synchronized (this.monitor) { try { return this.repositorySystem.resolveArtifact(this.repositorySystemSession, new ArtifactRequest( new DefaultArtifact(groupId, artifactId, "pom", version), repositories, null)); } catch (ArtifactResolutionException ex) { throw new IllegalStateException( "Pom '" + groupId + ":" + artifactId + ":" + version + "' could not be resolved", ex); } } } private static ServiceLocator createServiceLocator() { DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator(); locator.addService(RepositorySystem.class, DefaultRepositorySystem.class); locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class); locator.addService(TransporterFactory.class, HttpTransporterFactory.class); return locator; } }
synchronized (this.monitor) { try { return this.repositorySystem.readArtifactDescriptor(this.repositorySystemSession, new ArtifactDescriptorRequest(new DefaultArtifact(groupId, artifactId, "pom", version), repositories, null)); } catch (ArtifactDescriptorException ex) { throw new IllegalStateException( "Bom '" + groupId + ":" + artifactId + ":" + version + "' could not be resolved", ex); } }
1,364
131
1,495
<no_super_class>
spring-io_initializr
initializr/initializr-web/src/main/java/io/spring/initializr/web/autoconfigure/InitializrAutoConfiguration.java
InitializrWebConfiguration
projectGenerationController
class InitializrWebConfiguration { @Bean InitializrWebConfig initializrWebConfig() { return new InitializrWebConfig(); } @Bean @ConditionalOnMissingBean ProjectGenerationController<ProjectRequest> projectGenerationController( InitializrMetadataProvider metadataProvider, ObjectProvider<ProjectRequestPlatformVersionTransformer> platformVersionTransformer, ApplicationContext applicationContext) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnMissingBean ProjectMetadataController projectMetadataController(InitializrMetadataProvider metadataProvider, DependencyMetadataProvider dependencyMetadataProvider) { return new ProjectMetadataController(metadataProvider, dependencyMetadataProvider); } @Bean @ConditionalOnMissingBean CommandLineMetadataController commandLineMetadataController(InitializrMetadataProvider metadataProvider, TemplateRenderer templateRenderer) { return new CommandLineMetadataController(metadataProvider, templateRenderer); } @Bean @ConditionalOnMissingBean SpringCliDistributionController cliDistributionController(InitializrMetadataProvider metadataProvider) { return new SpringCliDistributionController(metadataProvider); } @Bean InitializrModule InitializrJacksonModule() { return new InitializrModule(); } }
ProjectGenerationInvoker<ProjectRequest> projectGenerationInvoker = new ProjectGenerationInvoker<>( applicationContext, new DefaultProjectRequestToDescriptionConverter(platformVersionTransformer .getIfAvailable(DefaultProjectRequestPlatformVersionTransformer::new))); return new DefaultProjectGenerationController(metadataProvider, projectGenerationInvoker);
330
83
413
<no_super_class>
spring-io_initializr
initializr/initializr-web/src/main/java/io/spring/initializr/web/autoconfigure/InitializrWebConfig.java
CommandLineContentNegotiationStrategy
resolveMediaTypes
class CommandLineContentNegotiationStrategy implements ContentNegotiationStrategy { private final UrlPathHelper urlPathHelper = new UrlPathHelper(); @Override public List<MediaType> resolveMediaTypes(NativeWebRequest request) {<FILL_FUNCTION_BODY>} }
String path = this.urlPathHelper .getPathWithinApplication(request.getNativeRequest(HttpServletRequest.class)); if (!StringUtils.hasText(path) || !path.equals("/")) { // Only care about "/" return MEDIA_TYPE_ALL_LIST; } String userAgent = request.getHeader(HttpHeaders.USER_AGENT); if (userAgent != null) { Agent agent = Agent.fromUserAgent(userAgent); if (agent != null) { if (AgentId.CURL.equals(agent.getId()) || AgentId.HTTPIE.equals(agent.getId())) { return Collections.singletonList(MediaType.TEXT_PLAIN); } } } return Collections.singletonList(MediaType.APPLICATION_JSON);
73
210
283
<no_super_class>
spring-io_initializr
initializr/initializr-web/src/main/java/io/spring/initializr/web/controller/AbstractMetadataController.java
AbstractMetadataController
generateAppUrl
class AbstractMetadataController { protected final InitializrMetadataProvider metadataProvider; private Boolean forceSsl; protected AbstractMetadataController(InitializrMetadataProvider metadataProvider) { this.metadataProvider = metadataProvider; } /** * Generate a full URL of the service, mostly for use in templates. * @return the app URL * @see io.spring.initializr.metadata.InitializrConfiguration.Env#isForceSsl() */ protected String generateAppUrl() {<FILL_FUNCTION_BODY>} protected String createUniqueId(String content) { StringBuilder builder = new StringBuilder(); DigestUtils.appendMd5DigestAsHex(content.getBytes(StandardCharsets.UTF_8), builder); return builder.toString(); } private boolean isForceSsl() { if (this.forceSsl == null) { this.forceSsl = this.metadataProvider.get().getConfiguration().getEnv().isForceSsl(); } return this.forceSsl; } }
ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentServletMapping(); if (isForceSsl()) { builder.scheme("https"); } return builder.build().toString();
268
56
324
<no_super_class>
spring-io_initializr
initializr/initializr-web/src/main/java/io/spring/initializr/web/controller/CommandLineMetadataController.java
CommandLineMetadataController
serviceCapabilitiesText
class CommandLineMetadataController extends AbstractMetadataController { private final CommandLineHelpGenerator commandLineHelpGenerator; public CommandLineMetadataController(InitializrMetadataProvider metadataProvider, TemplateRenderer templateRenderer) { super(metadataProvider); this.commandLineHelpGenerator = new CommandLineHelpGenerator(templateRenderer); } @GetMapping(path = "/", produces = "text/plain") public ResponseEntity<String> serviceCapabilitiesText( @RequestHeader(value = HttpHeaders.USER_AGENT, required = false) String userAgent) throws IOException {<FILL_FUNCTION_BODY>} }
String appUrl = generateAppUrl(); InitializrMetadata metadata = this.metadataProvider.get(); BodyBuilder builder = ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN); if (userAgent != null) { Agent agent = Agent.fromUserAgent(userAgent); if (agent != null) { if (AgentId.CURL.equals(agent.getId())) { String content = this.commandLineHelpGenerator.generateCurlCapabilities(metadata, appUrl); return builder.eTag(createUniqueId(content)).body(content); } if (AgentId.HTTPIE.equals(agent.getId())) { String content = this.commandLineHelpGenerator.generateHttpieCapabilities(metadata, appUrl); return builder.eTag(createUniqueId(content)).body(content); } if (AgentId.SPRING_BOOT_CLI.equals(agent.getId())) { String content = this.commandLineHelpGenerator.generateSpringBootCliCapabilities(metadata, appUrl); return builder.eTag(createUniqueId(content)).body(content); } } } String content = this.commandLineHelpGenerator.generateGenericCapabilities(metadata, appUrl); return builder.eTag(createUniqueId(content)).body(content);
148
335
483
<methods><variables>private java.lang.Boolean forceSsl,protected final non-sealed io.spring.initializr.metadata.InitializrMetadataProvider metadataProvider
spring-io_initializr
initializr/initializr-web/src/main/java/io/spring/initializr/web/controller/DefaultProjectGenerationController.java
DefaultProjectGenerationController
projectRequest
class DefaultProjectGenerationController extends ProjectGenerationController<ProjectRequest> { public DefaultProjectGenerationController(InitializrMetadataProvider metadataProvider, ProjectGenerationInvoker<ProjectRequest> projectGenerationInvoker) { super(metadataProvider, projectGenerationInvoker); } @Override public ProjectRequest projectRequest(Map<String, String> headers) {<FILL_FUNCTION_BODY>} }
WebProjectRequest request = new WebProjectRequest(); request.getParameters().putAll(headers); request.initialize(getMetadata()); return request;
104
45
149
<methods>public void <init>(io.spring.initializr.metadata.InitializrMetadataProvider, ProjectGenerationInvoker<io.spring.initializr.web.project.ProjectRequest>) ,public ResponseEntity<byte[]> gradle(io.spring.initializr.web.project.ProjectRequest) ,public void invalidProjectRequest(HttpServletResponse, io.spring.initializr.web.project.InvalidProjectRequestException) throws java.io.IOException,public ResponseEntity<byte[]> pom(io.spring.initializr.web.project.ProjectRequest) ,public abstract io.spring.initializr.web.project.ProjectRequest projectRequest(Map<java.lang.String,java.lang.String>) ,public ResponseEntity<byte[]> springTgz(io.spring.initializr.web.project.ProjectRequest) throws java.io.IOException,public ResponseEntity<byte[]> springZip(io.spring.initializr.web.project.ProjectRequest) throws java.io.IOException<variables>private static final org.apache.commons.logging.Log logger,private final non-sealed io.spring.initializr.metadata.InitializrMetadataProvider metadataProvider,private final non-sealed ProjectGenerationInvoker<io.spring.initializr.web.project.ProjectRequest> projectGenerationInvoker
spring-io_initializr
initializr/initializr-web/src/main/java/io/spring/initializr/web/controller/ProjectGenerationController.java
ProjectGenerationController
upload
class ProjectGenerationController<R extends ProjectRequest> { private static final Log logger = LogFactory.getLog(ProjectGenerationController.class); private final InitializrMetadataProvider metadataProvider; private final ProjectGenerationInvoker<R> projectGenerationInvoker; public ProjectGenerationController(InitializrMetadataProvider metadataProvider, ProjectGenerationInvoker<R> projectGenerationInvoker) { this.metadataProvider = metadataProvider; this.projectGenerationInvoker = projectGenerationInvoker; } @ModelAttribute R projectRequest(@RequestHeader Map<String, String> headers, @RequestParam(name = "style", required = false) String style) { if (style != null) { throw new InvalidProjectRequestException("Dependencies must be specified using 'dependencies'"); } return projectRequest(headers); } /** * Create an initialized {@link ProjectRequest} instance to use to bind the parameters * of a project generation request. * @param headers the headers of the request * @return a new {@link ProjectRequest} instance */ public abstract R projectRequest(@RequestHeader Map<String, String> headers); protected InitializrMetadata getMetadata() { return this.metadataProvider.get(); } @ExceptionHandler public void invalidProjectRequest(HttpServletResponse response, InvalidProjectRequestException ex) throws IOException { response.sendError(HttpStatus.BAD_REQUEST.value(), ex.getMessage()); } @RequestMapping(path = { "/pom", "/pom.xml" }, method = { RequestMethod.GET, RequestMethod.POST }) public ResponseEntity<byte[]> pom(R request) { request.setType("maven-build"); byte[] mavenPom = this.projectGenerationInvoker.invokeBuildGeneration(request); return createResponseEntity(mavenPom, "application/octet-stream", "pom.xml"); } @RequestMapping(path = { "/build", "/build.gradle" }, method = { RequestMethod.GET, RequestMethod.POST }) public ResponseEntity<byte[]> gradle(R request) { request.setType("gradle-build"); byte[] gradleBuild = this.projectGenerationInvoker.invokeBuildGeneration(request); return createResponseEntity(gradleBuild, "application/octet-stream", "build.gradle"); } @RequestMapping(path = "/starter.zip", method = { RequestMethod.GET, RequestMethod.POST }) public ResponseEntity<byte[]> springZip(R request) throws IOException { ProjectGenerationResult result = this.projectGenerationInvoker.invokeProjectStructureGeneration(request); Path archive = createArchive(result, "zip", ZipArchiveOutputStream::new, ZipArchiveEntry::new, ZipArchiveEntry::setUnixMode); return upload(archive, result.getRootDirectory(), generateFileName(result.getProjectDescription().getArtifactId(), "zip"), "application/zip"); } @RequestMapping(path = "/starter.tgz", method = { RequestMethod.GET, RequestMethod.POST }, produces = "application/x-compress") public ResponseEntity<byte[]> springTgz(R request) throws IOException { ProjectGenerationResult result = this.projectGenerationInvoker.invokeProjectStructureGeneration(request); Path archive = createArchive(result, "tar.gz", this::createTarArchiveOutputStream, TarArchiveEntry::new, TarArchiveEntry::setMode); return upload(archive, result.getRootDirectory(), generateFileName(result.getProjectDescription().getArtifactId(), "tar.gz"), "application/x-compress"); } private TarArchiveOutputStream createTarArchiveOutputStream(OutputStream output) { try { TarArchiveOutputStream out = new TarArchiveOutputStream(new GzipCompressorOutputStream(output)); out.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX); return out; } catch (IOException ex) { throw new IllegalStateException(ex); } } private <T extends ArchiveEntry> Path createArchive(ProjectGenerationResult result, String fileExtension, Function<OutputStream, ? extends ArchiveOutputStream> archiveOutputStream, BiFunction<File, String, T> archiveEntry, BiConsumer<T, Integer> setMode) throws IOException { Path archive = this.projectGenerationInvoker.createDistributionFile(result.getRootDirectory(), "." + fileExtension); String wrapperScript = getWrapperScript(result.getProjectDescription()); try (ArchiveOutputStream output = archiveOutputStream.apply(Files.newOutputStream(archive))) { Files.walk(result.getRootDirectory()) .filter((path) -> !result.getRootDirectory().equals(path)) .forEach((path) -> { try { String entryName = getEntryName(result.getRootDirectory(), path); T entry = archiveEntry.apply(path.toFile(), entryName); setMode.accept(entry, getUnixMode(wrapperScript, entryName, path)); output.putArchiveEntry(entry); if (!Files.isDirectory(path)) { Files.copy(path, output); } output.closeArchiveEntry(); } catch (IOException ex) { throw new IllegalStateException(ex); } }); } return archive; } private String getEntryName(Path root, Path path) { String entryName = root.relativize(path).toString().replace('\\', '/'); if (Files.isDirectory(path)) { entryName += "/"; } return entryName; } private int getUnixMode(String wrapperScript, String entryName, Path path) { if (Files.isDirectory(path)) { return UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM; } return UnixStat.FILE_FLAG | (entryName.equals(wrapperScript) ? 0755 : UnixStat.DEFAULT_FILE_PERM); } private String generateFileName(String artifactId, String extension) { String candidate = (StringUtils.hasText(artifactId) ? artifactId : this.metadataProvider.get().getArtifactId().getContent()); try { return URLEncoder.encode(candidate, "UTF-8") + "." + extension; } catch (UnsupportedEncodingException ex) { throw new IllegalStateException("Cannot encode URL", ex); } } private static String getWrapperScript(ProjectDescription description) { BuildSystem buildSystem = description.getBuildSystem(); String script = buildSystem.id().equals(MavenBuildSystem.ID) ? "mvnw" : "gradlew"; return (description.getBaseDirectory() != null) ? description.getBaseDirectory() + "/" + script : script; } private ResponseEntity<byte[]> upload(Path archive, Path dir, String fileName, String contentType) throws IOException {<FILL_FUNCTION_BODY>} private ResponseEntity<byte[]> createResponseEntity(byte[] content, String contentType, String fileName) { String contentDispositionValue = "attachment; filename=\"" + fileName + "\""; return ResponseEntity.ok() .header("Content-Type", contentType) .header("Content-Disposition", contentDispositionValue) .body(content); } }
byte[] bytes = Files.readAllBytes(archive); logger.info(String.format("Uploading: %s (%s bytes)", archive, bytes.length)); ResponseEntity<byte[]> result = createResponseEntity(bytes, contentType, fileName); this.projectGenerationInvoker.cleanTempFiles(dir); return result;
1,864
89
1,953
<no_super_class>
spring-io_initializr
initializr/initializr-web/src/main/java/io/spring/initializr/web/controller/ProjectMetadataController.java
ProjectMetadataController
getJsonMapper
class ProjectMetadataController extends AbstractMetadataController { /** * HAL JSON content type. */ public static final MediaType HAL_JSON_CONTENT_TYPE = MediaType.parseMediaType("application/hal+json"); private final DependencyMetadataProvider dependencyMetadataProvider; public ProjectMetadataController(InitializrMetadataProvider metadataProvider, DependencyMetadataProvider dependencyMetadataProvider) { super(metadataProvider); this.dependencyMetadataProvider = dependencyMetadataProvider; } @GetMapping(path = "/metadata/config", produces = "application/json") public InitializrMetadata config() { return this.metadataProvider.get(); } @GetMapping(path = { "/", "/metadata/client" }, produces = "application/hal+json") public ResponseEntity<String> serviceCapabilitiesHal() { return serviceCapabilitiesFor(InitializrMetadataVersion.V2_1, HAL_JSON_CONTENT_TYPE); } @GetMapping(path = { "/", "/metadata/client" }, produces = { "application/vnd.initializr.v2.2+json" }) public ResponseEntity<String> serviceCapabilitiesV22() { return serviceCapabilitiesFor(InitializrMetadataVersion.V2_2); } @GetMapping(path = { "/", "/metadata/client" }, produces = { "application/vnd.initializr.v2.1+json", "application/json" }) public ResponseEntity<String> serviceCapabilitiesV21() { return serviceCapabilitiesFor(InitializrMetadataVersion.V2_1); } @GetMapping(path = { "/", "/metadata/client" }, produces = "application/vnd.initializr.v2+json") public ResponseEntity<String> serviceCapabilitiesV2() { return serviceCapabilitiesFor(InitializrMetadataVersion.V2); } @GetMapping(path = "/dependencies", produces = "application/vnd.initializr.v2.2+json") public ResponseEntity<String> dependenciesV22(@RequestParam(required = false) String bootVersion) { return dependenciesFor(InitializrMetadataVersion.V2_2, bootVersion); } @GetMapping(path = "/dependencies", produces = { "application/vnd.initializr.v2.1+json", "application/json" }) public ResponseEntity<String> dependenciesV21(@RequestParam(required = false) String bootVersion) { return dependenciesFor(InitializrMetadataVersion.V2_1, bootVersion); } @ExceptionHandler public void invalidMetadataRequest(HttpServletResponse response, InvalidInitializrMetadataException ex) throws IOException { response.sendError(HttpStatus.BAD_REQUEST.value(), ex.getMessage()); } @ExceptionHandler public void invalidProjectRequest(HttpServletResponse response, InvalidProjectRequestException ex) throws IOException { response.sendError(HttpStatus.BAD_REQUEST.value(), ex.getMessage()); } /** * Return the {@link CacheControl} response headers to use for the specified * {@link InitializrMetadata metadata}. If no cache should be applied * {@link CacheControl#empty()} can be used. * @param metadata the metadata about to be exposed * @return the {@code Cache-Control} headers to use */ protected CacheControl determineCacheControlFor(InitializrMetadata metadata) { return CacheControl.maxAge(2, TimeUnit.HOURS); } private ResponseEntity<String> dependenciesFor(InitializrMetadataVersion version, String bootVersion) { InitializrMetadata metadata = this.metadataProvider.get(); Version v = (bootVersion != null) ? Version.parse(bootVersion) : Version.parse(metadata.getBootVersions().getDefault().getId()); Platform platform = metadata.getConfiguration().getEnv().getPlatform(); if (!platform.isCompatibleVersion(v)) { throw new InvalidProjectRequestException("Invalid Spring Boot version '" + bootVersion + "', Spring Boot compatibility range is " + platform.determineCompatibilityRangeRequirement()); } DependencyMetadata dependencyMetadata = this.dependencyMetadataProvider.get(metadata, v); String content = new DependencyMetadataV21JsonMapper().write(dependencyMetadata); return ResponseEntity.ok() .contentType(version.getMediaType()) .eTag(createUniqueId(content)) .cacheControl(determineCacheControlFor(metadata)) .body(content); } private ResponseEntity<String> serviceCapabilitiesFor(InitializrMetadataVersion version) { return serviceCapabilitiesFor(version, version.getMediaType()); } private ResponseEntity<String> serviceCapabilitiesFor(InitializrMetadataVersion version, MediaType contentType) { String appUrl = generateAppUrl(); InitializrMetadata metadata = this.metadataProvider.get(); String content = getJsonMapper(version).write(metadata, appUrl); return ResponseEntity.ok() .contentType(contentType) .eTag(createUniqueId(content)) .varyBy("Accept") .cacheControl(determineCacheControlFor(metadata)) .body(content); } private static InitializrMetadataJsonMapper getJsonMapper(InitializrMetadataVersion version) {<FILL_FUNCTION_BODY>} }
switch (version) { case V2: return new InitializrMetadataV2JsonMapper(); case V2_1: return new InitializrMetadataV21JsonMapper(); default: return new InitializrMetadataV22JsonMapper(); }
1,296
74
1,370
<methods><variables>private java.lang.Boolean forceSsl,protected final non-sealed io.spring.initializr.metadata.InitializrMetadataProvider metadataProvider
spring-io_initializr
initializr/initializr-web/src/main/java/io/spring/initializr/web/mapper/DependencyMetadataV21JsonMapper.java
DependencyMetadataV21JsonMapper
mapRepository
class DependencyMetadataV21JsonMapper implements DependencyMetadataJsonMapper { private static final JsonNodeFactory nodeFactory = JsonNodeFactory.instance; @Override public String write(DependencyMetadata metadata) { ObjectNode json = nodeFactory.objectNode(); json.put("bootVersion", metadata.getBootVersion().toString()); json.set("dependencies", mapNode(metadata.getDependencies() .entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, (entry) -> mapDependency(entry.getValue()))))); json.set("repositories", mapNode(metadata.getRepositories() .entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, (entry) -> mapRepository(entry.getValue()))))); json.set("boms", mapNode(metadata.getBoms() .entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, (entry) -> mapBom(entry.getValue()))))); return json.toString(); } private static JsonNode mapDependency(Dependency dep) { ObjectNode node = nodeFactory.objectNode(); node.put("groupId", dep.getGroupId()); node.put("artifactId", dep.getArtifactId()); if (dep.getVersion() != null) { node.put("version", dep.getVersion()); } node.put("scope", dep.getScope()); if (dep.getBom() != null) { node.put("bom", dep.getBom()); } if (dep.getRepository() != null) { node.put("repository", dep.getRepository()); } return node; } private static JsonNode mapRepository(Repository repo) {<FILL_FUNCTION_BODY>} private static JsonNode mapBom(BillOfMaterials bom) { ObjectNode node = nodeFactory.objectNode(); node.put("groupId", bom.getGroupId()); node.put("artifactId", bom.getArtifactId()); if (bom.getVersion() != null) { node.put("version", bom.getVersion()); } if (bom.getRepositories() != null) { ArrayNode array = nodeFactory.arrayNode(); bom.getRepositories().forEach(array::add); node.set("repositories", array); } return node; } private static JsonNode mapNode(Map<String, JsonNode> content) { ObjectNode node = nodeFactory.objectNode(); content.forEach(node::set); return node; } }
ObjectNode node = nodeFactory.objectNode(); node.put("name", repo.getName()) .put("url", (repo.getUrl() != null) ? repo.getUrl().toString() : null) .put("snapshotEnabled", repo.isSnapshotsEnabled()); return node;
704
78
782
<no_super_class>
spring-io_initializr
initializr/initializr-web/src/main/java/io/spring/initializr/web/mapper/InitializrMetadataV21JsonMapper.java
InitializrMetadataV21JsonMapper
dependenciesLink
class InitializrMetadataV21JsonMapper extends InitializrMetadataV2JsonMapper { private final TemplateVariables dependenciesVariables; public InitializrMetadataV21JsonMapper() { this.dependenciesVariables = new TemplateVariables( new TemplateVariable("bootVersion", TemplateVariable.VariableType.REQUEST_PARAM)); } @Override protected ObjectNode links(ObjectNode parent, List<Type> types, String appUrl) { ObjectNode links = super.links(parent, types, appUrl); links.set("dependencies", dependenciesLink(appUrl)); parent.set("_links", links); return links; } @Override protected ObjectNode mapDependency(Dependency dependency) { ObjectNode content = mapValue(dependency); if (dependency.getRange() != null) { content.put("versionRange", formatVersionRange(dependency.getRange())); } if (dependency.getLinks() != null && !dependency.getLinks().isEmpty()) { content.set("_links", LinkMapper.mapLinks(dependency.getLinks())); } return content; } protected String formatVersionRange(VersionRange versionRange) { return versionRange.format(Format.V1).toRangeString(); } private ObjectNode dependenciesLink(String appUrl) {<FILL_FUNCTION_BODY>} }
String uri = (appUrl != null) ? appUrl + "/dependencies" : "/dependencies"; UriTemplate uriTemplate = UriTemplate.of(uri, this.dependenciesVariables); ObjectNode result = nodeFactory().objectNode(); result.put("href", uriTemplate.toString()); result.put("templated", true); return result;
344
96
440
<methods>public void <init>() ,public java.lang.String write(io.spring.initializr.metadata.InitializrMetadata, java.lang.String) <variables>private static final JsonNodeFactory nodeFactory,private final non-sealed TemplateVariables templateVariables