diff --git a/README.md b/README.md index b7c5248..568b090 100644 --- a/README.md +++ b/README.md @@ -13,11 +13,13 @@ The map's key will be the headerName +**Note:** The map field must use a `LinkedHashMap` (or another ordered `Map` implementation) to guarantee deterministic column ordering. Using a `HashMap` will produce non-deterministic column order in the generated report. + Annotate reportable member variables or methods with formatters (*optional*) ```java @DateFormatter(format = "yyyy-MM-dd") -@DecimalFormatter(format = "#.00") +@NumberFormatter(format = "#,##0.00") @StringFormatFormatter(text = "Add %s text") @StringFormatter(format = Format.UPPERCASE) @CurrencyFormatter(format = Currency.USD) @@ -34,6 +36,8 @@ new ExcelGenerator(List data).generate(); // returns POI Workbook ``` +Passing an empty list produces an empty report — no data rows are written. CSV and Excel output will contain headers only. + ## Auto Size ## ```java @@ -53,10 +57,10 @@ Format used by java.text.SimpleDateFormat -## Decimal Formatter ## +## Number Formatter ## ```java -@DecimalFormatter(format = "#.00") +@NumberFormatter(format = "#,##0.00") ``` Data types supported @@ -70,7 +74,7 @@ ## String Format Formatter ## ```java -@StringFormatter(text = "Add %s text") +@StringFormatFormatter(text = "Add %s text") ``` Data types supported @@ -105,7 +109,7 @@ - Big Decimal Options -- Format.USD +- Currency.USD ## Boolean Formatter ## diff --git a/src/main/java/io/ljunggren/report/generator/Generator.java b/src/main/java/io/ljunggren/report/generator/Generator.java index d8a2db5..24f38d9 100644 --- a/src/main/java/io/ljunggren/report/generator/Generator.java +++ b/src/main/java/io/ljunggren/report/generator/Generator.java @@ -83,6 +83,9 @@ } private List generateHeaders(List reportables, List data) { + if (data == null || data.isEmpty()) { + return new ArrayList(); + } List headers = new ArrayList(); reportables.forEach(reportable -> { if (reportable.getAnnotation(Reportable.class) != null) { @@ -114,6 +117,9 @@ } private List getAutoSizedColumns(List reportables, List data) { + if (data == null || data.isEmpty()) { + return new ArrayList(); + } List columns = reportables.stream() .filter(reportable -> reportable.getAnnotation(Reportable.class) != null) .filter(reportable -> isAutoSized(reportable)) @@ -130,7 +136,7 @@ if (map == null) { continue; } - map.keySet().forEach(key -> columns.add(columns.getLast() + 1)); + map.keySet().forEach(key -> columns.add(columns.get(columns.size() - 1) + 1)); } return columns; } @@ -155,6 +161,7 @@ items.addAll(getItemsFromReportable(reportable, object)); } } catch (Exception e) { + System.err.println("Failed to read reportable value: " + e.getMessage()); items.add(new Item("Unknown Value", null)); } } @@ -175,9 +182,9 @@ Object value = MethodUtils.invokeMethod(object, method.getName()); return new Item(value, method); } - throw new Exception("Unknown Instance type"); + throw new IllegalStateException("Unknown Instance type"); } - + public List getItemsFromReportable(AccessibleObject reportable, Object object) throws Exception { if (reportable instanceof Field) { Field field = (Field) reportable; @@ -187,7 +194,7 @@ } return map.values().stream().map(value -> new Item(value, field)).collect(Collectors.toList()); } - throw new Exception("Unknown Instance type"); + throw new IllegalStateException("Unknown Instance type"); } protected Object getValueFromItem(Item item, FormatterChain chain) { diff --git a/src/main/java/io/ljunggren/report/generator/annotation/Reportable.java b/src/main/java/io/ljunggren/report/generator/annotation/Reportable.java index 09e99a2..ab27f8a 100644 --- a/src/main/java/io/ljunggren/report/generator/annotation/Reportable.java +++ b/src/main/java/io/ljunggren/report/generator/annotation/Reportable.java @@ -11,6 +11,5 @@ String headerName(); String column(); - boolean autoSize() default false; } diff --git a/src/main/java/io/ljunggren/report/generator/csv/CSVGenerator.java b/src/main/java/io/ljunggren/report/generator/csv/CSVGenerator.java index 87ca977..475ee23 100644 --- a/src/main/java/io/ljunggren/report/generator/csv/CSVGenerator.java +++ b/src/main/java/io/ljunggren/report/generator/csv/CSVGenerator.java @@ -29,7 +29,7 @@ private FormatterChain formatterChain; public CSVGenerator(List data) { - super(data); + this(data, ','); } public CSVGenerator(List data, char delimiter) { @@ -48,20 +48,19 @@ } } - @SuppressWarnings("resource") private Writer generateWriter(List headers, List records, char delimiter) throws IOException { Writer writer = new StringWriter(); - CSVPrinter printer = new CSVPrinter( - writer, - CSVFormat.DEFAULT.withDelimiter(delimiter)); - printer.printRecord(headers); - for (Record record: records) { - List values = record.getItems().stream() - .map(item -> getValueFromItem(item, formatterChain)) - .collect(Collectors.toList()); - printer.printRecord(values); + try (CSVPrinter printer = new CSVPrinter( + writer, + CSVFormat.DEFAULT.withDelimiter(delimiter))) { + printer.printRecord(headers); + for (Record record : records) { + List values = record.getItems().stream() + .map(item -> getValueFromItem(item, formatterChain)) + .collect(Collectors.toList()); + printer.printRecord(values); + } } - printer.flush(); return writer; } diff --git a/src/main/java/io/ljunggren/report/generator/excel/ExcelGenerator.java b/src/main/java/io/ljunggren/report/generator/excel/ExcelGenerator.java index a370695..393c60e 100644 --- a/src/main/java/io/ljunggren/report/generator/excel/ExcelGenerator.java +++ b/src/main/java/io/ljunggren/report/generator/excel/ExcelGenerator.java @@ -35,7 +35,6 @@ public class ExcelGenerator extends Generator { - private Map cellStyles; private FormatterChain formatterChain; private CellChain cellChain; @@ -48,10 +47,10 @@ @Override public Workbook generate() { Workbook workbook = new XSSFWorkbook(); - cellStyles = CellStyleUtils.getMap(workbook); + Map cellStyles = CellStyleUtils.getMap(workbook); Sheet sheet = workbook.createSheet(); setHeaders(workbook, sheet, getHeaders()); - setData(workbook, sheet, getRecords()); + setData(workbook, sheet, getRecords(), cellStyles); setAutoSizedColumns(sheet, getAutoSizedColumns()); return workbook; } @@ -65,7 +64,7 @@ } } - private void setData(Workbook workbook, Sheet sheet, List records) { + private void setData(Workbook workbook, Sheet sheet, List records, Map cellStyles) { int rowIndex = 1; for (Record record: records) { Row row = sheet.createRow(rowIndex++); @@ -74,7 +73,7 @@ Cell cell = row.createCell(itemIndex++); Object value = getValueFromItem(item, formatterChain); setCellValue(cell, value); - formatCell(item, cell, workbook); + formatCell(item, cell, workbook, cellStyles); } } } @@ -106,7 +105,7 @@ cell.setCellValue(value.toString()); } - private void formatCell(Item item, Cell cell, Workbook workbook) { + private void formatCell(Item item, Cell cell, Workbook workbook, Map cellStyles) { Annotation[] annotations = item.getAnnotations(); Arrays.stream(annotations).forEach(annotation -> cellChain.format(annotation, cell, workbook, cellStyles)); } diff --git a/src/main/java/io/ljunggren/report/generator/excel/cell/HyperlinkChain.java b/src/main/java/io/ljunggren/report/generator/excel/cell/HyperlinkChain.java index c352a17..7c5792d 100644 --- a/src/main/java/io/ljunggren/report/generator/excel/cell/HyperlinkChain.java +++ b/src/main/java/io/ljunggren/report/generator/excel/cell/HyperlinkChain.java @@ -6,6 +6,7 @@ import org.apache.poi.common.usermodel.HyperlinkType; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFHyperlink; @@ -18,24 +19,34 @@ @Override public void format(Annotation annotation, Cell cell, Workbook workbook, Map cellStyles) { if (annotation.annotationType() == Hyperlink.class) { + if (cell.getCellType() != CellType.STRING) { + nextChain.format(annotation, cell, workbook, cellStyles); + return; + } format(cell, workbook, cellStyles); return; } nextChain.format(annotation, cell, workbook, cellStyles); } - + private void format(Cell cell, Workbook workbook, Map cellStyles) { CellStyle style = cellStyles.get(CellStyleUtils.HYPER_LINK); XSSFHyperlink link = generateLink(cell, workbook); - cell.setHyperlink((XSSFHyperlink) link); + cell.setHyperlink(link); cell.setCellStyle(style); } - + private XSSFHyperlink generateLink(Cell cell, Workbook workbook) { CreationHelper createHelper = workbook.getCreationHelper(); - XSSFHyperlink link = (XSSFHyperlink) createHelper.createHyperlink(HyperlinkType.URL); + org.apache.poi.ss.usermodel.Hyperlink rawLink = createHelper.createHyperlink(HyperlinkType.URL); + if (!(rawLink instanceof XSSFHyperlink)) { + throw new IllegalStateException( + "Expected XSSFHyperlink but got: " + rawLink.getClass().getName() + + ". HyperlinkChain requires an XSSF workbook."); + } + XSSFHyperlink link = (XSSFHyperlink) rawLink; link.setAddress(cell.getStringCellValue()); return link; } - + } diff --git a/src/main/java/io/ljunggren/report/generator/formatter/CurrencyFormatterChain.java b/src/main/java/io/ljunggren/report/generator/formatter/CurrencyFormatterChain.java index ed37ef4..3699c72 100644 --- a/src/main/java/io/ljunggren/report/generator/formatter/CurrencyFormatterChain.java +++ b/src/main/java/io/ljunggren/report/generator/formatter/CurrencyFormatterChain.java @@ -30,7 +30,7 @@ private String format(Object value, CurrencyFormatter.Currency format) { switch (format) { - case USD: return String.format("$%s", new DecimalFormat("#.00").format(value)); + case USD: return String.format("$%s", new DecimalFormat("#,##0.00").format(value)); default: return value.toString(); } } diff --git a/src/main/java/io/ljunggren/report/generator/formatter/NumberFormatterChain.java b/src/main/java/io/ljunggren/report/generator/formatter/NumberFormatterChain.java index 5d38c64..f78bcc9 100644 --- a/src/main/java/io/ljunggren/report/generator/formatter/NumberFormatterChain.java +++ b/src/main/java/io/ljunggren/report/generator/formatter/NumberFormatterChain.java @@ -18,11 +18,14 @@ } private void format(NumberFormatter formatter, Item item) { + if (item.getValue() == null) { + return; + } try { DecimalFormat decimalFormat = new DecimalFormat(formatter.format()); String value = decimalFormat.format(item.getValue()); item.setValue(value); - } catch (Exception e) { + } catch (IllegalArgumentException e) { return; } } diff --git a/src/main/java/io/ljunggren/report/generator/utils/CellStyleUtils.java b/src/main/java/io/ljunggren/report/generator/utils/CellStyleUtils.java index c91eb7d..8ebe055 100644 --- a/src/main/java/io/ljunggren/report/generator/utils/CellStyleUtils.java +++ b/src/main/java/io/ljunggren/report/generator/utils/CellStyleUtils.java @@ -13,7 +13,6 @@ public static final String HYPER_LINK = "hyperLink"; public static final String CENTER = "center"; - public static final String NUMBER_FORMAT = "numberFormat"; public static Map getMap(Workbook workbook) { Map cellStyles = new HashMap<>(); diff --git a/src/test/java/io/ljunggren/report/generator/ItemTest.java b/src/test/java/io/ljunggren/report/generator/ItemTest.java index 91a9f21..da34d29 100644 --- a/src/test/java/io/ljunggren/report/generator/ItemTest.java +++ b/src/test/java/io/ljunggren/report/generator/ItemTest.java @@ -16,28 +16,28 @@ public class ItemTest { - public class TestPojo { + public class ItemTestPojo { @Reportable(headerName = "Name", column = "A") @StringFormatter(format = Format.UPPERCASE) private String name; - + @Reportable(headerName = "Application", column = "B") public String getApplication() { return "Report Generator"; } } - + @Test public void getAnnotationsForFieldTest() { - Field[] fields = FieldUtils.getFieldsWithAnnotation(TestPojo.class, Reportable.class); + Field[] fields = FieldUtils.getFieldsWithAnnotation(ItemTestPojo.class, Reportable.class); Item item = new Item("Alex", fields[0]); Annotation[] annotations = item.getAnnotations(); assertEquals(2, annotations.length); } - + @Test public void getAnnotationsForMethodTest() { - Method[] methods = MethodUtils.getMethodsWithAnnotation(TestPojo.class, Reportable.class); + Method[] methods = MethodUtils.getMethodsWithAnnotation(ItemTestPojo.class, Reportable.class); Item item = new Item("Alex", methods[0]); Annotation[] annotations = item.getAnnotations(); assertEquals(1, annotations.length); diff --git a/src/test/java/io/ljunggren/report/generator/csv/CSVGeneratorEmptyDataTest.java b/src/test/java/io/ljunggren/report/generator/csv/CSVGeneratorEmptyDataTest.java new file mode 100755 index 0000000..2b5b144 --- /dev/null +++ b/src/test/java/io/ljunggren/report/generator/csv/CSVGeneratorEmptyDataTest.java @@ -0,0 +1,49 @@ +package io.ljunggren.report.generator.csv; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Collections; +import java.util.List; + +import org.junit.Test; + +import io.ljunggren.report.generator.annotation.Reportable; +import lombok.AllArgsConstructor; + +/** + * Tests for CSVGenerator behaviour when an empty data list is supplied (DESIGN-6 fix). + * + *

