001package com.streamconverter.examples;
002
003import com.streamconverter.StreamConverter;
004import com.streamconverter.command.impl.SampleStreamCommand;
005import com.streamconverter.command.impl.csv.CsvValidateCommand;
006import java.io.ByteArrayInputStream;
007import java.io.ByteArrayOutputStream;
008import java.io.IOException;
009import java.nio.charset.StandardCharsets;
010import org.slf4j.Logger;
011import org.slf4j.LoggerFactory;
012
013/**
014 * バリデーション機能のデモンストレーション
015 *
016 * <p>JSON、XML、CSVの各形式に対するバリデーション機能と、 ValidationDecoratorの使用方法を示します。
017 */
018public class ValidationExample {
019  private static final Logger logger = LoggerFactory.getLogger(ValidationExample.class);
020
021  /**
022   * メインメソッド
023   *
024   * @param args コマンドライン引数
025   */
026  public static void main(String[] args) {
027    logger.info("🔍 Validation Feature Demonstration");
028    logger.info("====================================\n");
029
030    try {
031      // JSON バリデーションのデモ
032      demonstrateJsonValidation();
033
034      // CSV バリデーションのデモ
035      demonstrateCsvValidation();
036
037      // バリデーション結果の確認デモ
038      demonstrateValidationResult();
039
040    } catch (Exception e) {
041      logger.error("Validation demonstration failed: {}", e.getMessage(), e);
042    }
043  }
044
045  /** JSONバリデーションのデモ */
046  private static void demonstrateJsonValidation() throws IOException {
047    logger.info("📄 JSON Validation Demonstration");
048    logger.info("================================");
049
050    // 有効なJSONデータ
051    String validJsonData =
052        """
053        {
054          "name": "John Doe",
055          "age": 30,
056          "email": "john@example.com"
057        }
058        """;
059
060    // 無効なJSONデータ(フィールド不足)
061    String invalidJsonData =
062        """
063        {
064          "name": "Jane Doe"
065        }
066        """;
067
068    logger.info("📥 Valid JSON data processing...");
069    try {
070      processWithCsvValidation(validJsonData, "Valid JSON");
071      logger.info("✅ Valid JSON processed successfully");
072    } catch (Exception e) {
073      logger.error("❌ Valid JSON processing failed: {}", e.getMessage());
074    }
075
076    logger.info("\n📥 Invalid JSON data processing...");
077    try {
078      processWithCsvValidation(invalidJsonData, "Invalid JSON");
079      logger.info("✅ Invalid JSON processed successfully (unexpected!)");
080    } catch (Exception e) {
081      logger.info("❌ Invalid JSON processing failed as expected: {}", e.getMessage());
082    }
083
084    logger.info("\n" + "=".repeat(50) + "\n");
085  }
086
087  /** CSVバリデーションのデモ */
088  private static void demonstrateCsvValidation() throws IOException {
089    logger.info("📊 CSV Validation Demonstration");
090    logger.info("===============================");
091
092    // 有効なCSVデータ
093    String validCsvData =
094        """
095        id,name,email
096        1,John Doe,john@example.com
097        2,Jane Smith,jane@example.com
098        """;
099
100    // 無効なCSVデータ(必須カラム不足)
101    String invalidCsvData =
102        """
103        id,name
104        1,John Doe
105        2,Jane Smith
106        """;
107
108    String[] requiredColumns = {"id", "name", "email"};
109
110    logger.info("📥 Valid CSV data processing...");
111    try {
112      processWithCsvValidation(validCsvData, requiredColumns, "Valid CSV");
113      logger.info("✅ Valid CSV processed successfully");
114    } catch (Exception e) {
115      logger.error("❌ Valid CSV processing failed: {}", e.getMessage());
116    }
117
118    logger.info("\n📥 Invalid CSV data processing...");
119    try {
120      processWithCsvValidation(invalidCsvData, requiredColumns, "Invalid CSV");
121      logger.info("✅ Invalid CSV processed successfully (unexpected!)");
122    } catch (Exception e) {
123      logger.info("❌ Invalid CSV processing failed as expected: {}", e.getMessage());
124    }
125
126    logger.info("\n" + "=".repeat(50) + "\n");
127  }
128
129  /** バリデーション結果の詳細確認デモ */
130  private static void demonstrateValidationResult() throws IOException {
131    logger.info("📋 Validation Result Demonstration");
132    logger.info("==================================");
133
134    String csvData =
135        """
136        id,name,email
137        1,John Doe,john@example.com
138        """;
139
140    String[] requiredColumns = {"id", "name", "email"};
141
142    // CsvValidateCommandを直接使用してバリデーション実行
143    CsvValidateCommand csvValidator = new CsvValidateCommand(requiredColumns);
144    SampleStreamCommand dataProcessor = new SampleStreamCommand("validation-demo");
145
146    ByteArrayInputStream inputStream =
147        new ByteArrayInputStream(csvData.getBytes(StandardCharsets.UTF_8));
148    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
149
150    try {
151      // バリデーション実行
152      ByteArrayInputStream csvValidationInputStream =
153          new ByteArrayInputStream(csvData.getBytes(StandardCharsets.UTF_8));
154      csvValidator.consume(csvValidationInputStream);
155      logger.info("📊 CSV validation completed successfully");
156
157      // データ処理実行
158      dataProcessor.execute(inputStream, outputStream);
159      logger.info("✅ Data processing completed successfully");
160
161    } catch (Exception e) {
162      logger.error("❌ Validation or processing failed: {}", e.getMessage());
163    }
164
165    logger.info("\n" + "=".repeat(50) + "\n");
166  }
167
168  /** CSVバリデーション付きでデータを処理 */
169  private static void processWithCsvValidation(String data, String description) throws IOException {
170    processWithCsvValidation(data, new String[0], description);
171  }
172
173  /** CSVバリデーション付きでデータを処理 */
174  private static void processWithCsvValidation(
175      String data, String[] requiredColumns, String description) throws IOException {
176    logger.debug("Processing {}: {}", description, data.substring(0, Math.min(50, data.length())));
177
178    CsvValidateCommand csvValidator = new CsvValidateCommand(requiredColumns);
179    SampleStreamCommand processor = new SampleStreamCommand("csv-processor");
180
181    ByteArrayInputStream inputStream =
182        new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
183    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
184
185    // パイプラインでバリデーションと処理を実行
186    StreamConverter converter = StreamConverter.create(csvValidator, processor);
187    converter.run(inputStream, outputStream);
188
189    String result = outputStream.toString(StandardCharsets.UTF_8);
190    logger.debug("Processing result: {}", result.trim());
191  }
192}