|
| 1 | +/* |
| 2 | + * Copyright (C) 2026 B3Partners B.V. |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: MIT |
| 5 | + */ |
| 6 | +package org.tailormap.api.controller; |
| 7 | + |
| 8 | +import static java.util.concurrent.TimeUnit.MINUTES; |
| 9 | +import static java.util.concurrent.TimeUnit.SECONDS; |
| 10 | +import static org.hamcrest.MatcherAssert.assertThat; |
| 11 | +import static org.hamcrest.Matchers.containsString; |
| 12 | +import static org.hamcrest.Matchers.greaterThanOrEqualTo; |
| 13 | +import static org.junit.jupiter.api.Assertions.assertAll; |
| 14 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 15 | +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; |
| 16 | +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; |
| 17 | +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; |
| 18 | +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; |
| 19 | +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; |
| 20 | +import static org.tailormap.api.TestRequestProcessor.setServletPath; |
| 21 | +import static org.tailormap.api.controller.TestUrls.layerOsmPolygonPostgis; |
| 22 | + |
| 23 | +import java.io.ByteArrayInputStream; |
| 24 | +import java.io.InputStream; |
| 25 | +import java.nio.charset.StandardCharsets; |
| 26 | +import java.util.HashMap; |
| 27 | +import java.util.Map; |
| 28 | +import org.apache.poi.ss.usermodel.CellType; |
| 29 | +import org.apache.poi.ss.usermodel.Sheet; |
| 30 | +import org.apache.poi.ss.usermodel.Workbook; |
| 31 | +import org.apache.poi.ss.usermodel.WorkbookFactory; |
| 32 | +import org.apache.poi.util.IOUtils; |
| 33 | +import org.awaitility.Awaitility; |
| 34 | +import org.junit.jupiter.api.BeforeEach; |
| 35 | +import org.junit.jupiter.api.MethodOrderer; |
| 36 | +import org.junit.jupiter.api.Test; |
| 37 | +import org.junit.jupiter.api.TestMethodOrder; |
| 38 | +import org.junit.jupiter.api.parallel.Execution; |
| 39 | +import org.junit.jupiter.api.parallel.ExecutionMode; |
| 40 | +import org.junitpioneer.jupiter.Issue; |
| 41 | +import org.junitpioneer.jupiter.Stopwatch; |
| 42 | +import org.springframework.beans.factory.annotation.Autowired; |
| 43 | +import org.springframework.beans.factory.annotation.Value; |
| 44 | +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; |
| 45 | +import org.springframework.http.MediaType; |
| 46 | +import org.springframework.test.web.servlet.MockMvc; |
| 47 | +import org.springframework.test.web.servlet.MvcResult; |
| 48 | +import org.tailormap.api.annotation.PostgresIntegrationTest; |
| 49 | + |
| 50 | +@PostgresIntegrationTest |
| 51 | +@AutoConfigureMockMvc |
| 52 | +@Execution(ExecutionMode.CONCURRENT) |
| 53 | +@Issue("HTM-2017: Large Excel export takes long time") |
| 54 | +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) |
| 55 | +class LayerExtractControllerLargeExcelIntegrationTest extends SseParsingUtils { |
| 56 | + private static final String extractPath = "/extract/"; |
| 57 | + private static final String downloadPath = "/extract/download/"; |
| 58 | + // Use a unique clientId per test instance to avoid cross-test interference |
| 59 | + // when running concurrently. |
| 60 | + private final String sseClientId = "testcase-" + System.nanoTime(); |
| 61 | + |
| 62 | + @Autowired |
| 63 | + private MockMvc mockMvc; |
| 64 | + |
| 65 | + @Value("${tailormap-api.base-path}") |
| 66 | + private String apiBasePath; |
| 67 | + |
| 68 | + /** SSE connection result; its response buffer accumulates server-sent events. */ |
| 69 | + private MvcResult sseResult; |
| 70 | + |
| 71 | + @BeforeEach |
| 72 | + void start_sse_stream() throws Exception { |
| 73 | + final String sseUrl = apiBasePath + "/events/" + sseClientId; |
| 74 | + sseResult = mockMvc.perform(get(sseUrl) |
| 75 | + .accept(MediaType.TEXT_EVENT_STREAM) |
| 76 | + .with(setServletPath(sseUrl)) |
| 77 | + .acceptCharset(StandardCharsets.UTF_8)) |
| 78 | + .andExpect(request().asyncStarted()) |
| 79 | + .andReturn(); |
| 80 | + } |
| 81 | + |
| 82 | + @Stopwatch |
| 83 | + @Test |
| 84 | + void should_export_large_dataset_to_excel() throws Exception { |
| 85 | + final String extractUrl = apiBasePath + layerOsmPolygonPostgis + extractPath + sseClientId; |
| 86 | + mockMvc.perform(post(extractUrl) |
| 87 | + .accept(MediaType.APPLICATION_JSON) |
| 88 | + .with(setServletPath(extractUrl)) |
| 89 | + .with(csrf()) |
| 90 | + .param( |
| 91 | + "attributes", |
| 92 | + "osm_id,access,addr:housename,addr:housenumber,addr:interpolation,admin_level,aerialway,aeroway,amenity,area,barrier,bicycle,brand,bridge,boundary,building,construction,covered,culvert,cutting,denomination,disused,embankment,foot,generator:source,harbour,highway,historic,horse,intermittent,junction,landuse,layer,leisure,lock,man_made,military,motorcar,name,natural,office,oneway,operator,place,population,power,power_source,public_transport,railway,ref,religion,route,service,shop,sport,surface,toll,tourism,tower:type,tracktype,tunnel,water,waterway,wetland,width,wood,z_order,way_area") |
| 93 | + .param("outputFormat", "xlsx") |
| 94 | + .acceptCharset(StandardCharsets.UTF_8) |
| 95 | + .characterEncoding(StandardCharsets.UTF_8) |
| 96 | + .contentType(MediaType.APPLICATION_FORM_URLENCODED)) |
| 97 | + .andExpect(status().isAccepted()); |
| 98 | + |
| 99 | + // The SseEventBus may dispatch events slightly after the POST returns. |
| 100 | + // Awaitility polls the buffered SSE response until the expected content appears. |
| 101 | + Awaitility.await() |
| 102 | + .atMost(10, SECONDS) |
| 103 | + .untilAsserted(() -> assertThat( |
| 104 | + sseResult.getResponse().getContentAsString(), containsString("Extract task received"))); |
| 105 | + |
| 106 | + // should finish in less than 2 minutes |
| 107 | + Awaitility.await().pollInterval(5, SECONDS).atMost(2, MINUTES).untilAsserted(() -> { |
| 108 | + final String stream = sseResult.getResponse().getContentAsString(); |
| 109 | + assertThat(count_completed_messages(stream), greaterThanOrEqualTo(1)); |
| 110 | + }); |
| 111 | + |
| 112 | + final String lastCompletedEventJson = |
| 113 | + getLastCompletedEventJson(sseResult.getResponse().getContentAsString()); |
| 114 | + assertThat(lastCompletedEventJson.length(), greaterThanOrEqualTo(100)); |
| 115 | + |
| 116 | + final String extractedDownloadId = getDownloadId(lastCompletedEventJson); |
| 117 | + assertThat(extractedDownloadId, containsString(".xlsx")); |
| 118 | + |
| 119 | + final String downloadUrl = apiBasePath + layerOsmPolygonPostgis + downloadPath + extractedDownloadId; |
| 120 | + MvcResult download = mockMvc.perform(get(downloadUrl).with(setServletPath(downloadUrl))) |
| 121 | + .andExpect(status().isOk()) |
| 122 | + .andExpect(result -> { |
| 123 | + String contentType = result.getResponse().getContentType(); |
| 124 | + assertThat( |
| 125 | + contentType, |
| 126 | + containsString("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")); |
| 127 | + |
| 128 | + String contentDisposition = result.getResponse().getHeader("Content-Disposition"); |
| 129 | + assertThat(contentDisposition, containsString("attachment; filename=")); |
| 130 | + assertThat(contentDisposition, containsString(extractedDownloadId)); |
| 131 | + }) |
| 132 | + .andReturn(); |
| 133 | + |
| 134 | + // open the Excel file and check that we have the expected content |
| 135 | + // allow reading large files into byte arrays, this is 10x the default value |
| 136 | + int rememberMaxOverride = IOUtils.getByteArrayMaxOverride(); |
| 137 | + IOUtils.setByteArrayMaxOverride(1_000_000_000); |
| 138 | + try (InputStream inp = new ByteArrayInputStream(download.getResponse().getContentAsByteArray()); |
| 139 | + Workbook wb = WorkbookFactory.create(inp)) { |
| 140 | + |
| 141 | + Sheet sheet = wb.getSheetAt(0); |
| 142 | + |
| 143 | + assertAll( |
| 144 | + "Check sheet", |
| 145 | + () -> assertEquals( |
| 146 | + 102467 + /*header row*/ 1, |
| 147 | + sheet.getPhysicalNumberOfRows(), |
| 148 | + () -> "Expected " + 102467 + /*header row*/ 1 |
| 149 | + + " rows in the Excel sheet, including header and data rows"), |
| 150 | + () -> assertEquals("osm_polygon", sheet.getSheetName(), "Expected sheet name to be osm_polygon"), |
| 151 | + () -> assertEquals( |
| 152 | + 69, sheet.getRow(0).getPhysicalNumberOfCells(), "Expected 69 columns in the header row")); |
| 153 | + |
| 154 | + Map<String, Integer> columnNames = new HashMap<>(); |
| 155 | + sheet.getRow(0).forEach(cell -> columnNames.put(cell.getStringCellValue(), cell.getColumnIndex())); |
| 156 | + |
| 157 | + assertAll( |
| 158 | + "Check first data row", |
| 159 | + () -> assertEquals( |
| 160 | + CellType.NUMERIC, |
| 161 | + sheet.getRow(1).getCell(columnNames.get("osm_id")).getCellType(), |
| 162 | + "Expected first cell in header to be numeric"), |
| 163 | + () -> assertEquals( |
| 164 | + CellType.BLANK, |
| 165 | + sheet.getRow(1).getCell(columnNames.get("access")).getCellType(), |
| 166 | + "Expected second cell in header to be a string"), |
| 167 | + () -> assertEquals( |
| 168 | + "meadow", |
| 169 | + sheet.getRow(1).getCell(columnNames.get("landuse")).getStringCellValue()), |
| 170 | + () -> assertEquals( |
| 171 | + 68651.3, |
| 172 | + sheet.getRow(1).getCell(columnNames.get("way_area")).getNumericCellValue(), |
| 173 | + 0.1)); |
| 174 | + } finally { |
| 175 | + IOUtils.setByteArrayMaxOverride(rememberMaxOverride); |
| 176 | + } |
| 177 | + } |
| 178 | +} |
0 commit comments