1
2
3
4
5
6 package org.tailormap.api.geotools.featuresources;
7
8 import jakarta.validation.constraints.NotNull;
9 import java.io.IOException;
10 import java.lang.invoke.MethodHandles;
11 import java.nio.ByteBuffer;
12 import java.sql.Connection;
13 import java.sql.DatabaseMetaData;
14 import java.sql.PreparedStatement;
15 import java.sql.ResultSet;
16 import java.sql.SQLException;
17 import java.sql.Statement;
18 import java.sql.Timestamp;
19 import java.text.MessageFormat;
20 import java.time.OffsetDateTime;
21 import java.time.ZoneId;
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Locale;
26 import java.util.Map;
27 import java.util.UUID;
28 import java.util.regex.Pattern;
29 import java.util.stream.Collectors;
30 import org.apache.commons.dbcp.DelegatingConnection;
31 import org.geotools.api.feature.type.AttributeDescriptor;
32 import org.geotools.jdbc.JDBCDataStore;
33 import org.jspecify.annotations.NonNull;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.springframework.security.core.context.SecurityContextHolder;
37 import org.tailormap.api.persistence.TMFeatureType;
38 import org.tailormap.api.persistence.json.JDBCConnectionProperties;
39 import org.tailormap.api.viewer.model.AttachmentMetadata;
40
41
42 public final class AttachmentsHelper {
43 private static final Logger logger =
44 LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
45
46 private static final Pattern NUMERIC_WITH_IDENTITY = Pattern.compile(
47 "(?i)\\b(?:int|integer|bigint|smallint|numeric|decimal|number)(?:\\s*\\(\\s*\\d+(?:\\s*,\\s*\\d+)?\\s*\\))?\\s+identity\\b");
48
49 private static final List<String> allowedPKTypesSupportingSize = List.of(
50
51
52
53 "CHARACTER",
54 "CHARACTER VARYING",
55 "CHAR",
56 "VARCHAR",
57
58 "NUMERIC",
59 "DECIMAL",
60
61
62 "NVARCHAR",
63 "NCHAR",
64
65 "VARCHAR2",
66 "NVARCHAR2",
67 "NUMBER",
68 "RAW");
69
70 private AttachmentsHelper() {
71
72 }
73
74 private static String getPostGISCreateAttachmentsTableStatement(
75 String tableName, String pkColumnName, String fkColumnType, String typeModifier, String schemaPrefix) {
76 if (!schemaPrefix.isEmpty()) {
77 schemaPrefix += ".";
78 }
79 return MessageFormat.format("""
80 CREATE TABLE IF NOT EXISTS {4}{0}_attachments (
81 {0}_pk {2}{3} NOT NULL REFERENCES {4}{0}({1}) ON DELETE CASCADE,
82 attachment_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
83 file_name VARCHAR(255),
84 attribute_name VARCHAR(255) NOT NULL,
85 description TEXT,
86 attachment BYTEA NOT NULL,
87 attachment_size INTEGER NOT NULL,
88 mime_type VARCHAR(100),
89 created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
90 created_by VARCHAR(255) NOT NULL)
91 """, tableName, pkColumnName, fkColumnType, typeModifier, schemaPrefix);
92 }
93
94 private static String getSQLServerCreateAttachmentsTableStatement(
95 String tableName, String pkColumnName, String fkColumnType, String typeModifier, String schemaPrefix) {
96 if (!schemaPrefix.isEmpty()) {
97 schemaPrefix += ".";
98 }
99 return MessageFormat.format("""
100 IF OBJECT_ID(N''{4}{0}_attachments'', ''U'') IS NULL
101 BEGIN
102 CREATE TABLE {4}{0}_attachments (
103 {0}_pk {2}{3} NOT NULL REFERENCES {4}{0}({1}) ON DELETE CASCADE,
104 attachment_id UNIQUEIDENTIFIER NOT NULL DEFAULT NEWID() PRIMARY KEY,
105 file_name NVARCHAR(255),
106 attribute_name VARCHAR(255) NOT NULL,
107 description NVARCHAR(MAX),
108 attachment VARBINARY(MAX) NOT NULL,
109 mime_type NVARCHAR(100),
110 attachment_size INT NOT NULL,
111 created_at DATETIMEOFFSET NOT NULL DEFAULT SYSDATETIMEOFFSET(),
112 created_by NVARCHAR(255) NOT NULL)
113 END
114 """, tableName, pkColumnName, fkColumnType, typeModifier, schemaPrefix);
115 }
116
117 private static String getOracleCreateAttachmentsTableStatement(
118 String tableName, String pkColumnName, String fkColumnType, String typeModifier, String schemaPrefix) {
119 if (!schemaPrefix.isEmpty()) {
120 schemaPrefix += ".";
121 }
122
123 return MessageFormat.format("""
124 CREATE TABLE IF NOT EXISTS {4}{0}_ATTACHMENTS (
125 {0}_PK {2}{3} NOT NULL REFERENCES {4}{0}({1}) ON DELETE CASCADE,
126 ATTACHMENT_ID RAW(16) DEFAULT SYS_GUID() PRIMARY KEY,
127 FILE_NAME VARCHAR2(255),
128 ATTACHMENT BLOB NOT NULL,
129 ATTRIBUTE_NAME VARCHAR2(255) NOT NULL,
130 DESCRIPTION CLOB,
131 MIME_TYPE VARCHAR2(100),
132 ATTACHMENT_SIZE INT NOT NULL,
133 CREATED_AT TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
134 CREATED_BY VARCHAR2(255) NOT NULL)
135 """, tableName, pkColumnName, fkColumnType, typeModifier, schemaPrefix);
136 }
137
138
139
140
141
142
143
144
145
146
147 public static void createAttachmentTableForFeatureType(TMFeatureType featureType)
148 throws IOException, SQLException, IllegalArgumentException {
149 if (featureType == null
150 || featureType.getSettings() == null
151 || featureType.getSettings().getAttachmentAttributes() == null
152 || featureType.getSettings().getAttachmentAttributes().isEmpty()) {
153 throw new IllegalArgumentException("FeatureType "
154 + (featureType != null ? featureType.getName() : "null")
155 + " is invalid or has no attachment attributes defined in its settings");
156 }
157
158 featureType.getSettings().getAttachmentAttributes().stream()
159 .filter(attachmentAttributeType -> (attachmentAttributeType.getAttributeName() == null
160 || attachmentAttributeType.getAttributeName().isEmpty()))
161 .findAny()
162 .ifPresent(attachmentAttributeType -> {
163 throw new IllegalArgumentException("FeatureType "
164 + featureType.getName()
165 + " has an attachment attribute with invalid (null or empty) attribute name");
166 });
167
168 logger.debug(
169 "Creating attachment table for FeatureType: {} and attachment names {}",
170 featureType.getName(),
171 featureType.getSettings().getAttachmentAttributes());
172
173 JDBCDataStore ds = null;
174 try {
175 ds = (JDBCDataStore) new JDBCFeatureSourceHelper().createDataStore(featureType.getFeatureSource());
176
177 try (Connection conn = ds.getDataSource().getConnection();
178 Statement stmt = conn.createStatement()) {
179 String sql = getCreateAttachmentsForFeatureTypeStatements(featureType, ds);
180 logger.debug("About to create attachments table using statement:\n{}", sql);
181 stmt.execute(sql);
182 logger.info("Attachment table created for FeatureType: {}", featureType.getName());
183
184 sql = getCreateAttachmentsIndexForFeatureTypeStatements(featureType, ds);
185 logger.debug("About to create attachments table FK index using statement:\n{}", sql);
186 stmt.execute(sql);
187 logger.info("Attachment table FK index created for FeatureType: {}", featureType.getName());
188 }
189 } finally {
190 if (ds != null) {
191 ds.dispose();
192 }
193 }
194 }
195
196 public static void dropAttachmentTableForFeatureType(TMFeatureType featureType) throws IOException, SQLException {
197 JDBCDataStore ds = null;
198 try {
199 ds = (JDBCDataStore) new JDBCFeatureSourceHelper().createDataStore(featureType.getFeatureSource());
200 String schemaPrefix = ds.getDatabaseSchema();
201 if (!schemaPrefix.isEmpty()) {
202 schemaPrefix += ".";
203 }
204 String dropSql = MessageFormat.format("DROP TABLE {1}{0}_attachments", featureType.getName(), schemaPrefix);
205 logger.debug("About to drop attachments table using statement:\n{}", dropSql);
206 try (Connection conn = ds.getDataSource().getConnection();
207 Statement stmt = conn.createStatement()) {
208 stmt.execute(dropSql);
209 logger.info("Attachment table dropped for FeatureType: {}", featureType.getName());
210 }
211 } finally {
212 if (ds != null) {
213 ds.dispose();
214 }
215 }
216 }
217
218
219
220
221
222
223
224
225
226 private static String getCreateAttachmentsForFeatureTypeStatements(TMFeatureType featureType, JDBCDataStore ds)
227 throws IOException, IllegalArgumentException, SQLException {
228
229 String fkColumnType = null;
230 int fkColumnSize = 0;
231 AttributeDescriptor pkDescriptor =
232 ds.getSchema(featureType.getName()).getDescriptor(featureType.getPrimaryKeyAttribute());
233
234 try (Connection conn = ((DelegatingConnection) ds.getDataSource().getConnection()).getInnermostDelegate()) {
235 DatabaseMetaData metaData = conn.getMetaData();
236 try (ResultSet rs = metaData.getColumns(
237 conn.getCatalog(),
238 ds.getDatabaseSchema(),
239 featureType.getName(),
240 featureType.getPrimaryKeyAttribute())) {
241 if (rs.next()) {
242 fkColumnType = rs.getString("TYPE_NAME");
243 fkColumnSize = rs.getInt("COLUMN_SIZE");
244 }
245 }
246
247
248
249 if (fkColumnType == null) {
250 try (ResultSet rs = metaData.getColumns(
251 conn.getCatalog(),
252 ds.getDatabaseSchema(),
253 featureType.getName().toUpperCase(Locale.ROOT),
254 featureType.getPrimaryKeyAttribute().toUpperCase(Locale.ROOT))) {
255 if (rs.next()) {
256 fkColumnType = rs.getString("TYPE_NAME");
257 fkColumnSize = rs.getInt("COLUMN_SIZE");
258 }
259 }
260 }
261
262
263 if (fkColumnType == null) {
264 fkColumnType = (String) pkDescriptor.getUserData().get("org.geotools.jdbc.nativeTypeName");
265 }
266 }
267
268 String typeModifier = "";
269 if (fkColumnSize > 0) {
270 typeModifier = getValidModifier(fkColumnType, fkColumnSize);
271 }
272 logger.debug(
273 "Creating attachment table for feature type with primary key {} (native type: {}, meta type: {}, size:"
274 + " {} (modifier: {}))",
275 pkDescriptor.getLocalName(),
276 fkColumnType,
277 pkDescriptor.getUserData().get("org.geotools.jdbc.nativeTypeName"),
278 fkColumnSize,
279 typeModifier);
280
281 JDBCConnectionProperties connProperties = featureType.getFeatureSource().getJdbcConnection();
282 fkColumnType = getValidColumnType(fkColumnType, connProperties.getDbtype());
283 return switch (connProperties.getDbtype()) {
284 case POSTGIS ->
285 getPostGISCreateAttachmentsTableStatement(
286 featureType.getName(),
287 featureType.getPrimaryKeyAttribute(),
288 fkColumnType,
289 typeModifier,
290 ds.getDatabaseSchema());
291 case ORACLE ->
292 getOracleCreateAttachmentsTableStatement(
293 featureType.getName(),
294 featureType.getPrimaryKeyAttribute(),
295 fkColumnType,
296 typeModifier,
297 ds.getDatabaseSchema());
298 case SQLSERVER ->
299 getSQLServerCreateAttachmentsTableStatement(
300 featureType.getName(),
301 featureType.getPrimaryKeyAttribute(),
302 fkColumnType,
303 typeModifier,
304 ds.getDatabaseSchema());
305 default ->
306 throw new IllegalArgumentException(
307 "Unsupported database type for attachments: " + connProperties.getDbtype());
308 };
309 }
310
311 private static String getValidColumnType(String columnType, JDBCConnectionProperties.DbtypeEnum dbtype) {
312 if (dbtype.equals(JDBCConnectionProperties.DbtypeEnum.SQLSERVER)
313 && NUMERIC_WITH_IDENTITY.matcher(columnType).find()) {
314
315 columnType = columnType.replaceAll("(?i)\\s+identity\\b", "");
316 }
317
318 return columnType;
319 }
320
321 private static String getValidModifier(String columnType, int fkColumnSize) {
322 if (fkColumnSize > 0 && allowedPKTypesSupportingSize.contains(columnType.toUpperCase(Locale.ROOT))) {
323 if (columnType.equalsIgnoreCase("NUMERIC")
324 || columnType.equalsIgnoreCase("DECIMAL")
325 || columnType.equalsIgnoreCase("NUMBER")) {
326
327
328 return "(" + fkColumnSize + ",0)";
329 }
330 return "(" + fkColumnSize + ")";
331 } else {
332 return "";
333 }
334 }
335
336
337
338
339
340
341
342
343 private static String getCreateAttachmentsIndexForFeatureTypeStatements(TMFeatureType featureType, JDBCDataStore ds)
344 throws IllegalArgumentException {
345
346 String schemaPrefix = ds.getDatabaseSchema();
347 if (!schemaPrefix.isEmpty()) {
348 schemaPrefix += ".";
349 }
350
351 JDBCConnectionProperties connProperties = featureType.getFeatureSource().getJdbcConnection();
352 return switch (connProperties.getDbtype()) {
353 case POSTGIS ->
354 MessageFormat.format(
355 "CREATE INDEX IF NOT EXISTS {0}_attachments_fk ON {1}{0}_attachments({0}_pk)",
356 featureType.getName(), schemaPrefix);
357 case SQLSERVER -> MessageFormat.format("""
358 IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = ''{0}_attachments_fk'' AND object_id = OBJECT_ID(N''{1}{0}_attachments''))
359 BEGIN
360 CREATE INDEX {0}_attachments_fk ON {1}{0}_attachments({0}_pk)
361 END
362 """, featureType.getName(), schemaPrefix);
363 case ORACLE ->
364 MessageFormat.format(
365 "CREATE INDEX IF NOT EXISTS {1}{0}_attachments_fk ON {1}{0}_attachments({0}_pk)",
366 featureType.getName(), schemaPrefix)
367 .toUpperCase(Locale.ROOT);
368 default ->
369 throw new IllegalArgumentException(
370 "Unsupported database type for attachments: " + connProperties.getDbtype());
371 };
372 }
373
374
375 private static byte[] asBytes(UUID uuid) {
376 ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
377 bb.putLong(uuid.getMostSignificantBits());
378 bb.putLong(uuid.getLeastSignificantBits());
379 return bb.array();
380 }
381
382 public static AttachmentMetadata insertAttachment(
383 TMFeatureType featureType, AttachmentMetadata attachment, Object primaryKey, byte[] fileData)
384 throws IOException, SQLException {
385
386
387 attachment.setAttachmentId(UUID.randomUUID());
388 attachment.setAttachmentSize((long) fileData.length);
389 attachment.createdAt(OffsetDateTime.now(ZoneId.of("UTC")));
390 attachment.setCreatedBy(
391 SecurityContextHolder.getContext().getAuthentication().getName());
392
393 logger.debug(
394 "Adding attachment {} for feature {}:{}, type {}: {} (bytes: {})",
395 attachment.getAttachmentId(),
396 featureType.getName(),
397 primaryKey,
398 attachment.getMimeType(),
399 attachment,
400 fileData.length);
401
402 JDBCDataStore ds = null;
403 try {
404 ds = (JDBCDataStore) new JDBCFeatureSourceHelper().createDataStore(featureType.getFeatureSource());
405
406 String insertSql = MessageFormat.format(
407 """
408 INSERT INTO {1}{0}_attachments (
409 {0}_pk, attachment_id, file_name, attribute_name, description, attachment, attachment_size,
410 mime_type, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
411 """, featureType.getName(), ds.getDatabaseSchema().isEmpty() ? "" : ds.getDatabaseSchema() + ".");
412
413 logger.debug("Insert attachment SQL: {}", insertSql);
414 try (Connection conn = ds.getDataSource().getConnection();
415 PreparedStatement stmt = conn.prepareStatement(insertSql)) {
416
417 stmt.setObject(1, primaryKey);
418 if (featureType
419 .getFeatureSource()
420 .getJdbcConnection()
421 .getDbtype()
422 .equals(JDBCConnectionProperties.DbtypeEnum.ORACLE)) {
423
424 stmt.setBytes(2, asBytes(attachment.getAttachmentId()));
425 } else {
426 stmt.setObject(2, attachment.getAttachmentId());
427 }
428 stmt.setString(3, attachment.getFileName());
429 stmt.setString(4, attachment.getAttributeName());
430 stmt.setString(5, attachment.getDescription());
431 stmt.setBytes(6, fileData);
432 stmt.setLong(7, fileData.length);
433 stmt.setString(8, attachment.getMimeType());
434 stmt.setTimestamp(9, Timestamp.from(attachment.getCreatedAt().toInstant()));
435 stmt.setString(10, attachment.getCreatedBy());
436
437 stmt.executeUpdate();
438
439 return attachment;
440 }
441 } finally {
442 if (ds != null) {
443 ds.dispose();
444 }
445 }
446 }
447
448 public static void deleteAttachment(UUID attachmentId, TMFeatureType featureType) throws IOException, SQLException {
449 JDBCDataStore ds = null;
450 try {
451 ds = (JDBCDataStore) new JDBCFeatureSourceHelper().createDataStore(featureType.getFeatureSource());
452
453 String deleteSql = MessageFormat.format(
454 """
455 DELETE FROM {1}{0}_attachments WHERE attachment_id = ?
456 """, featureType.getName(), ds.getDatabaseSchema().isEmpty() ? "" : ds.getDatabaseSchema() + ".");
457
458 try (Connection conn = ds.getDataSource().getConnection();
459 PreparedStatement stmt = conn.prepareStatement(deleteSql)) {
460 if (featureType
461 .getFeatureSource()
462 .getJdbcConnection()
463 .getDbtype()
464 .equals(JDBCConnectionProperties.DbtypeEnum.ORACLE)) {
465 stmt.setBytes(1, asBytes(attachmentId));
466 } else {
467 stmt.setObject(1, attachmentId);
468 }
469
470 stmt.executeUpdate();
471 }
472 } finally {
473 if (ds != null) {
474 ds.dispose();
475 }
476 }
477 }
478
479 public static List<AttachmentMetadata> listAttachmentsForFeature(TMFeatureType featureType, Object primaryKey)
480 throws IOException, SQLException {
481
482 List<AttachmentMetadata> attachments = new ArrayList<>();
483 JDBCDataStore ds = null;
484 try {
485 ds = (JDBCDataStore) new JDBCFeatureSourceHelper().createDataStore(featureType.getFeatureSource());
486 String querySql = MessageFormat.format(
487 """
488 SELECT
489 {0}_pk,
490 attachment_id,
491 file_name,
492 attribute_name,
493 description,
494 attachment_size,
495 mime_type,
496 created_at,
497 created_by
498 FROM {1}{0}_attachments WHERE {0}_pk = ?
499 """, featureType.getName(), ds.getDatabaseSchema().isEmpty() ? "" : ds.getDatabaseSchema() + ".");
500 try (Connection conn = ds.getDataSource().getConnection();
501 PreparedStatement stmt = conn.prepareStatement(querySql)) {
502
503 stmt.setObject(1, primaryKey);
504
505 try (ResultSet rs = stmt.executeQuery()) {
506 while (rs.next()) {
507 AttachmentMetadata a = getAttachmentMetadata(rs);
508 attachments.add(a);
509 }
510 }
511 }
512 } finally {
513 if (ds != null) {
514 ds.dispose();
515 }
516 }
517 return attachments;
518 }
519
520 public static AttachmentWithBinary getAttachment(TMFeatureType featureType, UUID attachmentId)
521 throws IOException, SQLException {
522
523 JDBCDataStore ds = null;
524 try {
525 byte[] attachment;
526 ds = (JDBCDataStore) new JDBCFeatureSourceHelper().createDataStore(featureType.getFeatureSource());
527 String querySql = MessageFormat.format(
528 "SELECT attachment, attachment_size, mime_type, file_name FROM {1}{0}_attachments WHERE attachment_id = ?",
529 featureType.getName(), ds.getDatabaseSchema().isEmpty() ? "" : ds.getDatabaseSchema() + ".");
530 try (Connection conn = ds.getDataSource().getConnection();
531 PreparedStatement stmt = conn.prepareStatement(querySql)) {
532
533 if (featureType
534 .getFeatureSource()
535 .getJdbcConnection()
536 .getDbtype()
537 .equals(JDBCConnectionProperties.DbtypeEnum.ORACLE)) {
538 stmt.setBytes(1, asBytes(attachmentId));
539 } else {
540 stmt.setObject(1, attachmentId);
541 }
542
543 try (ResultSet rs = stmt.executeQuery()) {
544 if (rs.next()) {
545 attachment = rs.getBytes("attachment");
546 AttachmentMetadata a = new AttachmentMetadata();
547 long size = rs.getLong("attachment_size");
548 if (!rs.wasNull()) {
549 a.setAttachmentSize(size);
550 }
551 a.setMimeType(rs.getString("mime_type"));
552 a.setFileName(rs.getString("file_name"));
553 return new AttachmentWithBinary(
554 a, ByteBuffer.wrap(attachment).asReadOnlyBuffer());
555 } else {
556 return null;
557 }
558 }
559 }
560 } finally {
561 if (ds != null) {
562 ds.dispose();
563 }
564 }
565 }
566
567
568
569
570
571
572
573
574
575
576 public static @NonNull Map<String, List<AttachmentMetadata>> listAttachmentsForFeaturesByFeatureId(
577 TMFeatureType featureType, List<Object> featurePKs) throws IOException {
578 List<AttachmentMetadataListItem> attachments = new ArrayList<>();
579 if (featurePKs == null || featurePKs.isEmpty()) {
580 return new HashMap<>();
581 }
582
583 JDBCDataStore ds = null;
584 try {
585 ds = (JDBCDataStore) new JDBCFeatureSourceHelper().createDataStore(featureType.getFeatureSource());
586 String querySql = MessageFormat.format(
587 """
588 SELECT
589 {0}_pk,
590 attachment_id,
591 file_name,
592 attribute_name,
593 description,
594 attachment_size,
595 mime_type,
596 created_at,
597 created_by
598 FROM {2}{0}_attachments WHERE {0}_pk IN ( {1} )
599 """,
600 featureType.getName(),
601 String.join(", ", featurePKs.stream().map(id -> "?").toArray(String[]::new)),
602 ds.getDatabaseSchema().isEmpty() ? "" : ds.getDatabaseSchema() + ".");
603
604 try (Connection conn = ds.getDataSource().getConnection();
605 PreparedStatement stmt = conn.prepareStatement(querySql)) {
606
607 Object firstPK = featurePKs.getFirst();
608 boolean isUUID = firstPK instanceof UUID;
609 boolean isByteBuffer = firstPK instanceof ByteBuffer;
610
611 switch (featureType.getFeatureSource().getJdbcConnection().getDbtype()) {
612 case ORACLE -> {
613 for (int i = 0; i < featurePKs.size(); i++) {
614 if (isUUID) {
615
616
617 stmt.setBytes(i + 1, asBytes((UUID) featurePKs.get(i)));
618 } else if (isByteBuffer) {
619
620 stmt.setBytes(i + 1, ((ByteBuffer) featurePKs.get(i)).array());
621 } else {
622 stmt.setObject(i + 1, featurePKs.get(i));
623 }
624 }
625 }
626 case SQLSERVER -> {
627 for (int i = 0; i < featurePKs.size(); i++) {
628 if (isUUID) {
629
630 stmt.setString(
631 i + 1, featurePKs.get(i).toString().toUpperCase(Locale.ROOT));
632 } else {
633 stmt.setObject(i + 1, featurePKs.get(i));
634 }
635 }
636 }
637 case POSTGIS -> {
638 for (int i = 0; i < featurePKs.size(); i++) {
639 stmt.setObject(i + 1, featurePKs.get(i));
640 }
641 }
642 default ->
643 throw new UnsupportedOperationException("Unsupported database type: "
644 + featureType
645 .getFeatureSource()
646 .getJdbcConnection()
647 .getDbtype());
648 }
649
650 try (ResultSet rs = stmt.executeQuery()) {
651 while (rs.next()) {
652 Object keyObject = rs.getObject(1);
653 if (isUUID
654 && featureType
655 .getFeatureSource()
656 .getJdbcConnection()
657 .getDbtype()
658 .equals(JDBCConnectionProperties.DbtypeEnum.ORACLE)) {
659
660 byte[] rawBytes = rs.getBytes(1);
661 ByteBuffer bb = ByteBuffer.wrap(rawBytes);
662 keyObject = new UUID(bb.getLong(), bb.getLong());
663 } else if (isUUID
664 && featureType
665 .getFeatureSource()
666 .getJdbcConnection()
667 .getDbtype()
668 .equals(JDBCConnectionProperties.DbtypeEnum.SQLSERVER)) {
669
670 keyObject = UUID.fromString(rs.getString(1));
671 } else if (isByteBuffer) {
672 assert keyObject instanceof byte[];
673 keyObject = ByteBuffer.wrap((byte[]) keyObject);
674 }
675 attachments.add(new AttachmentMetadataListItem(
676 AttachmentsHelper.fidFromPK(featureType, keyObject), getAttachmentMetadata(rs)));
677 }
678 }
679 } catch (SQLException ex) {
680 logger.error("Failed to get attachments for {}", featureType.getName(), ex);
681 }
682 } finally {
683 if (ds != null) {
684 ds.dispose();
685 }
686 }
687 logger.debug(
688 "Found {} attachments for {} features (features: {}, attachments: {})",
689 attachments.size(),
690 featurePKs.size(),
691 featurePKs,
692 attachments.toArray());
693
694 return attachments.stream()
695 .collect(Collectors.groupingBy(
696 AttachmentMetadataListItem::fid,
697 Collectors.mapping(AttachmentMetadataListItem::value, Collectors.toList())));
698 }
699
700
701
702
703
704
705
706
707
708 public static String fidFromPK(@NotNull TMFeatureType featureType, @NotNull Object featurePK) {
709 if (featurePK == null) {
710 throw new IllegalArgumentException("featurePK cannot be null");
711 }
712 if (featureType == null) {
713 throw new IllegalArgumentException("featureType cannot be null");
714 }
715 if (featurePK instanceof byte[] pkBytes) {
716 ByteBuffer bb = ByteBuffer.wrap(pkBytes);
717 UUID pkUUID = new UUID(bb.getLong(), bb.getLong());
718 return "%s.%s".formatted(featureType.getName(), pkUUID);
719 } else {
720 return "%s.%s".formatted(featureType.getName(), featurePK);
721 }
722 }
723
724 private static AttachmentMetadata getAttachmentMetadata(ResultSet rs) throws SQLException {
725 AttachmentMetadata a = new AttachmentMetadata();
726
727 Object idObj = rs.getObject("attachment_id");
728 if (idObj instanceof UUID u) {
729 a.setAttachmentId(u);
730 } else if (idObj instanceof byte[] b) {
731 ByteBuffer bb = ByteBuffer.wrap(b);
732 a.setAttachmentId(new UUID(bb.getLong(), bb.getLong()));
733 } else {
734 String s = rs.getString("attachment_id");
735 if (s != null && !s.isEmpty()) {
736 a.setAttachmentId(UUID.fromString(s));
737 }
738 }
739 a.setFileName(rs.getString("file_name"));
740 a.setAttributeName(rs.getString("attribute_name"));
741 a.setDescription(rs.getString("description"));
742 long size = rs.getLong("attachment_size");
743 if (!rs.wasNull()) {
744 a.setAttachmentSize(size);
745 }
746 a.setMimeType(rs.getString("mime_type"));
747 Timestamp ts = rs.getTimestamp("created_at");
748 if (ts != null) {
749 a.setCreatedAt(OffsetDateTime.ofInstant(ts.toInstant(), ZoneId.of("UTC")));
750 }
751 a.setCreatedBy(rs.getString("created_by"));
752 return a;
753 }
754
755 public record AttachmentWithBinary(
756 @NotNull AttachmentMetadata attachmentMetadata,
757 @NotNull ByteBuffer attachment) {}
758
759 private record AttachmentMetadataListItem(
760 @NotNull String fid, @NotNull AttachmentMetadata value) {}
761 }