diff --git a/.gitignore b/.gitignore index 5ff6309..c0ceab4 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ target/ !**/src/test/**/target/ ### IntelliJ IDEA ### +.idea .idea/modules.xml .idea/jarRepositories.xml .idea/compiler.xml @@ -35,4 +36,6 @@ build/ .vscode/ ### Mac OS ### -.DS_Store \ No newline at end of file +.DS_Store + +.gradle \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..07a78c6 --- /dev/null +++ b/build.gradle @@ -0,0 +1,109 @@ +plugins { + id 'java-library' + id 'maven-publish' + id 'jacoco' + id 'org.sonarqube' version '4.4.1.3373' +} + +group = 'org.writer' +version = projectVersion + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } + withSourcesJar() + withJavadocJar() +} + +jacoco { + toolVersion = "0.8.10" + reportsDirectory = layout.buildDirectory.dir('reports/jacoco') +} + +repositories { + mavenCentral() +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +dependencies { + implementation "com.github.javafaker:javafaker:$fakerLibVersion" + testImplementation platform("org.junit:junit-bom:$jupiterPomVersion") + testImplementation "org.junit.jupiter:junit-jupiter" + testImplementation "org.mockito:mockito-core:$mockitoCoreVersion" +} + +test { + useJUnitPlatform() + finalizedBy jacocoTestReport +} + +jacocoTestReport { + dependsOn test + + reports { + xml.required = true + html.required = true + csv.required = false + + xml.outputLocation = layout.buildDirectory.file("reports/jacoco/test/jacocoTestReport.xml") + html.outputLocation = layout.buildDirectory.dir("reports/jacoco/test/html") + } + + classDirectories.setFrom(files( + sourceSets.main.output.classesDirs.files.collect { + fileTree(dir: it, excludes: [ + '**/org/writer/util/GeneratorFakeData.class', + '**/org/writer/util/GeneratorFakeData$*.class', + '**/org/writer/exception/CsvWriterException.java' + ]) + } + )) + +} + +publishing { + publications { + mavenJava(MavenPublication) { + from components.java + artifactId = 'scv-writer' + } + } + repositories { + mavenLocal() + } +} + +tasks.named('test') { + finalizedBy jacocoTestReport +} + +tasks.named('jacocoTestReport') { + finalizedBy tasks.named('sonar') +} + +tasks.named('build') { + dependsOn tasks.named('sonar') +} + +tasks.named('sonar') { + mustRunAfter tasks.named('jacocoTestReport') +} + +tasks.named('compileJava') { + finalizedBy tasks.named('sonar') +} + +sonarqube { + properties { + property "sonar.gradle.skipCompile", "true" + property "sonar.coverage.exclusions", ["**/org/writer/util/GeneratorFakeData.java", + "**/org/writer/exception/CsvWriterException.java"] + + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..6171a32 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,10 @@ +systemProp.sonar.host.url=http://localhost:9000 +systemProp.sonar.projectKey=Csv-writer +systemProp.sonar.projectName=Csv-writer library +systemProp.sonar.token=squ_b5f679133764b0c8b6acc6456985df489522849a + +fakerLibVersion=1.0.2 +mockitoCoreVersion=5.20.0 +jupiterPomVersion=5.10.0 + +projectVersion=1.0-SNAPSHOT diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a441313 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..b740cf1 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..7101f8e --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/pom.xml b/pom.xml deleted file mode 100644 index effc1bd..0000000 --- a/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - 4.0.0 - - org.writer - csv - 1.0-SNAPSHOT - - - 17 - 17 - UTF-8 - - - - - org.projectlombok - lombok - 1.18.34 - provided - - - org.junit.jupiter - junit-jupiter - 5.8.1 - test - - - - \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..452d8c7 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "csv" diff --git a/src/main/java/org/writer/Main.java b/src/main/java/org/writer/Main.java index 40e8213..5a9a556 100644 --- a/src/main/java/org/writer/Main.java +++ b/src/main/java/org/writer/Main.java @@ -1,7 +1,18 @@ package org.writer; +import org.writer.model.Person; +import org.writer.model.Student; +import org.writer.util.GeneratorFakeData; +import org.writer.writer.CSVWriter; + +import java.util.List; + public class Main { public static void main(String[] args) { - System.out.println("Hello world!"); + List persons = GeneratorFakeData.generatePersons(12); + List students = GeneratorFakeData.generateStudents(3); + CSVWriter csvWriter = new CSVWriter(); + csvWriter.writeToFile(persons, "persons.csv"); + csvWriter.writeToFile(students, "students.csv"); } } \ No newline at end of file diff --git a/src/main/java/org/writer/annotation/CSVField.java b/src/main/java/org/writer/annotation/CSVField.java new file mode 100644 index 0000000..047c3de --- /dev/null +++ b/src/main/java/org/writer/annotation/CSVField.java @@ -0,0 +1,36 @@ +package org.writer.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Аннотация для маркировки полей, + * которые должны быть включены в CSV + * + * @author Sidorin Aleksei + * @version 1.0 + * @since 16.10.2025 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface CSVField { + /** + * Название колонки в CSV файле + * @return название колонки + */ + String name() default ""; + + /** + * Порядок колонки в CSV файле + * @return порядковый номер + */ + int order() default 0; + + /** + * Формат для преобразования значения (например, для дат) + * @return строка формата + */ + String format() default ""; +} diff --git a/src/main/java/org/writer/exception/CsvWriterException.java b/src/main/java/org/writer/exception/CsvWriterException.java new file mode 100644 index 0000000..d7dda6d --- /dev/null +++ b/src/main/java/org/writer/exception/CsvWriterException.java @@ -0,0 +1,16 @@ +package org.writer.exception; + +/** + * @author Sidorin Aleksei + * @version 1.0 + * @since 19.12.2025 + */ +public class CsvWriterException extends RuntimeException { + public CsvWriterException(String message) { + super(message); + } + + public CsvWriterException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/org/writer/model/Person.java b/src/main/java/org/writer/model/Person.java index ba8576b..46b90e0 100644 --- a/src/main/java/org/writer/model/Person.java +++ b/src/main/java/org/writer/model/Person.java @@ -1,22 +1,72 @@ package org.writer.model; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; +import org.writer.annotation.CSVField; -@Data -@Builder -@AllArgsConstructor public class Person { + @CSVField(name = "Имя", order = 1) private String firstName; + @CSVField(name = "Фамилия", order = 2) private String lastName; + @CSVField(name = "День рождения", order = 3) private int dayOfBirth; + @CSVField(name = "Месяц рождения", order = 4) private Months monthOfBirth; + @CSVField(name = "Год рождения", order = 5) private int yearOfBirth; + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public int getDayOfBirth() { + return dayOfBirth; + } + + public void setDayOfBirth(int dayOfBirth) { + this.dayOfBirth = dayOfBirth; + } + + public Months getMonthOfBirth() { + return monthOfBirth; + } + + public void setMonthOfBirth(Months monthOfBirth) { + this.monthOfBirth = monthOfBirth; + } + + public int getYearOfBirth() { + return yearOfBirth; + } + + public void setYearOfBirth(int yearOfBirth) { + this.yearOfBirth = yearOfBirth; + } + + public Person() { + } + + public Person(String firstName, String lastName, int dayOfBirth, Months monthOfBirth, int yearOfBirth) { + this.firstName = firstName; + this.lastName = lastName; + this.dayOfBirth = dayOfBirth; + this.monthOfBirth = monthOfBirth; + this.yearOfBirth = yearOfBirth; + } } diff --git a/src/main/java/org/writer/model/Student.java b/src/main/java/org/writer/model/Student.java index 2b549c4..9dba7d4 100644 --- a/src/main/java/org/writer/model/Student.java +++ b/src/main/java/org/writer/model/Student.java @@ -1,17 +1,39 @@ package org.writer.model; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; +import org.writer.annotation.CSVField; import java.util.List; -@Data -@Builder -@AllArgsConstructor public class Student { + @CSVField(name = "Имя", order = 1) private String name; + @CSVField(name = "Баллы", order = 2) private List score; + + public Student() { + } + + public Student(String name, List score) { + this.name = name; + this.score = score; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getScore() { + return score; + } + + public void setScore(List score) { + this.score = score; + } + } \ No newline at end of file diff --git a/src/main/java/org/writer/util/GeneratorFakeData.java b/src/main/java/org/writer/util/GeneratorFakeData.java new file mode 100644 index 0000000..ef48a28 --- /dev/null +++ b/src/main/java/org/writer/util/GeneratorFakeData.java @@ -0,0 +1,93 @@ +package org.writer.util; + +import com.github.javafaker.Faker; +import org.writer.model.Months; +import org.writer.model.Person; +import org.writer.model.Student; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** + * Генератор случайных данных + * для сущностей Person и Student + * + * @author Sidorin Aleksei + * @version 1.0 + * @since 16.10.2025 + */ +public class GeneratorFakeData { + + private static final Faker faker = new Faker(new Locale("ru")); + + private GeneratorFakeData() { + + } + + /** + * Генерирует список объектов Person со случайными данными + * + * @param count количество генерируемых объектов + * @return список объектов Person со случайными данными + * @throws IllegalArgumentException если count меньше или равен 0 + */ + public static List generatePersons(int count) { + List persons = new ArrayList<>(); + for (int i = 0; i < count; i++) { + persons.add(generatePerson()); + } + return persons; + } + + private static Person generatePerson() { + Person person = new Person(); + person.setLastName(faker.name().lastName()); + person.setDayOfBirth(faker.number().numberBetween(1, 28)); + person.setMonthOfBirth(Months.values()[faker.number().numberBetween(0, Months.values().length - 1)]); + person.setYearOfBirth(faker.number().numberBetween(1950, 2005)); + return person; + } + + /** + * Генерирует список объектов Student со случайными данными + * + * @param count количество генерируемых объектов + * @return список объектов Student со случайными данными + * @throws IllegalArgumentException если count меньше или равен 0 + */ + public static List generateStudents(int count) { + List students = new ArrayList<>(); + for (int i = 0; i < count; i++) { + students.add(generateStudent()); + } + return students; + } + + private static Student generateStudent() { + Student student = new Student(); + student.setName(faker.name().firstName() + " " + faker.name().lastName()); + student.setScore(generateScores()); + return student; + + } + + /** + * Генерирует список случайных баллов в диапазоне от 0 до 100 + * + * @return список строк, содержащих числовые баллы от 0 до 100 + */ + private static List generateScores() { + List scores = new ArrayList<>(); + + int count = 1 + faker.random().nextInt(10); + + for (int i = 0; i < count; i++) { + int score = faker.random().nextInt(101); + scores.add(String.valueOf(score)); + } + + return scores; + } + +} diff --git a/src/main/java/org/writer/writer/CSVWriter.java b/src/main/java/org/writer/writer/CSVWriter.java new file mode 100644 index 0000000..dfe6b75 --- /dev/null +++ b/src/main/java/org/writer/writer/CSVWriter.java @@ -0,0 +1,170 @@ +package org.writer.writer; + +import org.writer.exception.CsvWriterException; +import org.writer.Writable; +import org.writer.annotation.CSVField; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.lang.reflect.Field; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * Имплиментация генератора csv файлов + * на основе интерфейса Writable + * + * @author Sidorin Aleksei + * @version 1.0 + * @since 16.10.2025 + */ +public class CSVWriter implements Writable { + + private static final String CSV_DELIMITER = ","; + private static final String CSV_QUOTE = "\""; + private static final String NEW_LINE = "\n"; + + @Override + public void writeToFile(List data, String fileName) { + if (Objects.isNull(data) || data.isEmpty()) { + throw new IllegalArgumentException("List of data cant be null or empty"); + } + if (Objects.isNull(fileName)) { + throw new IllegalArgumentException("File name can't be null"); + } + + File outputDir = new File("outputs"); + if (!outputDir.exists()) { + outputDir.mkdirs(); + } + + File outputFile = new File(outputDir, fileName); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) { + Class objectClass = data.get(0).getClass(); + List fields = getAnnotatedFields(objectClass); + + writer.write(generateHeader(fields)); + writer.write(NEW_LINE); + + for (var object : data) { + writer.write(generateDataRow(object, fields)); + writer.write(NEW_LINE); + } + } catch (IOException e) { + throw new CsvWriterException("You have uncorrected path way", e); + } + } + + /** + * Экранирует кавычки для CSV + * @param value значение для экранирования + * @return экранированная строка + */ + private String escapeCsvValue(Object value) { + if (value == null) { + return ""; + } + + String stringValue = value.toString(); + if (stringValue.contains(CSV_DELIMITER) || + stringValue.contains(CSV_QUOTE) || + stringValue.trim().isEmpty() + ) { + stringValue = stringValue.replace(CSV_QUOTE, CSV_QUOTE + CSV_QUOTE); + return CSV_QUOTE + stringValue + CSV_QUOTE; + } + return stringValue; + } + + /** + * Получает аннотированные поля класса в правильном порядке + * @param clazz класс для анализа + * @return список полей с аннотацией CSVField, отсортированный по order + */ + private List getAnnotatedFields(Class clazz) { + List annotatedFields = new ArrayList<>(); + + Class currentClass = clazz; + while (currentClass != null) { + Field[] fields = currentClass.getDeclaredFields(); + for (Field field : fields) { + if (field.isAnnotationPresent(CSVField.class)) { + field.setAccessible(true); + annotatedFields.add(field); + } + } + currentClass = currentClass.getSuperclass(); + } + + return annotatedFields.stream() + .sorted(Comparator.comparingInt(field -> + field.getAnnotation(CSVField.class).order())) + .toList(); + } + + /** + * Форматирует значение поля согласно аннотации + * @param field поле + * @param value значение + * @return отформатированное значение + */ + private String formatFieldValue(Field field, Object value) { + if (value == null) { + return ""; + } + + CSVField annotation = field.getAnnotation(CSVField.class); + String format = annotation.format(); + + if (!format.isEmpty() && value instanceof LocalDateTime localDateTime) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format); + return localDateTime.format(formatter); + } + + return value.toString(); + } + + /** + * Генерирует заголовок CSV на основе аннотаций полей + * @param fields список полей + * @return строка заголовка + */ + private String generateHeader(List fields) { + return fields.stream() + .map(field -> { + CSVField annotation = field.getAnnotation(CSVField.class); + String columnName = annotation.name().isEmpty() ? + field.getName() : annotation.name(); + return escapeCsvValue(columnName); + }) + .collect(Collectors.joining(CSV_DELIMITER)); + } + + /** + * Генерирует строку данных для объекта + * @param object объект + * @param fields список полей + * @return строка данных + */ + private String generateDataRow(Object object, List fields) { + return fields.stream() + .map(field -> { + try { + Object value = field.get(object); + String formattedValue = formatFieldValue(field, value); + return escapeCsvValue(formattedValue); + } catch (IllegalAccessException e) { + throw new CsvWriterException("Cant generate data csv",e); + } + }) + .collect(Collectors.joining(CSV_DELIMITER)); + } + +} diff --git a/src/test/java/org/writer/writer/CSVWriterTest.java b/src/test/java/org/writer/writer/CSVWriterTest.java new file mode 100644 index 0000000..866808d --- /dev/null +++ b/src/test/java/org/writer/writer/CSVWriterTest.java @@ -0,0 +1,209 @@ +package org.writer.writer; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.writer.model.Months; +import org.writer.model.Person; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Тестовый класс для проверки функциональности CSVWriter. + * + * @author Sidorin Aleksei + * @version 1.0 + * @since 16.10.2025 + */ +class CSVWriterTest { + + /** + * Очищает все тестовые файлы после каждого теста. + * Удаляет CSV файлы из директории outputs, которые могли быть созданы в ходе тестирования. + * + * @throws IOException если возникают ошибки ввода-вывода при удалении файлов + */ + @AfterEach + void cleanUpTestFiles() throws IOException { + String outputDir = "outputs"; + Path outputPath = Paths.get(outputDir); + + if (!Files.exists(outputPath)) { + return; + } + + try (var files = Files.list(outputPath)) { + files.filter(Files::isRegularFile) + .filter(path -> path.toString().toLowerCase().endsWith(".csv") + && path.toString().contains("test")) + .forEach(path -> { + try { + Files.delete(path); + } catch (IOException e) { + throw new RuntimeException("Ошибка при удалении файла " + path.getFileName() + ": " + e.getMessage()); + } + }); + } + } + + /** + * Тестирует запись корректных данных в CSV файл. + * Проверяет создание файла, его содержимое, количество строк, + * соответствие заголовка и данных ожидаемым значениям. + * + * @throws IOException если возникают ошибки ввода-вывода при чтении файла + */ + @Test + void testWriteToFile_WithValidData_CreatesFileWithCorrectContent() throws IOException { + CSVWriter csvWriter = new CSVWriter(); + List testData = Arrays.asList( + new Person("John", "Doe", 1, Months.APRIL, 2003), + new Person("Jane", "Smith", 12, Months.AUGUST, 1998), + new Person("Rex", "Miller", 10, Months.SEPTEMBER, 1990) + ); + + String fileName = "test_output.csv"; + File outputFile = new File("outputs", fileName); + + csvWriter.writeToFile(testData, fileName); + + assertTrue(outputFile.exists(), "File should be created"); + assertTrue(outputFile.length() > 0, "File should not be empty"); + + List lines = Files.readAllLines(outputFile.toPath()); + assertEquals(4, lines.size(), "Should have header + 3 data rows"); + + String expectedHeader = "Имя,Фамилия,День рождения,Месяц рождения,Год рождения"; + assertEquals(expectedHeader, lines.get(0), "Header should match annotation names"); + + assertEquals("John,Doe,1,APRIL,2003", lines.get(1), "First data row should match"); + assertEquals("Jane,Smith,12,AUGUST,1998", lines.get(2), "Second data row should match"); + assertEquals("Rex,Miller,10,SEPTEMBER,1990", lines.get(3), "Third data row should match"); + } + + /** + * Тестирует обработку кавычек в данных. + * Проверяет корректное экранирование запятых, кавычек, + * символов новой строки и возврата каретки. + * + * @throws IOException если возникают ошибки ввода-вывода при чтении файла + */ + @Test + void testWriteToFile_WithQuoteCorrect() throws IOException { + CSVWriter csvWriter = new CSVWriter(); + List testData = Arrays.asList( + new Person("John, Jr.", "Doe\"Smith", 1, Months.APRIL, 2003) + ); + + String fileName = "special_chars_test.csv"; + File outputFile = new File("outputs", fileName); + + csvWriter.writeToFile(testData, fileName); + + assertTrue(outputFile.exists(), "File should be created"); + + String fileContent = new String(Files.readAllBytes(outputFile.toPath())); + String[] lines = fileContent.split("\n"); + + String firstDataLine = lines[1]; + assertTrue(firstDataLine.contains("\"John, Jr.\"")); + assertTrue(firstDataLine.contains("\"Doe\"\"Smith\"")); + + List fileLines = Files.readAllLines(outputFile.toPath(), StandardCharsets.UTF_8); + assertEquals(2, fileLines.size()); + + assertTrue(fileLines.get(1).startsWith("\"John, Jr.\",\"Doe\"\"Smith\",1,APRIL,2003")); + } + + /** + * Тестирует поведение метода при передаче пустого списка данных. + * Ожидается выброс исключения IllegalArgumentException с соответствующим сообщением. + */ + @Test + void testWriteToFile_WithEmptyList_ThrowsException() { + CSVWriter csvWriter = new CSVWriter(); + List emptyData = Arrays.asList(); + + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, + () -> csvWriter.writeToFile(emptyData, "empty_test.csv")); + + assertEquals("List of data cant be null or empty", exception.getMessage()); + } + + /** + * Тестирует поведение метода при передаче null в качестве списка данных. + * Ожидается выброс исключения IllegalArgumentException с соответствующим сообщением. + */ + @Test + void testWriteToFile_WithNullList_ThrowsException() { + CSVWriter csvWriter = new CSVWriter(); + + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, + () -> csvWriter.writeToFile(null, "null_test.csv")); + + assertEquals("List of data cant be null or empty", exception.getMessage()); + } + + /** + * Тестирует создание выходной директории, если она не существует. + * Проверяет, что директория создается и файл сохраняется в правильном расположении. + * + * @throws IOException если возникают ошибки ввода-вывода при проверке существования файла + */ + @Test + void testWriteToFile_CreatesOutputDirectory() throws IOException { + CSVWriter csvWriter = new CSVWriter(); + List testData = Arrays.asList( + new Person("John", "Doe", 1, Months.APRIL, 2003) + ); + + String fileName = "test_output.csv"; + File outputFile = new File("outputs", fileName); + + csvWriter.writeToFile(testData, fileName); + + assertTrue(outputFile.exists(), "Output directory should be created"); + assertTrue(outputFile.exists(), "File should be created in custom directory"); + } + + /** + * Тестирует соблюдение порядка полей в выходном CSV файле. + * Проверяет, что заголовки колонок соответствуют ожидаемому порядку. + * + * @throws IOException если возникают ошибки ввода-вывода при чтении файла + */ + @Test + void testWriteToFile_FieldOrderRespected() throws IOException { + CSVWriter csvWriter = new CSVWriter(); + List testData = Arrays.asList( + new Person("John", "Doe", 1, Months.APRIL, 2003), + new Person("Jane", "Smith", 12, Months.AUGUST, 1998), + new Person("Rex", "Miller", 10, Months.SEPTEMBER, 1990) + ); + + String fileName = "test_output.csv"; + File outputFile = new File("outputs", fileName); + + csvWriter.writeToFile(testData, fileName); + List lines = Files.readAllLines(outputFile.toPath()); + String header = lines.get(0); + + String[] columns = header.split(","); + assertEquals("Имя", columns[0]); + assertEquals("Фамилия", columns[1]); + assertEquals("День рождения", columns[2]); + assertEquals("Месяц рождения", columns[3]); + assertEquals("Год рождения", columns[4]); + } + +} \ No newline at end of file