Skip to content

Commit 26dbba8

Browse files
committed
Added examples for DataFrame Spring integration with CSV data sources and improved build.gradle configuration.
1 parent a322fa1 commit 26dbba8

File tree

10 files changed

+391
-35
lines changed

10 files changed

+391
-35
lines changed

build.gradle.kts

Lines changed: 36 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -172,42 +172,47 @@ val modulesUsingJava17 = with(projects) {
172172
}.map { it.path }
173173

174174
allprojects {
175-
if (path in modulesUsingJava11) {
176-
tasks.withType<KotlinCompile> {
177-
compilerOptions {
178-
jvmTarget = JvmTarget.JVM_11
179-
freeCompilerArgs.add("-Xjdk-release=11")
175+
when (path) {
176+
in modulesUsingJava11 -> {
177+
tasks.withType<KotlinCompile> {
178+
compilerOptions {
179+
jvmTarget = JvmTarget.JVM_11
180+
freeCompilerArgs.add("-Xjdk-release=11")
181+
}
180182
}
181-
}
182-
tasks.withType<JavaCompile> {
183-
sourceCompatibility = JavaVersion.VERSION_11.toString()
184-
targetCompatibility = JavaVersion.VERSION_11.toString()
185-
options.release.set(11)
186-
}
187-
}
188-
else if (path in modulesUsingJava17) {
189-
tasks.withType<KotlinCompile> {
190-
compilerOptions {
191-
jvmTarget = JvmTarget.JVM_17
192-
freeCompilerArgs.add("-Xjdk-release=17")
183+
tasks.withType<JavaCompile> {
184+
sourceCompatibility = JavaVersion.VERSION_11.toString()
185+
targetCompatibility = JavaVersion.VERSION_11.toString()
186+
options.release.set(11)
193187
}
194188
}
195-
tasks.withType<JavaCompile> {
196-
sourceCompatibility = JavaVersion.VERSION_17.toString()
197-
targetCompatibility = JavaVersion.VERSION_17.toString()
198-
options.release.set(17)
199-
}
200-
} else {
201-
tasks.withType<KotlinCompile> {
202-
compilerOptions {
203-
jvmTarget = JvmTarget.JVM_1_8
204-
freeCompilerArgs.add("-Xjdk-release=8")
189+
190+
in modulesUsingJava17 -> {
191+
tasks.withType<KotlinCompile> {
192+
compilerOptions {
193+
jvmTarget = JvmTarget.JVM_17
194+
freeCompilerArgs.add("-Xjdk-release=17")
195+
}
196+
}
197+
tasks.withType<JavaCompile> {
198+
sourceCompatibility = JavaVersion.VERSION_17.toString()
199+
targetCompatibility = JavaVersion.VERSION_17.toString()
200+
options.release.set(17)
205201
}
206202
}
207-
tasks.withType<JavaCompile> {
208-
sourceCompatibility = JavaVersion.VERSION_1_8.toString()
209-
targetCompatibility = JavaVersion.VERSION_1_8.toString()
210-
options.release.set(8)
203+
204+
else -> {
205+
tasks.withType<KotlinCompile> {
206+
compilerOptions {
207+
jvmTarget = JvmTarget.JVM_1_8
208+
freeCompilerArgs.add("-Xjdk-release=8")
209+
}
210+
}
211+
tasks.withType<JavaCompile> {
212+
sourceCompatibility = JavaVersion.VERSION_1_8.toString()
213+
targetCompatibility = JavaVersion.VERSION_1_8.toString()
214+
options.release.set(8)
215+
}
211216
}
212217
}
213218
tasks.withType<KotlinCompile> {

dataframe-spring/build.gradle.kts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,37 @@ dependencies {
4141
testImplementation(libs.kotestAssertions)
4242
}
4343

44+
// Define examples source set
45+
val examples by sourceSets.creating {
46+
kotlin.srcDir("examples/src")
47+
resources.srcDir("examples/resources")
48+
}
49+
50+
// Configure examples classpath
51+
configurations {
52+
named("examplesImplementation") {
53+
extendsFrom(configurations.implementation.get())
54+
}
55+
named("examplesRuntimeOnly") {
56+
extendsFrom(configurations.runtimeOnly.get())
57+
}
58+
}
59+
60+
// Add dependencies for examples
61+
dependencies {
62+
"examplesImplementation"(project(":dataframe-spring"))
63+
"examplesImplementation"("org.springframework:spring-context:6.2.7")
64+
"examplesImplementation"("org.springframework:spring-beans:6.2.7")
65+
}
66+
67+
// Task for running examples
68+
tasks.register<JavaExec>("runExamples") {
69+
group = "Examples"
70+
description = "Runs the DataFrame Spring examples"
71+
classpath = examples.runtimeClasspath
72+
mainClass.set("org.jetbrains.kotlinx.dataframe.spring.examples.ExampleRunnerKt")
73+
}
74+
4475
tasks.test {
4576
useJUnitPlatform()
4677
}

dataframe-spring/examples/README.md

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# DataFrame Spring Examples
2+
3+
This directory contains examples demonstrating the usage of the DataFrame Spring integration.
4+
5+
## Overview
6+
7+
The examples show how to use the DataFrame Spring module to automatically load data from various sources into DataFrames using annotations.
8+
9+
## Examples
10+
11+
1. **CSV Data Source** - Demonstrates loading DataFrames from CSV files using the `@CsvDataSource` annotation
12+
2. **CSV Data Source with Spring Context** - Shows how to use the `@CsvDataSource` annotation within a Spring application context
13+
14+
## Running Examples
15+
16+
To run all examples:
17+
18+
```bash
19+
./gradlew :dataframe-spring:runExamples
20+
```
21+
22+
## Example Descriptions
23+
24+
### CSV Data Source
25+
26+
This example demonstrates how to use the `DataFramePostProcessor` to process a bean with `@CsvDataSource` annotations outside of a Spring context.
27+
28+
Key features:
29+
- Loading CSV data with default comma delimiter
30+
- Loading CSV data with custom delimiter (semicolon)
31+
- Accessing the loaded data through a typed DataFrame
32+
33+
### CSV Data Source with Spring Context
34+
35+
This example demonstrates how to use the `DataFramePostProcessor` within a Spring application context to process beans with `@CsvDataSource` annotations.
36+
37+
Key features:
38+
- Registering the `DataFramePostProcessor` in a Spring context
39+
- Automatically processing beans with `@CsvDataSource` annotations
40+
- Retrieving processed beans from the Spring context
41+
42+
## Data Models
43+
44+
The examples use the following data models:
45+
46+
- `CustomerRow` - Represents customer data with id, name, email, and age
47+
- `SalesRow` - Represents sales data with sale ID, customer ID, amount, and date
48+
49+
## File Structure
50+
51+
```
52+
examples/
53+
├── src/ # Source code for examples
54+
│ └── org/jetbrains/kotlinx/dataframe/spring/examples/
55+
│ ├── CsvDataSourceExample.kt # Basic CSV example
56+
│ ├── CsvDataSourceWithContextExample.kt # Spring context example
57+
│ ├── DataModels.kt # Data models and utilities
58+
│ └── ExampleRunner.kt # Main entry point
59+
└── resources/ # Resource files for examples
60+
└── data/ # Data files
61+
├── customers.csv # Customer data (created at runtime)
62+
└── sales.csv # Sales data (created at runtime)
63+
```
64+
65+
## Learning Path
66+
67+
1. Start with the basic CSV example to understand how the `@CsvDataSource` annotation works
68+
2. Move on to the Spring context example to see how to integrate with Spring
69+
70+
## Additional Resources
71+
72+
For more information, see:
73+
- [DataFrame Spring README](../README.md)
74+
- [DataFrame Spring Integration Guide](../INTEGRATION_GUIDE.md)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
This directory contains data files used by the DataFrame Spring examples.
2+
3+
The CSV files (customers.csv and sales.csv) are created dynamically when the examples are run.
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package org.jetbrains.kotlinx.dataframe.spring.examples
2+
3+
import org.jetbrains.kotlinx.dataframe.spring.DataFramePostProcessor
4+
5+
/**
6+
* Example demonstrating basic CSV data source processing.
7+
*
8+
* This example shows how to use the DataFramePostProcessor to process
9+
* a bean with @CsvDataSource annotations outside of a Spring context.
10+
*/
11+
fun csvDataSourceExample() {
12+
// Create sample CSV files in the resources directory
13+
val resourcesDir = System.getProperty("user.dir") + "\\dataframe-spring\\examples\\resources"
14+
createSampleData(resourcesDir)
15+
16+
try {
17+
println("1. Creating DataFramePostProcessor...")
18+
val processor = DataFramePostProcessor()
19+
20+
println("2. Processing @CsvDataSource annotations...")
21+
val service = ExampleDataService()
22+
processor.postProcessBeforeInitialization(service, "exampleService")
23+
24+
println("3. DataFrame loaded successfully!")
25+
println(" - Rows loaded: ${service.customerData.rowsCount()}")
26+
println(" - Columns: ${service.customerData.columnNames()}")
27+
28+
println("4. Running business logic...")
29+
service.printCustomerCount()
30+
service.printSalesCount()
31+
32+
println("✓ @CsvDataSource annotation processing completed successfully!")
33+
34+
} catch (e: Exception) {
35+
println("✗ Error processing @DataSource annotations: ${e.message}")
36+
e.printStackTrace()
37+
} finally {
38+
// Clean up sample files
39+
cleanupSampleData(resourcesDir)
40+
}
41+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package org.jetbrains.kotlinx.dataframe.spring.examples
2+
3+
import org.jetbrains.kotlinx.dataframe.spring.DataFramePostProcessor
4+
import org.springframework.context.annotation.AnnotationConfigApplicationContext
5+
6+
/**
7+
* Example demonstrating CSV data source processing with Spring context.
8+
*
9+
* This example shows how to use the DataFramePostProcessor within a Spring
10+
* application context to process beans with @CsvDataSource annotations.
11+
*/
12+
fun csvDataSourceWithContextExample() {
13+
// Create sample CSV files in the resources directory
14+
val resourcesDir = System.getProperty("user.dir") + "\\dataframe-spring\\examples\\resources"
15+
createSampleData(resourcesDir)
16+
17+
try {
18+
println("1. Bootstrapping Spring context...")
19+
val ctx = AnnotationConfigApplicationContext().apply {
20+
register(DataFramePostProcessor::class.java)
21+
register(ExampleDataService::class.java)
22+
refresh()
23+
}
24+
25+
println("2. Getting ExampleDataService bean from context...")
26+
val dataService = ctx.getBean(ExampleDataService::class.java)
27+
28+
println("3. DataFrame loaded successfully!")
29+
println(" - Rows loaded: ${dataService.customerData.rowsCount()}")
30+
println(" - Columns: ${dataService.customerData.columnNames()}")
31+
32+
println("4. Running business logic...")
33+
dataService.printCustomerCount()
34+
dataService.printSalesCount()
35+
36+
println("✓ @CsvDataSource annotation processing with Spring context completed successfully!")
37+
38+
} catch (e: Exception) {
39+
println("✗ Error processing @DataSource annotations: ${e.message}")
40+
e.printStackTrace()
41+
} finally {
42+
// Clean up sample files
43+
cleanupSampleData(resourcesDir)
44+
}
45+
}
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
package org.jetbrains.kotlinx.dataframe.spring.examples
2+
3+
import org.jetbrains.kotlinx.dataframe.DataFrame
4+
import org.jetbrains.kotlinx.dataframe.annotations.DataSchema
5+
import org.jetbrains.kotlinx.dataframe.spring.annotations.CsvDataSource
6+
import java.io.File
7+
8+
/**
9+
* Data schema for customer records.
10+
*
11+
* This interface defines the structure of customer data loaded from CSV files.
12+
*/
13+
@DataSchema
14+
interface CustomerRow {
15+
val id: Int
16+
val name: String
17+
val email: String
18+
val age: Int
19+
}
20+
21+
/**
22+
* Data schema for sales records.
23+
*
24+
* This interface defines the structure of sales data loaded from CSV files.
25+
*/
26+
@DataSchema
27+
interface SalesRow {
28+
val saleId: Int
29+
val customerId: Int
30+
val amount: Double
31+
val date: String
32+
}
33+
34+
/**
35+
* Example service class that uses DataFrame annotations.
36+
*
37+
* This class demonstrates how to use the @CsvDataSource annotation
38+
* to automatically load data from CSV files into DataFrames.
39+
*/
40+
class ExampleDataService {
41+
@CsvDataSource(file = CUSTOMERS_CSV)
42+
lateinit var customerData: DataFrame<CustomerRow>
43+
44+
@CsvDataSource(file = SALES_CSV, delimiter = ';')
45+
lateinit var salesData: DataFrame<SalesRow>
46+
47+
/**
48+
* Prints the total number of customers.
49+
*/
50+
fun printCustomerCount() {
51+
println("Number of customers: ${customerData.rowsCount()}")
52+
}
53+
54+
/**
55+
* Prints the total number of sales.
56+
*/
57+
fun printSalesCount() {
58+
println("Number of sales: ${salesData.rowsCount()}")
59+
}
60+
}
61+
62+
// Constants for file paths
63+
const val CUSTOMERS_CSV = "data\\customers.csv"
64+
const val SALES_CSV = "data\\sales.csv"
65+
66+
/**
67+
* Creates sample CSV data files for the examples.
68+
*
69+
* This function creates customer and sales data files in the specified directory.
70+
*
71+
* @param directory The directory where the files will be created
72+
*/
73+
fun createSampleData(directory: String) {
74+
// Create customer data
75+
File("$directory\\$CUSTOMERS_CSV").apply {
76+
parentFile.mkdirs()
77+
writeText("""
78+
id,name,email,age
79+
1,John Doe,[email protected],28
80+
2,Jane Smith,[email protected],32
81+
3,Bob Johnson,[email protected],25
82+
4,Alice Brown,[email protected],30
83+
""".trimIndent())
84+
}
85+
86+
// Create sales data with semicolon delimiter
87+
File("$directory\\$SALES_CSV").apply {
88+
parentFile.mkdirs()
89+
writeText("""
90+
sale_id;customer_id;amount;date
91+
1;1;150.00;2023-01-15
92+
2;2;200.50;2023-01-16
93+
3;1;75.25;2023-01-17
94+
4;3;300.00;2023-01-18
95+
""".trimIndent())
96+
}
97+
}
98+
99+
/**
100+
* Cleans up the sample data files.
101+
*
102+
* @param directory The directory where the files were created
103+
*/
104+
fun cleanupSampleData(directory: String) {
105+
File("$directory\\$CUSTOMERS_CSV").delete()
106+
File("$directory\\$SALES_CSV").delete()
107+
}

0 commit comments

Comments
 (0)