Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ public enum Parameter {
LAYER_NAME("layer_name"),
COLLECTION_TITLE("collection_title"),
FULL_METADATA_LINK("full_metadata_link"),
// These two are Batch parameters only, not request inputs. Filled from the
// Elasticsearch record (DownloadCitationService).
SUGGESTED_CITATION("suggested_citation"),
USAGE_CONSTRAINTS("usage_constraints"),
KEY("key"),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
package au.org.aodn.ogcapi.server.processes;

import au.org.aodn.ogcapi.server.core.service.ElasticSearchBase;
import au.org.aodn.ogcapi.server.core.service.Search;
import au.org.aodn.ogcapi.server.core.util.ConstructUtils;
import au.org.aodn.stac.model.CitationModel;
import au.org.aodn.stac.model.StacCollectionModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Clock;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;

/**
* Builds the suggested citation and usage constraints of a download from the Elasticsearch
* record, so the request body carries no long metadata text.
* The portal download dialog builds the same citation and constraints (CitationUtils.ts in
* aodn-portal-v2). Keep the two rules the same.
*/
@Service
public class DownloadCitationService {

private static final String SUMMARY_TAB = "?tab=summary";

private static final Pattern YEAR_PLACEHOLDER =
Pattern.compile("\\[year-of-data-download(?:ed)?]", Pattern.CASE_INSENSITIVE);
private static final Pattern TITLE_PLACEHOLDER =
Pattern.compile("\\[title]", Pattern.CASE_INSENSITIVE);
private static final Pattern ACCESS_URL_PLACEHOLDER =
Pattern.compile("\\[data-access-url]", Pattern.CASE_INSENSITIVE);
private static final Pattern ACCESS_DATE_PLACEHOLDER =
Pattern.compile("\\[date-of-access]", Pattern.CASE_INSENSITIVE);

private static final DateTimeFormatter ACCESS_DATE_FORMAT =
DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.ENGLISH);

// Same as the JavaScript \s the portal uses, which also matches non-breaking spaces
private static final Pattern WHITESPACE = Pattern.compile("\\s+", Pattern.UNICODE_CHARACTER_CLASS);

private final Search search;
// UTC, the same time zone the portal uses for the year and the date of access
private final Clock clock;

@Autowired
public DownloadCitationService(Search search) {
this(search, Clock.systemUTC());
}

DownloadCitationService(Search search, Clock clock) {
this.search = search;
this.clock = clock;
}

/**
* The values sent to AWS Batch as suggested_citation and usage_constraints.
*/
public record DownloadCitation(
String suggestedCitation,
List<String> usageConstraints
) {
}

/**
* Look up the dataset by uuid and build its citation and constraints.
* fullMetadataLink is the portal page link from the request, used for [data-access-url].
* Throws NoSuchElementException when the uuid is not in Elasticsearch.
*/
public DownloadCitation lookup(String uuid, String fullMetadataLink) {
if (uuid == null || uuid.isBlank()) {
throw new IllegalArgumentException("Missing uuid");
}

ElasticSearchBase.SearchResult<StacCollectionModel> result = search.searchCollections(uuid);
if (result == null || result.getCollections() == null || result.getCollections().isEmpty()) {
throw new NoSuchElementException("No collection found for uuid " + uuid);
}

StacCollectionModel model = result.getCollections().get(0);
String title = model.getTitle() == null ? "" : model.getTitle();
CitationModel citation = parseCitation(model.getCitation());
// The portal built the same url: its details page link plus the summary tab
String dataAccessUrl = fullMetadataLink == null || fullMetadataLink.isEmpty()
? ""
: fullMetadataLink + SUMMARY_TAB;

return new DownloadCitation(
resolveSuggestedCitation(citation.getSuggestedCitation(), title, dataAccessUrl),
usageConstraints(citation, model.getLicense())
);
}

private static CitationModel parseCitation(String json) {
if (json == null || json.isEmpty()) {
return new CitationModel();
}
return ConstructUtils.constructByJsonString(json, CitationModel.class).orElseGet(CitationModel::new);
}

// Fill the placeholders, in the same order as the portal. Empty when there is no citation.
private String resolveSuggestedCitation(String suggestedCitation, String title, String dataAccessUrl) {
if (suggestedCitation == null || suggestedCitation.isEmpty()) {
return "";
}

LocalDate accessDate = LocalDate.now(clock);

String citation = replaceAll(YEAR_PLACEHOLDER, suggestedCitation, String.valueOf(accessDate.getYear()));
citation = replaceAll(TITLE_PLACEHOLDER, citation, title);
citation = replaceAll(ACCESS_URL_PLACEHOLDER, citation, dataAccessUrl);
return replaceAll(ACCESS_DATE_PLACEHOLDER, citation, ACCESS_DATE_FORMAT.format(accessDate));
}

// The value is used as plain text, so a $ or \ in a title is not read as a group reference
private static String replaceAll(Pattern placeholder, String text, String value) {
return placeholder.matcher(text).replaceAll(Matcher.quoteReplacement(value));
}

/**
* Use limitations then other constraints, with these removed:
* 1. Empty items.
* 2. An item that equals the licence.
* 3. Duplicates, the first one is kept.
* Items are compared after trim, single spaces and lower case.
*/
private static List<String> usageConstraints(CitationModel citation, String license) {
String normalizedLicense = license == null ? "" : normalize(license);
Set<String> seen = new HashSet<>();
List<String> constraints = new ArrayList<>();

Stream.concat(
Objects.requireNonNullElse(citation.getUseLimitations(), List.<String>of()).stream(),
Objects.requireNonNullElse(citation.getOtherConstraints(), List.<String>of()).stream())
.filter(Objects::nonNull)
.forEach(constraint -> {
String normalized = normalize(constraint);
if (!normalized.isEmpty() && !normalized.equals(normalizedLicense) && seen.add(normalized)) {
constraints.add(constraint);
}
});

return constraints;
}

private static String normalize(String text) {
return WHITESPACE.matcher(text).replaceAll(" ").trim().toLowerCase(Locale.ROOT);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@
import java.util.List;

/**
* The inputs of one {@code download} execute request, as extracted from the OGC Execute
* body. Carried as a unit so a request that has to wait for a free slot can be submitted
* later exactly as it arrived.
* <p>
* Empty when the dataset has none, or when the input is missing.
* One download execute request. Most values come from the OGC Execute body. The citation and
* constraints come from the Elasticsearch record (DownloadCitationService). Carried as a unit
* so a request that has to wait for a free slot can be submitted later exactly as it arrived.
*/
public record DownloadRequest(
String uuid,
Expand All @@ -27,7 +25,7 @@ public record DownloadRequest(
Long estimatedSizeBytes
) {
public DownloadRequest {
// A missing input means no constraints to show
// Null means no constraints to show
usageConstraints = usageConstraints == null ? List.of() : usageConstraints;
// A negative size is not a real estimate, treat it as missing
estimatedSizeBytes = estimatedSizeBytes != null && estimatedSizeBytes < 0 ? null : estimatedSizeBytes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ public class RestApi implements ProcessesApi, JobsApi {
@Autowired
private DownloadAdmissionService downloadAdmissionService;

@Autowired
private DownloadCitationService downloadCitationService;

@Override
// because the produces value in the interface declaration includes "/_" which may
// cause exception thrown sometimes. So i re-declared the produces value here
Expand Down Expand Up @@ -113,14 +116,19 @@ public ResponseEntity<InlineResponse200> execute(
String recipient = DatasetDownloadEnums.Parameter.RECIPIENT.getStringInput(body);
String collectionTitle = DatasetDownloadEnums.Parameter.COLLECTION_TITLE.getStringInput(body);
String fullMetadataLink = DatasetDownloadEnums.Parameter.FULL_METADATA_LINK.getStringInput(body);
String suggestedCitation = DatasetDownloadEnums.Parameter.SUGGESTED_CITATION.getStringInput(body);
List<String> usageConstraints = DatasetDownloadEnums.Parameter.USAGE_CONSTRAINTS.getListInput(body);
String outputFormat = DatasetDownloadEnums.Parameter.OUTPUT_FORMAT.getStringInput(body);
Object multiPolygon = DatasetDownloadEnums.Parameter.MULTI_POLYGON.getObjectInput(body);
Long estimatedSizeBytes = DatasetDownloadEnums.Parameter.ESTIMATED_SIZE_BYTES.getLongInput(body);

// The citation and constraints are long text, so they come from the Elasticsearch
// record, not from the request. A uuid that is not in Elasticsearch throws, so
// nothing is submitted.
DownloadCitationService.DownloadCitation citation =
downloadCitationService.lookup(uuid, fullMetadataLink);

DownloadRequest request = new DownloadRequest(uuid, key, startDate, endDate, multiPolygon,
recipient, collectionTitle, fullMetadataLink, suggestedCitation, usageConstraints,
recipient, collectionTitle, fullMetadataLink,
citation.suggestedCitation(), citation.usageConstraints(),
outputFormat, estimatedSizeBytes);

// The size limit and the per-user limit are applied here: a download that is too
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
package au.org.aodn.ogcapi.server.processes;

import au.org.aodn.ogcapi.server.core.service.ElasticSearchBase;
import au.org.aodn.ogcapi.server.core.service.Search;
import au.org.aodn.stac.model.CitationModel;
import au.org.aodn.stac.model.StacCollectionModel;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
public class DownloadCitationServiceTest {

private static final String UUID = "b299cdcd-3dee-48aa-abdd-e0fcdbb9cadc";
private static final String TITLE = "Test Ocean Data Collection";
private static final String METADATA_LINK = "https://portal.example.test/details/" + UUID;

private final ObjectMapper objectMapper = new ObjectMapper();

@Mock
private Search search;

private DownloadCitationService service;

@BeforeEach
public void setUp() {
// 19 Nov in Sydney, still 18 Nov in UTC
Clock clock = Clock.fixed(Instant.parse("2026-11-18T23:30:00Z"), ZoneOffset.UTC);
service = new DownloadCitationService(search, clock);
}

@Test
public void testLookupFillsCitationPlaceholders() throws JsonProcessingException {
// Placeholders are case-insensitive, and both year spellings are filled
String citation = "IMOS [year-of-data-download], [Title], [data-access-URL], accessed [date-of-access]. "
+ "Data downloaded [YEAR-OF-DATA-DOWNLOADED].";
givenRecord(StacCollectionModel.builder().uuid(UUID).title(TITLE)
.citation(citationJson(citation, null, null)).build());

DownloadCitationService.DownloadCitation result = service.lookup(UUID, METADATA_LINK);

assertEquals("IMOS 2026, Test Ocean Data Collection, "
+ METADATA_LINK + "?tab=summary, accessed 18-Nov-2026. "
+ "Data downloaded 2026.",
result.suggestedCitation());
}

@Test
public void testLookupWithoutMetadataLinkLeavesAccessUrlEmpty() throws JsonProcessingException {
givenRecord(StacCollectionModel.builder().uuid(UUID).title(TITLE)
.citation(citationJson("Accessed at [data-access-url].", null, null)).build());

assertEquals("Accessed at .", service.lookup(UUID, null).suggestedCitation());
}

@Test
public void testLookupKeepsSpecialCharactersInTitle() throws JsonProcessingException {
// A $ or \ in the title is plain text, not a regex group reference
String title = "Price $1 and C:\\data";
givenRecord(StacCollectionModel.builder().uuid(UUID).title(title)
.citation(citationJson("[title]", null, null)).build());

assertEquals(title, service.lookup(UUID, METADATA_LINK).suggestedCitation());
}

@Test
public void testLookupWithoutCitationGivesEmptyValues() {
givenRecord(StacCollectionModel.builder().uuid(UUID).title(TITLE).license("CC BY 4.0").build());

DownloadCitationService.DownloadCitation result = service.lookup(UUID, METADATA_LINK);

// An empty citation is sent as "Suggested Citation not available" by RestServices
assertEquals("", result.suggestedCitation());
assertEquals(List.of(), result.usageConstraints());
}

@Test
public void testLookupDropsEmptyLicenceAndDuplicateConstraints() throws JsonProcessingException {
List<String> useLimitations = Arrays.asList("Use with care", "", " ", null);
List<String> otherConstraints = List.of(
" Creative Commons Attribution 4.0 ",
"use WITH care ",
"Credit CSIRO",
"credit csiro");
givenRecord(StacCollectionModel.builder().uuid(UUID).title(TITLE)
.license("creative commons attribution 4.0")
.citation(citationJson("A citation", useLimitations, otherConstraints)).build());

// Use limitations come first, the first of each duplicate is kept as written
assertEquals(List.of("Use with care", "Credit CSIRO"), service.lookup(UUID, METADATA_LINK).usageConstraints());
}

@Test
public void testLookupWithoutLicenceKeepsAllConstraints() throws JsonProcessingException {
givenRecord(StacCollectionModel.builder().uuid(UUID).title(TITLE)
.citation(citationJson(null, List.of("Use with care"), List.of("Credit CSIRO"))).build());

assertEquals(List.of("Use with care", "Credit CSIRO"), service.lookup(UUID, METADATA_LINK).usageConstraints());
}

@Test
public void testLookupUuidNotFoundThrows() {
ElasticSearchBase.SearchResult<StacCollectionModel> result = new ElasticSearchBase.SearchResult<>();
result.setCollections(List.of());
when(search.searchCollections(UUID)).thenReturn(result);

assertThrows(NoSuchElementException.class, () -> service.lookup(UUID, METADATA_LINK));
}

@Test
public void testLookupMissingUuidThrows() {
assertThrows(IllegalArgumentException.class, () -> service.lookup(null, METADATA_LINK));
assertThrows(IllegalArgumentException.class, () -> service.lookup(" ", METADATA_LINK));
}

private void givenRecord(StacCollectionModel model) {
ElasticSearchBase.SearchResult<StacCollectionModel> result = new ElasticSearchBase.SearchResult<>();
result.setCollections(List.of(model));
when(search.searchCollections(UUID)).thenReturn(result);
}

// Elasticsearch stores sci:citation as a JSON string
private String citationJson(String suggestedCitation, List<String> useLimitations, List<String> otherConstraints)
throws JsonProcessingException {
return objectMapper.writeValueAsString(new CitationModel(suggestedCitation, useLimitations, otherConstraints));
}
}
Loading
Loading