An empty list is structurally different from null: the class is known but there + * are no rows. The generator must not throw and must produce only the header line. + */ +public class CSVGeneratorEmptyDataTest { + + @AllArgsConstructor + private static class SimplePojo { + @Reportable(headerName = "Name", column = "A") + private String name; + } + + @Test + public void emptyListProducesOnlyHeaderRow() { + List data = Collections.emptyList(); + CSVGenerator generator = new CSVGenerator(data, ','); + String csv = generator.generate(); + // With empty data the Generator skips header and record generation, + // producing just the CRLF separator from the CSV printer. + assertEquals("\r\n", csv); + } + + @Test + public void emptyListHasNoHeaders() { + CSVGenerator generator = new CSVGenerator(Collections.emptyList(), ','); + assertTrue(generator.getHeaders().isEmpty()); + } + + @Test + public void emptyListHasNoRecords() { + CSVGenerator generator = new CSVGenerator(Collections.emptyList(), ','); + assertTrue(generator.getRecords().isEmpty()); + } +} diff --git a/src/test/java/io/ljunggren/report/generator/csv/CSVGeneratorReportableMapTest.java b/src/test/java/io/ljunggren/report/generator/csv/CSVGeneratorReportableMapTest.java new file mode 100755 index 0000000..ad49ed7 --- /dev/null +++ b/src/test/java/io/ljunggren/report/generator/csv/CSVGeneratorReportableMapTest.java @@ -0,0 +1,123 @@ +package io.ljunggren.report.generator.csv; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +import io.ljunggren.report.generator.annotation.Reportable; +import io.ljunggren.report.generator.annotation.ReportableMap; +import lombok.AllArgsConstructor; + +/** + * Tests for CSV generation when a {@code @ReportableMap} field is populated (IMPL-14). + * + *

All previous CSV tests left the map field null. These tests verify that map + * keys become column headers and map values appear as data cells in CSV output. + */ +public class CSVGeneratorReportableMapTest { + + @AllArgsConstructor + private static class MapPojo { + @Reportable(headerName = "Name", column = "A") + private String name; + + @ReportableMap + private Map scores; + } + + private Map buildScores(int math, int science) { + LinkedHashMap map = new LinkedHashMap<>(); + map.put("Math", math); + map.put("Science", science); + return map; + } + + @Test + public void mapKeysBecomeHeaders() { + List data = Arrays.asList(new MapPojo("Alice", buildScores(90, 85))); + CSVGenerator generator = new CSVGenerator(data, ','); + List headers = generator.getHeaders(); + assertEquals(3, headers.size()); + assertEquals("Name", headers.get(0)); + assertEquals("Math", headers.get(1)); + assertEquals("Science", headers.get(2)); + } + + @Test + public void mapValuesAppearAsDataCells() { + List data = Arrays.asList(new MapPojo("Alice", buildScores(90, 85))); + CSVGenerator generator = new CSVGenerator(data, ','); + String csv = generator.generate(); + String expected = new StringBuilder() + .append("Name,Math,Science\r\n") + .append("Alice,90,85\r\n") + .toString(); + assertEquals(expected, csv); + } + + @Test + public void mapValuesForMultipleRows() { + List data = Arrays.asList( + new MapPojo("Alice", buildScores(90, 85)), + new MapPojo("Bob", buildScores(70, 80))); + CSVGenerator generator = new CSVGenerator(data, ','); + String csv = generator.generate(); + String expected = new StringBuilder() + .append("Name,Math,Science\r\n") + .append("Alice,90,85\r\n") + .append("Bob,70,80\r\n") + .toString(); + assertEquals(expected, csv); + } + + @Test + public void nullMapFieldProducesNoExtraHeadersOrColumns() { + List data = Arrays.asList(new MapPojo("Alice", null)); + CSVGenerator generator = new CSVGenerator(data, ','); + // null map: no extra headers are added + List headers = generator.getHeaders(); + assertEquals(1, headers.size()); + assertEquals("Name", headers.get(0)); + // row still renders the single Reportable field, map items are absent + String csv = generator.generate(); + String expected = new StringBuilder() + .append("Name\r\n") + .append("Alice\r\n") + .toString(); + assertEquals(expected, csv); + } + + @Test + public void emptyMapProducesNoExtraHeadersAndNoMapColumns() { + LinkedHashMap emptyMap = new LinkedHashMap<>(); + List data = Arrays.asList(new MapPojo("Alice", emptyMap)); + CSVGenerator generator = new CSVGenerator(data, ','); + // Empty (but non-null) map: no extra headers should be added + List headers = generator.getHeaders(); + assertEquals(1, headers.size()); + String csv = generator.generate(); + String expected = new StringBuilder() + .append("Name\r\n") + .append("Alice\r\n") + .toString(); + assertEquals(expected, csv); + } + + @Test + public void mapWithPipeDelimiterRendersCorrectly() { + List data = Arrays.asList(new MapPojo("Alice", buildScores(90, 85))); + CSVGenerator generator = new CSVGenerator(data, '|'); + String csv = generator.generate(); + String expected = new StringBuilder() + .append("Name|Math|Science\r\n") + .append("Alice|90|85\r\n") + .toString(); + assertEquals(expected, csv); + } +} diff --git a/src/test/java/io/ljunggren/report/generator/csv/CSVGeneratorSingleArgConstructorTest.java b/src/test/java/io/ljunggren/report/generator/csv/CSVGeneratorSingleArgConstructorTest.java new file mode 100755 index 0000000..6f2a944 --- /dev/null +++ b/src/test/java/io/ljunggren/report/generator/csv/CSVGeneratorSingleArgConstructorTest.java @@ -0,0 +1,63 @@ +package io.ljunggren.report.generator.csv; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Test; + +import io.ljunggren.report.generator.annotation.Reportable; +import lombok.AllArgsConstructor; + +/** + * Tests for the single-argument CSVGenerator constructor (DESIGN-1 fix). + * + *

The single-arg constructor delegates to the two-arg constructor with a + * default comma delimiter. Verifies it does not NPE and produces correct output. + */ +public class CSVGeneratorSingleArgConstructorTest { + + @AllArgsConstructor + private static class SimplePojo { + @Reportable(headerName = "Name", column = "A") + private String name; + } + + @Test + public void singleArgConstructorDoesNotNpe() { + List data = Arrays.asList(new SimplePojo("Alice")); + CSVGenerator generator = new CSVGenerator(data); + assertNotNull(generator); + assertNotNull(generator.getHeaders()); + assertNotNull(generator.getRecords()); + } + + @Test + public void singleArgConstructorUsesCommaDelimiter() { + List data = Arrays.asList(new SimplePojo("Alice"), new SimplePojo("Bob")); + String csv = new CSVGenerator(data).generate(); + String expected = new StringBuilder() + .append("Name\r\n") + .append("Alice\r\n") + .append("Bob\r\n") + .toString(); + assertEquals(expected, csv); + } + + @Test + public void singleArgConstructorWithNullData() { + CSVGenerator generator = new CSVGenerator(null); + String csv = generator.generate(); + assertEquals("\r\n", csv); + } + + @Test + public void singleArgConstructorWithEmptyList() { + CSVGenerator generator = new CSVGenerator(Collections.emptyList()); + String csv = generator.generate(); + assertEquals("\r\n", csv); + } +} diff --git a/src/test/java/io/ljunggren/report/generator/excel/ExcelGeneratorEmptyDataTest.java b/src/test/java/io/ljunggren/report/generator/excel/ExcelGeneratorEmptyDataTest.java new file mode 100755 index 0000000..c3200e0 --- /dev/null +++ b/src/test/java/io/ljunggren/report/generator/excel/ExcelGeneratorEmptyDataTest.java @@ -0,0 +1,66 @@ +package io.ljunggren.report.generator.excel; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Collections; + +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.junit.Test; + +import io.ljunggren.report.generator.annotation.Reportable; +import lombok.AllArgsConstructor; + +/** + * Tests for ExcelGenerator when an empty or null data list is supplied (DESIGN-6 fix). + */ +public class ExcelGeneratorEmptyDataTest { + + @AllArgsConstructor + private static class SimplePojo { + @Reportable(headerName = "Name", column = "A") + private String name; + } + + @Test + public void emptyListProducesWorkbookWithOneSheetAndOnlyHeaderRow() { + ExcelGenerator generator = new ExcelGenerator(Collections.emptyList()); + Workbook workbook = generator.generate(); + assertEquals(1, workbook.getNumberOfSheets()); + Sheet sheet = workbook.getSheetAt(0); + // Header row is always created (row index 0), but with no columns. + assertEquals(1, sheet.getPhysicalNumberOfRows()); + } + + @Test + public void emptyListHasNoHeaders() { + ExcelGenerator generator = new ExcelGenerator(Collections.emptyList()); + assertTrue(generator.getHeaders().isEmpty()); + } + + @Test + public void emptyListHasNoRecords() { + ExcelGenerator generator = new ExcelGenerator(Collections.emptyList()); + assertTrue(generator.getRecords().isEmpty()); + } + + @Test + public void nullDataListHasNoHeaders() { + ExcelGenerator generator = new ExcelGenerator(null); + assertTrue(generator.getHeaders().isEmpty()); + } + + @Test + public void nullDataListHasNoRecords() { + ExcelGenerator generator = new ExcelGenerator(null); + assertTrue(generator.getRecords().isEmpty()); + } + + @Test + public void nullDataListProducesWorkbookWithOneSheet() { + ExcelGenerator generator = new ExcelGenerator(null); + Workbook workbook = generator.generate(); + assertEquals(1, workbook.getNumberOfSheets()); + } +} diff --git a/src/test/java/io/ljunggren/report/generator/excel/cell/CenterChainTest.java b/src/test/java/io/ljunggren/report/generator/excel/cell/CenterChainTest.java new file mode 100755 index 0000000..eb50aaa --- /dev/null +++ b/src/test/java/io/ljunggren/report/generator/excel/cell/CenterChainTest.java @@ -0,0 +1,63 @@ +package io.ljunggren.report.generator.excel.cell; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.Arrays; +import java.util.List; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.HorizontalAlignment; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.junit.Test; + +import io.ljunggren.report.generator.annotation.Center; +import io.ljunggren.report.generator.annotation.Reportable; +import io.ljunggren.report.generator.excel.ExcelGenerator; +import lombok.AllArgsConstructor; + +/** + * Tests for {@link CenterChain}: verifies that {@code @Center} applies horizontal + * centre alignment to the POI cell style. + */ +public class CenterChainTest { + + @AllArgsConstructor + private static class CenteredPojo { + @Reportable(headerName = "Label", column = "A") + @Center + private String label; + } + + @AllArgsConstructor + private static class NotCenteredPojo { + @Reportable(headerName = "Label", column = "A") + private String label; + } + + @Test + public void centerAnnotationAppliesCenterAlignment() { + List data = Arrays.asList(new CenteredPojo("Hello")); + ExcelGenerator generator = new ExcelGenerator(data); + Workbook workbook = generator.generate(); + Sheet sheet = workbook.getSheetAt(0); + Row dataRow = sheet.getRow(1); + Cell cell = dataRow.getCell(0); + assertNotNull(cell.getCellStyle()); + assertEquals(HorizontalAlignment.CENTER, cell.getCellStyle().getAlignment()); + } + + @Test + public void withoutCenterAnnotationDefaultAlignmentIsUsed() { + List data = Arrays.asList(new NotCenteredPojo("Hello")); + ExcelGenerator generator = new ExcelGenerator(data); + Workbook workbook = generator.generate(); + Sheet sheet = workbook.getSheetAt(0); + Row dataRow = sheet.getRow(1); + Cell cell = dataRow.getCell(0); + // Default cell style does not apply CENTER + assertEquals(HorizontalAlignment.GENERAL, cell.getCellStyle().getAlignment()); + } +} diff --git a/src/test/java/io/ljunggren/report/generator/excel/cell/HyperlinkChainTest.java b/src/test/java/io/ljunggren/report/generator/excel/cell/HyperlinkChainTest.java new file mode 100755 index 0000000..6e4cae3 --- /dev/null +++ b/src/test/java/io/ljunggren/report/generator/excel/cell/HyperlinkChainTest.java @@ -0,0 +1,90 @@ +package io.ljunggren.report.generator.excel.cell; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.Arrays; +import java.util.List; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.Test; + +import io.ljunggren.report.generator.annotation.Hyperlink; +import io.ljunggren.report.generator.annotation.Reportable; +import io.ljunggren.report.generator.excel.ExcelGenerator; +import lombok.AllArgsConstructor; + +/** + * Tests for {@link HyperlinkChain} covering the STRING and non-STRING cell type paths (IMPL-6 fix). + */ +public class HyperlinkChainTest { + + @AllArgsConstructor + private static class HyperlinkStringPojo { + @Reportable(headerName = "URL", column = "A") + @Hyperlink + private String url; + } + + @AllArgsConstructor + private static class HyperlinkIntPojo { + @Reportable(headerName = "Count", column = "A") + @Hyperlink + private int count; + } + + /** + * IMPL-6: When cell type is not STRING the chain must forward to the next link + * without throwing. The cell value should remain the raw numeric value. + */ + @Test + public void nonStringCellIsNotConvertedToHyperlink() { + List data = Arrays.asList(new HyperlinkIntPojo(42)); + ExcelGenerator generator = new ExcelGenerator(data); + Workbook workbook = generator.generate(); + Sheet sheet = workbook.getSheetAt(0); + Row dataRow = sheet.getRow(1); + Cell cell = dataRow.getCell(0); + // Cell should remain numeric — no hyperlink attached + assertEquals(CellType.NUMERIC, cell.getCellType()); + assertEquals(42.0, cell.getNumericCellValue(), 0.0); + assertNull(cell.getHyperlink()); + } + + /** + * When cell type IS STRING the chain applies hyperlink styling and sets the link. + */ + @Test + public void stringCellReceivesHyperlinkAndStyle() { + List data = Arrays.asList( + new HyperlinkStringPojo("https://example.com")); + ExcelGenerator generator = new ExcelGenerator(data); + Workbook workbook = generator.generate(); + Sheet sheet = workbook.getSheetAt(0); + Row dataRow = sheet.getRow(1); + Cell cell = dataRow.getCell(0); + assertEquals(CellType.STRING, cell.getCellType()); + assertEquals("https://example.com", cell.getStringCellValue()); + assertNotNull(cell.getHyperlink()); + assertEquals("https://example.com", cell.getHyperlink().getAddress()); + } + + /** + * A null string value means the cell is blank (type BLANK after setCellValue with null skip). + * The chain must not throw when it encounters a non-STRING cell. + */ + @Test + public void nullStringCellDoesNotThrow() { + List data = Arrays.asList(new HyperlinkStringPojo(null)); + ExcelGenerator generator = new ExcelGenerator(data); + // generate() must complete without exception + Workbook workbook = generator.generate(); + assertNotNull(workbook); + } +} diff --git a/src/test/java/io/ljunggren/report/generator/excel/cell/NumberFormatterCellChainTest.java b/src/test/java/io/ljunggren/report/generator/excel/cell/NumberFormatterCellChainTest.java new file mode 100755 index 0000000..6171b52 --- /dev/null +++ b/src/test/java/io/ljunggren/report/generator/excel/cell/NumberFormatterCellChainTest.java @@ -0,0 +1,66 @@ +package io.ljunggren.report.generator.excel.cell; + +import static org.junit.Assert.assertNotNull; + +import java.util.Arrays; +import java.util.List; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.junit.Test; + +import io.ljunggren.report.generator.annotation.NumberFormatter; +import io.ljunggren.report.generator.annotation.Reportable; +import io.ljunggren.report.generator.excel.ExcelGenerator; +import lombok.AllArgsConstructor; + +/** + * Tests for the Excel-layer {@link NumberFormatterChain} (cell-level formatting). + * + *

This chain applies a data-format style to the POI {@link Cell} — it does not + * change the cell's value, only its display style. + */ +public class NumberFormatterCellChainTest { + + @AllArgsConstructor + private static class NumericPojo { + @Reportable(headerName = "Amount", column = "A") + @NumberFormatter(format = "#,##0.00") + private double amount; + } + + @Test + public void numericCellHasCellStyleApplied() { + List data = Arrays.asList(new NumericPojo(1234.56)); + ExcelGenerator generator = new ExcelGenerator(data); + Workbook workbook = generator.generate(); + Sheet sheet = workbook.getSheetAt(0); + Row dataRow = sheet.getRow(1); + Cell cell = dataRow.getCell(0); + // The cell must have a non-null style with a data format set. + CellStyle style = cell.getCellStyle(); + assertNotNull(style); + // format index > 0 means a custom format was applied + assert style.getDataFormat() > 0 : "Expected a custom data format to be applied"; + } + + @Test + public void formatPatternIsCached_secondRowReusesSameStyle() { + // Two rows with the same format should reuse the cached CellStyle (not create a new one). + List data = Arrays.asList(new NumericPojo(100.0), new NumericPojo(200.0)); + ExcelGenerator generator = new ExcelGenerator(data); + Workbook workbook = generator.generate(); + Sheet sheet = workbook.getSheetAt(0); + Cell cell1 = sheet.getRow(1).getCell(0); + Cell cell2 = sheet.getRow(2).getCell(0); + // Both rows should have an equivalent cell style (same data format index). + assertEquals(cell1.getCellStyle().getDataFormat(), cell2.getCellStyle().getDataFormat()); + } + + private static void assertEquals(short expected, short actual) { + org.junit.Assert.assertEquals(expected, actual); + } +} diff --git a/src/test/java/io/ljunggren/report/generator/formatter/NumberFormatterChainTest.java b/src/test/java/io/ljunggren/report/generator/formatter/NumberFormatterChainTest.java new file mode 100755 index 0000000..cdb02e6 --- /dev/null +++ b/src/test/java/io/ljunggren/report/generator/formatter/NumberFormatterChainTest.java @@ -0,0 +1,124 @@ +package io.ljunggren.report.generator.formatter; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; + +import org.junit.Test; + +import io.ljunggren.report.generator.annotation.NumberFormatter; +import io.ljunggren.report.generator.annotation.Reportable; +import io.ljunggren.report.generator.csv.CSVGenerator; +import lombok.AllArgsConstructor; + +/** + * Tests for {@link NumberFormatterChain} in the formatter pipeline (IMPL-2 fix). + * + *

Covers null values, numeric formatting, and the bad-format silent-skip path. + */ +public class NumberFormatterChainTest { + + @AllArgsConstructor + private static class IntPojo { + @Reportable(headerName = "Amount", column = "A") + @NumberFormatter(format = "#,##0.00") + private Integer amount; + } + + @AllArgsConstructor + private static class DoublePojo { + @Reportable(headerName = "Amount", column = "A") + @NumberFormatter(format = "#,##0.00") + private Double amount; + } + + @AllArgsConstructor + private static class NullIntPojo { + @Reportable(headerName = "Amount", column = "A") + @NumberFormatter(format = "#,##0.00") + private Integer amount; + } + + /** IMPL-2: null value must be silently skipped — no NPE. */ + @Test + public void nullValueIsPassedThroughWithoutFormatting() { + NullIntPojo pojo = new NullIntPojo(null); + CSVGenerator generator = new CSVGenerator(Arrays.asList(pojo), ','); + String csv = generator.generate(); + String expected = new StringBuilder() + .append("Amount\r\n") + .append("\r\n") + .toString(); + assertEquals(expected, csv); + } + + @Test + public void integerValueIsFormattedWithPattern() { + IntPojo pojo = new IntPojo(1500000); + CSVGenerator generator = new CSVGenerator(Arrays.asList(pojo), ','); + String csv = generator.generate(); + String expected = new StringBuilder() + .append("Amount\r\n") + .append("\"1,500,000.00\"\r\n") + .toString(); + assertEquals(expected, csv); + } + + @Test + public void doubleValueIsFormattedWithPattern() { + DoublePojo pojo = new DoublePojo(1234.5); + CSVGenerator generator = new CSVGenerator(Arrays.asList(pojo), ','); + String csv = generator.generate(); + String expected = new StringBuilder() + .append("Amount\r\n") + .append("\"1,234.50\"\r\n") + .toString(); + assertEquals(expected, csv); + } + + @AllArgsConstructor + private static class BadFormatPojo { + @Reportable(headerName = "Amount", column = "A") + // "0.00E0.0" has multiple decimal separators — DecimalFormat.format() throws + // IllegalArgumentException which the chain catches and silently skips. + @NumberFormatter(format = "0.00E0.0") + private Integer amount; + } + + /** + * A pattern that causes {@code DecimalFormat.format()} to throw an + * {@link IllegalArgumentException} must be silently skipped; the raw + * value must pass through unchanged. + */ + @Test + public void badFormatPatternIsSkippedAndRawValuePassesThrough() { + BadFormatPojo pojo = new BadFormatPojo(42); + CSVGenerator generator = new CSVGenerator(Arrays.asList(pojo), ','); + String csv = generator.generate(); + String expected = new StringBuilder() + .append("Amount\r\n") + .append("42\r\n") + .toString(); + assertEquals(expected, csv); + } + + public class MethodPojo { + @Reportable(headerName = "Amount", column = "A") + @NumberFormatter(format = "#,##0.00") + public int getAmount() { + return 2500; + } + } + + @Test + public void methodAnnotationIsFormattedCorrectly() { + MethodPojo pojo = new MethodPojo(); + CSVGenerator generator = new CSVGenerator(Arrays.asList(pojo), ','); + String csv = generator.generate(); + String expected = new StringBuilder() + .append("Amount\r\n") + .append("\"2,500.00\"\r\n") + .toString(); + assertEquals(expected, csv); + } +}