From 4a3a31a155d9f964ffe54d54748f4ea678ad05ce Mon Sep 17 00:00:00 2001 From: ddariod Date: Wed, 14 Oct 2026 17:23:15 -0500 Subject: [PATCH 01/28] spec(content-drive): export content to CSV, Content Search parity first, then selection (#37900) Filter mode brings the Content Search export to Drive: with the listing filtered to exactly one content type, export every result of its location and filters as one CSV. Selection mode is new: up to 60 folders and contentlets of any types, exported as a zip with one CSV per type. Both reuse the Content Search CSV writer and file names, and refuse exports over 100,000 rows instead of truncating them. Co-Authored-By: Claude Opus 5.5 --- specs/37900-content-drive-export/spec.md | 508 +++++++++++++++++++++++ 1 file changed, 508 insertions(+) create mode 100644 specs/37900-content-drive-export/spec.md diff --git a/specs/37900-content-drive-export/spec.md b/specs/37900-content-drive-export/spec.md new file mode 100644 index 000000000000..db3df10a52bb --- /dev/null +++ b/specs/37900-content-drive-export/spec.md @@ -0,0 +1,508 @@ +# Feature Specification: Content Drive — export content to CSV + +**Feature Branch**: `37900-content-drive-add-content-export` + +**Created**: 2026-10-13 + +**Status**: Draft + +**Type**: New Feature + +**Related GitHub Issue**: [#37900](https://github.com/dotCMS/core/issues/37900) + +**Input**: User description: "https://github.com/dotCMS/core/issues/37900 — Content Drive: Add content export. Open points to capture from the previous analysis: (1) zip entries can't be interleaved and scroll runs in batches, so the same content type can appear in several batches — writing strategy (sort by contentType vs temp CSV per type) is a plan decision, but the spec must require one CSV per type with no duplicate headers; (2) the zip filename `_export_.zip` doesn't define `` for a mixed selection; (3) the rule \"readable contentlet inside unreadable folder is exported when selected directly\" has not been reproduced with a limited user yet; (4) the legacy writer does N+1 lookups per row (categories, tags, relationships, identifiers) — parity is required, performance is not in scope but should be noted." + +**Refined with the developer and the team (2026-10-14)**: + +- **Feature parity with Content Search comes first.** Whatever the Content Search export supports, + Drive must support (filter mode). With the listing filtered to exactly one content type, Export + downloads every result of the listing's filters (site or folder, language, workflow, status, + text, Include System Host), without paging, as one CSV. +- **Selection is a new, additional capability** (selection mode): folders and contentlets of + several content types, exported as a zip with one CSV per content type. +- Both are in scope, delivered parity first, then selection. +- The Content Search CSV format and file name are reused: `_contents_.csv`. + The zip is `_export_.zip`. +- The 100,000-row limit is kept in both modes, but a bigger export is refused with a clear message + instead of truncated. +- When there is a selection, the selection wins over the filter. +- A selection can hold at most 60 items (folders and contentlets together). + +## Context + +Content Drive cannot export content today. The only CSV export in dotCMS is in the legacy Content +Search portlet. It exports every result of the current search filters in one go (no paging), but +only when exactly one content type is chosen. Its filters include site (with or without System +Host), folder (only what sits directly in it), language, workflow and text. It stops at 100,000 +rows without telling the user. + +This feature brings that export to Drive, through one new endpoint, in two modes: + +- **Filter mode (feature parity).** Nothing is selected and the Drive listing is filtered to exactly + one content type. The export holds every contentlet the listing would show with the current + location and filters, across all pages, as one CSV. Drive's views map onto Content Search's + filters: All Site Content is the site filter, a folder is the folder filter (direct content only, + in both), and the Include System Host chip is the System Host option. +- **Selection mode (new).** The user selects folders and contentlets, of any content types. A + selected folder brings every contentlet below it, at any depth. Folders themselves are never + rows. The result is a zip with one CSV per content type. Drive's filters do not apply: **what you + select is what you export.** + +Each CSV has the same columns, values and file name as the Content Search export, so it can be +imported again (the import is a separate ticket, #37896). In both modes the only thing that removes +an item is permission: if the user cannot read it, it is not exported. + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - Export everything the listing shows for one content type (Priority: P1) + +An editor filters the Drive listing to one content type, optionally narrowing it with the location +(All Site Content, the site root, a folder, System Host) and more filters (language, workflow, +status, text, Include System Host). With nothing selected, the editor clicks **Export**. One CSV +downloads with every contentlet the listing would show, across all pages, not only the page that +is loaded. + +**Why this priority**: This is feature parity with the Content Search export, the only export +editors have today. It must exist in Drive before anything new is added. + +**Independent Test**: In All Site Content, filter to content type "Blog" and language Spanish. The +listing reports 2,500 contentlets over several pages. Export with nothing selected. +`Blog_contents_.csv` downloads with 2,500 data rows, all Spanish. Then open folder `/blog/` +with the same filters and export again: only the Blog contentlets directly in `/blog/` are in the +CSV. + +**Acceptance Scenarios**: + +1. **Given** nothing is selected and the listing is filtered to exactly one content type that is not + a Form, **When** the toolbar renders, **Then** the Export button is shown, in every Drive view + (All Site Content, site root, a folder, System Host). +2. **Given** nothing is selected and the listing is filtered to no content type or to more than one, + **When** the toolbar renders, **Then** the Export button is not shown. +3. **Given** the listing is filtered to one content type plus language, workflow, status, text or + Include System Host, **When** the user exports, **Then** the CSV holds exactly the contentlets + the listing shows with those filters, across every page. +4. **Given** the user is in All Site Content, **When** the user exports, **Then** matching + contentlets from the whole site, at any depth, are exported, plus System Host content when the + listing includes it. +5. **Given** the user is inside a folder, **When** the user exports, **Then** only the matching + contentlets directly in that folder are exported, as the listing shows them and as Content + Search's folder filter does. +6. **Given** the user is in the site-root view or the System Host view, **When** the user exports, + **Then** exactly the matching contentlets that view lists are exported. +7. **Given** a filter-mode export, **When** it finishes, **Then** a single CSV (not a zip) named + `_contents_.csv` downloads, and a toast reports the number of rows. +8. **Given** an export is running, **When** the user looks at the Export button, **Then** it shows a + loading state and cannot be clicked again until the export ends. + +--- + +### User Story 2 - Export selected contentlets of several content types (Priority: P2) + +An editor selects contentlets in Drive and clicks **Export**. A zip downloads with one CSV per +content type among them. Every language version of each selected contentlet is a row. + +**Why this priority**: It is new capability beyond Content Search. It reuses the CSV writer, the +endpoint and the download from User Story 1, and adds the selection, the zip and the grouping by +content type. + +**Independent Test**: On site `demo.dotcms.com`, select two contentlets of type "Blog" and one of +type "News", with one of the Blog contentlets having an English and a Spanish version. Export. The +zip is `demo.dotcms.com_export_.zip` and holds `Blog_contents_.csv` with 3 data rows and +`News_contents_.csv` with 1 data row. The toast reports 4 items and 2 files. + +**Acceptance Scenarios**: + +1. **Given** one or more items are selected in Drive, **When** the toolbar renders, **Then** an + Export button is shown beside the workflow actions, and the Action Center does not list an + Export row. +2. **Given** contentlets of two content types are selected, **When** the user clicks Export, + **Then** a zip downloads that holds one CSV per content type, and the toast reports the number + of rows and CSV files exported. +3. **Given** a selected contentlet has versions in two languages, **When** it is exported, + **Then** its CSV has one row per language version, with the languageCode and countryCode + columns filled for each. +4. **Given** a selected contentlet is archived and readable by the user, **When** it is exported, + **Then** it appears in its CSV. +5. **Given** Drive's filters are active (content type, text, workflow, status, language), **When** + the user exports a selection, **Then** the filters do not change which items are exported. +6. **Given** items are selected and the listing is filtered to one content type, **When** the user + exports, **Then** the selection is exported and the filter is ignored. +7. **Given** more than 60 items are selected (folders and contentlets together), **When** the + toolbar renders, **Then** the Export button is disabled and explains that at most 60 items can be + exported at once. +8. **Given** a request whose selection has more than 60 entries, **When** it reaches the server, + **Then** it is refused as a bad request and no file is produced. + +--- + +### User Story 3 - Export whole folders (Priority: P2) + +An editor selects one or more folders, optionally together with contentlets, and exports them. The +zip holds every contentlet inside the folders at any depth, plus the selected contentlets, each +exported once. Folders are only walked to reach their content; they are never rows. + +**Why this priority**: Exporting a whole section of a site, of every content type, is what +selection adds over Content Search, which has no recursive folder export. + +**Independent Test**: Build `/a/` holding contentlet X and subfolder `/a/b/c/` holding contentlet +Y. Select folder `/a/`, folder `/a/b/`, and contentlet X directly. Export. X and Y each appear once +and no row stands for a folder. + +**Acceptance Scenarios**: + +1. **Given** a folder is selected, **When** it is exported, **Then** the contentlets directly in it + and in all of its subfolders, at any depth, are exported, and no folder is a row. +2. **Given** a selected folder holds files and pages, **When** it is exported, **Then** they are + exported in their own content types' CSVs, with binary fields as a download URL. +3. **Given** a folder and a contentlet outside it are selected, **When** they are exported, **Then** + both are in the same zip. +4. **Given** a contentlet is selected directly and is also inside a selected folder, **When** they + are exported, **Then** the contentlet appears in its CSV once. +5. **Given** a folder and one of its subfolders are both selected, **When** they are exported, + **Then** each contentlet appears once. +6. **Given** a selected folder contains Form or Host content, **When** it is exported, **Then** that + content is not exported. + +--- + +### User Story 4 - Exports never reveal what the user cannot read (Priority: P1) + +A limited user exports, in either mode. Only content the user can read is exported, and nothing in +the response says how much was left out. + +**Why this priority**: Both modes read past what is on screen (every page of the listing, or deep +folder trees). Without this, the export would hand out content the user cannot see in Drive. + +**Independent Test**: With a limited user who can read `/a/` but not `/a/secret/`, and cannot read +contentlet Z in `/a/`, export folder `/a/` (selection mode), then filter to Z's content type in +All Site Content and export (filter mode). Neither file holds anything from `/a/secret/` or below, +nor Z. Neither response gives a count of skipped items. + +**Acceptance Scenarios**: + +1. **Given** a contentlet the user cannot read, in a filter-mode result, selected, or inside a + selected folder, **When** the export runs, **Then** that contentlet is not exported. +2. **Given** a selected folder has a subfolder the user cannot read, **When** it is exported, + **Then** no content from that subfolder or anything below it is exported. +3. **Given** a contentlet the user can read lives in a folder the user cannot read, **When** the + user selects it directly and exports, **Then** it is exported. +4. **Given** the request names a folder the user cannot read, **When** it is submitted, **Then** it + is refused as forbidden and no file is produced. +5. **Given** some items were skipped for permissions, **When** the export finishes, **Then** neither + the file, the counts, nor the toast reveals how many were skipped. + +--- + +### User Story 5 - Exports over the limit are refused with a clear message (Priority: P1) + +**Why this priority**: The Content Search export cuts at 100,000 rows without saying so, which +leaves the user with a file that looks complete and is not. In selection mode a silent cut would +drop arbitrary rows. + +**Independent Test**: Filter to a content type with 100,001 readable contentlets and export. Nothing +downloads, and the toast says the export has 100,001 rows and the limit is 100,000, and asks the +user to narrow the filters. Repeat with a selection of folders holding 100,001 readable rows. + +**Acceptance Scenarios**: + +1. **Given** a filter-mode export producing more than 100,000 rows the user can read, **When** it is + exported, **Then** it is refused, no file downloads, and the message gives the row count and the + limit. +2. **Given** a selection producing more than 100,000 readable rows, **When** it is exported, + **Then** it is refused in the same way. +3. **Given** an export of between 10,001 and 100,000 rows, in either mode, **When** it is exported, + **Then** it succeeds with every row. + +--- + +### User Story 6 - CSVs can be imported back (Priority: P2) + +An editor exports content, edits a CSV, and imports it back to update the same contentlets. + +**Why this priority**: Round-tripping is the stated purpose of keeping the legacy format. It depends +on the import ticket (#37896), so it is verified after that lands. + +**Independent Test**: Export a folder. Import one of its CSVs with Identifier as the key field and +no language selected (multilingual mode). The same contentlets are updated with no row errors. + +**Acceptance Scenarios**: + +1. **Given** a CSV from either mode, **When** it is imported with Identifier as the key field and no + language, **Then** the same contentlets are updated with no row errors. +2. **Given** the same content exported by the Content Search export and by Drive, **When** the two + CSVs are compared, **Then** the columns and values match, except for the host/folder column + (FR-022). + +--- + +### User Story 7 - Clear outcome when there is nothing to export or the export fails (Priority: P1) + +**Why this priority**: Without it the user cannot tell an empty export from a failed one. + +**Independent Test**: Export a filter that matches nothing the user can read, then force a +server-side failure. Each shows its own toast and neither downloads a file. + +**Acceptance Scenarios**: + +1. **Given** the filtered listing or the selection holds nothing the user can read, **When** the + user exports, **Then** the toast says there is nothing to export and no file downloads. +2. **Given** the export is refused or fails on the server, **When** it ends, **Then** the toast + shows the server's message and no file downloads. + +### Edge Cases + +- **Same content type reached several ways.** In selection mode, a content type's rows can be + reached through several folders, direct selections and query batches. The zip still has exactly + one CSV per content type with one header row (FR-018). +- **Two content types with the same name.** Content type names are not unique, but file names in a + zip must be. Both CSVs are kept, under distinct names (FR-019). +- **Content type name with characters not allowed in a file name** (`/`, `:`, …). The file name is + made safe and the CSV is still produced (FR-019). +- **Same identifier sent twice in a selection.** Exported once (FR-017). +- **Content type with no exportable fields.** Its CSV still has the Identifier, languageCode and + countryCode columns. +- **A field's value cannot be formatted.** As in legacy, the cell is left empty and the export + continues. +- **Relationship to content the user cannot read.** The relationship column lists every related + identifier, without filtering by the user's permissions, as legacy does (FR-024). +- **Filter mode on a Form type.** Forms are never exported, so the Export button is not offered for + a Form type filter (FR-007). +- **Listing changes while it is being exported.** Content created or deleted during a filter-mode + export may or may not be in the file; the export does not lock the listing. +- **60 items selected, one of them a large folder.** The 60-item limit counts what the user selected, + not what is below it: a folder is one item. The 100,000-row limit still applies to what the + selection expands to (FR-010). +- **Selected folder deleted between selection and export.** The path no longer resolves and the + request is rejected as invalid. +- **Failure halfway through.** The user gets an error status, not a truncated file, and no temporary + file stays on the server (FR-031, FR-032). + +## Requirements *(mandatory)* + +### Functional Requirements + +**Modes** + +- **FR-001**: The system MUST export in **filter mode** when the request carries no selection and + instead carries the Drive listing query (location and filters) restricted to exactly one content + type. Any Drive view is accepted: All Site Content, the site root, a folder, or System Host. +- **FR-002**: The system MUST export in **selection mode** when the request carries a selection: a + list of site-qualified folder paths (`//site/path/`, the form Drive sends for bulk duplicate) + and/or a list of contentlet identifiers. +- **FR-003**: When a request carries both a selection and a listing query, the selection MUST win + and the listing query MUST be ignored. +- **FR-004**: A filter-mode request whose listing query names no content type or more than one MUST + be refused as a bad request. Filter mode with several content types is not supported, so that the + Content Search behavior it mirrors is not changed. +- **FR-004a**: A selection MUST hold at most 60 items, counting folders and contentlets together. A + folder counts as one item, whatever it contains. A request whose selection has more than 60 + entries MUST be refused as a bad request. + +**What gets exported** + +- **FR-005**: In filter mode, the export MUST hold exactly the contentlets the Drive listing returns + for the same location and filters, across every page and with no paging limit. This includes the + listing's location rules: All Site Content spans the whole site at any depth; a folder, the site + root and System Host give only the contentlets that view lists. +- **FR-006**: In selection mode, a selected folder MUST export the contentlets directly in it and in + every subfolder at any depth. Folders MUST never be rows. +- **FR-007**: Form and Host content MUST never be exported in either mode. +- **FR-008**: In selection mode, every language version of each exported contentlet MUST be a row of + its own, and archived contentlets MUST be exported. Drive's filters (content type, text, workflow, + status, language, Include System Host) MUST NOT change what is exported. +- **FR-009**: In selection mode, a selected contentlet MUST be exported when the user can read it, + even if the user cannot read the folder it lives in. + +**Size limit** + +- **FR-010**: An export MUST hold at most 100,000 rows. In both modes, an export of more than + 100,000 rows the user can read MUST be refused before any file is produced, with a bad-request + response whose message states the row count and the limit. +- **FR-011**: Between 10,001 and 100,000 rows, every row MUST be exported. + +**Permissions** + +- **FR-012**: A contentlet the user cannot read MUST NOT be exported in either mode. +- **FR-013**: In selection mode, content in a subfolder the user cannot read MUST NOT be exported, at + any depth below that subfolder. +- **FR-014**: A request naming a folder the user cannot read MUST be refused as forbidden. +- **FR-015**: The response MUST NOT reveal how many items were skipped for permissions. The row + count given when refusing an export over the limit (FR-010) MUST count only rows the user can + read. + +**Files and names** + +- **FR-016**: A filter-mode export MUST produce a single CSV, not a zip. A selection-mode export MUST + produce a zip named `_export_.zip`, where `` is the site the user is + browsing in Drive and the date is the export date. +- **FR-017**: Each contentlet version (inode) MUST appear at most once. This applies when a + contentlet is selected and also inside a selected folder, when nested folders are both selected, + and when the same identifier is sent twice. +- **FR-018**: The zip MUST hold exactly one CSV per content type found, with exactly one header row. +- **FR-019**: Every CSV, alone or inside the zip, MUST be named + `_contents_.csv`, the name the Content Search export uses, where + `` is the content type's name. Names within one zip MUST be distinct and safe as file + names. When two content types would produce the same name, both CSVs MUST be kept under distinct + names. + +**CSV format** + +- **FR-020**: The CSV MUST be written by the same code as the Content Search export, moved into a + reusable piece that both call. +- **FR-021**: Each CSV's columns MUST be Identifier, languageCode, countryCode, then the content + type's exportable fields in field order, the same columns the Content Search export writes for the + same content type. +- **FR-022**: Field values MUST be formatted as the Content Search export formats them (category + keys, tag names, related identifiers, key-value fields as JSON, a page's URL as its path, image + paths, binary fields as a download URL, the legacy import/export date, datetime and time formats, + and the legacy quoting and line-ending rules), with one change: the host/folder field MUST be + written as `//site/path/` instead of the raw identifier. +- **FR-023**: The Content Search export MUST keep producing the same output it does today, including + its file name, its 100,000-row cut and its messages. +- **FR-024**: The relationship column MUST list every related identifier, without filtering by the + user's permissions, as legacy does. + +**Endpoint contract** + +- **FR-025**: Both modes MUST be served by one new Drive export endpoint. +- **FR-026**: On success the system MUST return the file as a download, with headers giving the + number of rows exported (`X-Export-Contentlets`), the number of CSV files (`X-Export-Files`) and + the file's size (`Content-Length`), all matching the file. +- **FR-027**: When there is nothing the user can read to export, the system MUST return "no + content" (204) and no file. +- **FR-028**: An empty selection with no listing query, a malformed or unresolvable folder path, a + filter-mode query not naming exactly one content type, a selection of more than 60 entries, and an + export over 100,000 rows MUST return "bad request" (400) with a message the UI can show. +- **FR-029**: When the export fails, the system MUST return a server error (500) with a JSON error + body carrying a message the UI can show. +- **FR-030**: The endpoint MUST be documented in the generated API documentation. +- **FR-031**: The system MUST NOT send a partial file. The whole file is built before any of it is + sent, so a failure halfway is reported as an error status. +- **FR-032**: The system MUST delete any temporary file it created for the export once the response + ends, whether the export succeeded or failed. +- **FR-033**: The export MUST NOT push websocket system messages ("Please wait…", "A total of N…"). + The Drive UI reports start, end and failure itself. + +**User interface** + +- **FR-034**: When nothing is selected and the listing is filtered to exactly one content type that + is not a Form, Drive MUST show the Export button in the toolbar, which exports in filter mode. + Otherwise, with nothing selected, it MUST NOT be shown. +- **FR-035**: When one or more items are selected, Drive MUST show the Export button beside the + workflow actions in the toolbar, which exports the selection. The Action Center MUST NOT list an + Export row. With more than 60 items selected, the button MUST be disabled and tell the user that + at most 60 items can be exported at once. +- **FR-036**: While an export runs, the Export button MUST show a loading state and be disabled. +- **FR-037**: On success, the browser MUST download the file under the server's file name, and a + toast MUST report the number of items and CSV files exported. +- **FR-038**: On a "no content" response the toast MUST say there is nothing to export. On a + bad-request or error response the toast MUST show the server's message. In none of these cases MAY + a file download. + +### Key Entities + +- **Listing query**: The Drive listing's location (All Site Content, site root, a folder, System + Host) and filters, restricted to one content type. +- **Export selection**: The folders (as site-qualified paths) and contentlets (as identifiers) the + user selected in Drive. +- **Readable folder set**: In selection mode, the selected folders plus every subfolder the user can + read, reached only through folders the user can read, without duplicates. +- **Export row**: One version of one contentlet in one language, written once. +- **Content-type CSV**: All export rows of one content type, with one header row, named + `_contents_.csv`. +- **Export file**: A single content-type CSV (filter mode) or a zip of content-type CSVs (selection + mode), with its row and file counts. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: Every export an editor can make today from Content Search (one content type, filtered + by site or folder, language, workflow, text and System Host) can be made from Drive in one + action, without paging through the listing first. +- **SC-002**: A user can export any mix of up to 60 selected folders and contentlets they can read, + of any number of content types, in one action, up to 100,000 rows. +- **SC-003**: For the same content, 100% of columns and values in a Drive CSV match the Content + Search export, except the host/folder column. +- **SC-004**: A CSV from either mode, imported back with Identifier as key and no language, updates + the same contentlets with 0 row errors. +- **SC-005**: With a limited user, 0 items the user cannot read appear in any export, across every + permission scenario in User Story 4. +- **SC-006**: In every export, each contentlet version appears exactly once and each content type + has exactly one CSV with one header row. +- **SC-007**: 0 exports are silently truncated. Every export over 100,000 rows is refused with a + message giving the count and the limit. +- **SC-008**: After any export, successful or failed, 0 temporary export files remain on the server. + +## Legacy Considerations *(dotCMS-specific — mandatory)* + +- **Existing behavior touched**: The CSV export of the legacy Content Search portlet + (`EditContentletAction`, `cmd=export`, written by `downloadToExcel`). Its row formatting is moved + into a reusable piece so Drive and Content Search write the same CSV (FR-020). Content Search + itself keeps its filters, single-type limit, silent 100,000-row cut and websocket messages + (FR-023). Drive's toolbar gains the Export button. Filter mode reuses the Drive listing's own + search, so it exports what the listing shows rather than reimplementing its filters. +- **Backward-compatibility expectations**: The Content Search export's file name, columns, values + and messages stay the same. The new endpoint is additive. No database schema or index mapping + changes. The Drive listing's search keeps its current behavior; filter mode only reads every page + of it. +- **Known related decisions**: + - Feature parity with Content Search is the first goal; selection is additional (team decision, + 2026-10-14). + - The Export button sits in the toolbar, beside the workflow actions when there is a selection, + not in the Action Center. This was decided in the team meeting. + - The relationship column keeps legacy behavior and is not filtered by the user's permissions + (FR-024). + - Content Search's folder filter and Drive's folder view both give only what sits directly in the + folder (`conFolder`). The Drive listing never treats a named folder as recursive + (`ContentDriveHelper.skipsFolderConstraint`), so filter mode in a folder matches Content Search + (FR-005). + - Folder paths use the same site-qualified form Drive already sends to bulk duplicate. + - The plan will formally consult `dotCMS/platform-adrs`. + +## Out of Scope + +- **Filter mode with more than one content type.** Content Search supports exactly one, and the + team chose not to change that behavior. Several content types are exported through selection. +- **Exporting across all sites at once.** Content Search's "all hosts" option has no Drive + equivalent, because Drive always works inside one site. +- **Recursive filter mode in a folder.** Content Search's folder filter is not recursive either. + Selecting the folder exports everything below it. +- Import (separate ticket, #37896). +- Background-job exports with a download link, for exports too large to hold in browser memory. +- Exporting file contents. Binary fields export as a download URL, as in legacy, so a folder of + files exports as metadata plus links, not a backup. +- Speeding up the legacy row writer (see Assumptions). + +## Assumptions + +- **Delivery order.** Filter mode (User Stories 1, 4, 5 and 7 for filter mode) is delivered first, + because it is parity. Selection mode (User Stories 2 and 3, and the selection cases of 4 and 5) + follows. They can ship as separate implementation PRs against this one spec. +- **Direction for the plan: resolve before writing, in both modes.** First, gather the distinct + contentlet versions the user can read, each with its content type: in filter mode by reading every + page of the listing, in selection mode by resolving the folders (recursively) and identifiers. + That gives the row count, so "nothing to export" (FR-027) and "over the limit" (FR-010) are + decided before any file is written. Then write one content type at a time, handing each type's + versions to the reused Content Search writer, which already works from a content type and a list + of versions. In selection mode this also avoids interleaving zip entries. The plan confirms or + changes this; the spec only fixes the outcomes. +- **Reading every page of the listing is the main risk of filter mode.** The listing combines + database and index results behind cursors, in pages of 2,000. Reusing it guarantees filter mode + matches what the user sees; the plan must confirm it can be walked to the end (or past 100,000) + correctly. +- **Readable contentlet in an unreadable folder (FR-009) comes from reading the code, not from a + reproduction.** A contentlet whose own permissions allow reading can show up in Drive's site-wide + listing, so it can be selected, and what is selected is exported. This has not yet been + reproduced with a limited user. The integration tests for User Story 4, scenario 3 are the first + confirmation. +- **Performance is out of scope beyond correctness.** The legacy row writer looks up categories, + tags, relationships and identifiers once per row, and the recursive folder walk checks + permissions one folder at a time. Parity with legacy output is required. Speeding these up is + not, but the plan should measure an export near 100,000 rows and a deep folder tree so the cost is + known. +- **The browser holds the file in memory.** The 100,000-row limit bounds its size. +- **Files and pages are content.** File assets, dotAssets and pages are contentlets and are exported + in their own types' CSVs. Menu links are not contentlets and are not exported. +- **Import is a separate ticket (#37896).** User Story 6 is verified once it lands; until then the + legacy import is used for the round-trip check. From 0472ab19e46596e79de3eb12bbe633c9ead66d8b Mon Sep 17 00:00:00 2001 From: ddariod Date: Wed, 14 Oct 2026 17:36:18 -0500 Subject: [PATCH 02/28] spec(content-drive): replace the stale input notes with the agreed export scope (#37900) The Input line still carried the open points from the first analysis, including the undefined in the zip file name, which the issue has since settled as _export_.zip. It now summarizes the agreed scope, and the refinement-history block is folded into it. Co-Authored-By: Claude Opus 5.5 --- specs/37900-content-drive-export/spec.md | 25 ++++++++---------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/specs/37900-content-drive-export/spec.md b/specs/37900-content-drive-export/spec.md index db3df10a52bb..364379f567e5 100644 --- a/specs/37900-content-drive-export/spec.md +++ b/specs/37900-content-drive-export/spec.md @@ -10,23 +10,14 @@ **Related GitHub Issue**: [#37900](https://github.com/dotCMS/core/issues/37900) -**Input**: User description: "https://github.com/dotCMS/core/issues/37900 — Content Drive: Add content export. Open points to capture from the previous analysis: (1) zip entries can't be interleaved and scroll runs in batches, so the same content type can appear in several batches — writing strategy (sort by contentType vs temp CSV per type) is a plan decision, but the spec must require one CSV per type with no duplicate headers; (2) the zip filename `_export_.zip` doesn't define `` for a mixed selection; (3) the rule \"readable contentlet inside unreadable folder is exported when selected directly\" has not been reproduced with a limited user yet; (4) the legacy writer does N+1 lookups per row (categories, tags, relationships, identifiers) — parity is required, performance is not in scope but should be noted." - -**Refined with the developer and the team (2026-10-14)**: - -- **Feature parity with Content Search comes first.** Whatever the Content Search export supports, - Drive must support (filter mode). With the listing filtered to exactly one content type, Export - downloads every result of the listing's filters (site or folder, language, workflow, status, - text, Include System Host), without paging, as one CSV. -- **Selection is a new, additional capability** (selection mode): folders and contentlets of - several content types, exported as a zip with one CSV per content type. -- Both are in scope, delivered parity first, then selection. -- The Content Search CSV format and file name are reused: `_contents_.csv`. - The zip is `_export_.zip`. -- The 100,000-row limit is kept in both modes, but a bigger export is refused with a clear message - instead of truncated. -- When there is a selection, the selection wins over the filter. -- A selection can hold at most 60 items (folders and contentlets together). +**Input**: [#37900](https://github.com/dotCMS/core/issues/37900) — Content Drive: Add content export. +Bring the Content Search CSV export to Drive with feature parity first (filter mode: exactly one +content type, every result of the listing's location and filters, as one CSV), then add selection +as new capability (selection mode: up to 60 folders and contentlets of any content types, as a zip +with one CSV per content type). Both reuse the Content Search CSV writer and file names +(`_contents_.csv`; the zip is `_export_.zip`), keep the +100,000-row limit but refuse bigger exports instead of truncating them, and let the selection win +over the filter. ## Context From 64fd7d0ed0ee26f6b2525054537ef2c485f41b21 Mon Sep 17 00:00:00 2001 From: ddariod Date: Thu, 15 Oct 2026 12:57:59 -0500 Subject: [PATCH 03/28] spec(content-drive): export only the selected language, empty listings and the full row range (#37900) A contentlet selected on its own is exported in the language version that was selected, while a selected folder still brings every language version and archived content below it. In filter mode the Export button is disabled when the listing shows nothing. Every export of 1 to 100,000 rows is complete, and exported CSVs must still import back unchanged. Co-Authored-By: Claude Opus 5.5 --- specs/37900-content-drive-export/spec.md | 128 ++++++++++++++--------- 1 file changed, 76 insertions(+), 52 deletions(-) diff --git a/specs/37900-content-drive-export/spec.md b/specs/37900-content-drive-export/spec.md index 364379f567e5..e3bf14c0ec3d 100644 --- a/specs/37900-content-drive-export/spec.md +++ b/specs/37900-content-drive-export/spec.md @@ -11,10 +11,10 @@ **Related GitHub Issue**: [#37900](https://github.com/dotCMS/core/issues/37900) **Input**: [#37900](https://github.com/dotCMS/core/issues/37900) — Content Drive: Add content export. -Bring the Content Search CSV export to Drive with feature parity first (filter mode: exactly one -content type, every result of the listing's location and filters, as one CSV), then add selection -as new capability (selection mode: up to 60 folders and contentlets of any content types, as a zip -with one CSV per content type). Both reuse the Content Search CSV writer and file names +Bring the Content Search CSV export to Content Drive with feature parity first (filter mode: exactly +one content type, every result of the listing's location and filters, as one CSV), then add +selection as new capability (selection mode: up to 60 folders and contentlets of any content types, +as a zip with one CSV per content type). Both reuse the Content Search CSV writer and file names (`_contents_.csv`; the zip is `_export_.zip`), keep the 100,000-row limit but refuse bigger exports instead of truncating them, and let the selection win over the filter. @@ -35,8 +35,9 @@ This feature brings that export to Drive, through one new endpoint, in two modes filters: All Site Content is the site filter, a folder is the folder filter (direct content only, in both), and the Include System Host chip is the System Host option. - **Selection mode (new).** The user selects folders and contentlets, of any content types. A - selected folder brings every contentlet below it, at any depth. Folders themselves are never - rows. The result is a zip with one CSV per content type. Drive's filters do not apply: **what you + selected contentlet is exported in the language version the user selected, and only that one. A + selected folder brings every contentlet below it, at any depth, in every language version and + including archived ones. Folders themselves are never rows. The result is a zip with one CSV per content type. Drive's filters do not apply: **what you select is what you export.** Each CSV has the same columns, values and file name as the Content Search export, so it can be @@ -67,22 +68,24 @@ CSV. 1. **Given** nothing is selected and the listing is filtered to exactly one content type that is not a Form, **When** the toolbar renders, **Then** the Export button is shown, in every Drive view (All Site Content, site root, a folder, System Host). -2. **Given** nothing is selected and the listing is filtered to no content type or to more than one, +2. **Given** the same, but the listing shows no contentlets for the current filters (none exist, or + none the user can read), **When** the toolbar renders, **Then** the Export button is disabled. +3. **Given** nothing is selected and the listing is filtered to no content type or to more than one, **When** the toolbar renders, **Then** the Export button is not shown. -3. **Given** the listing is filtered to one content type plus language, workflow, status, text or +4. **Given** the listing is filtered to one content type plus language, workflow, status, text or Include System Host, **When** the user exports, **Then** the CSV holds exactly the contentlets the listing shows with those filters, across every page. -4. **Given** the user is in All Site Content, **When** the user exports, **Then** matching +5. **Given** the user is in All Site Content, **When** the user exports, **Then** matching contentlets from the whole site, at any depth, are exported, plus System Host content when the listing includes it. -5. **Given** the user is inside a folder, **When** the user exports, **Then** only the matching +6. **Given** the user is inside a folder, **When** the user exports, **Then** only the matching contentlets directly in that folder are exported, as the listing shows them and as Content Search's folder filter does. -6. **Given** the user is in the site-root view or the System Host view, **When** the user exports, +7. **Given** the user is in the site-root view or the System Host view, **When** the user exports, **Then** exactly the matching contentlets that view lists are exported. -7. **Given** a filter-mode export, **When** it finishes, **Then** a single CSV (not a zip) named +8. **Given** a filter-mode export, **When** it finishes, **Then** a single CSV (not a zip) named `_contents_.csv` downloads, and a toast reports the number of rows. -8. **Given** an export is running, **When** the user looks at the Export button, **Then** it shows a +9. **Given** an export is running, **When** the user looks at the Export button, **Then** it shows a loading state and cannot be clicked again until the export ends. --- @@ -90,16 +93,18 @@ CSV. ### User Story 2 - Export selected contentlets of several content types (Priority: P2) An editor selects contentlets in Drive and clicks **Export**. A zip downloads with one CSV per -content type among them. Every language version of each selected contentlet is a row. +content type among them. Each selected row is exported as it was selected: the contentlet in that +language, and no other language version of it. **Why this priority**: It is new capability beyond Content Search. It reuses the CSV writer, the endpoint and the download from User Story 1, and adds the selection, the zip and the grouping by content type. **Independent Test**: On site `demo.dotcms.com`, select two contentlets of type "Blog" and one of -type "News", with one of the Blog contentlets having an English and a Spanish version. Export. The -zip is `demo.dotcms.com_export_.zip` and holds `Blog_contents_.csv` with 3 data rows and -`News_contents_.csv` with 1 data row. The toast reports 4 items and 2 files. +type "News", in English. One of the Blog contentlets also has a Spanish version, which is not +selected. Export. The zip is `demo.dotcms.com_export_.zip` and holds +`Blog_contents_.csv` with 2 data rows, both English, and `News_contents_.csv` with 1 +data row. The toast reports 3 items and 2 files. **Acceptance Scenarios**: @@ -109,9 +114,9 @@ zip is `demo.dotcms.com_export_.zip` and holds `Blog_contents_.csv` 2. **Given** contentlets of two content types are selected, **When** the user clicks Export, **Then** a zip downloads that holds one CSV per content type, and the toast reports the number of rows and CSV files exported. -3. **Given** a selected contentlet has versions in two languages, **When** it is exported, - **Then** its CSV has one row per language version, with the languageCode and countryCode - columns filled for each. +3. **Given** a contentlet has versions in two languages and only its English row is selected, + **When** it is exported, **Then** its CSV has only the English row. **Given** both language rows + are selected, **Then** both are exported, each with its languageCode and countryCode. 4. **Given** a selected contentlet is archived and readable by the user, **When** it is exported, **Then** it appears in its CSV. 5. **Given** Drive's filters are active (content type, text, workflow, status, language), **When** @@ -143,15 +148,18 @@ and no row stands for a folder. 1. **Given** a folder is selected, **When** it is exported, **Then** the contentlets directly in it and in all of its subfolders, at any depth, are exported, and no folder is a row. -2. **Given** a selected folder holds files and pages, **When** it is exported, **Then** they are +2. **Given** a selected folder holds a contentlet with versions in two languages, and an archived + contentlet, **When** it is exported, **Then** both language versions and the archived contentlet + are exported, each as its own row. +3. **Given** a selected folder holds files and pages, **When** it is exported, **Then** they are exported in their own content types' CSVs, with binary fields as a download URL. -3. **Given** a folder and a contentlet outside it are selected, **When** they are exported, **Then** +4. **Given** a folder and a contentlet outside it are selected, **When** they are exported, **Then** both are in the same zip. -4. **Given** a contentlet is selected directly and is also inside a selected folder, **When** they +5. **Given** a contentlet is selected directly and is also inside a selected folder, **When** they are exported, **Then** the contentlet appears in its CSV once. -5. **Given** a folder and one of its subfolders are both selected, **When** they are exported, +6. **Given** a folder and one of its subfolders are both selected, **When** they are exported, **Then** each contentlet appears once. -6. **Given** a selected folder contains Form or Host content, **When** it is exported, **Then** that +7. **Given** a selected folder contains Form or Host content, **When** it is exported, **Then** that content is not exported. --- @@ -201,25 +209,28 @@ user to narrow the filters. Repeat with a selection of folders holding 100,001 r limit. 2. **Given** a selection producing more than 100,000 readable rows, **When** it is exported, **Then** it is refused in the same way. -3. **Given** an export of between 10,001 and 100,000 rows, in either mode, **When** it is exported, - **Then** it succeeds with every row. +3. **Given** an export of 1 to 100,000 rows, in either mode, **When** it is exported, **Then** it + succeeds with every row. This includes exports of more than 10,000 rows, where a single search + page would stop. --- -### User Story 6 - CSVs can be imported back (Priority: P2) +### User Story 6 - CSVs can be imported back (Priority: P1) An editor exports content, edits a CSV, and imports it back to update the same contentlets. -**Why this priority**: Round-tripping is the stated purpose of keeping the legacy format. It depends -on the import ticket (#37896), so it is verified after that lands. +**Why this priority**: Keeping the legacy format is what makes the files importable. This ticket +moves the CSV writer and changes one column (host/folder), and neither may break importing. It is +checked as part of this ticket, without waiting for the Drive import ticket (#37896). -**Independent Test**: Export a folder. Import one of its CSVs with Identifier as the key field and -no language selected (multilingual mode). The same contentlets are updated with no row errors. +**Independent Test**: Export a filter-mode CSV and a selection-mode zip. Import one CSV of each with +Identifier as the key field and no language (multilingual file). The same contentlets are updated +with no row errors. **Acceptance Scenarios**: -1. **Given** a CSV from either mode, **When** it is imported with Identifier as the key field and no - language, **Then** the same contentlets are updated with no row errors. +1. **Given** a CSV from either mode, **When** it is imported back with Identifier as the key field + and no language, **Then** the same contentlets are updated with no row errors. 2. **Given** the same content exported by the Content Search export and by Drive, **When** the two CSVs are compared, **Then** the columns and values match, except for the host/folder column (FR-022). @@ -230,13 +241,18 @@ no language selected (multilingual mode). The same contentlets are updated with **Why this priority**: Without it the user cannot tell an empty export from a failed one. -**Independent Test**: Export a filter that matches nothing the user can read, then force a -server-side failure. Each shows its own toast and neither downloads a file. +In filter mode the user never reaches an empty export, because the button is disabled when the +listing is empty (FR-034). A selection can still turn out empty: a limited user can select a folder +they can read whose content they cannot read, or a folder with no content at all. + +**Independent Test**: As a limited user, select a folder you can read whose contentlets you cannot +read, and export. Then force a server-side failure. Each shows its own toast and neither downloads a +file. **Acceptance Scenarios**: -1. **Given** the filtered listing or the selection holds nothing the user can read, **When** the - user exports, **Then** the toast says there is nothing to export and no file downloads. +1. **Given** the selection holds nothing the user can read, **When** the user exports, **Then** the + toast says there is nothing to export and no file downloads. 2. **Given** the export is refused or fails on the server, **When** it ends, **Then** the toast shows the server's message and no file downloads. @@ -249,7 +265,10 @@ server-side failure. Each shows its own toast and neither downloads a file. zip must be. Both CSVs are kept, under distinct names (FR-019). - **Content type name with characters not allowed in a file name** (`/`, `:`, …). The file name is made safe and the CSV is still produced (FR-019). -- **Same identifier sent twice in a selection.** Exported once (FR-017). +- **Same contentlet version sent twice in a selection.** Exported once (FR-017). +- **A contentlet selected in one language that is also inside a selected folder.** The folder brings + every language version of its content (FR-006), so all of them are exported, and the selected + version still appears once (FR-017). - **Content type with no exportable fields.** Its CSV still has the Identifier, languageCode and countryCode columns. - **A field's value cannot be formatted.** As in legacy, the cell is left empty and the export @@ -279,7 +298,7 @@ server-side failure. Each shows its own toast and neither downloads a file. type. Any Drive view is accepted: All Site Content, the site root, a folder, or System Host. - **FR-002**: The system MUST export in **selection mode** when the request carries a selection: a list of site-qualified folder paths (`//site/path/`, the form Drive sends for bulk duplicate) - and/or a list of contentlet identifiers. + and/or a list of the selected contentlet versions, each naming one contentlet in one language. - **FR-003**: When a request carries both a selection and a listing query, the selection MUST win and the listing query MUST be ignored. - **FR-004**: A filter-mode request whose listing query names no content type or more than one MUST @@ -296,11 +315,13 @@ server-side failure. Each shows its own toast and neither downloads a file. listing's location rules: All Site Content spans the whole site at any depth; a folder, the site root and System Host give only the contentlets that view lists. - **FR-006**: In selection mode, a selected folder MUST export the contentlets directly in it and in - every subfolder at any depth. Folders MUST never be rows. + every subfolder at any depth, in every language version and including archived contentlets, each + version as its own row. Folders MUST never be rows. - **FR-007**: Form and Host content MUST never be exported in either mode. -- **FR-008**: In selection mode, every language version of each exported contentlet MUST be a row of - its own, and archived contentlets MUST be exported. Drive's filters (content type, text, workflow, - status, language, Include System Host) MUST NOT change what is exported. +- **FR-008**: In selection mode, a selected contentlet MUST be exported only in the language version + the user selected; its other language versions MUST NOT be exported unless they were selected + too. A selected archived contentlet MUST be exported. Drive's filters (content type, text, + workflow, status, language, Include System Host) MUST NOT change what is exported. - **FR-009**: In selection mode, a selected contentlet MUST be exported when the user can read it, even if the user cannot read the folder it lives in. @@ -309,7 +330,8 @@ server-side failure. Each shows its own toast and neither downloads a file. - **FR-010**: An export MUST hold at most 100,000 rows. In both modes, an export of more than 100,000 rows the user can read MUST be refused before any file is produced, with a bad-request response whose message states the row count and the limit. -- **FR-011**: Between 10,001 and 100,000 rows, every row MUST be exported. +- **FR-011**: Any export of 1 to 100,000 rows MUST include every row, including exports of more than + 10,000 rows. **Permissions** @@ -328,7 +350,7 @@ server-side failure. Each shows its own toast and neither downloads a file. browsing in Drive and the date is the export date. - **FR-017**: Each contentlet version (inode) MUST appear at most once. This applies when a contentlet is selected and also inside a selected folder, when nested folders are both selected, - and when the same identifier is sent twice. + and when the same version is sent twice. - **FR-018**: The zip MUST hold exactly one CSV per content type found, with exactly one header row. - **FR-019**: Every CSV, alone or inside the zip, MUST be named `_contents_.csv`, the name the Content Search export uses, where @@ -377,8 +399,9 @@ server-side failure. Each shows its own toast and neither downloads a file. **User interface** - **FR-034**: When nothing is selected and the listing is filtered to exactly one content type that - is not a Form, Drive MUST show the Export button in the toolbar, which exports in filter mode. - Otherwise, with nothing selected, it MUST NOT be shown. + is not a Form, Drive MUST show the Export button in the toolbar, which exports in filter mode. If + the listing shows no contentlets for the current filters, the button MUST be disabled. Otherwise, + with nothing selected, it MUST NOT be shown. - **FR-035**: When one or more items are selected, Drive MUST show the Export button beside the workflow actions in the toolbar, which exports the selection. The Action Center MUST NOT list an Export row. With more than 60 items selected, the button MUST be disabled and tell the user that @@ -394,8 +417,8 @@ server-side failure. Each shows its own toast and neither downloads a file. - **Listing query**: The Drive listing's location (All Site Content, site root, a folder, System Host) and filters, restricted to one content type. -- **Export selection**: The folders (as site-qualified paths) and contentlets (as identifiers) the - user selected in Drive. +- **Export selection**: The folders (as site-qualified paths) and contentlet versions (each one + contentlet in one language) the user selected in Drive. - **Readable folder set**: In selection mode, the selected folders plus every subfolder the user can read, reached only through folders the user can read, without duplicates. - **Export row**: One version of one contentlet in one language, written once. @@ -495,5 +518,6 @@ server-side failure. Each shows its own toast and neither downloads a file. - **The browser holds the file in memory.** The 100,000-row limit bounds its size. - **Files and pages are content.** File assets, dotAssets and pages are contentlets and are exported in their own types' CSVs. Menu links are not contentlets and are not exported. -- **Import is a separate ticket (#37896).** User Story 6 is verified once it lands; until then the - legacy import is used for the round-trip check. +- **Importing is not changed by this ticket.** The export changes must not affect how CSVs import. + User Story 6 is checked within this ticket; the Drive import (#37896) is a separate ticket and is + not needed to verify it. From 8d3e9b4e081fabc7a9f99eceae29a70946e1687f Mon Sep 17 00:00:00 2001 From: ddariod Date: Thu, 15 Oct 2026 13:12:44 -0500 Subject: [PATCH 04/28] spec(content-drive): address the spec review on export versions, completeness and leaks (#37900) Export only the working version, one row per identifier and language, so a published contentlet edited afterwards cannot produce two rows. Filter mode must read a complete result for the listing's query instead of walking the listing's screen pages, which come back short past the database scan budget. The content type is validated after it is resolved, so a missing or unreadable type is refused instead of falling through to every type. Rows that become unreadable mid-export are skipped and not counted. An unreadable folder and a missing one get the same 404, and selections are limited to the browsed site and System Host. Co-Authored-By: Claude Opus 5.5 --- specs/37900-content-drive-export/spec.md | 116 +++++++++++++++-------- 1 file changed, 78 insertions(+), 38 deletions(-) diff --git a/specs/37900-content-drive-export/spec.md b/specs/37900-content-drive-export/spec.md index e3bf14c0ec3d..1848e3239a95 100644 --- a/specs/37900-content-drive-export/spec.md +++ b/specs/37900-content-drive-export/spec.md @@ -72,20 +72,23 @@ CSV. none the user can read), **When** the toolbar renders, **Then** the Export button is disabled. 3. **Given** nothing is selected and the listing is filtered to no content type or to more than one, **When** the toolbar renders, **Then** the Export button is not shown. -4. **Given** the listing is filtered to one content type plus language, workflow, status, text or +4. **Given** a filter-mode request names a content type that does not exist or that the user + cannot read, **When** it reaches the server, **Then** it is refused with the same bad-request + message in both cases, and no other content type is exported in its place. +5. **Given** the listing is filtered to one content type plus language, workflow, status, text or Include System Host, **When** the user exports, **Then** the CSV holds exactly the contentlets the listing shows with those filters, across every page. -5. **Given** the user is in All Site Content, **When** the user exports, **Then** matching +6. **Given** the user is in All Site Content, **When** the user exports, **Then** matching contentlets from the whole site, at any depth, are exported, plus System Host content when the listing includes it. -6. **Given** the user is inside a folder, **When** the user exports, **Then** only the matching +7. **Given** the user is inside a folder, **When** the user exports, **Then** only the matching contentlets directly in that folder are exported, as the listing shows them and as Content Search's folder filter does. -7. **Given** the user is in the site-root view or the System Host view, **When** the user exports, +8. **Given** the user is in the site-root view or the System Host view, **When** the user exports, **Then** exactly the matching contentlets that view lists are exported. -8. **Given** a filter-mode export, **When** it finishes, **Then** a single CSV (not a zip) named +9. **Given** a filter-mode export, **When** it finishes, **Then** a single CSV (not a zip) named `_contents_.csv` downloads, and a toast reports the number of rows. -9. **Given** an export is running, **When** the user looks at the Export button, **Then** it shows a +10. **Given** an export is running, **When** the user looks at the Export button, **Then** it shows a loading state and cannot be clicked again until the export ends. --- @@ -185,10 +188,17 @@ nor Z. Neither response gives a count of skipped items. **Then** no content from that subfolder or anything below it is exported. 3. **Given** a contentlet the user can read lives in a folder the user cannot read, **When** the user selects it directly and exports, **Then** it is exported. -4. **Given** the request names a folder the user cannot read, **When** it is submitted, **Then** it - is refused as forbidden and no file is produced. -5. **Given** some items were skipped for permissions, **When** the export finishes, **Then** neither +4. **Given** the request names a folder the user cannot read, or a folder that does not exist, + **When** it is submitted, **Then** both are refused with the same "not found" response, so a + limited user cannot tell whether the folder exists, and no file is produced. +5. **Given** a hand-built request names a folder from a site other than the one being browsed, or + a contentlet that is neither in that site nor in System Host, **When** it is submitted, **Then** + it is refused with the same "not found" response. +6. **Given** some items were skipped for permissions, **When** the export finishes, **Then** neither the file, the counts, nor the toast reveals how many were skipped. +7. **Given** a contentlet stops being readable between the moment the export counts it and the + moment its row is written, **When** the export runs, **Then** that row is skipped, the export + still succeeds, and the reported row count matches the rows actually written. --- @@ -282,8 +292,13 @@ file. - **60 items selected, one of them a large folder.** The 60-item limit counts what the user selected, not what is below it: a folder is one item. The 100,000-row limit still applies to what the selection expands to (FR-010). +- **Published contentlet edited afterwards.** It has a live and a working version in the same + language. Only the working version is exported, so the file never holds two rows with the same + Identifier and language (FR-017a). - **Selected folder deleted between selection and export.** The path no longer resolves and the - request is rejected as invalid. + request is refused with the same "not found" response as an unreadable folder (FR-014). +- **Permissions change while the export runs.** A contentlet that stops being readable after it was + counted is skipped, not turned into an error (FR-026a). - **Failure halfway through.** The user gets an error status, not a truncated file, and no temporary file stays on the server (FR-031, FR-032). @@ -298,22 +313,32 @@ file. type. Any Drive view is accepted: All Site Content, the site root, a folder, or System Host. - **FR-002**: The system MUST export in **selection mode** when the request carries a selection: a list of site-qualified folder paths (`//site/path/`, the form Drive sends for bulk duplicate) - and/or a list of the selected contentlet versions, each naming one contentlet in one language. + and/or a list of the selected contentlet versions, each naming one contentlet in one language. The + request MUST also name the site being browsed in Drive. +- **FR-002a**: Every selected folder MUST belong to the site being browsed, and every selected + contentlet MUST belong to that site or to System Host (which All Site Content can list). Any other + entry MUST be refused with the same "not found" response as an unreadable folder (FR-014). - **FR-003**: When a request carries both a selection and a listing query, the selection MUST win and the listing query MUST be ignored. - **FR-004**: A filter-mode request whose listing query names no content type or more than one MUST be refused as a bad request. Filter mode with several content types is not supported, so that the - Content Search behavior it mirrors is not changed. + Content Search behavior it mirrors is not changed. The check MUST be made on the content type as + resolved for the user, before any content is read: a content type that does not exist and one the + user cannot read MUST both be refused, with the same bad-request message. An unresolved type MUST + never fall through to a query with no content type restriction. - **FR-004a**: A selection MUST hold at most 60 items, counting folders and contentlets together. A folder counts as one item, whatever it contains. A request whose selection has more than 60 entries MUST be refused as a bad request. **What gets exported** -- **FR-005**: In filter mode, the export MUST hold exactly the contentlets the Drive listing returns - for the same location and filters, across every page and with no paging limit. This includes the - listing's location rules: All Site Content spans the whole site at any depth; a folder, the site - root and System Host give only the contentlets that view lists. +- **FR-005**: In filter mode, the export MUST hold the complete set of readable contentlets that the + same query the Drive listing uses would return, with the listing's location rules: All Site + Content spans the whole site at any depth; a folder, the site root and System Host give only the + contentlets that view lists. The export MUST obtain that set through an operation that guarantees + it is complete. It MUST NOT depend on how the listing pages its results for the screen (page + sizes, cursors, scan budgets), so that a change to the listing's paging cannot silently drop + rows from an export. - **FR-006**: In selection mode, a selected folder MUST export the contentlets directly in it and in every subfolder at any depth, in every language version and including archived contentlets, each version as its own row. Folders MUST never be rows. @@ -338,7 +363,9 @@ file. - **FR-012**: A contentlet the user cannot read MUST NOT be exported in either mode. - **FR-013**: In selection mode, content in a subfolder the user cannot read MUST NOT be exported, at any depth below that subfolder. -- **FR-014**: A request naming a folder the user cannot read MUST be refused as forbidden. +- **FR-014**: A request naming a folder the user cannot read, or a folder that does not exist, MUST + be refused with the same "not found" (404) response and message, so the response never reveals + whether a folder exists. - **FR-015**: The response MUST NOT reveal how many items were skipped for permissions. The row count given when refusing an export over the limit (FR-010) MUST count only rows the user can read. @@ -351,6 +378,9 @@ file. - **FR-017**: Each contentlet version (inode) MUST appear at most once. This applies when a contentlet is selected and also inside a selected folder, when nested folders are both selected, and when the same version is sent twice. +- **FR-017a**: Every row MUST be the working version of its contentlet in its language, in both + modes, as the Content Search export does. There MUST be at most one row per identifier and + language. A live version that differs from the working one MUST NOT be exported. - **FR-018**: The zip MUST hold exactly one CSV per content type found, with exactly one header row. - **FR-019**: Every CSV, alone or inside the zip, MUST be named `_contents_.csv`, the name the Content Search export uses, where @@ -381,11 +411,15 @@ file. - **FR-026**: On success the system MUST return the file as a download, with headers giving the number of rows exported (`X-Export-Contentlets`), the number of CSV files (`X-Export-Files`) and the file's size (`Content-Length`), all matching the file. +- **FR-026a**: A contentlet that was counted for the export but cannot be read when its row is + written (its permissions changed in between) MUST be skipped, not turned into an error. The + row count in `X-Export-Contentlets` and in the toast MUST be the number of rows actually written. - **FR-027**: When there is nothing the user can read to export, the system MUST return "no content" (204) and no file. -- **FR-028**: An empty selection with no listing query, a malformed or unresolvable folder path, a - filter-mode query not naming exactly one content type, a selection of more than 60 entries, and an - export over 100,000 rows MUST return "bad request" (400) with a message the UI can show. +- **FR-028**: An empty selection with no listing query, a malformed folder path, a filter-mode query + not naming exactly one readable content type, a selection of more than 60 entries, and an export + over 100,000 rows MUST return "bad request" (400) with a message the UI can show. A folder that + does not resolve is "not found" (404), as an unreadable one is (FR-014). - **FR-029**: When the export fails, the system MUST return a server error (500) with a JSON error body carrying a message the UI can show. - **FR-030**: The endpoint MUST be documented in the generated API documentation. @@ -417,11 +451,11 @@ file. - **Listing query**: The Drive listing's location (All Site Content, site root, a folder, System Host) and filters, restricted to one content type. -- **Export selection**: The folders (as site-qualified paths) and contentlet versions (each one - contentlet in one language) the user selected in Drive. +- **Export selection**: The site being browsed, plus the folders (as site-qualified paths) and + contentlet versions (each one contentlet in one language) the user selected in Drive. - **Readable folder set**: In selection mode, the selected folders plus every subfolder the user can read, reached only through folders the user can read, without duplicates. -- **Export row**: One version of one contentlet in one language, written once. +- **Export row**: The working version of one contentlet in one language, written once. - **Content-type CSV**: All export rows of one content type, with one header row, named `_contents_.csv`. - **Export file**: A single content-type CSV (filter mode) or a zip of content-type CSVs (selection @@ -454,12 +488,12 @@ file. (`EditContentletAction`, `cmd=export`, written by `downloadToExcel`). Its row formatting is moved into a reusable piece so Drive and Content Search write the same CSV (FR-020). Content Search itself keeps its filters, single-type limit, silent 100,000-row cut and websocket messages - (FR-023). Drive's toolbar gains the Export button. Filter mode reuses the Drive listing's own - search, so it exports what the listing shows rather than reimplementing its filters. + (FR-023). Drive's toolbar gains the Export button. Filter mode uses the same query as the Drive + listing, so it exports what the listing shows rather than reimplementing its filters, but reads it + through an operation that returns the complete set (FR-005). - **Backward-compatibility expectations**: The Content Search export's file name, columns, values and messages stay the same. The new endpoint is additive. No database schema or index mapping - changes. The Drive listing's search keeps its current behavior; filter mode only reads every page - of it. + changes. The Drive listing's search keeps its current behavior for the screen. - **Known related decisions**: - Feature parity with Content Search is the first goal; selection is additional (team decision, 2026-10-14). @@ -494,17 +528,23 @@ file. because it is parity. Selection mode (User Stories 2 and 3, and the selection cases of 4 and 5) follows. They can ship as separate implementation PRs against this one spec. - **Direction for the plan: resolve before writing, in both modes.** First, gather the distinct - contentlet versions the user can read, each with its content type: in filter mode by reading every - page of the listing, in selection mode by resolving the folders (recursively) and identifiers. - That gives the row count, so "nothing to export" (FR-027) and "over the limit" (FR-010) are - decided before any file is written. Then write one content type at a time, handing each type's - versions to the reused Content Search writer, which already works from a content type and a list - of versions. In selection mode this also avoids interleaving zip entries. The plan confirms or - changes this; the spec only fixes the outcomes. -- **Reading every page of the listing is the main risk of filter mode.** The listing combines - database and index results behind cursors, in pages of 2,000. Reusing it guarantees filter mode - matches what the user sees; the plan must confirm it can be walked to the end (or past 100,000) - correctly. + contentlet versions the user can read, each with its content type: in filter mode from the + complete result of the listing's query (FR-005), in selection mode by resolving the folders + (recursively) and the selected versions. Keep this step light: only identifiers, languages and + content types, with permissions checked in batches (`permissionAPI.filterCollection`), and no + loading or formatting of contentlets. That gives the row count, so "nothing to export" (FR-027) + and "over the limit" (FR-010) are decided before any file is written. Then write one content type + at a time, handing each type's versions to the reused Content Search writer, which already works + from a content type and a list of versions. In selection mode this also avoids interleaving zip + entries. The plan confirms or changes this; the spec only fixes the outcomes. +- **A complete listing result is the main risk of filter mode.** The listing's search is built to + serve the screen. Walking its pages to the end is not safe: past the database scan budget + (`BROWSER_DB_MAX_SCAN_ROWS`, 50,000 by default, compared against the absolute offset in + `BrowserAPIImpl.getContentByChunks`) nearly every page comes back short while still reporting more + results, so an exporter that stops on a short page would drop rows silently. The existing + fetch-everything path (`maxRows <= 0`) only covers searches without a text filter. The plan must + choose an operation that returns the complete set for the same query and hides the chunking, for + example a dedicated `BrowserAPI` method. - **Readable contentlet in an unreadable folder (FR-009) comes from reading the code, not from a reproduction.** A contentlet whose own permissions allow reading can show up in Drive's site-wide listing, so it can be selected, and what is selected is exported. This has not yet been From 6824a7be47a4d8d29e5296934a451e2f7a0bff2f Mon Sep 17 00:00:00 2001 From: ddariod Date: Thu, 15 Oct 2026 13:32:18 -0500 Subject: [PATCH 05/28] spec(content-drive): stop counting past the export limit and keep the shared writer silent (#37900) Refusing an export over 100,000 rows no longer needs the exact total, so counting can stop at 100,001 instead of resolving and permission-checking a content type with millions of contentlets just to reject it. The message says the export has more than 100,000 rows. The writer moved out of downloadToExcel must not push websocket messages itself: Content Search keeps sending them from its caller, Drive does not. Co-Authored-By: Claude Opus 5.5 --- specs/37900-content-drive-export/spec.md | 31 +++++++++++++++--------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/specs/37900-content-drive-export/spec.md b/specs/37900-content-drive-export/spec.md index 1848e3239a95..8bc35c67f6ce 100644 --- a/specs/37900-content-drive-export/spec.md +++ b/specs/37900-content-drive-export/spec.md @@ -209,14 +209,15 @@ leaves the user with a file that looks complete and is not. In selection mode a drop arbitrary rows. **Independent Test**: Filter to a content type with 100,001 readable contentlets and export. Nothing -downloads, and the toast says the export has 100,001 rows and the limit is 100,000, and asks the -user to narrow the filters. Repeat with a selection of folders holding 100,001 readable rows. +downloads, and the toast says the export has more than 100,000 rows, that 100,000 is the limit, and +asks the user to narrow the filters. Repeat with a selection of folders holding 100,001 readable +rows. **Acceptance Scenarios**: 1. **Given** a filter-mode export producing more than 100,000 rows the user can read, **When** it is - exported, **Then** it is refused, no file downloads, and the message gives the row count and the - limit. + exported, **Then** it is refused, no file downloads, and the message says the export has more + than 100,000 rows and that 100,000 is the limit. 2. **Given** a selection producing more than 100,000 readable rows, **When** it is exported, **Then** it is refused in the same way. 3. **Given** an export of 1 to 100,000 rows, in either mode, **When** it is exported, **Then** it @@ -354,7 +355,10 @@ file. - **FR-010**: An export MUST hold at most 100,000 rows. In both modes, an export of more than 100,000 rows the user can read MUST be refused before any file is produced, with a bad-request - response whose message states the row count and the limit. + response whose message says the export has more than 100,000 rows and that 100,000 is the limit. + The message MUST NOT need the exact total: counting MAY stop at the first row past the limit, so + rejecting a very large export (for example a content type with millions of contentlets) costs no + more than resolving 100,001 rows. - **FR-011**: Any export of 1 to 100,000 rows MUST include every row, including exports of more than 10,000 rows. @@ -366,9 +370,8 @@ file. - **FR-014**: A request naming a folder the user cannot read, or a folder that does not exist, MUST be refused with the same "not found" (404) response and message, so the response never reveals whether a folder exists. -- **FR-015**: The response MUST NOT reveal how many items were skipped for permissions. The row - count given when refusing an export over the limit (FR-010) MUST count only rows the user can - read. +- **FR-015**: The response MUST NOT reveal how many items were skipped for permissions. Only rows + the user can read count toward the 100,000 limit (FR-010). **Files and names** @@ -391,7 +394,10 @@ file. **CSV format** - **FR-020**: The CSV MUST be written by the same code as the Content Search export, moved into a - reusable piece that both call. + reusable piece that both call. The shared piece MUST only write the CSV and MUST NOT push websocket + system messages. Today `downloadToExcel` pushes the "A total of N…" and error messages itself, so + the extraction moves them to its caller: Content Search keeps sending them (FR-023), and Drive + does not (FR-033). - **FR-021**: Each CSV's columns MUST be Identifier, languageCode, countryCode, then the content type's exportable fields in field order, the same columns the Content Search export writes for the same content type. @@ -479,7 +485,7 @@ file. - **SC-006**: In every export, each contentlet version appears exactly once and each content type has exactly one CSV with one header row. - **SC-007**: 0 exports are silently truncated. Every export over 100,000 rows is refused with a - message giving the count and the limit. + message saying it has more than 100,000 rows and that 100,000 is the limit. - **SC-008**: After any export, successful or failed, 0 temporary export files remain on the server. ## Legacy Considerations *(dotCMS-specific — mandatory)* @@ -532,8 +538,9 @@ file. complete result of the listing's query (FR-005), in selection mode by resolving the folders (recursively) and the selected versions. Keep this step light: only identifiers, languages and content types, with permissions checked in batches (`permissionAPI.filterCollection`), and no - loading or formatting of contentlets. That gives the row count, so "nothing to export" (FR-027) - and "over the limit" (FR-010) are decided before any file is written. Then write one content type + loading or formatting of contentlets, and stop as soon as the count passes 100,000. That gives + the row count, so "nothing to export" (FR-027) and "over the limit" (FR-010) are decided before + any file is written. Then write one content type at a time, handing each type's versions to the reused Content Search writer, which already works from a content type and a list of versions. In selection mode this also avoids interleaving zip entries. The plan confirms or changes this; the spec only fixes the outcomes. From e63e59cb78da6cd508f6905333b3b2f95583244e Mon Sep 17 00:00:00 2001 From: ddariod Date: Thu, 15 Oct 2026 15:29:05 -0500 Subject: [PATCH 06/28] spec(content-drive): keep root content on its site on re-import and harden the shared writer (#37900) Written as //site/, content at a site root is moved to System Host on re-import, because the import resolves the path / to the system folder. The host/folder column now uses the form the import already resolves for each case: //site/path/ in a folder, the bare hostname at a site root, and SYSTEM_HOST for System Host. Re-import tests must check the location, not only the absence of row errors. The writer moved out of downloadToExcel propagates whole-file failures, skips rows that are no longer readable, writes to a given output instead of the response, and reports how many rows it wrote. The working-version rule cites the Content Search query it mirrors and must be proven with a contentlet published and then edited. Co-Authored-By: Claude Opus 5.5 --- specs/37900-content-drive-export/spec.md | 48 ++++++++++++++++++++---- 1 file changed, 40 insertions(+), 8 deletions(-) diff --git a/specs/37900-content-drive-export/spec.md b/specs/37900-content-drive-export/spec.md index 8bc35c67f6ce..ce8ec1237bb7 100644 --- a/specs/37900-content-drive-export/spec.md +++ b/specs/37900-content-drive-export/spec.md @@ -234,15 +234,19 @@ An editor exports content, edits a CSV, and imports it back to update the same c moves the CSV writer and changes one column (host/folder), and neither may break importing. It is checked as part of this ticket, without waiting for the Drive import ticket (#37896). -**Independent Test**: Export a filter-mode CSV and a selection-mode zip. Import one CSV of each with -Identifier as the key field and no language (multilingual file). The same contentlets are updated -with no row errors. +**Independent Test**: Export a filter-mode CSV and a selection-mode zip that together hold content in +a folder, content at a site root and content in System Host. Import one CSV of each with Identifier +as the key field and no language (multilingual file). The same contentlets are updated with no row +errors, and each one is still on the same site and in the same folder. **Acceptance Scenarios**: 1. **Given** a CSV from either mode, **When** it is imported back with Identifier as the key field and no language, **Then** the same contentlets are updated with no row errors. -2. **Given** the same content exported by the Content Search export and by Drive, **When** the two +2. **Given** a CSV holding a contentlet in a folder, one at a site root and one in System Host, + **When** it is imported back, **Then** each contentlet ends up on the same site and in the same + folder it was exported from. A missing row error is not enough: the location itself is checked. +3. **Given** the same content exported by the Content Search export and by Drive, **When** the two CSVs are compared, **Then** the columns and values match, except for the host/folder column (FR-022). @@ -293,6 +297,9 @@ file. - **60 items selected, one of them a large folder.** The 60-item limit counts what the user selected, not what is below it: a folder is one item. The 100,000-row limit still applies to what the selection expands to (FR-010). +- **Content at a site root.** Its host/folder column is the bare hostname, not `//site/`. Written as + `//site/`, the import would resolve the path `/` to the system folder and silently move the + contentlet to System Host, with no row error (FR-022). - **Published contentlet edited afterwards.** It has a live and a working version in the same language. Only the working version is exported, so the file never holds two rows with the same Identifier and language (FR-017a). @@ -382,8 +389,10 @@ file. contentlet is selected and also inside a selected folder, when nested folders are both selected, and when the same version is sent twice. - **FR-017a**: Every row MUST be the working version of its contentlet in its language, in both - modes, as the Content Search export does. There MUST be at most one row per identifier and - language. A live version that differs from the working one MUST NOT be exported. + modes, as the Content Search export does (its search adds `+working:true`, + `ContentletAjax.java:1049`). There MUST be at most one row per identifier and language. A live + version that differs from the working one MUST NOT be exported. This MUST be proven with a + contentlet that was published and then edited: the export holds one row with the edited values. - **FR-018**: The zip MUST hold exactly one CSV per content type found, with exactly one header row. - **FR-019**: Every CSV, alone or inside the zip, MUST be named `_contents_.csv`, the name the Content Search export uses, where @@ -398,6 +407,17 @@ file. system messages. Today `downloadToExcel` pushes the "A total of N…" and error messages itself, so the extraction moves them to its caller: Content Search keeps sending them (FR-023), and Drive does not (FR-033). +- **FR-020a**: The shared writer MUST change how `downloadToExcel` handles failures today, while + keeping its output: + - A failure of the whole file MUST propagate to the caller, not be caught and followed by a + success message. Drive turns it into a server error (FR-029); Content Search's caller keeps + catching it and pushing its messages (FR-023). + - A failure formatting one field MUST still leave that cell empty and continue, as today. + - A contentlet that can no longer be read when its row is written MUST be skipped, not abort the + export (FR-026a). + - It MUST write to an output it is given, not to the HTTP response, so the file is complete before + anything is sent (FR-031). + - It MUST report the number of rows it wrote, which is the count Drive returns (FR-026a). - **FR-021**: Each CSV's columns MUST be Identifier, languageCode, countryCode, then the content type's exportable fields in field order, the same columns the Content Search export writes for the same content type. @@ -405,7 +425,18 @@ file. keys, tag names, related identifiers, key-value fields as JSON, a page's URL as its path, image paths, binary fields as a download URL, the legacy import/export date, datetime and time formats, and the legacy quoting and line-ending rules), with one change: the host/folder field MUST be - written as `//site/path/` instead of the raw identifier. + written as a readable location instead of the raw identifier, in the form the existing import + already resolves correctly for each case: + - content in a folder: `//site/path/`; + - content at a site root: the bare hostname, for example `demo.dotcms.com`; + - content in System Host: `SYSTEM_HOST`. + + The column is deliberately not uniform, and MUST NOT be "normalized" to `//site/path/` for every + row. The import splits `//site/` into the site and the path `/`, and resolving `/` always gives + the system folder, whose host is System Host (`ImportUtil.getSiteAndFolderFromIdOrName`, + `FolderFactoryImpl.findFolderByPath`). Content at a site root written that way would be moved to + System Host on re-import, with no row error. A bare hostname is resolved by name, and + `SYSTEM_HOST` by identifier, with no folder lookup. This ticket does not change the import. - **FR-023**: The Content Search export MUST keep producing the same output it does today, including its file name, its 100,000-row cut and its messages. - **FR-024**: The relationship column MUST list every related identifier, without filtering by the @@ -479,7 +510,8 @@ file. - **SC-003**: For the same content, 100% of columns and values in a Drive CSV match the Content Search export, except the host/folder column. - **SC-004**: A CSV from either mode, imported back with Identifier as key and no language, updates - the same contentlets with 0 row errors. + the same contentlets with 0 row errors, and 100% of them stay on the same site and in the same + folder, for content in a folder, at a site root and in System Host. - **SC-005**: With a limited user, 0 items the user cannot read appear in any export, across every permission scenario in User Story 4. - **SC-006**: In every export, each contentlet version appears exactly once and each content type From 8a81572efd6c243f5aad0ed2c82e8e3ae50ebed7 Mon Sep 17 00:00:00 2001 From: ddariod Date: Thu, 15 Oct 2026 16:15:36 -0500 Subject: [PATCH 07/28] spec(content-drive): record the relationship-column parity decision and its follow-up (#37900) The relationship column keeps listing every related identifier, as the Content Search export does today. That is now recorded as an explicit feature-parity decision from the spec review rather than inherited behavior, with filtering by read permission and protecting hidden relationships on re-import tracked in #38055. Co-Authored-By: Claude Opus 5.5 --- specs/37900-content-drive-export/spec.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/specs/37900-content-drive-export/spec.md b/specs/37900-content-drive-export/spec.md index ce8ec1237bb7..3f08d9c3fd8c 100644 --- a/specs/37900-content-drive-export/spec.md +++ b/specs/37900-content-drive-export/spec.md @@ -440,7 +440,9 @@ file. - **FR-023**: The Content Search export MUST keep producing the same output it does today, including its file name, its 100,000-row cut and its messages. - **FR-024**: The relationship column MUST list every related identifier, without filtering by the - user's permissions, as legacy does. + user's permissions, as legacy does. This is an explicit feature-parity decision, not inherited + behavior: filtering related identifiers by read permission changes the Content Search export too, + so it is handled in #38055, together with keeping hidden relationships on re-import. **Endpoint contract** @@ -538,7 +540,11 @@ file. - The Export button sits in the toolbar, beside the workflow actions when there is a selection, not in the Action Center. This was decided in the team meeting. - The relationship column keeps legacy behavior and is not filtered by the user's permissions - (FR-024). + (FR-024). This was decided explicitly in the spec review, as feature parity: today's Content + Search export already writes every related identifier unchecked (`loadRelationships`, with + records from `getFieldValue`, which takes no user). Filtering by read permission, and keeping + relationships the importing user cannot read on re-import, is tracked in #38055, which builds on + the shared writer this ticket creates. - Content Search's folder filter and Drive's folder view both give only what sits directly in the folder (`conFolder`). The Drive listing never treats a named folder as recursive (`ContentDriveHelper.skipsFolderConstraint`), so filter mode in a folder matches Content Search @@ -554,6 +560,8 @@ file. equivalent, because Drive always works inside one site. - **Recursive filter mode in a folder.** Content Search's folder filter is not recursive either. Selecting the folder exports everything below it. +- **Filtering related identifiers by read permission** in the relationship column, and keeping + hidden relationships on re-import (#38055). This ticket keeps the legacy behavior (FR-024). - Import (separate ticket, #37896). - Background-job exports with a download link, for exports too large to hold in browser memory. - Exporting file contents. Binary fields export as a download URL, as in legacy, so a folder of From 2d02e6ca0320e1ed9a2f42038d69429a50fe7156 Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 16 Oct 2026 12:14:07 -0500 Subject: [PATCH 08/28] spec(content-drive): close the contentlet existence oracle and dedupe by identifier and language (#37900) A selected contentlet that does not exist, cannot be read, or sits outside the browsed site is now skipped the same way in all three cases, so the response no longer tells a limited user that an identifier exists or which site it belongs to, and a stale entry never fails the whole export. Selection entries name an identifier and a language and resolve to the working version at export time; duplicates are removed by identifier and language, so a contentlet edited after it was selected cannot produce two rows. Filter mode gains a scenario that scans past the database scan budget with a text filter, and the timing measurement near 100,000 rows now decides whether the limit fits the proxy idle timeout. Co-Authored-By: Claude Opus 5.5 --- specs/37900-content-drive-export/spec.md | 72 +++++++++++++++++------- 1 file changed, 52 insertions(+), 20 deletions(-) diff --git a/specs/37900-content-drive-export/spec.md b/specs/37900-content-drive-export/spec.md index 3f08d9c3fd8c..a91c015a4d97 100644 --- a/specs/37900-content-drive-export/spec.md +++ b/specs/37900-content-drive-export/spec.md @@ -90,6 +90,10 @@ CSV. `_contents_.csv` downloads, and a toast reports the number of rows. 10. **Given** an export is running, **When** the user looks at the Export button, **Then** it shows a loading state and cannot be clicked again until the export ends. +11. **Given** a filter-mode export with a text filter whose search has to scan more rows than the + database scan budget (`BROWSER_DB_MAX_SCAN_ROWS`, 50,000 by default), **When** it is exported, + **Then** every matching row is in the CSV. The integration test can lower that property instead + of creating 50,000 contentlets. --- @@ -191,12 +195,16 @@ nor Z. Neither response gives a count of skipped items. 4. **Given** the request names a folder the user cannot read, or a folder that does not exist, **When** it is submitted, **Then** both are refused with the same "not found" response, so a limited user cannot tell whether the folder exists, and no file is produced. -5. **Given** a hand-built request names a folder from a site other than the one being browsed, or - a contentlet that is neither in that site nor in System Host, **When** it is submitted, **Then** - it is refused with the same "not found" response. -6. **Given** some items were skipped for permissions, **When** the export finishes, **Then** neither +5. **Given** a hand-built request names a folder from a site other than the one being browsed, + **When** it is submitted, **Then** it is refused with the same "not found" response. +6. **Given** a selection holds a contentlet that does not exist, one the user cannot read, and one + that is outside the browsed site and System Host, **When** it is exported, **Then** all three + are skipped the same way, and the response is the same in all three cases (the rest of the + selection is exported, or "no content" if nothing is left), so it never reveals which of the + three applied. +7. **Given** some items were skipped for permissions, **When** the export finishes, **Then** neither the file, the counts, nor the toast reveals how many were skipped. -7. **Given** a contentlet stops being readable between the moment the export counts it and the +8. **Given** a contentlet stops being readable between the moment the export counts it and the moment its row is written, **When** the export runs, **Then** that row is skipped, the export still succeeds, and the reported row count matches the rows actually written. @@ -280,10 +288,13 @@ file. zip must be. Both CSVs are kept, under distinct names (FR-019). - **Content type name with characters not allowed in a file name** (`/`, `:`, …). The file name is made safe and the CSV is still produced (FR-019). -- **Same contentlet version sent twice in a selection.** Exported once (FR-017). +- **Same contentlet and language sent twice in a selection.** Exported once (FR-017). +- **Contentlet edited after it was selected, and also inside a selected folder.** Its working + version is now a different inode from the one selected. It is still exported once, as the + current working version (FR-002, FR-017). - **A contentlet selected in one language that is also inside a selected folder.** The folder brings every language version of its content (FR-006), so all of them are exported, and the selected - version still appears once (FR-017). + language still appears once (FR-017). - **Content type with no exportable fields.** Its CSV still has the Identifier, languageCode and countryCode columns. - **A field's value cannot be formatted.** As in legacy, the cell is left empty and the export @@ -303,6 +314,8 @@ file. - **Published contentlet edited afterwards.** It has a live and a working version in the same language. Only the working version is exported, so the file never holds two rows with the same Identifier and language (FR-017a). +- **Selected contentlet deleted, made unreadable or outside the site.** Skipped silently, all three + the same way; the rest of the selection is still exported (FR-002a). - **Selected folder deleted between selection and export.** The path no longer resolves and the request is refused with the same "not found" response as an unreadable folder (FR-014). - **Permissions change while the export runs.** A contentlet that stops being readable after it was @@ -321,11 +334,17 @@ file. type. Any Drive view is accepted: All Site Content, the site root, a folder, or System Host. - **FR-002**: The system MUST export in **selection mode** when the request carries a selection: a list of site-qualified folder paths (`//site/path/`, the form Drive sends for bulk duplicate) - and/or a list of the selected contentlet versions, each naming one contentlet in one language. The - request MUST also name the site being browsed in Drive. -- **FR-002a**: Every selected folder MUST belong to the site being browsed, and every selected - contentlet MUST belong to that site or to System Host (which All Site Content can list). Any other - entry MUST be refused with the same "not found" response as an unreadable folder (FR-014). + and/or a list of selected contentlets, each entry naming an identifier and a language. An entry + always resolves to the working version of that identifier in that language at export time, not + to the version that was on screen when it was selected. The request MUST also name the site being + browsed in Drive. +- **FR-002a**: Every selected folder MUST belong to the site being browsed; a folder outside it MUST + be refused with the same "not found" response as an unreadable folder (FR-014). Every selected + contentlet MUST belong to that site or to System Host (which All Site Content can list). A + selected contentlet that does not exist, that the user cannot read, or that is outside the + browsed site and System Host MUST be skipped silently, all three in the same way (FR-012), so the + response never reveals that an identifier exists or which site it belongs to. A stale entry, such + as content deleted by someone else after it was selected, therefore never fails the whole export. - **FR-003**: When a request carries both a selection and a listing query, the selection MUST win and the listing query MUST be ignored. - **FR-004**: A filter-mode request whose listing query names no content type or more than one MUST @@ -371,7 +390,9 @@ file. **Permissions** -- **FR-012**: A contentlet the user cannot read MUST NOT be exported in either mode. +- **FR-012**: A contentlet the user cannot read MUST NOT be exported in either mode. In selection + mode it is skipped silently, exactly like a selected contentlet that does not exist or is outside + the browsed site (FR-002a). - **FR-013**: In selection mode, content in a subfolder the user cannot read MUST NOT be exported, at any depth below that subfolder. - **FR-014**: A request naming a folder the user cannot read, or a folder that does not exist, MUST @@ -385,9 +406,12 @@ file. - **FR-016**: A filter-mode export MUST produce a single CSV, not a zip. A selection-mode export MUST produce a zip named `_export_.zip`, where `` is the site the user is browsing in Drive and the date is the export date. -- **FR-017**: Each contentlet version (inode) MUST appear at most once. This applies when a - contentlet is selected and also inside a selected folder, when nested folders are both selected, - and when the same version is sent twice. +- **FR-017**: Each contentlet MUST appear at most once per language: duplicates are removed by + identifier and language, not by inode. This applies when a contentlet is selected and also inside + a selected folder, when nested folders are both selected, when the same entry is sent twice, and + when the contentlet was edited after it was selected (its working version is then a different + inode from the one the user saw). Together with FR-017a, every identifier and language gives + exactly one row, the working version. - **FR-017a**: Every row MUST be the working version of its contentlet in its language, in both modes, as the Content Search export does (its search adds `+working:true`, `ContentletAjax.java:1049`). There MUST be at most one row per identifier and language. A live @@ -491,10 +515,11 @@ file. - **Listing query**: The Drive listing's location (All Site Content, site root, a folder, System Host) and filters, restricted to one content type. - **Export selection**: The site being browsed, plus the folders (as site-qualified paths) and - contentlet versions (each one contentlet in one language) the user selected in Drive. + contentlets (each an identifier and a language) the user selected in Drive. - **Readable folder set**: In selection mode, the selected folders plus every subfolder the user can read, reached only through folders the user can read, without duplicates. -- **Export row**: The working version of one contentlet in one language, written once. +- **Export row**: The working version of one contentlet in one language, written once per + identifier and language. - **Content-type CSV**: All export rows of one content type, with one header row, named `_contents_.csv`. - **Export file**: A single content-type CSV (filter mode) or a zip of content-type CSVs (selection @@ -516,8 +541,8 @@ file. folder, for content in a folder, at a site root and in System Host. - **SC-005**: With a limited user, 0 items the user cannot read appear in any export, across every permission scenario in User Story 4. -- **SC-006**: In every export, each contentlet version appears exactly once and each content type - has exactly one CSV with one header row. +- **SC-006**: In every export, each contentlet appears exactly once per language and each content + type has exactly one CSV with one header row. - **SC-007**: 0 exports are silently truncated. Every export over 100,000 rows is refused with a message saying it has more than 100,000 rows and that 100,000 is the limit. - **SC-008**: After any export, successful or failed, 0 temporary export files remain on the server. @@ -602,6 +627,13 @@ file. permissions one folder at a time. Parity with legacy output is required. Speeding these up is not, but the plan should measure an export near 100,000 rows and a deep folder tree so the cost is known. +- **That measurement decides the limit.** The export builds the whole file before sending anything + (FR-031), so the connection stays silent while it is built. If an export near 100,000 rows takes + longer than the idle timeout of the load balancer or proxy in front of dotCMS, the user would get + a generic gateway error instead of the server's message (FR-038), and the server would finish a + file nobody downloads. If the measurement does not fit within that timeout, the plan MUST either + lower the row limit to what fits or bring the background-job export (currently out of scope) into + scope. It must not ship a limit that the proxy cannot serve. - **The browser holds the file in memory.** The 100,000-row limit bounds its size. - **Files and pages are content.** File assets, dotAssets and pages are contentlets and are exported in their own types' CSVs. Menu links are not contentlets and are not exported. From 4d7f54803f2e28ee0a6ed1d311d7d17c111726e9 Mon Sep 17 00:00:00 2001 From: ddariod Date: Thu, 26 Nov 2026 13:01:01 -0500 Subject: [PATCH 09/28] test(content-drive): add failing tests and stubs for the export foundation Tests written and approved before the implementation (TDD Red) for the Content Drive export (#37900): the shared CSV writer extracted from the legacy Content Search export, the readable-row filter, export file names, the request form, and the temp-file builder. The classes under test are stubs that throw UnsupportedOperationException; only the characterization of the legacy downloadToExcel passes. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- .../com/dotcms/browser/ExportCandidates.java | 13 + .../java/com/dotcms/browser/ExportRow.java | 22 + .../com/dotcms/browser/ReadableRowFilter.java | 52 ++ .../content/export/ContentletCsvWriter.java | 84 +++ .../dotcms/content/export/HostFolderMode.java | 20 + .../AbstractDriveExportRequestForm.java | 79 ++ .../AbstractExportContentletRefForm.java | 40 ++ .../export/AbstractExportSelectionForm.java | 36 + .../rest/api/v1/drive/export/ExportFile.java | 15 + .../v1/drive/export/ExportFileBuilder.java | 91 +++ .../api/v1/drive/export/ExportFileNames.java | 78 ++ .../export/DriveExportRequestFormTest.java | 213 ++++++ .../v1/drive/export/ExportFileNamesTest.java | 168 +++++ .../src/test/java/com/dotcms/MainSuite2a.java | 3 + .../dotcms/browser/ReadableRowFilterTest.java | 246 +++++++ .../export/ContentletCsvWriterTest.java | 672 ++++++++++++++++++ .../drive/export/ExportFileBuilderTest.java | 278 ++++++++ 17 files changed, 2110 insertions(+) create mode 100644 dotCMS/src/main/java/com/dotcms/browser/ExportCandidates.java create mode 100644 dotCMS/src/main/java/com/dotcms/browser/ExportRow.java create mode 100644 dotCMS/src/main/java/com/dotcms/browser/ReadableRowFilter.java create mode 100644 dotCMS/src/main/java/com/dotcms/content/export/ContentletCsvWriter.java create mode 100644 dotCMS/src/main/java/com/dotcms/content/export/HostFolderMode.java create mode 100644 dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractDriveExportRequestForm.java create mode 100644 dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractExportContentletRefForm.java create mode 100644 dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractExportSelectionForm.java create mode 100644 dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFile.java create mode 100644 dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilder.java create mode 100644 dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileNames.java create mode 100644 dotCMS/src/test/java/com/dotcms/rest/api/v1/drive/export/DriveExportRequestFormTest.java create mode 100644 dotCMS/src/test/java/com/dotcms/rest/api/v1/drive/export/ExportFileNamesTest.java create mode 100644 dotcms-integration/src/test/java/com/dotcms/browser/ReadableRowFilterTest.java create mode 100644 dotcms-integration/src/test/java/com/dotcms/content/export/ContentletCsvWriterTest.java create mode 100644 dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilderTest.java diff --git a/dotCMS/src/main/java/com/dotcms/browser/ExportCandidates.java b/dotCMS/src/main/java/com/dotcms/browser/ExportCandidates.java new file mode 100644 index 000000000000..428235587a8f --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/browser/ExportCandidates.java @@ -0,0 +1,13 @@ +package com.dotcms.browser; + +import java.util.List; + +/** + * The rows a Content Drive export resolved, before anything is written. + * + * @param rows the readable rows, deduplicated by {@link ExportRow#key()}, in output order + * @param overLimit {@code true} when more readable rows exist than the limit allowed; {@code rows} + * is then incomplete and must not be written + */ +public record ExportCandidates(List rows, boolean overLimit) { +} diff --git a/dotCMS/src/main/java/com/dotcms/browser/ExportRow.java b/dotCMS/src/main/java/com/dotcms/browser/ExportRow.java new file mode 100644 index 000000000000..06e479dae8f5 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/browser/ExportRow.java @@ -0,0 +1,22 @@ +package com.dotcms.browser; + +/** + * One row of a Content Drive export, resolved before any contentlet is loaded: the working version + * of one contentlet in one language. + * + * @param inode the working inode of the contentlet in this language + * @param identifier the contentlet identifier + * @param languageId the language of this version + * @param contentTypeId the identifier of the contentlet's content type + */ +public record ExportRow(String inode, String identifier, long languageId, String contentTypeId) { + + /** + * The key rows are deduplicated by: one row per identifier and language, whatever the inode. + * + * @return {@code identifier + ":" + languageId} + */ + public String key() { + throw new UnsupportedOperationException("not implemented"); + } +} diff --git a/dotCMS/src/main/java/com/dotcms/browser/ReadableRowFilter.java b/dotCMS/src/main/java/com/dotcms/browser/ReadableRowFilter.java new file mode 100644 index 000000000000..b46b79209d9c --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/browser/ReadableRowFilter.java @@ -0,0 +1,52 @@ +package com.dotcms.browser; + +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.PermissionAPI; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.portlets.contentlet.business.ContentletAPI; +import com.liferay.portal.model.User; +import java.util.List; + +/** + * Keeps the export rows a user can read. + *

+ * Rows are checked in chunks with one batch permission query each. The batch query can wrongly + * deny a row whose inherited permissions were never computed, or that the user reads only as its + * owner, so every row it rejects is checked again one at a time before it is dropped. + */ +public class ReadableRowFilter { + + private final PermissionAPI permissionAPI; + private final ContentletAPI contentletAPI; + + /** + * Creates a filter that uses the standard dotCMS APIs. + */ + public ReadableRowFilter() { + this(APILocator.getPermissionAPI(), APILocator.getContentletAPI()); + } + + /** + * Creates a filter with the given APIs. Tests use it to observe the permission calls. + * + * @param permissionAPI checks READ, in batch and per item + * @param contentletAPI loads the rows the batch check rejected, for the per-item check + */ + ReadableRowFilter(final PermissionAPI permissionAPI, final ContentletAPI contentletAPI) { + this.permissionAPI = permissionAPI; + this.contentletAPI = contentletAPI; + } + + /** + * Returns the rows {@code user} can read, in their input order. + * + * @param rows the candidate rows + * @param user the {@link User} the export runs as + * @return the readable rows + * @throws DotDataException if the permissions cannot be read + */ + public List filter(final List rows, final User user) + throws DotDataException { + throw new UnsupportedOperationException("not implemented"); + } +} diff --git a/dotCMS/src/main/java/com/dotcms/content/export/ContentletCsvWriter.java b/dotCMS/src/main/java/com/dotcms/content/export/ContentletCsvWriter.java new file mode 100644 index 000000000000..876b1069d976 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/content/export/ContentletCsvWriter.java @@ -0,0 +1,84 @@ +package com.dotcms.content.export; + +import com.dotcms.contenttype.model.type.ContentType; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.IdentifierAPI; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.portlets.categories.business.CategoryAPI; +import com.dotmarketing.portlets.contentlet.business.ContentletAPI; +import com.dotmarketing.portlets.contentlet.business.HostAPI; +import com.dotmarketing.portlets.folders.business.FolderAPI; +import com.dotmarketing.tag.business.TagAPI; +import com.liferay.portal.model.User; +import java.io.IOException; +import java.io.Writer; +import java.util.List; +import javax.servlet.http.HttpServletRequest; + +/** + * Writes contentlets of one content type as CSV, in the format the Content Search export has always + * produced and the content import reads back. Content Search and the Content Drive export both use + * it, so the two write the same file. + */ +public class ContentletCsvWriter { + + private final ContentletAPI contentletAPI; + private final CategoryAPI categoryAPI; + private final TagAPI tagAPI; + private final IdentifierAPI identifierAPI; + private final HostAPI hostAPI; + private final FolderAPI folderAPI; + + /** + * Creates a writer that uses the standard dotCMS APIs. + */ + public ContentletCsvWriter() { + this(APILocator.getContentletAPI(), APILocator.getCategoryAPI(), APILocator.getTagAPI(), + APILocator.getIdentifierAPI(), APILocator.getHostAPI(), APILocator.getFolderAPI()); + } + + /** + * Creates a writer with the given APIs. Tests use it to inject failures. + * + * @param contentletAPI loads each contentlet and reads its field values + * @param categoryAPI resolves the categories of category fields + * @param tagAPI reads the tags of tag fields + * @param identifierAPI resolves the paths of images, files and page URLs + * @param hostAPI resolves the host of the host/folder column + * @param folderAPI resolves the folder of the host/folder column + */ + ContentletCsvWriter(final ContentletAPI contentletAPI, final CategoryAPI categoryAPI, + final TagAPI tagAPI, final IdentifierAPI identifierAPI, final HostAPI hostAPI, + final FolderAPI folderAPI) { + this.contentletAPI = contentletAPI; + this.categoryAPI = categoryAPI; + this.tagAPI = tagAPI; + this.identifierAPI = identifierAPI; + this.hostAPI = hostAPI; + this.folderAPI = folderAPI; + } + + /** + * Writes the header row and then one row per contentlet version, in the order given. + *

+ * Each row is loaded as {@code user}. A row the user can no longer read, or that no longer + * exists, is skipped and not counted. A field whose value cannot be formatted is written as an + * empty cell. Any other failure stops the write and is thrown, so the caller never sends a + * partial file. No websocket messages are sent. + * + * @param contentType the {@link ContentType} every inode belongs to; it decides the columns + * @param inodes the contentlet versions to write, in output order + * @param user the {@link User} the rows are loaded as + * @param request the request used to build the download links of binary fields + * @param hostFolderMode how the host/folder column is written + * @param out where the CSV is written; it is not closed + * @return the number of data rows written, not counting the header + * @throws DotDataException if the export cannot be written + * @throws IOException if {@code out} fails + */ + public int write(final ContentType contentType, final List inodes, final User user, + final HttpServletRequest request, final HostFolderMode hostFolderMode, final Writer out) + throws DotDataException, IOException { + throw new UnsupportedOperationException("not implemented"); + } +} diff --git a/dotCMS/src/main/java/com/dotcms/content/export/HostFolderMode.java b/dotCMS/src/main/java/com/dotcms/content/export/HostFolderMode.java new file mode 100644 index 000000000000..56d1176a8dc9 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/content/export/HostFolderMode.java @@ -0,0 +1,20 @@ +package com.dotcms.content.export; + +/** + * How {@link ContentletCsvWriter} writes the host/folder column of a contentlet. + */ +public enum HostFolderMode { + + /** + * The value Content Search has always written: the host identifier when the contentlet sits in + * a site's system folder, otherwise the folder inode. + */ + IDENTIFIER, + + /** + * A readable location that the content import resolves back to the same place: + * {@code //host/path/} for content in a folder, the bare host name for content at a site root, + * and {@code SYSTEM_HOST} for content in System Host. + */ + LOCATION +} diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractDriveExportRequestForm.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractDriveExportRequestForm.java new file mode 100644 index 000000000000..ef47aacc9a49 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractDriveExportRequestForm.java @@ -0,0 +1,79 @@ +package com.dotcms.rest.api.v1.drive.export; + +import com.dotcms.rest.api.v1.drive.DriveRequestForm; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import javax.annotation.Nullable; +import org.immutables.value.Value; + +/** + * Request body of {@code POST /api/v1/drive/export}. + *

+ * A request with a non-empty {@code selection} exports that selection; otherwise a request with a + * {@code query} exports everything the Drive listing shows for that query, which must name exactly + * one content type. The selection wins when both are sent. + */ +@Value.Style(typeImmutable = "*", typeAbstract = "Abstract*") +@Value.Immutable +@JsonSerialize(as = DriveExportRequestForm.class) +@JsonDeserialize(as = DriveExportRequestForm.class) +@JsonIgnoreProperties(ignoreUnknown = true) +public interface AbstractDriveExportRequestForm { + + /** The most folders and contentlets one selection can hold, together. */ + int MAX_SELECTION_ITEMS = 60; + + /** + * Which of the two exports a request asks for. + */ + enum Mode { + /** Everything the listing shows for one content type: one CSV. */ + FILTER, + /** The selected folders and contentlets: a zip with one CSV per content type. */ + SELECTION + } + + /** + * The identifier of the site being browsed. Required in selection mode, ignored in filter mode, + * where the site comes from the query's asset path. + * + * @return the site identifier, or {@code null} + */ + @Nullable + @JsonProperty("siteId") + String siteId(); + + /** + * The selected folders and contentlets. + * + * @return the selection, or {@code null} when nothing is selected + */ + @Nullable + @JsonProperty("selection") + ExportSelectionForm selection(); + + /** + * The listing request, exactly as Drive sends it to {@code /api/v1/drive/search}. Paging, + * sorting, {@code showFolders}, {@code showLinks} and {@code live} are ignored. + * + * @return the listing query, or {@code null} + */ + @Nullable + @JsonProperty("query") + DriveRequestForm query(); + + /** + * Checks the request and tells which export it asks for. + * + * @return {@link Mode#SELECTION} when the selection has at least one entry, otherwise + * {@link Mode#FILTER} when a query is present + * @throws com.dotcms.rest.exception.BadRequestException when the request asks for neither, the + * selection holds more than {@link #MAX_SELECTION_ITEMS} entries, or a contentlet entry + * has no identifier or no valid language + */ + default Mode validate() { + throw new UnsupportedOperationException("not implemented"); + } +} diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractExportContentletRefForm.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractExportContentletRefForm.java new file mode 100644 index 000000000000..d5b3bab9e045 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractExportContentletRefForm.java @@ -0,0 +1,40 @@ +package com.dotcms.rest.api.v1.drive.export; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import javax.annotation.Nullable; +import org.immutables.value.Value; + +/** + * One contentlet of an export selection: an identifier in one language. It always exports the + * working version of that identifier in that language at export time. + */ +@Value.Style(typeImmutable = "*", typeAbstract = "Abstract*") +@Value.Immutable +@JsonSerialize(as = ExportContentletRefForm.class) +@JsonDeserialize(as = ExportContentletRefForm.class) +@JsonIgnoreProperties(ignoreUnknown = true) +public interface AbstractExportContentletRefForm { + + /** + * The contentlet identifier. + * + * @return the identifier; blank or {@code null} makes the request invalid + */ + @Nullable + @JsonProperty("identifier") + String identifier(); + + /** + * The language of the selected version. + * + * @return the language id; {@code 0} or less makes the request invalid + */ + @JsonProperty("languageId") + @Value.Default + default long languageId() { + return 0; + } +} diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractExportSelectionForm.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractExportSelectionForm.java new file mode 100644 index 000000000000..9631372d4b00 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractExportSelectionForm.java @@ -0,0 +1,36 @@ +package com.dotcms.rest.api.v1.drive.export; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import java.util.List; +import org.immutables.value.Value; + +/** + * The folders and contentlets selected in Content Drive for an export. + */ +@Value.Style(typeImmutable = "*", typeAbstract = "Abstract*") +@Value.Immutable +@JsonSerialize(as = ExportSelectionForm.class) +@JsonDeserialize(as = ExportSelectionForm.class) +@JsonIgnoreProperties(ignoreUnknown = true) +public interface AbstractExportSelectionForm { + + /** + * Site-qualified folder paths, {@code //host/path/}, as Drive sends them for bulk duplicate. + * Each folder brings every contentlet below it. + * + * @return the selected folders; empty when none + */ + @JsonProperty("folders") + List folders(); + + /** + * The selected contentlets, each in the language that was selected. + * + * @return the selected contentlets; empty when none + */ + @JsonProperty("contentlets") + List contentlets(); +} diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFile.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFile.java new file mode 100644 index 000000000000..2ca09461d531 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFile.java @@ -0,0 +1,15 @@ +package com.dotcms.rest.api.v1.drive.export; + +import java.nio.file.Path; + +/** + * A finished export file, waiting in a temp file to be sent. + * + * @param path the temp file holding the complete export + * @param fileName the name the browser saves it under + * @param mediaType {@code text/csv; charset=UTF-8} or {@code application/zip} + * @param contentlets the number of data rows written, over every CSV + * @param files the number of CSVs written + */ +public record ExportFile(Path path, String fileName, String mediaType, int contentlets, int files) { +} diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilder.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilder.java new file mode 100644 index 000000000000..aee42126131b --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilder.java @@ -0,0 +1,91 @@ +package com.dotcms.rest.api.v1.drive.export; + +import com.dotcms.content.export.ContentletCsvWriter; +import com.dotcms.contenttype.model.type.ContentType; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.util.ConfigUtils; +import com.liferay.portal.model.User; +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.StreamingOutput; + +/** + * Builds a Content Drive export into a temp file before anything is sent, so a failure halfway is + * reported as an error instead of a truncated download. The file is deleted when sending ends, + * when building fails, and by a sweep of leftovers older than one hour at the start of each export. + */ +public class ExportFileBuilder { + + /** The directory, under the asset temp path, that export files are written to. */ + public static final String DIRECTORY_NAME = "drive-export"; + + private final ContentletCsvWriter writer; + private final Path directory; + + /** + * Creates a builder that writes with the shared CSV writer under the asset temp path. + */ + public ExportFileBuilder() { + this(new ContentletCsvWriter(), Path.of(ConfigUtils.getAssetTempPath(), DIRECTORY_NAME)); + } + + /** + * Creates a builder with the given writer and directory. Tests use it to inject failures. + * + * @param writer writes each content type's CSV + * @param directory where the temp files are written + */ + ExportFileBuilder(final ContentletCsvWriter writer, final Path directory) { + this.writer = writer; + this.directory = directory; + } + + /** + * Writes one content type's rows as a single CSV. + * + * @param contentType the {@link ContentType} of every inode + * @param inodes the rows, in output order + * @param user the {@link User} the rows are loaded as + * @param request the request used for binary links + * @return the finished file; it holds zero rows when every row became unreadable while writing, + * and is then already deleted + * @throws DotDataException if the export cannot be written; the temp file is deleted first + * @throws IOException if the temp file cannot be written; it is deleted first + */ + public ExportFile buildCsv(final ContentType contentType, final List inodes, + final User user, final HttpServletRequest request) throws DotDataException, IOException { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * Writes a zip with one CSV per content type, one content type at a time. + * + * @param hostname the site being browsed, which the zip is named after + * @param inodesByType the rows of each {@link ContentType}, in output order + * @param user the {@link User} the rows are loaded as + * @param request the request used for binary links + * @return the finished file; it holds zero rows when every row became unreadable while writing, + * and is then already deleted + * @throws DotDataException if the export cannot be written; the temp file is deleted first + * @throws IOException if the temp file cannot be written; it is deleted first + */ + public ExportFile buildZip(final String hostname, + final Map> inodesByType, final User user, + final HttpServletRequest request) throws DotDataException, IOException { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * Streams a finished file to the response and deletes it afterwards, whether or not sending + * succeeded. + * + * @param file the file to send + * @return the response entity + */ + public static StreamingOutput toStreamingOutput(final ExportFile file) { + throw new UnsupportedOperationException("not implemented"); + } +} diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileNames.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileNames.java new file mode 100644 index 000000000000..6217fd0e6c85 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileNames.java @@ -0,0 +1,78 @@ +package com.dotcms.rest.api.v1.drive.export; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +/** + * Names the files of a Content Drive export and builds their {@code Content-Disposition} header. + *

+ * CSVs are named as the Content Search export names them, {@code _contents_.csv}; + * a zip is named {@code _export_.zip}. Names are made safe for a file system, a zip + * entry and an HTTP header, and are kept distinct within one zip. + */ +public final class ExportFileNames { + + /** The date pattern Content Search uses in its file name. */ + public static final String DATE_PATTERN = "M_d_yyyy"; + + private ExportFileNames() { + } + + /** + * The name of one content type's CSV. + * + * @param contentTypeName the content type's name, which the file is named after + * @param contentTypeVariable the content type's variable, used when the name has nothing safe left + * @param date the export date + * @return {@code _contents_.csv} + */ + public static String csvName(final String contentTypeName, final String contentTypeVariable, + final Date date) { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * The name of a selection-mode zip. + * + * @param hostname the name of the site being browsed + * @param date the export date + * @return {@code _export_.zip} + */ + public static String zipName(final String hostname, final Date date) { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * Names the CSVs of one zip. Content types are named in content type name order, and a name + * already taken gets {@code -2}, {@code -3}, and so on before {@code .csv}. + * + * @param types the content types in the zip + * @param date the export date + * @return the file name of each content type, keyed by its id, in the order the entries are written + */ + public static Map csvNames(final List types, final Date date) { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * Builds the {@code Content-Disposition} value for a download: an ASCII {@code filename} for old + * clients and the exact name, percent-encoded, in {@code filename*}. + * + * @param fileName the file name, already made safe + * @return {@code attachment; filename="..."; filename*=UTF-8''...} + */ + public static String contentDisposition(final String fileName) { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * The parts of a content type that its CSV name is built from. + * + * @param id the content type id + * @param name the content type name + * @param variable the content type variable + */ + public record TypeName(String id, String name, String variable) { + } +} diff --git a/dotCMS/src/test/java/com/dotcms/rest/api/v1/drive/export/DriveExportRequestFormTest.java b/dotCMS/src/test/java/com/dotcms/rest/api/v1/drive/export/DriveExportRequestFormTest.java new file mode 100644 index 000000000000..519fb8743c06 --- /dev/null +++ b/dotCMS/src/test/java/com/dotcms/rest/api/v1/drive/export/DriveExportRequestFormTest.java @@ -0,0 +1,213 @@ +package com.dotcms.rest.api.v1.drive.export; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; + +import com.dotcms.rest.api.v1.DotObjectMapperProvider; +import com.dotcms.rest.api.v1.drive.DriveRequestForm; +import com.dotcms.rest.api.v1.drive.export.AbstractDriveExportRequestForm.Mode; +import com.dotcms.rest.exception.BadRequestException; +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; + +/** + * Unit tests for {@link DriveExportRequestForm}: which export a request asks for, and the checks + * made before anything is resolved (contract § 400, data-model "Request"). + *

+ * Every query pins {@code language}: its declared default asks the language API for the default + * language, which reaches the database. + */ +public class DriveExportRequestFormTest { + + private static final String NO_MODE = + "Select items or filter the listing to one content type to export."; + private static final String TOO_MANY = "You can export at most 60 items at once."; + private static final String BAD_CONTENTLET = "Invalid contentlet in the selection."; + + /** + * The message the client receives. {@code getMessage()} is WebApplicationException's + * ("HTTP 400 Bad Request"); the text travels in the {@code error-message} header. + */ + private static String messageOf(final BadRequestException exception) { + return exception.getResponse().getHeaderString("error-message"); + } + + private static DriveRequestForm query() { + return DriveRequestForm.builder().assetPath("//demo.dotcms.com/") + .language(List.of("1")).contentTypes(List.of("Blog")).build(); + } + + private static ExportContentletRefForm ref(final String identifier, final long languageId) { + return ExportContentletRefForm.builder().identifier(identifier).languageId(languageId).build(); + } + + /** + * Method to test: {@link DriveExportRequestForm#validate()} + * Given Scenario: A request with a query and no selection + * ExpectedResult: Filter mode + */ + @Test + public void test_validate_queryOnly_isFilterMode() { + final DriveExportRequestForm form = DriveExportRequestForm.builder().query(query()).build(); + + assertEquals(Mode.FILTER, form.validate()); + } + + /** + * Method to test: {@link DriveExportRequestForm#validate()} + * Given Scenario: A request with a selection holding one folder and also a query (FR-003) + * ExpectedResult: Selection mode: the selection wins over the query + */ + @Test + public void test_validate_selectionAndQuery_selectionWins() { + final DriveExportRequestForm form = DriveExportRequestForm.builder() + .siteId("site-id") + .selection(ExportSelectionForm.builder().addFolders("//demo.dotcms.com/blog/").build()) + .query(query()) + .build(); + + assertEquals(Mode.SELECTION, form.validate()); + } + + /** + * Method to test: {@link DriveExportRequestForm#validate()} + * Given Scenario: A selection holding only a contentlet + * ExpectedResult: Selection mode + */ + @Test + public void test_validate_contentletOnlySelection_isSelectionMode() { + final DriveExportRequestForm form = DriveExportRequestForm.builder() + .siteId("site-id") + .selection(ExportSelectionForm.builder().addContentlets(ref("abc", 1)).build()) + .build(); + + assertEquals(Mode.SELECTION, form.validate()); + } + + /** + * Method to test: {@link DriveExportRequestForm#validate()} + * Given Scenario: An empty selection and a query + * ExpectedResult: Filter mode: an empty selection does not count as a selection + */ + @Test + public void test_validate_emptySelectionWithQuery_isFilterMode() { + final DriveExportRequestForm form = DriveExportRequestForm.builder() + .selection(ExportSelectionForm.builder().build()) + .query(query()) + .build(); + + assertEquals(Mode.FILTER, form.validate()); + } + + /** + * Method to test: {@link DriveExportRequestForm#validate()} + * Given Scenario: Neither a selection nor a query; and an empty selection with no query + * ExpectedResult: 400 with the "select or filter" message in both cases + */ + @Test + public void test_validate_nothingToExport_isRejected() { + final BadRequestException empty = assertThrows(BadRequestException.class, + () -> DriveExportRequestForm.builder().build().validate()); + assertEquals(NO_MODE, messageOf(empty)); + + final BadRequestException emptySelection = assertThrows(BadRequestException.class, + () -> DriveExportRequestForm.builder() + .selection(ExportSelectionForm.builder().build()).build().validate()); + assertEquals(NO_MODE, messageOf(emptySelection)); + } + + /** + * Method to test: {@link DriveExportRequestForm#validate()} + * Given Scenario: 60 entries (folders and contentlets together), then 61 + * ExpectedResult: 60 is accepted; 61 gives 400 with the 60-item message (FR-004a) + */ + @Test + public void test_validate_sixtyItemsLimit() { + assertEquals(60, AbstractDriveExportRequestForm.MAX_SELECTION_ITEMS); + + assertEquals(Mode.SELECTION, selectionOf(30, 30).validate()); + + final BadRequestException tooMany = assertThrows(BadRequestException.class, + () -> selectionOf(30, 31).validate()); + assertEquals(TOO_MANY, messageOf(tooMany)); + } + + private static DriveExportRequestForm selectionOf(final int folders, final int contentlets) { + final List folderPaths = new ArrayList<>(); + for (int i = 0; i < folders; i++) { + folderPaths.add("//demo.dotcms.com/f" + i + "/"); + } + final List refs = new ArrayList<>(); + for (int i = 0; i < contentlets; i++) { + refs.add(ref("id-" + i, 1)); + } + return DriveExportRequestForm.builder().siteId("site-id") + .selection(ExportSelectionForm.builder().folders(folderPaths).contentlets(refs).build()) + .build(); + } + + /** + * Method to test: {@link DriveExportRequestForm#validate()} + * Given Scenario: A contentlet entry with a blank identifier, with no identifier, and with a + * language of 0 or below + * ExpectedResult: 400 with the same "invalid contentlet" message each time + */ + @Test + public void test_validate_invalidContentletRef_isRejected() { + for (final ExportContentletRefForm bad : List.of(ref(" ", 1), + ExportContentletRefForm.builder().languageId(1).build(), ref("abc", 0), + ref("abc", -3))) { + final DriveExportRequestForm form = DriveExportRequestForm.builder().siteId("site-id") + .selection(ExportSelectionForm.builder().addContentlets(bad).build()).build(); + + final BadRequestException error = + assertThrows(BadRequestException.class, form::validate); + assertEquals(BAD_CONTENTLET, messageOf(error)); + } + } + + /** + * Method to test: JSON deserialisation of {@link DriveExportRequestForm} + * Given Scenario: The selection-mode body the UI sends, with unknown properties at every level + * ExpectedResult: It reads into the form; unknown properties are ignored, and a contentlet entry + * without a language reads as 0 (so validation rejects it) + */ + @Test + public void test_deserialisesFromTheRequestBody_ignoringUnknownProperties() throws Exception { + final DriveExportRequestForm form = DotObjectMapperProvider.getInstance() + .getDefaultObjectMapper().readValue("{" + + "\"siteId\":\"site-id\",\"unknown\":true," + + "\"selection\":{\"folders\":[\"//demo.dotcms.com/blog/\"]," + + "\"contentlets\":[{\"identifier\":\"abc\",\"languageId\":2,\"extra\":1}," + + "{\"identifier\":\"def\"}],\"other\":[]}," + + "\"query\":{\"assetPath\":\"//demo.dotcms.com/\",\"language\":[\"1\"]," + + "\"contentTypes\":[\"Blog\"],\"mystery\":\"x\"}}", + DriveExportRequestForm.class); + + assertEquals("site-id", form.siteId()); + assertEquals(List.of("//demo.dotcms.com/blog/"), form.selection().folders()); + assertEquals("abc", form.selection().contentlets().get(0).identifier()); + assertEquals(2, form.selection().contentlets().get(0).languageId()); + assertEquals(0, form.selection().contentlets().get(1).languageId()); + assertEquals(List.of("Blog"), form.query().contentTypes()); + } + + /** + * Method to test: JSON deserialisation of {@link DriveExportRequestForm} + * Given Scenario: The filter-mode body, which carries no selection and no site + * ExpectedResult: Selection and site read as null + */ + @Test + public void test_deserialisesFilterModeBody() throws Exception { + final DriveExportRequestForm form = DotObjectMapperProvider.getInstance() + .getDefaultObjectMapper().readValue("{\"query\":{\"assetPath\":\"//demo.dotcms.com/\"," + + "\"language\":[\"1\"],\"contentTypes\":[\"Blog\"]}}", + DriveExportRequestForm.class); + + assertNull(form.selection()); + assertNull(form.siteId()); + assertEquals(Mode.FILTER, form.validate()); + } +} diff --git a/dotCMS/src/test/java/com/dotcms/rest/api/v1/drive/export/ExportFileNamesTest.java b/dotCMS/src/test/java/com/dotcms/rest/api/v1/drive/export/ExportFileNamesTest.java new file mode 100644 index 000000000000..a6dc3258ebd0 --- /dev/null +++ b/dotCMS/src/test/java/com/dotcms/rest/api/v1/drive/export/ExportFileNamesTest.java @@ -0,0 +1,168 @@ +package com.dotcms.rest.api.v1.drive.export; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import com.dotcms.rest.api.v1.drive.export.ExportFileNames.TypeName; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Map; +import org.junit.Test; + +/** + * Unit tests for {@link ExportFileNames}: the CSV and zip names, how they are made safe and kept + * distinct, and the {@code Content-Disposition} header (research R10, FR-016, FR-019). + */ +public class ExportFileNamesTest { + + /** November 26, 2026: {@code M_d_yyyy} gives {@code 11_26_2026}, with no zero padding. */ + private static final Date DATE = new GregorianCalendar(2026, Calendar.NOVEMBER, 26).getTime(); + /** March 5, 2026, to prove month and day are not zero-padded. */ + private static final Date SINGLE_DIGIT_DATE = + new GregorianCalendar(2026, Calendar.MARCH, 5).getTime(); + + /** + * Method to test: {@link ExportFileNames#csvName(String, String, Date)} and + * {@link ExportFileNames#zipName(String, Date)} + * Given Scenario: A plain content type name and a site host name + * ExpectedResult: The Content Search CSV name and the selection zip name, dated {@code M_d_yyyy} + */ + @Test + public void test_names_followTheContentSearchPattern() { + assertEquals("Blog_contents_11_26_2026.csv", ExportFileNames.csvName("Blog", "blog", DATE)); + assertEquals("demo.dotcms.com_export_11_26_2026.zip", + ExportFileNames.zipName("demo.dotcms.com", DATE)); + assertEquals("Blog_contents_3_5_2026.csv", + ExportFileNames.csvName("Blog", "blog", SINGLE_DIGIT_DATE)); + } + + /** + * Method to test: {@link ExportFileNames#csvName(String, String, Date)} + * Given Scenario: Names holding each character that is unsafe in a file name, a zip entry or a + * header: {@code / \ : * ? " < > |}, CR, LF and another control character + * ExpectedResult: Each becomes {@code _}; nothing unsafe survives + */ + @Test + public void test_csvName_replacesUnsafeCharacters() { + assertEquals("A_B_ C_contents_11_26_2026.csv", + ExportFileNames.csvName("A/B: C", "abc", DATE)); + assertEquals("a_b_c_d_e_f_g_h_i_contents_11_26_2026.csv", + ExportFileNames.csvName("a\\b*c?d\"eg|h:i", "x", DATE)); + assertEquals("tab_separated_contents_11_26_2026.csv", + ExportFileNames.csvName("tab\tseparated", "x", DATE)); + + final String withControls = ExportFileNames.csvName("bad\r\nname\u0007", "x", DATE); + assertFalse(withControls.contains("\r")); + assertFalse(withControls.contains("\n")); + assertFalse(withControls.contains("\u0007")); + assertEquals("bad__name__contents_11_26_2026.csv", withControls); + } + + /** + * Method to test: {@link ExportFileNames#csvName(String, String, Date)} + * Given Scenario: Names with leading and trailing dots and spaces, a name with nothing left after + * that, and a name with non-ASCII letters + * ExpectedResult: Leading and trailing dots and spaces are trimmed; an empty result falls back to + * the content type variable; Unicode letters are kept + */ + @Test + public void test_csvName_trimsAndFallsBack_andKeepsUnicode() { + assertEquals("News_contents_11_26_2026.csv", + ExportFileNames.csvName(" ..News.. ", "news", DATE)); + assertEquals("pressRelease_contents_11_26_2026.csv", + ExportFileNames.csvName(" . . ", "pressRelease", DATE)); + assertEquals("Artículo_contents_11_26_2026.csv", + ExportFileNames.csvName("Artículo", "articulo", DATE)); + } + + /** + * Method to test: {@link ExportFileNames#zipName(String, Date)} + * Given Scenario: A host name with a character unsafe for a file name + * ExpectedResult: It is replaced the same way as in CSV names + */ + @Test + public void test_zipName_isMadeSafe() { + assertEquals("my_site_export_11_26_2026.zip", ExportFileNames.zipName("my/site", DATE)); + } + + /** + * Method to test: {@link ExportFileNames#csvNames(List, Date)} + * Given Scenario: Three content types sent out of name order, two of them with the same name + * and a third that becomes the same name once made safe + * ExpectedResult: Names are assigned in content type name order; the first keeps the plain name, + * the next ones get {@code -2} and {@code -3} before {@code .csv}; the map iterates in that order + */ + @Test + public void test_csvNames_resolveCollisionsInNameOrder() { + final List types = List.of( + new TypeName("id-zeta", "Zeta", "zeta"), + new TypeName("id-blog-2", "Blog", "blog2"), + new TypeName("id-blog-1", "Blog", "blog1"), + new TypeName("id-alpha", "Alpha", "alpha")); + + final Map names = ExportFileNames.csvNames(types, DATE); + + assertEquals(4, names.size()); + assertEquals("Alpha_contents_11_26_2026.csv", names.get("id-alpha")); + assertEquals("Zeta_contents_11_26_2026.csv", names.get("id-zeta")); + + final List blogNames = List.of(names.get("id-blog-1"), names.get("id-blog-2")); + assertTrue(blogNames.contains("Blog_contents_11_26_2026.csv")); + assertTrue(blogNames.contains("Blog_contents_11_26_2026-2.csv")); + + final List order = new ArrayList<>(names.values()); + assertEquals("Alpha_contents_11_26_2026.csv", order.get(0)); + assertTrue(order.get(1).startsWith("Blog_contents_")); + assertTrue(order.get(2).startsWith("Blog_contents_")); + assertEquals("Zeta_contents_11_26_2026.csv", order.get(3)); + } + + /** + * Method to test: {@link ExportFileNames#csvNames(List, Date)} + * Given Scenario: Two names that differ before being made safe but are equal after + * ({@code A/B} and {@code A:B}) + * ExpectedResult: Both CSVs are kept, the second with {@code -2} + */ + @Test + public void test_csvNames_collisionAfterSanitizing() { + final Map names = ExportFileNames.csvNames(List.of( + new TypeName("one", "A/B", "ab1"), new TypeName("two", "A:B", "ab2")), DATE); + + assertEquals(List.of("A_B_contents_11_26_2026.csv", "A_B_contents_11_26_2026-2.csv"), + new ArrayList<>(names.values())); + } + + /** + * Method to test: {@link ExportFileNames#contentDisposition(String)} + * Given Scenario: An ASCII name and a name with non-ASCII letters + * ExpectedResult: {@code attachment; filename=""; filename*=UTF-8''} + */ + @Test + public void test_contentDisposition_hasAsciiFallbackAndEncodedName() { + assertEquals("attachment; filename=\"Blog_contents_11_26_2026.csv\"; " + + "filename*=UTF-8''Blog_contents_11_26_2026.csv", + ExportFileNames.contentDisposition("Blog_contents_11_26_2026.csv")); + + assertEquals("attachment; filename=\"Art_culo_contents_11_26_2026.csv\"; " + + "filename*=UTF-8''Art%C3%ADculo_contents_11_26_2026.csv", + ExportFileNames.contentDisposition("Artículo_contents_11_26_2026.csv")); + } + + /** + * Method to test: {@link ExportFileNames#contentDisposition(String)} + * Given Scenario: A name with a space and a percent sign + * ExpectedResult: The {@code filename*} part percent-encodes them ({@code %20}, {@code %25}), and + * never uses {@code +} for a space + */ + @Test + public void test_contentDisposition_encodesSpacesAndPercent() { + final String header = ExportFileNames.contentDisposition("A B 50%_contents_11_26_2026.csv"); + + assertTrue(header.contains("filename=\"A B 50%_contents_11_26_2026.csv\"")); + assertTrue(header.endsWith("filename*=UTF-8''A%20B%2050%25_contents_11_26_2026.csv")); + } +} diff --git a/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java b/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java index 04d28a46b986..107522968086 100644 --- a/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java +++ b/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java @@ -77,8 +77,10 @@ com.dotcms.rest.api.v1.workflow.WorkflowResourceLicenseIntegrationTest.class, com.dotcms.rest.api.v1.authentication.ResetPasswordResourceIntegrationTest.class, com.dotcms.rest.api.v1.authentication.CreateJsonWebTokenResourceIntegrationTest.class, + com.dotcms.browser.ReadableRowFilterTest.class, com.dotcms.rest.api.v1.relationships.RelationshipsResourceTest.class, com.dotcms.rest.api.v1.contenttype.ContentTypeResourceUpdateMetadataTest.class, + com.dotcms.rest.api.v1.drive.export.ExportFileBuilderTest.class, com.dotcms.rest.api.v2.contenttype.FieldResourceTest.class, com.dotcms.rest.api.v3.contenttype.FieldResourceTest.class, com.dotcms.rest.api.v3.contenttype.MoveFieldFormTest.class, @@ -92,6 +94,7 @@ com.dotmarketing.portlets.linkchecker.business.LinkCheckerAPITest.class, com.dotmarketing.portlets.contentlet.util.ContentletUtilTest.class, com.dotmarketing.portlets.contentlet.business.ContentletCheckInTest.class, + com.dotcms.content.export.ContentletCsvWriterTest.class, com.dotmarketing.portlets.contentlet.business.ContentletFactoryTest.class, ContainerStructureFinderStrategyResolverTest.class, com.dotmarketing.portlets.contentlet.business.ContentletAPITest.class, diff --git a/dotcms-integration/src/test/java/com/dotcms/browser/ReadableRowFilterTest.java b/dotcms-integration/src/test/java/com/dotcms/browser/ReadableRowFilterTest.java new file mode 100644 index 000000000000..68e5879474de --- /dev/null +++ b/dotcms-integration/src/test/java/com/dotcms/browser/ReadableRowFilterTest.java @@ -0,0 +1,246 @@ +package com.dotcms.browser; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +import com.dotcms.IntegrationTestBase; +import com.dotcms.contenttype.model.field.TextField; +import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.datagen.ContentTypeDataGen; +import com.dotcms.datagen.ContentletDataGen; +import com.dotcms.datagen.FieldDataGen; +import com.dotcms.datagen.FolderDataGen; +import com.dotcms.datagen.RoleDataGen; +import com.dotcms.datagen.SiteDataGen; +import com.dotcms.datagen.UserDataGen; +import com.dotcms.util.IntegrationTestInitService; +import com.dotmarketing.beans.Host; +import com.dotmarketing.beans.Permission; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.PermissionAPI; +import com.dotmarketing.business.Role; +import com.dotmarketing.common.db.DotConnect; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.folders.model.Folder; +import com.dotmarketing.util.Config; +import com.liferay.portal.model.User; +import java.util.List; +import java.util.stream.Collectors; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Integration tests for {@link ReadableRowFilter}: the batch permission check with the per-item + * re-check of what it rejects (research R4, FR-012). + *

+ * The batch query reads inherited permissions only through {@code permission_reference} rows, + * which are written lazily, and ignores CMS Owner grants. These cases prove such rows survive the + * filter, so an export never holds fewer rows than the listing shows, while unreadable rows are + * still dropped. + */ +public class ReadableRowFilterTest extends IntegrationTestBase { + + private static User systemUser; + private static PermissionAPI permissionAPI; + private static boolean asyncReferencesOldValue; + + private static User limitedUser; + private static ContentType contentType; + + /** Readable through an individual READ grant to the limited user's role. */ + private static Contentlet individuallyReadable; + /** Readable only by inheriting READ from its folder, with its permission references deleted. */ + private static Contentlet inheritedOnly; + /** Readable only because the limited user owns it and CMS Owner has READ on it. */ + private static Contentlet ownedByUser; + /** Not readable by the limited user at all. */ + private static Contentlet unreadable; + + @BeforeClass + public static void prepare() throws Exception { + IntegrationTestInitService.getInstance().init(); + systemUser = APILocator.systemUser(); + permissionAPI = APILocator.getPermissionAPI(); + + // Permission reference updates are async by default; the grants below must be in place + // before the assertions. ContentDriveLinksTest pins the same flag for the same reason. + asyncReferencesOldValue = Config.getBooleanProperty("PERMISSION_REFERENCES_UPDATE_ASYNC", true); + Config.setProperty("PERMISSION_REFERENCES_UPDATE_ASYNC", false); + + final String unique = String.valueOf(System.currentTimeMillis()); + final Host site = new SiteDataGen().name("readable-rows-" + unique + ".local").nextPersisted(); + final Folder openFolder = new FolderDataGen().site(site).name("open-" + unique).nextPersisted(); + contentType = new ContentTypeDataGen().host(site) + .field(new FieldDataGen().type(TextField.class).name("title").velocityVarName("title").next()) + .nextPersisted(); + + // A back-end user, as every Drive user is: dotCMS denies a front-end user READ on any + // contentlet that is not live, and these fixtures are working versions. + final Role role = new RoleDataGen().nextPersisted(); + limitedUser = new UserDataGen() + .roles(role, APILocator.getRoleAPI().loadBackEndUserRole()).nextPersisted(); + final String userRoleId = APILocator.getRoleAPI().getUserRole(limitedUser).getId(); + + individuallyReadable = contentlet(site, null, "individual"); + permissionAPI.save(new Permission(individuallyReadable.getPermissionId(), userRoleId, + PermissionAPI.PERMISSION_READ), individuallyReadable, systemUser, false); + assertTrue("Fixture error: the individually granted contentlet must be readable per item", + permissionAPI.doesUserHavePermission(individuallyReadable, + PermissionAPI.PERMISSION_READ, limitedUser, false)); + + // An inheritable READ on the folder, keyed on the Contentlet class: dotCMS keys inheritable + // grants on the child's class name. A new folder inherits from its site, so it first gets its + // own permission set; otherwise the grant below is not what its contentlets inherit. + permissionAPI.permissionIndividually(permissionAPI.findParentPermissionable(openFolder), + openFolder, systemUser); + permissionAPI.save(new Permission(Contentlet.class.getCanonicalName(), + openFolder.getPermissionId(), userRoleId, PermissionAPI.PERMISSION_READ, true), + openFolder, systemUser, false); + inheritedOnly = contentlet(site, openFolder, "inherited"); + assertTrue("Fixture error: the inherited contentlet must be readable per item", + permissionAPI.doesUserHavePermission(inheritedOnly, PermissionAPI.PERMISSION_READ, + limitedUser, false)); + new DotConnect().setSQL("DELETE FROM permission_reference WHERE asset_id = ?") + .addParam(inheritedOnly.getPermissionId()).loadResult(); + + final Contentlet ownedDraft = new ContentletDataGen(contentType).host(site) + .setProperty("title", "owned").next(); + ownedDraft.setOwner(limitedUser.getUserId()); + ownedByUser = ContentletDataGen.checkin(ownedDraft); + final Role cmsOwner = APILocator.getRoleAPI().loadCMSOwnerRole(); + permissionAPI.save(new Permission(ownedByUser.getPermissionId(), cmsOwner.getId(), + PermissionAPI.PERMISSION_READ), ownedByUser, systemUser, false); + assertEquals("Fixture error: the limited user must own this contentlet", + limitedUser.getUserId(), ownedByUser.getOwner()); + assertTrue("Fixture error: the owner must be able to read it per item", + permissionAPI.doesUserHavePermission(ownedByUser, PermissionAPI.PERMISSION_READ, + limitedUser, false)); + + unreadable = contentlet(site, null, "unreadable"); + assertFalse("Fixture error: the unreadable contentlet must not be readable", + permissionAPI.doesUserHavePermission(unreadable, PermissionAPI.PERMISSION_READ, + limitedUser, false)); + } + + @AfterClass + public static void restore() { + Config.setProperty("PERMISSION_REFERENCES_UPDATE_ASYNC", asyncReferencesOldValue); + } + + private static Contentlet contentlet(final Host site, final Folder folder, final String title) { + final ContentletDataGen dataGen = new ContentletDataGen(contentType).host(site) + .setProperty("title", title); + if (folder != null) { + dataGen.folder(folder); + } + return dataGen.nextPersisted(); + } + + private static ExportRow row(final Contentlet contentlet) { + return new ExportRow(contentlet.getInode(), contentlet.getIdentifier(), + contentlet.getLanguageId(), contentlet.getContentTypeId()); + } + + private static List identifiers(final List rows) { + return rows.stream().map(ExportRow::identifier).collect(Collectors.toList()); + } + + /** + * Method to test: {@link ReadableRowFilter#filter(List, User)} + * Given Scenario: A limited user and one row readable through an individual permission + * ExpectedResult: The row is kept + */ + @Test + public void test_filter_keepsIndividuallyReadableRow() throws Exception { + final List kept = new ReadableRowFilter() + .filter(List.of(row(individuallyReadable)), limitedUser); + + assertEquals(List.of(individuallyReadable.getIdentifier()), identifiers(kept)); + } + + /** + * Method to test: {@link ReadableRowFilter#filter(List, User)} + * Given Scenario: A row readable only through inheritance from its folder, whose + * {@code permission_reference} rows were deleted + * ExpectedResult: The row is kept, by the per-item re-check + */ + @Test + public void test_filter_keepsInheritedRowWithoutPermissionReferences() throws Exception { + final List kept = new ReadableRowFilter() + .filter(List.of(row(inheritedOnly)), limitedUser); + + assertEquals(List.of(inheritedOnly.getIdentifier()), identifiers(kept)); + } + + /** + * Method to test: {@link ReadableRowFilter#filter(List, User)} + * Given Scenario: A row the limited user can read only as its CMS Owner + * ExpectedResult: The row is kept + */ + @Test + public void test_filter_keepsRowReadableAsCmsOwner() throws Exception { + final List kept = new ReadableRowFilter() + .filter(List.of(row(ownedByUser)), limitedUser); + + assertEquals(List.of(ownedByUser.getIdentifier()), identifiers(kept)); + } + + /** + * Method to test: {@link ReadableRowFilter#filter(List, User)} + * Given Scenario: A row the limited user cannot read + * ExpectedResult: The row is dropped + */ + @Test + public void test_filter_dropsUnreadableRow() throws Exception { + final List kept = new ReadableRowFilter() + .filter(List.of(row(unreadable)), limitedUser); + + assertTrue(kept.isEmpty()); + } + + /** + * Method to test: {@link ReadableRowFilter#filter(List, User)} + * Given Scenario: A CMS Administrator and every row, including the one the limited user cannot + * read + * ExpectedResult: Every row is kept, and no batch permission query is made + */ + @Test + public void test_filter_adminKeepsEveryRowWithoutAPermissionQuery() throws Exception { + final User admin = new UserDataGen() + .roles(APILocator.getRoleAPI().loadCMSAdminRole()).nextPersisted(); + final PermissionAPI spiedPermissions = spy(APILocator.getPermissionAPI()); + final ReadableRowFilter filter = + new ReadableRowFilter(spiedPermissions, APILocator.getContentletAPI()); + + final List rows = List.of(row(individuallyReadable), row(inheritedOnly), + row(ownedByUser), row(unreadable)); + final List kept = filter.filter(rows, admin); + + assertEquals(identifiers(rows), identifiers(kept)); + verify(spiedPermissions, never()).filterCollection(anyCollection(), anyInt(), + any(User.class), anyBoolean()); + } + + /** + * Method to test: {@link ReadableRowFilter#filter(List, User)} + * Given Scenario: Readable and unreadable rows mixed, in an order that is not sorted + * ExpectedResult: The readable rows are returned in their input order + */ + @Test + public void test_filter_preservesInputOrder() throws Exception { + final List kept = new ReadableRowFilter().filter(List.of(row(ownedByUser), + row(unreadable), row(inheritedOnly), row(individuallyReadable)), limitedUser); + + assertEquals(List.of(ownedByUser.getIdentifier(), inheritedOnly.getIdentifier(), + individuallyReadable.getIdentifier()), identifiers(kept)); + } +} diff --git a/dotcms-integration/src/test/java/com/dotcms/content/export/ContentletCsvWriterTest.java b/dotcms-integration/src/test/java/com/dotcms/content/export/ContentletCsvWriterTest.java new file mode 100644 index 000000000000..1352d7a5a725 --- /dev/null +++ b/dotcms-integration/src/test/java/com/dotcms/content/export/ContentletCsvWriterTest.java @@ -0,0 +1,672 @@ +package com.dotcms.content.export; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import com.dotcms.IntegrationTestBase; +import com.dotcms.api.web.HttpServletRequestThreadLocal; +import com.dotcms.contenttype.model.field.BinaryField; +import com.dotcms.contenttype.model.field.CategoryField; +import com.dotcms.contenttype.model.field.CheckboxField; +import com.dotcms.contenttype.model.field.ColumnField; +import com.dotcms.contenttype.model.field.ConstantField; +import com.dotcms.contenttype.model.field.DateField; +import com.dotcms.contenttype.model.field.DateTimeField; +import com.dotcms.contenttype.model.field.Field; +import com.dotcms.contenttype.model.field.HiddenField; +import com.dotcms.contenttype.model.field.HostFolderField; +import com.dotcms.contenttype.model.field.ImageField; +import com.dotcms.contenttype.model.field.KeyValueField; +import com.dotcms.contenttype.model.field.LineDividerField; +import com.dotcms.contenttype.model.field.MultiSelectField; +import com.dotcms.contenttype.model.field.RadioField; +import com.dotcms.contenttype.model.field.RelationshipField; +import com.dotcms.contenttype.model.field.RowField; +import com.dotcms.contenttype.model.field.SelectField; +import com.dotcms.contenttype.model.field.StoryBlockField; +import com.dotcms.contenttype.model.field.TabDividerField; +import com.dotcms.contenttype.model.field.TagField; +import com.dotcms.contenttype.model.field.TextAreaField; +import com.dotcms.contenttype.model.field.TextField; +import com.dotcms.contenttype.model.field.TimeField; +import com.dotcms.contenttype.model.field.WysiwygField; +import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.datagen.CategoryDataGen; +import com.dotcms.datagen.ContentTypeDataGen; +import com.dotcms.datagen.ContentletDataGen; +import com.dotcms.datagen.FieldDataGen; +import com.dotcms.datagen.FieldRelationshipDataGen; +import com.dotcms.datagen.FileAssetDataGen; +import com.dotcms.datagen.FolderDataGen; +import com.dotcms.datagen.HTMLPageDataGen; +import com.dotcms.datagen.LanguageDataGen; +import com.dotcms.datagen.RoleDataGen; +import com.dotcms.datagen.SiteDataGen; +import com.dotcms.datagen.TemplateDataGen; +import com.dotcms.datagen.UserDataGen; +import com.dotcms.util.IntegrationTestInitService; +import com.dotmarketing.beans.Host; +import com.dotmarketing.beans.Identifier; +import com.dotmarketing.beans.Permission; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.PermissionAPI; +import com.dotmarketing.business.Role; +import com.dotmarketing.portlets.categories.model.Category; +import com.dotmarketing.portlets.contentlet.action.EditContentletAction; +import com.dotmarketing.portlets.contentlet.business.ContentletAPI; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.folders.model.Folder; +import com.dotmarketing.portlets.htmlpageasset.model.HTMLPageAsset; +import com.dotmarketing.portlets.languagesmanager.model.Language; +import com.dotmarketing.util.WebKeys; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.liferay.portal.model.User; +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.Writer; +import java.nio.file.Files; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Integration tests for {@link ContentletCsvWriter}, the CSV writer moved out of the Content Search + * export ({@code EditContentletAction.downloadToExcel}). + *

+ * The first test is a characterization of today's Content Search CSV (T004). It runs + * against the legacy code, so it must pass before the writer exists, and must keep passing after + * {@code downloadToExcel} delegates to the writer: that is what proves Content Search output does + * not change (FR-023). The identifiers, inodes and paths are generated, so the expected text is + * checked cell by cell rather than held in a constant; the byte-for-byte comparison with the new + * writer is made against the legacy output captured in the same run. + *

+ * The other tests cover what the writer adds (T005): the {@link HostFolderMode#LOCATION} column, + * skipping rows the user cannot read or that no longer exist, an empty cell for a field that fails, + * a whole-file failure propagating, and the header-only cases. + */ +public class ContentletCsvWriterTest extends IntegrationTestBase { + + private static final String TITLE_VALUE = "He said \"hi\", then\r\nleft"; + private static final String TITLE_EXPECTED = "He said \"hi\", then\nleft"; + private static final String STORY_BLOCK_VALUE = + "{\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":" + + "[{\"type\":\"text\",\"text\":\"Valid block\"}]}]}"; + private static final String CONSTANT_VALUE = "CONSTANT-VALUE"; + + private static User systemUser; + private static Host site; + private static Host systemHost; + private static Folder folder; + private static Language defaultLanguage; + private static Language secondLanguage; + private static Category childOne; + private static Category childTwo; + private static Contentlet imageAsset; + private static Contentlet relatedOne; + private static Contentlet relatedTwo; + private static ContentType contentType; + private static Date dateValue; + private static Date dateTimeValue; + private static Date timeValue; + + /** The main contentlet, in a folder, in the default language. */ + private static Contentlet inFolder; + /** The same identifier as {@link #inFolder}, in {@link #secondLanguage}. */ + private static Contentlet inFolderSecondLanguage; + /** A contentlet at the site root (the site's system folder). */ + private static Contentlet atSiteRoot; + /** A contentlet in System Host. */ + private static Contentlet inSystemHost; + + private static HttpServletRequest request; + + @BeforeClass + public static void prepare() throws Exception { + IntegrationTestInitService.getInstance().init(); + + systemUser = APILocator.systemUser(); + systemHost = APILocator.getHostAPI().findSystemHost(); + defaultLanguage = APILocator.getLanguageAPI().getDefaultLanguage(); + secondLanguage = new LanguageDataGen().nextPersisted(); + + final String unique = String.valueOf(System.currentTimeMillis()); + site = new SiteDataGen().name("csv-writer-" + unique + ".local").nextPersisted(); + folder = new FolderDataGen().site(site).name("csv-" + unique).nextPersisted(); + + final Category parent = new CategoryDataGen().setCategoryName("csvParent" + unique) + .setKey("csvParent" + unique).setCategoryVelocityVarName("csvParent" + unique) + .nextPersisted(); + childOne = new CategoryDataGen().setCategoryName("csvChildOne" + unique) + .setKey("csvKeyOne" + unique).setCategoryVelocityVarName("csvChildOne" + unique) + .parent(parent).nextPersisted(); + childTwo = new CategoryDataGen().setCategoryName("csvChildTwo" + unique) + .setKey("csvKeyTwo" + unique).setCategoryVelocityVarName("csvChildTwo" + unique) + .parent(parent).nextPersisted(); + + final File image = File.createTempFile("csv-image", ".png"); + Files.write(image.toPath(), new byte[]{1, 2, 3}); + imageAsset = new FileAssetDataGen(folder, image).nextPersisted(); + + final ContentType relatedType = new ContentTypeDataGen().host(site) + .field(new FieldDataGen().defaultValue(null).type(TextField.class).name("label") + .velocityVarName("label").next()) + .nextPersisted(); + relatedOne = new ContentletDataGen(relatedType).host(site).setProperty("label", "r1") + .nextPersisted(); + relatedTwo = new ContentletDataGen(relatedType).host(site).setProperty("label", "r2") + .nextPersisted(); + + // FieldDataGen gives every field a text default value; DateField rejects it, and a default + // would also fill cells the test expects empty, so every field here clears it. + final List fields = new ArrayList<>(); + fields.add(new FieldDataGen().defaultValue(null).type(TextField.class).name("title").velocityVarName("title").next()); + fields.add(new FieldDataGen().defaultValue(null).type(TextAreaField.class).name("notes").velocityVarName("notes").next()); + fields.add(new FieldDataGen().defaultValue(null).type(WysiwygField.class).name("body").velocityVarName("body").next()); + fields.add(new FieldDataGen().defaultValue(null).type(SelectField.class).name("color").velocityVarName("color") + .values("Red|red\r\nBlue|blue").next()); + fields.add(new FieldDataGen().defaultValue(null).type(MultiSelectField.class).name("letters").velocityVarName("letters") + .values("A|a\r\nB|b").next()); + fields.add(new FieldDataGen().defaultValue(null).type(CheckboxField.class).name("options").velocityVarName("options") + .values("X|x\r\nY|y").next()); + fields.add(new FieldDataGen().defaultValue(null).type(RadioField.class).name("choice").velocityVarName("choice") + .values("One|1\r\nTwo|2").next()); + fields.add(new FieldDataGen().defaultValue(null).type(DateField.class).name("pubDate").velocityVarName("pubDate").next()); + fields.add(new FieldDataGen().defaultValue(null).type(DateTimeField.class).name("eventAt").velocityVarName("eventAt").next()); + fields.add(new FieldDataGen().defaultValue(null).type(TimeField.class).name("startsAt").velocityVarName("startsAt").next()); + fields.add(new FieldDataGen().defaultValue(null).type(CategoryField.class).name("cats").velocityVarName("cats") + .values(parent.getInode()).next()); + fields.add(new FieldDataGen().defaultValue(null).type(TagField.class).name("tags").velocityVarName("tags").next()); + fields.add(new FieldDataGen().defaultValue(null).type(KeyValueField.class).name("meta").velocityVarName("meta").next()); + fields.add(new FieldDataGen().defaultValue(null).type(ImageField.class).name("picture").velocityVarName("picture").next()); + fields.add(new FieldDataGen().defaultValue(null).type(BinaryField.class).name("attachment").velocityVarName("attachment").next()); + fields.add(new FieldDataGen().defaultValue(null).type(HostFolderField.class).name("location").velocityVarName("location").next()); + fields.add(new FieldDataGen().defaultValue(null).type(ConstantField.class).name("fixedText").velocityVarName("fixedText") + .values(CONSTANT_VALUE).next()); + fields.add(new FieldDataGen().defaultValue(null).type(HiddenField.class).name("secret").velocityVarName("secret").next()); + fields.add(new FieldDataGen().defaultValue(null).type(StoryBlockField.class).name("story").velocityVarName("story").next()); + fields.add(new FieldDataGen().defaultValue(null).type(LineDividerField.class).name("divider").velocityVarName("divider").next()); + + final ContentType created = new ContentTypeDataGen().host(site) + .velocityVarName("csvWriter" + unique).name("CSV Writer " + unique) + .fields(fields).nextPersisted(); + new FieldRelationshipDataGen().parent(created).child(relatedType).nextPersisted(); + contentType = APILocator.getContentTypeAPI(systemUser).find(created.variable()); + + dateValue = new GregorianCalendar(2026, Calendar.MARCH, 5).getTime(); + dateTimeValue = new GregorianCalendar(2026, Calendar.MARCH, 5, 14, 30).getTime(); + timeValue = new GregorianCalendar(1970, Calendar.JANUARY, 1, 9, 15).getTime(); + + inFolder = fullContentlet().host(site).folder(folder).languageId(defaultLanguage.getId()) + .nextPersisted(); + + final Contentlet secondLanguageDraft = ContentletDataGen.checkout(inFolder); + secondLanguageDraft.setLanguageId(secondLanguage.getId()); + inFolderSecondLanguage = ContentletDataGen.checkin(secondLanguageDraft); + + atSiteRoot = new ContentletDataGen(contentType).host(site) + .languageId(defaultLanguage.getId()).setProperty("title", "root item") + .nextPersisted(); + + inSystemHost = new ContentletDataGen(contentType).host(systemHost) + .languageId(defaultLanguage.getId()).setProperty("title", "system host item") + .nextPersisted(); + + request = mock(HttpServletRequest.class); + when(request.isSecure()).thenReturn(false); + HttpServletRequestThreadLocal.INSTANCE.setRequest(request); + } + + private static ContentletDataGen fullContentlet() throws IOException { + final File binary = File.createTempFile("csv-binary", ".txt"); + Files.writeString(binary.toPath(), "binary content"); + + final Map keyValue = new LinkedHashMap<>(); + keyValue.put("k1", "v1"); + keyValue.put("k2", "v2"); + + return new ContentletDataGen(contentType) + .setProperty("title", TITLE_VALUE) + .setProperty("notes", "Plain notes") + .setProperty("body", "

Body

") + .setProperty("color", "red") + .setProperty("letters", "a,b") + .setProperty("options", "x,y") + .setProperty("choice", "1") + .setProperty("pubDate", dateValue) + .setProperty("eventAt", dateTimeValue) + .setProperty("startsAt", timeValue) + .setProperty("tags", "alpha,beta") + .setProperty("meta", keyValue) + .setProperty("picture", imageAsset.getIdentifier()) + .setProperty("attachment", binary) + .setProperty("secret", "hidden-value") + .setProperty("story", STORY_BLOCK_VALUE) + .setProperty(relationshipVariable(), List.of(relatedOne, relatedTwo)) + .addCategory(childOne) + .addCategory(childTwo); + } + + private static String relationshipVariable() { + return contentType.fields(RelationshipField.class).get(0).variable(); + } + + @AfterClass + public static void cleanup() { + HttpServletRequestThreadLocal.INSTANCE.setRequest(null); + } + + // --------------------------------------------------------------------------------------------- + // T004 — characterization of today's Content Search CSV + // --------------------------------------------------------------------------------------------- + + /** + * Method to test: {@link EditContentletAction#downloadToExcel(HttpServletResponse, User, List, String)} + * Given Scenario: The legacy Content Search export of a content type with one field of every + * exported kind, a layout field, and contentlets in a folder (two languages), at + * the site root and in System Host + * ExpectedResult: The CSV Content Search writes today: the header, the quoting and line endings, + * and every per-field format. It must pass before and after the writer move (FR-023). + */ + @Test + public void test_legacyDownloadToExcel_characterization() throws Exception { + final String csv = legacyCsv(List.of(inFolder, inFolderSecondLanguage, atSiteRoot, inSystemHost)); + + assertTrue("rows end with CRLF", csv.endsWith("\r\n")); + final List> rows = parseCsv(csv); + assertEquals("header plus four rows", 5, rows.size()); + + final List header = rows.get(0); + assertEquals(expectedHeader(), header); + assertFalse("layout fields are not exported", header.contains("divider")); + + final Map row = asMap(header, rows.get(1)); + assertEquals(inFolder.getIdentifier(), row.get("Identifier")); + assertEquals(defaultLanguage.getLanguageCode(), row.get("languageCode")); + assertEquals(defaultLanguage.getCountryCode(), row.get("countryCode")); + + assertEquals("CR stripped, quotes doubled inside a quoted cell", TITLE_EXPECTED, row.get("title")); + assertTrue("a value with a comma is quoted, with its quotes doubled", + csv.contains(",\"He said \"\"hi\"\", then\nleft\",")); + assertEquals("Plain notes", row.get("notes")); + assertEquals("

Body

", row.get("body")); + assertEquals("red", row.get("color")); + assertEquals("a,b", row.get("letters")); + assertEquals("x,y", row.get("options")); + assertEquals("1", row.get("choice")); + + assertEquals(new SimpleDateFormat(WebKeys.DateFormats.EXP_IMP_DATE).format(dateValue), + row.get("pubDate")); + assertEquals(new SimpleDateFormat(WebKeys.DateFormats.EXP_IMP_DATETIME).format(dateTimeValue), + row.get("eventAt")); + assertEquals(new SimpleDateFormat(WebKeys.DateFormats.EXP_IMP_TIME).format(timeValue), + row.get("startsAt")); + + assertEquals("categories as keys", Set.of(childOne.getKey(), childTwo.getKey()), + splitToSet(row.get("cats"))); + assertEquals("tags as names", Set.of("alpha", "beta"), splitToSet(row.get("tags"))); + assertEquals("key-value as JSON", Map.of("k1", "v1", "k2", "v2"), + new ObjectMapper().readValue(row.get("meta"), Map.class)); + + final Identifier imageId = APILocator.getIdentifierAPI().find(imageAsset.getIdentifier()); + assertEquals("image as path", imageId.getPath(), row.get("picture")); + assertTrue("binary as a download link: " + row.get("attachment"), + row.get("attachment").startsWith("http://" + site.getHostname() + "/")); + + assertEquals("host/folder as the folder inode", folder.getInode(), row.get("location")); + assertEquals(CONSTANT_VALUE, row.get("fixedText")); + assertEquals("hidden-value", row.get("secret")); + assertTrue(row.get("story").contains("Valid block")); + assertEquals("related identifiers, comma-joined", + Set.of(relatedOne.getIdentifier(), relatedTwo.getIdentifier()), + splitToSet(row.get(relationshipVariable()))); + + final Map secondLanguageRow = asMap(header, rows.get(2)); + assertEquals(inFolder.getIdentifier(), secondLanguageRow.get("Identifier")); + assertEquals(secondLanguage.getLanguageCode(), secondLanguageRow.get("languageCode")); + assertEquals(secondLanguage.getCountryCode(), secondLanguageRow.get("countryCode")); + + assertEquals("host/folder as the host id at a site root", site.getIdentifier(), + asMap(header, rows.get(3)).get("location")); + assertEquals("host/folder as the System Host id", systemHost.getIdentifier(), + asMap(header, rows.get(4)).get("location")); + } + + /** + * Method to test: {@link EditContentletAction#downloadToExcel(HttpServletResponse, User, List, String)} + * Given Scenario: The legacy export of a page + * ExpectedResult: The page's URL column is written as the page path + */ + @Test + public void test_legacyDownloadToExcel_pageUrlAsPath() throws Exception { + final HTMLPageAsset page = new HTMLPageDataGen(folder, new TemplateDataGen().nextPersisted()) + .nextPersisted(); + final ContentType pageType = page.getContentType(); + + final StringWriter out = new StringWriter(); + new EditContentletAction().downloadToExcel(responseWriting(out), systemUser, + legacyList(List.of(page)), pageType.inode()); + + final List> rows = parseCsv(out.toString()); + final Identifier pageId = APILocator.getIdentifierAPI().find(page.getIdentifier()); + assertEquals(pageId.getPath(), asMap(rows.get(0), rows.get(1)).get("url")); + } + + // --------------------------------------------------------------------------------------------- + // T005 — the new writer + // --------------------------------------------------------------------------------------------- + + /** + * Method to test: {@link ContentletCsvWriter#write} + * Given Scenario: The same contentlets as the characterization, written in + * {@link HostFolderMode#IDENTIFIER} + * ExpectedResult: Byte-for-byte the CSV the legacy export writes (FR-020, FR-023); four rows + * reported + */ + @Test + public void test_write_identifierMode_matchesLegacyByteForByte() throws Exception { + final List contentlets = + List.of(inFolder, inFolderSecondLanguage, atSiteRoot, inSystemHost); + final String legacy = legacyCsv(contentlets); + + final StringWriter out = new StringWriter(); + final int written = new ContentletCsvWriter().write(contentType, inodes(contentlets), + systemUser, request, HostFolderMode.IDENTIFIER, out); + + assertEquals(4, written); + assertEquals(legacy, out.toString()); + } + + /** + * Method to test: {@link ContentletCsvWriter#write} + * Given Scenario: The same contentlets written in {@link HostFolderMode#LOCATION} + * ExpectedResult: The host/folder column is {@code //host/path/} in a folder, the bare host name + * at a site root and {@code SYSTEM_HOST} in System Host (FR-022); every other column equals the + * {@link HostFolderMode#IDENTIFIER} output + */ + @Test + public void test_write_locationMode_writesReadableLocations() throws Exception { + final List contentlets = List.of(inFolder, atSiteRoot, inSystemHost); + + final StringWriter identifierOut = new StringWriter(); + new ContentletCsvWriter().write(contentType, inodes(contentlets), systemUser, request, + HostFolderMode.IDENTIFIER, identifierOut); + final StringWriter locationOut = new StringWriter(); + new ContentletCsvWriter().write(contentType, inodes(contentlets), systemUser, request, + HostFolderMode.LOCATION, locationOut); + + final List> identifierRows = parseCsv(identifierOut.toString()); + final List> locationRows = parseCsv(locationOut.toString()); + final List header = locationRows.get(0); + assertEquals(identifierRows.get(0), header); + + assertEquals("//" + site.getHostname() + folder.getPath(), + asMap(header, locationRows.get(1)).get("location")); + assertEquals(site.getHostname(), asMap(header, locationRows.get(2)).get("location")); + assertEquals("SYSTEM_HOST", asMap(header, locationRows.get(3)).get("location")); + + for (int i = 1; i < locationRows.size(); i++) { + final Map location = asMap(header, locationRows.get(i)); + final Map identifier = asMap(header, identifierRows.get(i)); + location.remove("location"); + identifier.remove("location"); + assertEquals("row " + i + " differs only in the host/folder column", identifier, location); + } + } + + /** + * Method to test: {@link ContentletCsvWriter#write} + * Given Scenario: A limited user who can read {@link #inFolder} through an individual + * permission but not {@link #atSiteRoot} + * ExpectedResult: The unreadable row is skipped and not counted; the count equals the data rows + * written (FR-026a) + */ + @Test + public void test_write_skipsRowsTheUserCannotRead() throws Exception { + final Role role = new RoleDataGen().nextPersisted(); + final User limitedUser = new UserDataGen().roles(role).nextPersisted(); + final PermissionAPI permissionAPI = APILocator.getPermissionAPI(); + permissionAPI.save(new Permission(inFolder.getPermissionId(), role.getId(), + PermissionAPI.PERMISSION_READ), inFolder, systemUser, false); + + final StringWriter out = new StringWriter(); + final int written = new ContentletCsvWriter().write(contentType, + inodes(List.of(inFolder, atSiteRoot)), limitedUser, request, + HostFolderMode.LOCATION, out); + + assertEquals(1, written); + final List> rows = parseCsv(out.toString()); + assertEquals(2, rows.size()); + assertEquals(inFolder.getIdentifier(), rows.get(1).get(0)); + } + + /** + * Method to test: {@link ContentletCsvWriter#write} + * Given Scenario: An inode that does not exist, between two that do + * ExpectedResult: It is skipped and not counted + */ + @Test + public void test_write_skipsInodesThatNoLongerExist() throws Exception { + final StringWriter out = new StringWriter(); + final int written = new ContentletCsvWriter().write(contentType, + List.of(inFolder.getInode(), "00000000-0000-0000-0000-000000000000", + atSiteRoot.getInode()), + systemUser, request, HostFolderMode.LOCATION, out); + + assertEquals(2, written); + assertEquals(3, parseCsv(out.toString()).size()); + } + + /** + * Method to test: {@link ContentletCsvWriter#write} + * Given Scenario: Reading one field's value throws + * ExpectedResult: That cell is empty and the next fields are still written, as legacy does + */ + @Test + public void test_write_fieldFailureWritesAnEmptyCell() throws Exception { + final ContentletAPI failing = spy(APILocator.getContentletAPI()); + doThrow(new RuntimeException("cannot read notes")).when(failing) + .getFieldValue(any(Contentlet.class), argThat((Field field) -> field != null + && "notes".equals(field.variable()))); + final ContentletCsvWriter writer = new ContentletCsvWriter(failing, + APILocator.getCategoryAPI(), APILocator.getTagAPI(), APILocator.getIdentifierAPI(), + APILocator.getHostAPI(), APILocator.getFolderAPI()); + + final StringWriter out = new StringWriter(); + final int written = writer.write(contentType, List.of(inFolder.getInode()), systemUser, + request, HostFolderMode.LOCATION, out); + + assertEquals(1, written); + final List> rows = parseCsv(out.toString()); + final Map row = asMap(rows.get(0), rows.get(1)); + assertEquals("", row.get("notes")); + assertEquals("

Body

", row.get("body")); + } + + /** + * Method to test: {@link ContentletCsvWriter#write} + * Given Scenario: The output fails while writing + * ExpectedResult: The failure propagates, so the caller never sends a partial file (FR-020a) + */ + @Test + public void test_write_outputFailurePropagates() { + final Writer broken = new Writer() { + @Override + public void write(final char[] buffer, final int offset, final int length) + throws IOException { + throw new IOException("disk full"); + } + + @Override + public void flush() throws IOException { + throw new IOException("disk full"); + } + + @Override + public void close() { + } + }; + + assertThrows(IOException.class, () -> new ContentletCsvWriter().write(contentType, + List.of(inFolder.getInode()), systemUser, request, HostFolderMode.LOCATION, broken)); + } + + /** + * Method to test: {@link ContentletCsvWriter#write} + * Given Scenario: No inodes + * ExpectedResult: Only the header row is written, and zero rows are reported + */ + @Test + public void test_write_noInodesWritesOnlyTheHeader() throws Exception { + final StringWriter out = new StringWriter(); + final int written = new ContentletCsvWriter().write(contentType, List.of(), systemUser, + request, HostFolderMode.LOCATION, out); + + assertEquals(0, written); + final List> rows = parseCsv(out.toString()); + assertEquals(1, rows.size()); + assertEquals(expectedHeader(), rows.get(0)); + } + + /** + * Method to test: {@link ContentletCsvWriter#write} + * Given Scenario: A content type whose only field is a layout field + * ExpectedResult: The header is {@code Identifier,languageCode,countryCode} + */ + @Test + public void test_write_typeWithNoExportableFields() throws Exception { + final ContentType layoutOnly = new ContentTypeDataGen().host(site) + .field(new FieldDataGen().defaultValue(null).type(LineDividerField.class).name("line") + .velocityVarName("line").next()) + .nextPersisted(); + + final StringWriter out = new StringWriter(); + new ContentletCsvWriter().write(layoutOnly, List.of(), systemUser, request, + HostFolderMode.LOCATION, out); + + assertEquals("Identifier,languageCode,countryCode\r\n", out.toString()); + } + + // --------------------------------------------------------------------------------------------- + // helpers + // --------------------------------------------------------------------------------------------- + + private static List expectedHeader() { + final List header = new ArrayList<>( + List.of("Identifier", "languageCode", "countryCode")); + // Layout fields are the @Unexportable ones; the content type API adds rows and columns on save + contentType.fields().stream() + .filter(field -> !(field instanceof LineDividerField || field instanceof RowField + || field instanceof ColumnField || field instanceof TabDividerField)) + .forEach(field -> header.add(field.variable())); + return header; + } + + private static String legacyCsv(final List contentlets) throws Exception { + final StringWriter out = new StringWriter(); + new EditContentletAction().downloadToExcel(responseWriting(out), systemUser, + legacyList(contentlets), contentType.inode()); + return out.toString(); + } + + private static HttpServletResponse responseWriting(final StringWriter out) throws IOException { + final HttpServletResponse response = mock(HttpServletResponse.class); + when(response.getWriter()).thenReturn(new PrintWriter(out)); + return response; + } + + /** + * The list in the shape Content Search hands to {@code downloadToExcel}: two leading entries it + * skips, then one map per contentlet holding its inode. + */ + private static List> legacyList(final List contentlets) { + final List> list = new ArrayList<>(); + list.add(new HashMap<>()); + list.add(new HashMap<>()); + for (final Contentlet contentlet : contentlets) { + final Map entry = new HashMap<>(); + entry.put("inode", contentlet.getInode()); + list.add(entry); + } + return list; + } + + private static List inodes(final List contentlets) { + return contentlets.stream().map(Contentlet::getInode).collect(Collectors.toList()); + } + + private static Map asMap(final List header, final List row) { + assertEquals("row has one cell per column", header.size(), row.size()); + final Map map = new LinkedHashMap<>(); + for (int i = 0; i < header.size(); i++) { + map.put(header.get(i), row.get(i)); + } + return map; + } + + private static Set splitToSet(final String value) { + return new HashSet<>(Arrays.asList(value.split(","))); + } + + /** + * Parses the legacy CSV format: rows end with CRLF, a cell is quoted when it holds a comma or a + * newline, and a quote inside a quoted cell is doubled. + */ + static List> parseCsv(final String csv) { + final List> rows = new ArrayList<>(); + List row = new ArrayList<>(); + final StringBuilder cell = new StringBuilder(); + boolean quoted = false; + for (int i = 0; i < csv.length(); i++) { + final char c = csv.charAt(i); + if (quoted) { + if (c == '"' && i + 1 < csv.length() && csv.charAt(i + 1) == '"') { + cell.append('"'); + i++; + } else if (c == '"') { + quoted = false; + } else { + cell.append(c); + } + } else if (c == '"' && cell.length() == 0) { + quoted = true; + } else if (c == ',') { + row.add(cell.toString()); + cell.setLength(0); + } else if (c == '\r' && i + 1 < csv.length() && csv.charAt(i + 1) == '\n') { + row.add(cell.toString()); + cell.setLength(0); + rows.add(row); + row = new ArrayList<>(); + i++; + } else { + cell.append(c); + } + } + return rows; + } +} diff --git a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilderTest.java b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilderTest.java new file mode 100644 index 000000000000..33e76b87be81 --- /dev/null +++ b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilderTest.java @@ -0,0 +1,278 @@ +package com.dotcms.rest.api.v1.drive.export; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +import com.dotcms.IntegrationTestBase; +import com.dotcms.content.export.ContentletCsvWriter; +import com.dotcms.content.export.HostFolderMode; +import com.dotcms.contenttype.model.field.TextField; +import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.datagen.ContentTypeDataGen; +import com.dotcms.datagen.FieldDataGen; +import com.dotcms.util.IntegrationTestInitService; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.util.ConfigUtils; +import com.liferay.portal.model.User; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.StreamingOutput; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Integration tests for {@link ExportFileBuilder}: the export is written to a temp file before + * anything is sent, and no temp file is left behind, whatever happens (research R11, FR-031, + * FR-032, SC-008). + *

+ * The CSV content itself is {@link ContentletCsvWriter}'s job and is covered by its own test; here + * a fake writer writes known text, so each case checks only what the builder adds. + */ +public class ExportFileBuilderTest extends IntegrationTestBase { + + private static User user; + private static HttpServletRequest request; + private static ContentType blog; + private static ContentType news; + + @BeforeClass + public static void prepare() throws Exception { + IntegrationTestInitService.getInstance().init(); + user = APILocator.systemUser(); + request = mock(HttpServletRequest.class); + + final String unique = String.valueOf(System.currentTimeMillis()); + blog = new ContentTypeDataGen().name("Blog " + unique).velocityVarName("blogExport" + unique) + .field(new FieldDataGen().type(TextField.class).name("title").velocityVarName("title").next()) + .nextPersisted(); + news = new ContentTypeDataGen().name("News " + unique).velocityVarName("newsExport" + unique) + .field(new FieldDataGen().type(TextField.class).name("title").velocityVarName("title").next()) + .nextPersisted(); + } + + /** + * Writes {@code header} and one line per inode, and reports one row per inode + * unless told otherwise. + */ + private static class FakeWriter extends ContentletCsvWriter { + + private final int reportedRows; + private final boolean fail; + + FakeWriter() { + this(-1, false); + } + + FakeWriter(final int reportedRows, final boolean fail) { + this.reportedRows = reportedRows; + this.fail = fail; + } + + @Override + public int write(final ContentType contentType, final List inodes, final User user, + final HttpServletRequest request, final HostFolderMode hostFolderMode, + final Writer out) throws DotDataException, IOException { + out.write(contentType.variable() + " header\r\n"); + if (fail) { + throw new DotDataException("writer failed halfway"); + } + for (final String inode : inodes) { + out.write(inode + "\r\n"); + } + return reportedRows >= 0 ? reportedRows : inodes.size(); + } + } + + private static List filesIn(final Path directory) throws IOException { + if (!Files.exists(directory)) { + return List.of(); + } + try (Stream files = Files.list(directory)) { + return files.collect(java.util.stream.Collectors.toList()); + } + } + + /** + * Method to test: {@link ExportFileBuilder#buildCsv} + * Given Scenario: One content type with two rows, built in the real export directory + * ExpectedResult: A temp file under {@code /drive-export/} holding the writer's + * output, named as Content Search names it, with 2 rows and 1 file + */ + @Test + public void test_buildCsv_writesTheFileInTheExportDirectory() throws Exception { + final Path exportDirectory = + Path.of(ConfigUtils.getAssetTempPath(), ExportFileBuilder.DIRECTORY_NAME); + final ExportFile file = new ExportFileBuilder(new FakeWriter(), exportDirectory) + .buildCsv(blog, List.of("inode-1", "inode-2"), user, request); + try { + assertEquals(exportDirectory.toAbsolutePath().normalize(), + file.path().getParent().toAbsolutePath().normalize()); + assertEquals(blog.variable() + " header\r\ninode-1\r\ninode-2\r\n", + Files.readString(file.path(), StandardCharsets.UTF_8)); + assertEquals(ExportFileNames.csvName(blog.name(), blog.variable(), new Date()), + file.fileName()); + assertEquals("text/csv; charset=UTF-8", file.mediaType()); + assertEquals(2, file.contentlets()); + assertEquals(1, file.files()); + } finally { + Files.deleteIfExists(file.path()); + } + } + + /** + * Method to test: {@link ExportFileBuilder#buildZip} + * Given Scenario: Two content types, two rows and one row + * ExpectedResult: A zip named after the site with one entry per content type, named by + * {@link ExportFileNames}, holding each type's CSV; 3 rows and 2 files + */ + @Test + public void test_buildZip_writesOneEntryPerContentType() throws Exception { + final Path directory = Files.createTempDirectory("drive-export-zip"); + final Map> rows = new LinkedHashMap<>(); + rows.put(news, List.of("news-1")); + rows.put(blog, List.of("blog-1", "blog-2")); + + final ExportFile file = new ExportFileBuilder(new FakeWriter(), directory) + .buildZip("demo.dotcms.com", rows, user, request); + try { + assertEquals(ExportFileNames.zipName("demo.dotcms.com", new Date()), file.fileName()); + assertEquals("application/zip", file.mediaType()); + assertEquals(3, file.contentlets()); + assertEquals(2, file.files()); + + final Map expectedNames = ExportFileNames.csvNames(List.of( + new ExportFileNames.TypeName(news.id(), news.name(), news.variable()), + new ExportFileNames.TypeName(blog.id(), blog.name(), blog.variable())), new Date()); + final Map entries = new LinkedHashMap<>(); + try (ZipInputStream zip = new ZipInputStream(Files.newInputStream(file.path()))) { + for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { + entries.put(entry.getName(), new String(zip.readAllBytes(), StandardCharsets.UTF_8)); + } + } + assertEquals(new ArrayList<>(expectedNames.values()), new ArrayList<>(entries.keySet())); + assertEquals(blog.variable() + " header\r\nblog-1\r\nblog-2\r\n", + entries.get(expectedNames.get(blog.id()))); + assertEquals(news.variable() + " header\r\nnews-1\r\n", + entries.get(expectedNames.get(news.id()))); + } finally { + Files.deleteIfExists(file.path()); + } + } + + /** + * Method to test: {@link ExportFileBuilder#buildCsv} and {@link ExportFileBuilder#buildZip} + * Given Scenario: The writer fails halfway + * ExpectedResult: The failure propagates and no temp file is left in the directory + */ + @Test + public void test_writerFailure_deletesTheTempFile() throws Exception { + final Path directory = Files.createTempDirectory("drive-export-fail"); + final ExportFileBuilder builder = new ExportFileBuilder(new FakeWriter(-1, true), directory); + + assertThrows(DotDataException.class, + () -> builder.buildCsv(blog, List.of("inode-1"), user, request)); + assertTrue(filesIn(directory).isEmpty()); + + assertThrows(DotDataException.class, + () -> builder.buildZip("demo.dotcms.com", Map.of(blog, List.of("inode-1")), user, + request)); + assertTrue(filesIn(directory).isEmpty()); + } + + /** + * Method to test: {@link ExportFileBuilder#toStreamingOutput(ExportFile)} + * Given Scenario: A finished file streamed to a response that accepts it, and another streamed + * to a response whose stream fails + * ExpectedResult: The bytes sent are the file's; the file is deleted in both cases + */ + @Test + public void test_streamingOutput_deletesTheFileAfterSending() throws Exception { + final Path directory = Files.createTempDirectory("drive-export-stream"); + final ExportFileBuilder builder = new ExportFileBuilder(new FakeWriter(), directory); + + final ExportFile sent = builder.buildCsv(blog, List.of("inode-1"), user, request); + final byte[] expected = Files.readAllBytes(sent.path()); + final ByteArrayOutputStream received = new ByteArrayOutputStream(); + ExportFileBuilder.toStreamingOutput(sent).write(received); + assertArrayEquals(expected, received.toByteArray()); + assertFalse(Files.exists(sent.path())); + + final ExportFile failing = builder.buildCsv(blog, List.of("inode-1"), user, request); + final StreamingOutput output = ExportFileBuilder.toStreamingOutput(failing); + final OutputStream broken = new OutputStream() { + @Override + public void write(final int b) throws IOException { + throw new IOException("client went away"); + } + }; + assertThrows(IOException.class, () -> output.write(broken)); + assertFalse(Files.exists(failing.path())); + } + + /** + * Method to test: {@link ExportFileBuilder#buildCsv} + * Given Scenario: The directory holds a leftover file older than one hour and a recent one + * ExpectedResult: Starting an export deletes the old leftover and keeps the recent file + */ + @Test + public void test_startingAnExport_sweepsLeftoversOlderThanOneHour() throws Exception { + final Path directory = Files.createTempDirectory("drive-export-sweep"); + final Path old = Files.writeString(directory.resolve("old-export.csv"), "old"); + Files.setLastModifiedTime(old, FileTime.from(Instant.now().minus(2, ChronoUnit.HOURS))); + final Path recent = Files.writeString(directory.resolve("recent-export.csv"), "recent"); + + final ExportFile file = new ExportFileBuilder(new FakeWriter(), directory) + .buildCsv(blog, List.of("inode-1"), user, request); + try { + assertFalse("the leftover older than one hour is swept", Files.exists(old)); + assertTrue("a recent file, possibly another export in progress, is kept", + Files.exists(recent)); + } finally { + Files.deleteIfExists(file.path()); + Files.deleteIfExists(recent); + } + } + + /** + * Method to test: {@link ExportFileBuilder#buildCsv} and {@link ExportFileBuilder#buildZip} + * Given Scenario: Every row became unreadable while writing, so the writer reports zero rows + * ExpectedResult: The result reports zero rows and the temp file is already gone + */ + @Test + public void test_zeroRowsWritten_deletesTheFile() throws Exception { + final Path directory = Files.createTempDirectory("drive-export-empty"); + final ExportFileBuilder builder = new ExportFileBuilder(new FakeWriter(0, false), directory); + + final ExportFile csv = builder.buildCsv(blog, List.of("inode-1"), user, request); + assertEquals(0, csv.contentlets()); + assertFalse(Files.exists(csv.path())); + + final ExportFile zip = builder.buildZip("demo.dotcms.com", Map.of(blog, List.of("inode-1")), + user, request); + assertEquals(0, zip.contentlets()); + assertFalse(Files.exists(zip.path())); + assertTrue(filesIn(directory).isEmpty()); + } +} From 78d56d41169942c626e82f51d343a34c0fdf9e7d Mon Sep 17 00:00:00 2001 From: ddariod Date: Thu, 26 Nov 2026 14:15:20 -0500 Subject: [PATCH 10/28] feat(content-drive): add the export foundation and share the Content Search CSV writer Moves the CSV row formatting out of EditContentletAction.downloadToExcel into ContentletCsvWriter, which Content Search now delegates to, so both exports write the same file. Adds the pieces the Content Drive export (#37900) builds on: the readable-row filter (batch permission check with a per-item re-check), export file names and Content-Disposition, the request form and its validation, and the temp-file builder for CSV and zip downloads. ContentDriveHelper exposes the listing's query building so the export runs the same query the listing shows; driveSearch behaves as before. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- .../java/com/dotcms/browser/ExportRow.java | 2 +- .../com/dotcms/browser/ReadableRowFilter.java | 98 +++++- .../content/export/ContentletCsvWriter.java | 332 +++++++++++++++++- .../rest/api/v1/drive/ContentDriveHelper.java | 90 +++-- .../AbstractDriveExportRequestForm.java | 23 +- .../v1/drive/export/ExportFileBuilder.java | 152 +++++++- .../api/v1/drive/export/ExportFileNames.java | 99 +++++- .../action/EditContentletAction.java | 167 +-------- .../export/ContentletCsvWriterTest.java | 5 +- 9 files changed, 767 insertions(+), 201 deletions(-) diff --git a/dotCMS/src/main/java/com/dotcms/browser/ExportRow.java b/dotCMS/src/main/java/com/dotcms/browser/ExportRow.java index 06e479dae8f5..5efe1192d867 100644 --- a/dotCMS/src/main/java/com/dotcms/browser/ExportRow.java +++ b/dotCMS/src/main/java/com/dotcms/browser/ExportRow.java @@ -17,6 +17,6 @@ public record ExportRow(String inode, String identifier, long languageId, String * @return {@code identifier + ":" + languageId} */ public String key() { - throw new UnsupportedOperationException("not implemented"); + return identifier + ":" + languageId; } } diff --git a/dotCMS/src/main/java/com/dotcms/browser/ReadableRowFilter.java b/dotCMS/src/main/java/com/dotcms/browser/ReadableRowFilter.java index b46b79209d9c..8aff91aab789 100644 --- a/dotCMS/src/main/java/com/dotcms/browser/ReadableRowFilter.java +++ b/dotCMS/src/main/java/com/dotcms/browser/ReadableRowFilter.java @@ -1,11 +1,18 @@ package com.dotcms.browser; +import com.dotmarketing.beans.PermissionableProxy; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.PermissionAPI; import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.contentlet.business.ContentletAPI; +import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.liferay.portal.model.User; +import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; /** * Keeps the export rows a user can read. @@ -16,6 +23,9 @@ */ public class ReadableRowFilter { + /** Rows per batch permission query. */ + static final int CHUNK_SIZE = 500; + private final PermissionAPI permissionAPI; private final ContentletAPI contentletAPI; @@ -38,7 +48,8 @@ public ReadableRowFilter() { } /** - * Returns the rows {@code user} can read, in their input order. + * Returns the rows {@code user} can read, in their input order. A CMS Administrator and the + * system user read everything, so no permission query is made for them. * * @param rows the candidate rows * @param user the {@link User} the export runs as @@ -47,6 +58,89 @@ public ReadableRowFilter() { */ public List filter(final List rows, final User user) throws DotDataException { - throw new UnsupportedOperationException("not implemented"); + if (rows.isEmpty() || readsEverything(user)) { + return new ArrayList<>(rows); + } + final List readable = new ArrayList<>(rows.size()); + for (int start = 0; start < rows.size(); start += CHUNK_SIZE) { + final List chunk = rows.subList(start, Math.min(start + CHUNK_SIZE, rows.size())); + final Set allowed = readableIdentifiers(chunk, user); + for (final ExportRow row : chunk) { + if (allowed.contains(row.identifier())) { + readable.add(row); + } + } + } + return readable; + } + + /** + * Whether the user reads every row without a check: the system user or a CMS Administrator. + * + * @param user the {@link User} the export runs as + * @return {@code true} when no permission check is needed + */ + private static boolean readsEverything(final User user) { + return APILocator.systemUser().getUserId().equals(user.getUserId()) || user.isAdmin(); + } + + /** + * Checks one chunk: one batch query, then a per-item check of what it rejected. + * + * @param chunk the rows to check + * @param user the {@link User} the export runs as + * @return the identifiers of the readable rows of the chunk + * @throws DotDataException if the permissions cannot be read + */ + private Set readableIdentifiers(final List chunk, final User user) + throws DotDataException { + // Permissions are kept per identifier, so the languages of one contentlet share one check + final List proxies = chunk.stream().map(ExportRow::identifier) + .distinct().map(ReadableRowFilter::proxy).collect(Collectors.toList()); + final Set allowed = new HashSet<>(); + try { + permissionAPI.filterCollection(proxies, PermissionAPI.PERMISSION_READ, user, false) + .forEach(proxy -> allowed.add(proxy.getIdentifier())); + } catch (final DotSecurityException e) { + throw new DotDataException(e.getMessage(), e); + } + + final List rejectedInodes = new ArrayList<>(); + final Set rejectedIdentifiers = new HashSet<>(); + for (final ExportRow row : chunk) { + if (!allowed.contains(row.identifier()) && rejectedIdentifiers.add(row.identifier())) { + rejectedInodes.add(row.inode()); + } + } + if (rejectedInodes.isEmpty()) { + return allowed; + } + final List rejected; + try { + rejected = contentletAPI.findContentlets(rejectedInodes); + } catch (final DotSecurityException e) { + throw new DotDataException(e.getMessage(), e); + } + for (final Contentlet contentlet : rejected) { + if (permissionAPI.doesUserHavePermission(contentlet, PermissionAPI.PERMISSION_READ, + user, false)) { + allowed.add(contentlet.getIdentifier()); + } + } + return allowed; + } + + /** + * A stand-in for a contentlet in the batch query, which reads only its permission id and type. + * + * @param identifier the contentlet identifier + * @return the proxy + */ + private static PermissionableProxy proxy(final String identifier) { + final PermissionableProxy proxy = new PermissionableProxy(); + proxy.setIdentifier(identifier); + proxy.setInode(identifier); + proxy.setType(Contentlet.class.getCanonicalName()); + return proxy; } } diff --git a/dotCMS/src/main/java/com/dotcms/content/export/ContentletCsvWriter.java b/dotCMS/src/main/java/com/dotcms/content/export/ContentletCsvWriter.java index 876b1069d976..9ec3cd8bddda 100644 --- a/dotCMS/src/main/java/com/dotcms/content/export/ContentletCsvWriter.java +++ b/dotCMS/src/main/java/com/dotcms/content/export/ContentletCsvWriter.java @@ -1,33 +1,85 @@ package com.dotcms.content.export; +import static com.dotmarketing.portlets.contentlet.util.ContentletUtil.isNewFieldTypeAllowedOnImportExport; + +import com.dotcms.contenttype.business.FieldAPI; +import com.dotcms.contenttype.model.field.BinaryField; +import com.dotcms.contenttype.model.field.CategoryField; +import com.dotcms.contenttype.model.field.DateField; +import com.dotcms.contenttype.model.field.DateTimeField; +import com.dotcms.contenttype.model.field.Field; +import com.dotcms.contenttype.model.field.FileField; +import com.dotcms.contenttype.model.field.HostFolderField; +import com.dotcms.contenttype.model.field.ImageField; +import com.dotcms.contenttype.model.field.KeyValueField; +import com.dotcms.contenttype.model.field.RelationshipField; +import com.dotcms.contenttype.model.field.TagField; +import com.dotcms.contenttype.model.field.TimeField; +import com.dotcms.contenttype.model.type.BaseContentType; import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.contenttype.model.type.PageContentType; +import com.dotmarketing.beans.Host; +import com.dotmarketing.beans.Identifier; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.IdentifierAPI; import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.categories.business.CategoryAPI; +import com.dotmarketing.portlets.categories.model.Category; import com.dotmarketing.portlets.contentlet.business.ContentletAPI; import com.dotmarketing.portlets.contentlet.business.HostAPI; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.contentlet.model.ResourceLink; import com.dotmarketing.portlets.folders.business.FolderAPI; +import com.dotmarketing.portlets.folders.model.Folder; +import com.dotmarketing.portlets.languagesmanager.business.LanguageAPI; +import com.dotmarketing.portlets.languagesmanager.model.Language; +import com.dotmarketing.portlets.structure.model.ContentletRelationships; +import com.dotmarketing.portlets.structure.model.ContentletRelationships.ContentletRelationshipRecords; import com.dotmarketing.tag.business.TagAPI; +import com.dotmarketing.tag.model.Tag; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.UtilMethods; +import com.dotmarketing.util.WebKeys; +import com.fasterxml.jackson.databind.ObjectMapper; import com.liferay.portal.model.User; +import com.liferay.util.StringPool; import java.io.IOException; import java.io.Writer; +import java.sql.Timestamp; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; /** * Writes contentlets of one content type as CSV, in the format the Content Search export has always * produced and the content import reads back. Content Search and the Content Drive export both use * it, so the two write the same file. + *

+ * The format: a header {@code Identifier,languageCode,countryCode} followed by the variable of every + * exportable field; one row per contentlet version; rows end with {@code \r\n}; carriage returns + * inside a value are removed; a value holding a comma or a line feed is quoted, with its quotes + * doubled. */ public class ContentletCsvWriter { + /** How often, in rows, progress is logged. */ + private static final int LOGGING_POINT = 2000; + private static final boolean DONT_RESPECT_FRONTEND_ROLES = false; + private final ContentletAPI contentletAPI; private final CategoryAPI categoryAPI; private final TagAPI tagAPI; private final IdentifierAPI identifierAPI; private final HostAPI hostAPI; private final FolderAPI folderAPI; + private final LanguageAPI languageAPI; + private final FieldAPI fieldAPI; /** * Creates a writer that uses the standard dotCMS APIs. @@ -56,6 +108,8 @@ public ContentletCsvWriter() { this.identifierAPI = identifierAPI; this.hostAPI = hostAPI; this.folderAPI = folderAPI; + this.languageAPI = APILocator.getLanguageAPI(); + this.fieldAPI = APILocator.getContentTypeFieldAPI(); } /** @@ -71,7 +125,7 @@ public ContentletCsvWriter() { * @param user the {@link User} the rows are loaded as * @param request the request used to build the download links of binary fields * @param hostFolderMode how the host/folder column is written - * @param out where the CSV is written; it is not closed + * @param out where the CSV is written; it is flushed but not closed * @return the number of data rows written, not counting the header * @throws DotDataException if the export cannot be written * @throws IOException if {@code out} fails @@ -79,6 +133,280 @@ public ContentletCsvWriter() { public int write(final ContentType contentType, final List inodes, final User user, final HttpServletRequest request, final HostFolderMode hostFolderMode, final Writer out) throws DotDataException, IOException { - throw new UnsupportedOperationException("not implemented"); + + final List fields = fieldAPI.byContentTypeId(contentType.id()).stream() + .filter(field -> isNewFieldTypeAllowedOnImportExport(field)) + .collect(Collectors.toList()); + final RowContext context = new RowContext(contentType, user, request, hostFolderMode); + + out.write("Identifier,languageCode,countryCode"); + for (final Field field : fields) { + out.write("," + field.variable()); + } + out.write("\r\n"); + + int written = 0; + int processed = 0; + for (final String inode : inodes) { + processed++; + if (processed % LOGGING_POINT == 0) { + Logger.info(this, String.format("Exporting %d out of %d contentlet(s)", processed, + inodes.size())); + } + final Optional contentlet = load(inode, user); + if (contentlet.isEmpty()) { + continue; + } + writeRow(contentlet.get(), fields, context, out); + written++; + } + out.flush(); + return written; + } + + /** + * Loads one contentlet version as the user. A version that no longer exists, or that the user + * cannot read, comes back empty. + * + * @param inode the inode of the version + * @param user the {@link User} it is loaded as + * @return the contentlet, or empty when it must be skipped + */ + private Optional load(final String inode, final User user) { + try { + return Optional.ofNullable(contentletAPI.find(inode, user, DONT_RESPECT_FRONTEND_ROLES)); + } catch (final DotSecurityException e) { + Logger.debug(this, () -> String.format( + "Skipping contentlet with Inode '%s': the user cannot read it", inode)); + return Optional.empty(); + } catch (final DotDataException e) { + Logger.warn(this, "Unable to find contentlet with Inode: " + inode); + return Optional.empty(); + } + } + + /** + * Writes one data row: identifier, language and country codes, then one cell per field. + * + * @param content the contentlet version + * @param fields the exportable fields, in column order + * @param context what every row of this write shares + * @param out where the row is written + * @throws DotDataException if the categories of the contentlet cannot be read + * @throws IOException if {@code out} fails + */ + private void writeRow(final Contentlet content, final List fields, + final RowContext context, final Writer out) throws DotDataException, IOException { + final List categories; + try { + categories = categoryAPI.getParents(content, context.user, DONT_RESPECT_FRONTEND_ROLES); + } catch (final DotSecurityException e) { + throw new DotDataException(e.getMessage(), e); + } + final Language language = languageAPI.getLanguage(content.getLanguageId()); + + out.write(content.getIdentifier()); + out.write("," + language.getLanguageCode()); + out.write("," + language.getCountryCode()); + for (final Field field : fields) { + String cell; + try { + cell = quote(formatValue(content, field, categories, context)); + } catch (final Exception e) { + cell = ","; + Logger.error(this, String.format("An error occurred when exporting field '%s' [%s] of" + + " contentlet '%s' to CSV: %s", field.name(), field.inode(), + content.getInode(), e.getMessage()), e); + } + out.write(cell); + } + out.write("\r\n"); + } + + /** + * Formats one field value the way the Content Search export does. + * + * @param content the contentlet version + * @param field the field + * @param categories the categories the contentlet belongs to + * @param context what every row of this write shares + * @return the cell text, before quoting + * @throws Exception whatever reading or formatting the value throws; the caller writes an + * empty cell + */ + private String formatValue(final Contentlet content, final Field field, + final List categories, final RowContext context) throws Exception { + final User user = context.user; + Object value = StringPool.BLANK; + if (contentletAPI.getFieldValue(content, field) != null) { + value = contentletAPI.getFieldValue(content, field); + } + String text = StringPool.BLANK; + if (field instanceof CategoryField) { + final Category category = categoryAPI.find(field.values(), user, DONT_RESPECT_FRONTEND_ROLES); + final List allChildren = + categoryAPI.getAllChildren(category, user, DONT_RESPECT_FRONTEND_ROLES); + if (!categories.isEmpty() + && categoryAPI.canUseCategory(category, user, DONT_RESPECT_FRONTEND_ROLES)) { + for (final Category cat : categories) { + if (allChildren.contains(cat)) { + text = text + "," + (UtilMethods.isSet(cat.getKey()) ? cat.getKey() + : cat.getCategoryName()); + } + } + } + if (UtilMethods.isSet(text)) { + text = text.substring(1); + } + } else if (field instanceof TagField) { + final List tags = + tagAPI.getTagsByInodeAndFieldVarName(content.getInode(), field.variable()); + for (final Tag tag : tags) { + text = text.equals(StringPool.BLANK) ? tag.getTagName() : text + "," + tag.getTagName(); + } + } else if (field instanceof RelationshipField) { + text = loadRelationships(((ContentletRelationships) value).getRelationshipsRecords()); + } else if (field instanceof KeyValueField) { + text = new ObjectMapper().writeValueAsString(value); + } else if (BaseContentType.HTMLPAGE.equals(context.contentType.baseType()) + && PageContentType.PAGE_URL_FIELD_VAR.equalsIgnoreCase(field.variable())) { + final Identifier id = identifierAPI.find(content.getIdentifier()); + if (null != id && UtilMethods.isSet(id.getId())) { + text = id.getPath(); + } + } else if (field instanceof ImageField || field instanceof FileField) { + // Both field types store the identifier of a file asset; export its path + final String fileIdentifier = value.toString(); + if (UtilMethods.isSet(fileIdentifier)) { + final Identifier id = identifierAPI.find(fileIdentifier); + if (null != id && UtilMethods.isSet(id.getId())) { + text = id.getPath(); + } + } + } else if (field instanceof BinaryField) { + text = new ResourceLink.ResourceLinkBuilder() + .getFileLink(context.request, user, content, field.variable()); + } else if (field instanceof HostFolderField + && context.hostFolderMode == HostFolderMode.LOCATION) { + text = context.location(content).orElse(value.toString()); + } else if (value instanceof Date || value instanceof Timestamp) { + if (field instanceof DateField) { + text = new SimpleDateFormat(WebKeys.DateFormats.EXP_IMP_DATE).format(value); + } else if (field instanceof DateTimeField) { + text = new SimpleDateFormat(WebKeys.DateFormats.EXP_IMP_DATETIME).format(value); + } else if (field instanceof TimeField) { + text = new SimpleDateFormat(WebKeys.DateFormats.EXP_IMP_TIME).format(value); + } + } else { + text = value.toString(); + if (text.endsWith(",")) { + text = text.substring(0, text.length() - 1); + } + } + return text; + } + + /** + * Turns a value into a cell, with its leading comma: carriage returns are removed, and a value + * holding a comma or a line feed is quoted with its quotes doubled. + * + * @param text the formatted value + * @return the cell as written, starting with {@code ,} + */ + private static String quote(final String text) { + final String clean = text.replaceAll("\r", ""); + if (clean.contains(",") || clean.contains("\n")) { + return ",\"" + clean.replaceAll("\"", "\"\"") + "\""; + } + return "," + clean; + } + + /** + * Builds the list of related identifiers, comma separated. + * + * @param relationshipRecords the related records of one relationship field + * @return the identifiers of every related contentlet + */ + private static String loadRelationships(final List relationshipRecords) { + final StringBuilder result = new StringBuilder(); + relationshipRecords.forEach(record -> result.append(String.join(StringPool.COMMA, + record.getRecords().stream().map(Contentlet::getIdentifier) + .collect(Collectors.toList())))); + return result.toString(); + } + + /** + * What every row of one {@link #write} call shares, including the hosts and folders already + * resolved for the host/folder column. + */ + private final class RowContext { + + private final ContentType contentType; + private final User user; + private final HttpServletRequest request; + private final HostFolderMode hostFolderMode; + private final Map> hosts = new HashMap<>(); + private final Map> folders = new HashMap<>(); + + private RowContext(final ContentType contentType, final User user, + final HttpServletRequest request, final HostFolderMode hostFolderMode) { + this.contentType = contentType; + this.user = user; + this.request = request; + this.hostFolderMode = hostFolderMode; + } + + /** + * The readable location of a contentlet: {@code //} in a folder, + * {@code } at a site root, {@code SYSTEM_HOST} in System Host. Hosts and folders + * are read as the system user: the column only names where the row lives. + * + * @param content the contentlet version + * @return the location, or empty when its host or folder cannot be resolved + */ + private Optional location(final Contentlet content) { + final String hostId = content.getHost(); + if (Host.SYSTEM_HOST.equals(hostId)) { + return Optional.of(Host.SYSTEM_HOST); + } + final Optional host = hosts.computeIfAbsent(hostId, this::findHost); + if (host.isEmpty()) { + return Optional.empty(); + } + final String folderInode = content.getFolder(); + if (!UtilMethods.isSet(folderInode) || FolderAPI.SYSTEM_FOLDER.equals(folderInode)) { + return Optional.of(host.get().getHostname()); + } + final Optional folder = folders.computeIfAbsent(folderInode, this::findFolder); + if (folder.isEmpty()) { + return Optional.empty(); + } + if (folder.get().isSystemFolder()) { + return Optional.of(host.get().getHostname()); + } + return Optional.of("//" + host.get().getHostname() + folder.get().getPath()); + } + + private Optional findHost(final String hostId) { + try { + return Optional.ofNullable( + hostAPI.find(hostId, APILocator.systemUser(), DONT_RESPECT_FRONTEND_ROLES)); + } catch (final DotDataException | DotSecurityException e) { + Logger.warn(ContentletCsvWriter.class, + String.format("Unable to find host '%s': %s", hostId, e.getMessage())); + return Optional.empty(); + } + } + + private Optional findFolder(final String folderInode) { + try { + return Optional.ofNullable(folderAPI.find(folderInode, APILocator.systemUser(), + DONT_RESPECT_FRONTEND_ROLES)); + } catch (final DotDataException | DotSecurityException e) { + Logger.warn(ContentletCsvWriter.class, + String.format("Unable to find folder '%s': %s", folderInode, e.getMessage())); + return Optional.empty(); + } + } } } diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveHelper.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveHelper.java index 270c3f4feea4..de614565d20c 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveHelper.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveHelper.java @@ -90,6 +90,56 @@ public class ContentDriveHelper { public PaginatedContents driveSearch(final DriveRequestForm requestForm, final User user) throws DotDataException, DotSecurityException { + final Builder builder = toBrowserQueryBuilder(requestForm, user); + + // Build once and log the query itself: flags such as showLinks and showFolders can be + // overridden by the workflow and userSearchable branches of toBrowserQueryBuilder, so + // logging the request would misreport what actually ran. BrowserQuery.toString() carries the + // effective flags, all three cursors and the filters. + // + // ⚠ EVERY builder mutation MUST go ABOVE this line. build() snapshots the builder, so a + // `builder.withX(...)` placed after it is silently discarded — the request succeeds and the + // filter simply does nothing. That is exactly how the status filter shipped broken once: + // the block was anchored on the Logger.debug below, and a refactor that hoisted build() + // above the log moved it to the wrong side without any compile or test failure. + final BrowserQuery browserQuery = builder.build(); + + Logger.debug(this, () -> String.format("Content drive search - User: %s, Path: %s, %s", + user.getUserId(), requestForm.assetPath(), browserQuery)); + + checkSearchable(browserQuery); + try { + return browserAPI.getPaginatedContents(browserQuery); + } catch (final DotDataException | DotRuntimeException e) { + if (ExceptionUtil.causedBy(e, ESQueryTooComplexException.class)) { + throw new BadRequestException(e, + "The search text or filter values are too complex to search for; simplify " + + "or shorten them and try again."); + } + throw e; + } + } + + /** + * Turns a Drive listing request into the {@link BrowserQuery} builder that serves it: the site + * or folder, the browse scope, languages, content and base types, text and field filters, + * workflow and status. The listing and the Content Drive export both start from it, so an + * export matches exactly what the listing shows. + *

+ * The builder is returned unbuilt so a caller can adjust it. Every adjustment must be made + * before {@code build()}, which snapshots the builder: a mutation after it is silently lost. + * Call {@link #checkSearchable(BrowserQuery)} on the built query before running it. + * + * @param requestForm the Drive listing request + * @param user the {@link User} the listing runs as + * @return the builder, with every part of the request applied + * @throws BadRequestException when the request is invalid + * @throws DotDataException when the site, folder or content types cannot be resolved + * @throws DotSecurityException when the user cannot read the site or folder + */ + public Builder toBrowserQueryBuilder(final DriveRequestForm requestForm, final User user) + throws DotDataException, DotSecurityException { + final List langIds = requestForm.language().stream() .map(LanguageUtil::getLanguageId) .collect(Collectors.toList()); @@ -257,40 +307,22 @@ public PaginatedContents driveSearch(final DriveRequestForm requestForm, final U if (!contentStatuses.isEmpty()) { builder.withContentStatuses(contentStatuses); } + return builder; + } - // Build once and log the query itself: flags such as showLinks and showFolders can be - // overridden by the workflow and userSearchable branches above, so logging the locals would - // misreport what actually ran. (The status branch is deliberately not in that list — it - // sets no flags, see the comment above it.) BrowserQuery.toString() carries the effective - // flags, all three cursors and the filters. - // - // ⚠ EVERY builder mutation MUST go ABOVE this line. build() snapshots the builder, so a - // `builder.withX(...)` placed after it is silently discarded — the request succeeds and the - // filter simply does nothing. That is exactly how the status filter shipped broken once: - // the block was anchored on the Logger.debug below, and a refactor that hoisted build() - // above the log moved it to the wrong side without any compile or test failure. - final BrowserQuery browserQuery = builder.build(); - - Logger.debug(this, () -> String.format("Content drive search - User: %s, Path: %s, %s", - user.getUserId(), assetPath, browserQuery)); - - // Search input the index cannot serve is bad input, not a server failure (issue #37488): - // a term or values too long to leave room for the per-sub-query inode restriction, and a - // query the index finds too complex to build from them. + /** + * Rejects a built query the index cannot serve. Search input the index cannot serve is bad + * input, not a server failure (issue #37488): a term or values too long to leave room for the + * per-sub-query inode restriction. + * + * @param browserQuery the query built from {@link #toBrowserQueryBuilder(DriveRequestForm, User)} + * @throws BadRequestException when the search text or filter values are too long + */ + public void checkSearchable(final BrowserQuery browserQuery) { if (!browserAPI.esQueryLeavesRoomForInodes(browserQuery)) { throw new BadRequestException( "The search text or filter values are too long; shorten them and try again."); } - try { - return browserAPI.getPaginatedContents(browserQuery); - } catch (final DotDataException | DotRuntimeException e) { - if (ExceptionUtil.causedBy(e, ESQueryTooComplexException.class)) { - throw new BadRequestException(e, - "The search text or filter values are too complex to search for; simplify " - + "or shorten them and try again."); - } - throw e; - } } /** diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractDriveExportRequestForm.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractDriveExportRequestForm.java index ef47aacc9a49..73498302584a 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractDriveExportRequestForm.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractDriveExportRequestForm.java @@ -1,6 +1,8 @@ package com.dotcms.rest.api.v1.drive.export; import com.dotcms.rest.api.v1.drive.DriveRequestForm; +import com.dotcms.rest.exception.BadRequestException; +import com.dotmarketing.util.UtilMethods; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; @@ -74,6 +76,25 @@ enum Mode { * has no identifier or no valid language */ default Mode validate() { - throw new UnsupportedOperationException("not implemented"); + final ExportSelectionForm selection = selection(); + final int selected = selection == null ? 0 + : selection.folders().size() + selection.contentlets().size(); + if (selected == 0) { + if (query() == null) { + throw new BadRequestException( + "Select items or filter the listing to one content type to export."); + } + return Mode.FILTER; + } + if (selected > MAX_SELECTION_ITEMS) { + throw new BadRequestException( + "You can export at most " + MAX_SELECTION_ITEMS + " items at once."); + } + for (final ExportContentletRefForm contentlet : selection.contentlets()) { + if (!UtilMethods.isSet(contentlet.identifier()) || contentlet.languageId() <= 0) { + throw new BadRequestException("Invalid contentlet in the selection."); + } + } + return Mode.SELECTION; } } diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilder.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilder.java index aee42126131b..09209b7b9592 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilder.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilder.java @@ -1,14 +1,29 @@ package com.dotcms.rest.api.v1.drive.export; import com.dotcms.content.export.ContentletCsvWriter; +import com.dotcms.content.export.HostFolderMode; import com.dotcms.contenttype.model.type.ContentType; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.util.ConfigUtils; +import com.dotmarketing.util.Logger; import com.liferay.portal.model.User; +import java.io.BufferedOutputStream; import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.Date; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.StreamingOutput; @@ -22,6 +37,12 @@ public class ExportFileBuilder { /** The directory, under the asset temp path, that export files are written to. */ public static final String DIRECTORY_NAME = "drive-export"; + /** How old a file in the export directory must be before a new export sweeps it away. */ + static final Duration LEFTOVER_AGE = Duration.ofHours(1); + + private static final String CSV_MEDIA_TYPE = "text/csv; charset=UTF-8"; + private static final String ZIP_MEDIA_TYPE = "application/zip"; + private final ContentletCsvWriter writer; private final Path directory; @@ -57,7 +78,19 @@ public ExportFileBuilder() { */ public ExportFile buildCsv(final ContentType contentType, final List inodes, final User user, final HttpServletRequest request) throws DotDataException, IOException { - throw new UnsupportedOperationException("not implemented"); + final Path file = newTempFile(".csv"); + try { + final int rows; + try (Writer out = new OutputStreamWriter( + new BufferedOutputStream(Files.newOutputStream(file)), StandardCharsets.UTF_8)) { + rows = writer.write(contentType, inodes, user, request, HostFolderMode.LOCATION, out); + } + return finish(file, ExportFileNames.csvName(contentType.name(), contentType.variable(), + new Date()), CSV_MEDIA_TYPE, rows, 1); + } catch (final DotDataException | IOException | RuntimeException e) { + deleteQuietly(file); + throw e; + } } /** @@ -75,7 +108,35 @@ public ExportFile buildCsv(final ContentType contentType, final List ino public ExportFile buildZip(final String hostname, final Map> inodesByType, final User user, final HttpServletRequest request) throws DotDataException, IOException { - throw new UnsupportedOperationException("not implemented"); + final Date date = new Date(); + final Map typesById = new LinkedHashMap<>(); + inodesByType.keySet().forEach(type -> typesById.put(type.id(), type)); + final Map entryNames = ExportFileNames.csvNames(typesById.values().stream() + .map(type -> new ExportFileNames.TypeName(type.id(), type.name(), type.variable())) + .collect(Collectors.toList()), date); + + final Path file = newTempFile(".zip"); + try { + int rows = 0; + try (ZipOutputStream zip = new ZipOutputStream( + new BufferedOutputStream(Files.newOutputStream(file)), StandardCharsets.UTF_8)) { + // One writer per entry, never closed: closing it would close the zip + for (final Map.Entry entry : entryNames.entrySet()) { + final ContentType type = typesById.get(entry.getKey()); + zip.putNextEntry(new ZipEntry(entry.getValue())); + final Writer out = new OutputStreamWriter(zip, StandardCharsets.UTF_8); + rows += writer.write(type, inodesByType.get(type), user, request, + HostFolderMode.LOCATION, out); + out.flush(); + zip.closeEntry(); + } + } + return finish(file, ExportFileNames.zipName(hostname, date), ZIP_MEDIA_TYPE, rows, + entryNames.size()); + } catch (final DotDataException | IOException | RuntimeException e) { + deleteQuietly(file); + throw e; + } } /** @@ -86,6 +147,91 @@ public ExportFile buildZip(final String hostname, * @return the response entity */ public static StreamingOutput toStreamingOutput(final ExportFile file) { - throw new UnsupportedOperationException("not implemented"); + return output -> { + try { + Files.copy(file.path(), output); + output.flush(); + } finally { + deleteQuietly(file.path()); + } + }; + } + + /** + * Creates the export directory if needed, sweeps leftovers older than one hour, and creates a + * new temp file in it. + * + * @param suffix the file extension + * @return the new, empty temp file + * @throws IOException if the directory or the file cannot be created + */ + private Path newTempFile(final String suffix) throws IOException { + Files.createDirectories(directory); + sweepLeftovers(); + return Files.createTempFile(directory, "export-", suffix); + } + + /** + * Deletes files in the export directory last modified more than {@link #LEFTOVER_AGE} ago: the + * remains of an export whose sending never ended, for instance after a crash. A younger file may + * be another export in progress and is kept. + */ + private void sweepLeftovers() { + final Instant cutoff = Instant.now().minus(LEFTOVER_AGE); + try (Stream files = Files.list(directory)) { + files.filter(Files::isRegularFile).filter(path -> isOlderThan(path, cutoff)) + .forEach(ExportFileBuilder::deleteQuietly); + } catch (final IOException e) { + Logger.warn(ExportFileBuilder.class, String.format( + "Unable to sweep old export files in '%s': %s", directory, e.getMessage())); + } + } + + /** + * Whether a file was last modified before a given instant. + * + * @param path the file + * @param cutoff the instant + * @return {@code true} when it is older; {@code false} when it is younger or unreadable + */ + private static boolean isOlderThan(final Path path, final Instant cutoff) { + try { + return Files.getLastModifiedTime(path).toInstant().isBefore(cutoff); + } catch (final IOException e) { + return false; + } + } + + /** + * Wraps a written temp file as the result. A file with zero rows is deleted right away, since + * there is nothing to send. + * + * @param file the temp file + * @param fileName the download name + * @param mediaType the response media type + * @param rows the data rows written + * @param files the CSVs written + * @return the export file + */ + private static ExportFile finish(final Path file, final String fileName, final String mediaType, + final int rows, final int files) { + if (rows == 0) { + deleteQuietly(file); + } + return new ExportFile(file, fileName, mediaType, rows, files); + } + + /** + * Deletes a file, logging instead of throwing when it cannot be deleted. + * + * @param path the file to delete + */ + private static void deleteQuietly(final Path path) { + try { + Files.deleteIfExists(path); + } catch (final IOException e) { + Logger.warn(ExportFileBuilder.class, String.format( + "Unable to delete export file '%s': %s", path, e.getMessage())); + } } } diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileNames.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileNames.java index 6217fd0e6c85..4f1392803417 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileNames.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileNames.java @@ -1,8 +1,17 @@ package com.dotcms.rest.api.v1.drive.export; +import com.dotmarketing.util.UtilMethods; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Comparator; import java.util.Date; +import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; /** * Names the files of a Content Drive export and builds their {@code Content-Disposition} header. @@ -16,6 +25,15 @@ public final class ExportFileNames { /** The date pattern Content Search uses in its file name. */ public static final String DATE_PATTERN = "M_d_yyyy"; + /** Characters a file name, a zip entry or a header must not hold: path and shell separators and every control character. */ + private static final Pattern UNSAFE = Pattern.compile("[/\\\\:*?\"<>|\\p{Cntrl}]"); + /** Dots and spaces at either end, which some file systems drop or reject. */ + private static final Pattern EDGE_DOTS_AND_SPACES = Pattern.compile("^[.\\s]+|[.\\s]+$"); + /** The characters RFC 5987 lets through unencoded in {@code filename*}, besides letters and digits. */ + private static final String ATTR_CHARS = "!#$&+-.^_`|~"; + + private static final String CSV_EXTENSION = ".csv"; + private ExportFileNames() { } @@ -29,7 +47,11 @@ private ExportFileNames() { */ public static String csvName(final String contentTypeName, final String contentTypeVariable, final Date date) { - throw new UnsupportedOperationException("not implemented"); + String base = safe(contentTypeName); + if (base.isEmpty()) { + base = safe(contentTypeVariable); + } + return base + "_contents_" + formatDate(date) + CSV_EXTENSION; } /** @@ -40,19 +62,35 @@ public static String csvName(final String contentTypeName, final String contentT * @return {@code _export_.zip} */ public static String zipName(final String hostname, final Date date) { - throw new UnsupportedOperationException("not implemented"); + return safe(hostname) + "_export_" + formatDate(date) + ".zip"; } /** * Names the CSVs of one zip. Content types are named in content type name order, and a name - * already taken gets {@code -2}, {@code -3}, and so on before {@code .csv}. + * already taken gets {@code -2}, {@code -3}, and so on before {@code .csv}. Names are compared + * ignoring case, since the zip may be extracted on a file system that does. * * @param types the content types in the zip * @param date the export date * @return the file name of each content type, keyed by its id, in the order the entries are written */ public static Map csvNames(final List types, final Date date) { - throw new UnsupportedOperationException("not implemented"); + final List sorted = new ArrayList<>(types); + sorted.sort(Comparator.comparing((TypeName type) -> String.valueOf(type.name()), + String.CASE_INSENSITIVE_ORDER)); + + final Map names = new LinkedHashMap<>(); + final Set taken = new HashSet<>(); + for (final TypeName type : sorted) { + final String plain = csvName(type.name(), type.variable(), date); + String name = plain; + final String stem = plain.substring(0, plain.length() - CSV_EXTENSION.length()); + for (int suffix = 2; !taken.add(name.toLowerCase(Locale.ROOT)); suffix++) { + name = stem + "-" + suffix + CSV_EXTENSION; + } + names.put(type.id(), name); + } + return names; } /** @@ -63,7 +101,58 @@ public static Map csvNames(final List types, final Dat * @return {@code attachment; filename="..."; filename*=UTF-8''...} */ public static String contentDisposition(final String fileName) { - throw new UnsupportedOperationException("not implemented"); + final StringBuilder ascii = new StringBuilder(fileName.length()); + fileName.codePoints().forEach(codePoint -> ascii.append( + codePoint < 0x20 || codePoint > 0x7E || codePoint == '"' || codePoint == '\\' + ? "_" : Character.toString(codePoint))); + return "attachment; filename=\"" + ascii + "\"; filename*=UTF-8''" + encode(fileName); + } + + /** + * Percent-encodes a value for an RFC 5987 extended parameter: every UTF-8 byte that is not a + * letter, a digit or an attribute character becomes {@code %XX}; a space is {@code %20}, never + * {@code +}. + * + * @param value the value + * @return the encoded value + */ + private static String encode(final String value) { + final StringBuilder encoded = new StringBuilder(); + for (final byte b : value.getBytes(StandardCharsets.UTF_8)) { + final char c = (char) (b & 0xFF); + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') + || ATTR_CHARS.indexOf(c) >= 0) { + encoded.append(c); + } else { + encoded.append('%').append(String.format("%02X", b & 0xFF)); + } + } + return encoded.toString(); + } + + /** + * Makes a name safe: every unsafe character becomes {@code _}, then dots and spaces are trimmed + * from both ends. Letters of any script are kept. + * + * @param name the name, possibly {@code null} + * @return the safe name, possibly empty + */ + private static String safe(final String name) { + if (name == null) { + return ""; + } + final String replaced = UNSAFE.matcher(name).replaceAll("_"); + return EDGE_DOTS_AND_SPACES.matcher(replaced).replaceAll(""); + } + + /** + * Formats the export date as Content Search does. + * + * @param date the export date + * @return the date as {@code M_d_yyyy} + */ + private static String formatDate(final Date date) { + return UtilMethods.dateToHTMLDate(date, DATE_PATTERN); } /** diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/action/EditContentletAction.java b/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/action/EditContentletAction.java index 57f69ef8c4c4..ad07f493a95c 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/action/EditContentletAction.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/action/EditContentletAction.java @@ -6,7 +6,9 @@ import com.dotcms.api.system.event.message.SystemMessageEventUtil; import com.dotcms.api.system.event.message.builder.SystemMessage; import com.dotcms.api.system.event.message.builder.SystemMessageBuilder; -import com.dotcms.api.web.HttpServletRequestThreadLocal; +import com.dotcms.api.web.HttpServletRequestThreadLocal; +import com.dotcms.content.export.ContentletCsvWriter; +import com.dotcms.content.export.HostFolderMode; import com.dotcms.business.CloseDBIfOpened; import com.dotcms.contenttype.business.ContentTypeAPI; import com.dotcms.contenttype.model.field.*; @@ -1910,6 +1912,8 @@ private void _loadForm(ActionRequest req, ActionResponse res, PortletConfig conf * - The Content Type Inode of the contentlets. * @throws DotSecurityException * An error occurred when retrieving contentlet data. + * @throws DotDataException + * The Content Type could not be read. */ public void downloadToExcel(final HttpServletResponse response, final User user, final List> contentletsToExport, final String contentTypeInode) throws DotSecurityException, DotDataException { PrintWriter writer = null; @@ -1918,20 +1922,11 @@ public void downloadToExcel(final HttpServletResponse response, final User user, final List contentletInodes = new ArrayList<>(); for (int i = 2; i < contentletsToExport.size(); ++i) { final Object contentletData = contentletsToExport.get(i); - if (contentletData != null && contentletData instanceof HashMap) { + if (contentletData instanceof HashMap) { final Map contentletMap = contentletsToExport.get(i); contentletInodes.add(contentletMap.get("inode")); } } - final List contentletList = new ArrayList<>(); - for (final String inode : contentletInodes) { - try{ - final Contentlet contentlet = this.conAPI.find(inode, user, DONT_RESPECT_FRONTEND_ROLES); - contentletList.add(contentlet); - } catch (final DotDataException ex){ - Logger.warn(this, "Unable to find contentlet with Inode: " + inode); - } - } int totalSize = 0; final ContentType contentType = APILocator.getContentTypeAPI(user).find(contentTypeInode); final String csvFileName = contentType.name() + "_contents_" + UtilMethods.dateToHTMLDate(new java @@ -1941,136 +1936,10 @@ public void downloadToExcel(final HttpServletResponse response, final User user, + StandardCharsets.UTF_8.name()); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + csvFileName +"\""); writer = response.getWriter(); - writer.print("Identifier"); - writer.print(",languageCode"); - writer.print(",countryCode"); - final List contentTypeFields = - APILocator.getContentTypeFieldAPI().byContentTypeId((contentTypeInode)); - for (final com.dotcms.contenttype.model.field.Field field : contentTypeFields) { - // Exclude fields that are not exportable - if (isNewFieldTypeAllowedOnImportExport(field)) { - writer.print("," + field.variable()); - } - } - - writer.print("\r\n"); - int counter = 0; - int loggingPoint = 2000; - totalSize = contentletList.size(); - for (final Contentlet content : contentletList) { - counter += 1; - if (counter % loggingPoint == 0) { - Logger.info(this, String.format("Exporting %d out of %d contentlet(s)", counter, totalSize)); - } - final List catList = this.catAPI.getParents(content, user, DONT_RESPECT_FRONTEND_ROLES); - writer.print(content.getIdentifier()); - final Language lang = APILocator.getLanguageAPI().getLanguage(content.getLanguageId()); - writer.print("," +lang.getLanguageCode()); - writer.print(","+lang.getCountryCode()); - - for (final com.dotcms.contenttype.model.field.Field field: contentTypeFields) { - try { - // We don't need to export fields of these types - if (!isNewFieldTypeAllowedOnImportExport(field)) { - continue; - } - - Object value = StringPool.BLANK; - if (this.conAPI.getFieldValue(content,field) != null) { - value = this.conAPI.getFieldValue(content,field); - } - String text = StringPool.BLANK; - if (field instanceof CategoryField) { - final Category category = this.catAPI.find(field.values(), user, DONT_RESPECT_FRONTEND_ROLES); - final List children = catList; - final List allChildren= this.catAPI.getAllChildren(category, user, DONT_RESPECT_FRONTEND_ROLES); - if (children.size() >= 1 && this.catAPI.canUseCategory(category, user, DONT_RESPECT_FRONTEND_ROLES)) { - for (final Category cat : children){ - if(allChildren.contains(cat)){ - if(UtilMethods.isSet(cat.getKey())){ - text = text+","+cat.getKey(); - }else{ - text = text+","+cat.getCategoryName(); - } - } - } - } - if(UtilMethods.isSet(text)){ - text=text.substring(1); - } - } else if (field instanceof TagField) { - //Get Content Tags per field's Velocity Var Name - final List tags = this.tagAPI.getTagsByInodeAndFieldVarName(content.getInode(), field.variable()); - if (!tags.isEmpty()) { - for (final Tag tag : tags){ - if(text.equals(StringPool.BLANK)) { - text = tag.getTagName(); - } else { - text = text + "," + tag.getTagName(); - } - } - } - } else if (field instanceof RelationshipField) { - text = loadRelationships(((ContentletRelationships)value).getRelationshipsRecords()); - } else if (field instanceof KeyValueField) { - text = new ObjectMapper().writeValueAsString(value); - } else if (BaseContentType.HTMLPAGE.equals(contentType.baseType()) && PageContentType - .PAGE_URL_FIELD_VAR.equalsIgnoreCase(field.variable())) { - final Identifier id = APILocator.getIdentifierAPI().find(content.getIdentifier()); - if (null != id && UtilMethods.isSet(id.getId())) { - text = id.getPath(); - } - } else if (field instanceof ImageField || field instanceof FileField) { - // Both field types store the identifier of a file asset; export its path - final String fileIdentifier = value.toString(); - if (UtilMethods.isSet(fileIdentifier)) { - final Identifier id = APILocator.getIdentifierAPI().find(fileIdentifier); - if (null != id && UtilMethods.isSet(id.getId())) { - text = id.getPath(); - } - } - - } else if (field instanceof BinaryField){ - final HttpServletRequest request = HttpServletRequestThreadLocal.INSTANCE.getRequest(); - final String fileLink = new ResourceLink.ResourceLinkBuilder().getFileLink(request, user, content, field.variable()); - text = fileLink; - } else{ - if (value instanceof Date || value instanceof Timestamp) { - if (field instanceof DateField) { - final SimpleDateFormat formatter = new SimpleDateFormat (WebKeys.DateFormats.EXP_IMP_DATE); - text = formatter.format(value); - } else if (field instanceof DateTimeField) { - final SimpleDateFormat formatter = new SimpleDateFormat (WebKeys.DateFormats.EXP_IMP_DATETIME); - text = formatter.format(value); - } else if (field instanceof TimeField) { - final SimpleDateFormat formatter = new SimpleDateFormat (WebKeys.DateFormats.EXP_IMP_TIME); - text = formatter.format(value); - } - } else { - text = value.toString(); - if(text.endsWith(",")){ - text = text.substring (0, text.length()-1); - } - } - } - //Windows carriage return conversion - text = text.replaceAll("\r",""); - if(text.contains(",") || text.contains("\n")) { - //Double quotes replacing - text = text.replaceAll("\"","\"\""); - writer.print(",\""+text+"\""); - } else { - writer.print(","+text); - } - } catch (final Exception e) { - writer.print(","); - Logger.error(this, String.format("An error occurred when exporting field '%s' [%s] to CSV" + - " file '%s': %s", field.name(), field.inode(), csvFileName, e.getMessage()), e); - } - } - writer.print("\r\n"); - } - writer.flush(); + // The Content Drive export writes the same file through the same writer + totalSize = new ContentletCsvWriter().write(contentType, contentletInodes, user, + HttpServletRequestThreadLocal.INSTANCE.getRequest(), HostFolderMode.IDENTIFIER, + writer); writer.close(); HibernateUtil.closeSession(); } catch (final Exception p) { @@ -2096,22 +1965,6 @@ public void downloadToExcel(final HttpServletResponse response, final User user, } } - /** - * Builds the list of related records separated by comma - */ - private String loadRelationships(List relationshipRecords) - throws DotDataException { - - final StringBuilder result = new StringBuilder(); - - relationshipRecords.forEach(record -> result.append(String - .join(StringPool.COMMA, - record.getRecords().stream().map(Contentlet::getIdentifier).collect( - Collectors.toList())))); - - return result.toString(); - } - /** * Returns the relationships associated to the current contentlet * diff --git a/dotcms-integration/src/test/java/com/dotcms/content/export/ContentletCsvWriterTest.java b/dotcms-integration/src/test/java/com/dotcms/content/export/ContentletCsvWriterTest.java index 1352d7a5a725..1b6eb51e1178 100644 --- a/dotcms-integration/src/test/java/com/dotcms/content/export/ContentletCsvWriterTest.java +++ b/dotcms-integration/src/test/java/com/dotcms/content/export/ContentletCsvWriterTest.java @@ -447,8 +447,11 @@ public void test_write_locationMode_writesReadableLocations() throws Exception { */ @Test public void test_write_skipsRowsTheUserCannotRead() throws Exception { + // A back-end user, as every Drive user is: dotCMS denies a front-end user READ on any + // contentlet that is not live, and these fixtures are working versions. final Role role = new RoleDataGen().nextPersisted(); - final User limitedUser = new UserDataGen().roles(role).nextPersisted(); + final User limitedUser = new UserDataGen() + .roles(role, APILocator.getRoleAPI().loadBackEndUserRole()).nextPersisted(); final PermissionAPI permissionAPI = APILocator.getPermissionAPI(); permissionAPI.save(new Permission(inFolder.getPermissionId(), role.getId(), PermissionAPI.PERMISSION_READ), inFolder, systemUser, false); From c261675ea8007e9519f6dfe1aad5f4c7ff2e2acd Mon Sep 17 00:00:00 2001 From: ddariod Date: Thu, 26 Nov 2026 15:27:37 -0500 Subject: [PATCH 11/28] test(content-drive): add failing tests and stubs for the filter-mode export Tests written and approved before the implementation (TDD Red) for exporting everything the Content Drive listing shows for one content type (#37900): BrowserAPI#getContentForExport against the listing paged to the end, the POST /api/v1/drive/export endpoint in filter mode, the Postman "Export" folder, the export service and Export button specs, and a Playwright test. The endpoint answers 501 and the new API, helper, service and button are stubs until the implementation lands. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- .../content-drive-export.spec.ts | 71 +++ core-web/libs/data-access/src/index.ts | 1 + .../dot-content-drive-export.service.spec.ts | 158 ++++++ .../dot-content-drive-export.service.ts | 56 ++ ...content-drive-export-button.component.html | 1 + ...tent-drive-export-button.component.spec.ts | 318 +++++++++++ ...t-content-drive-export-button.component.ts | 15 + ...ot-content-drive-toolbar.component.spec.ts | 36 +- .../java/com/dotcms/browser/BrowserAPI.java | 20 + .../com/dotcms/browser/BrowserAPIImpl.java | 7 + .../api/v1/drive/ContentDriveResource.java | 23 + .../export/ContentDriveExportHelper.java | 36 ++ .../src/test/java/com/dotcms/MainSuite3a.java | 2 + .../dotcms/browser/BrowserAPIExportTest.java | 496 ++++++++++++++++++ .../ContentDriveExportFilterModeTest.java | 484 +++++++++++++++++ ...ntentDriveResource.postman_collection.json | 318 +++++++++++ 16 files changed, 2038 insertions(+), 4 deletions(-) create mode 100644 core-web/apps/dotcms-ui-e2e/src/tests/content-drive/content-drive-export.spec.ts create mode 100644 core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.spec.ts create mode 100644 core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts create mode 100644 core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.html create mode 100644 core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts create mode 100644 core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts create mode 100644 dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java create mode 100644 dotcms-integration/src/test/java/com/dotcms/browser/BrowserAPIExportTest.java create mode 100644 dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java diff --git a/core-web/apps/dotcms-ui-e2e/src/tests/content-drive/content-drive-export.spec.ts b/core-web/apps/dotcms-ui-e2e/src/tests/content-drive/content-drive-export.spec.ts new file mode 100644 index 000000000000..6f3f93b0f35d --- /dev/null +++ b/core-web/apps/dotcms-ui-e2e/src/tests/content-drive/content-drive-export.spec.ts @@ -0,0 +1,71 @@ +import { ContentDrivePage } from '@pages'; +import { createFakePayloadTextField } from '@utils/dot-content-types.mock'; +import { Portlet } from '@utils/portlets'; + +import { expect, test } from '../../fixtures/content-drive.fixture'; +import { createContentlet, deleteContentlets } from '../../requests/contentlets'; +import { createFakeContentType, deleteContentType } from '../../requests/contentType'; + +/** + * Journey: exporting the Content Drive listing as a CSV (#37900), filter mode. + * + * With nothing selected and the listing filtered to one content type, the toolbar offers Export, + * and the browser receives a file named the way the Content Search export names it: + * `_contents_.csv`. + * + * What only a real browser can prove is the last step: that the blob the page receives is handed + * to the browser as a download under the server's file name. The rows and the headers are the + * backend suite's (`ContentDriveExportFilterModeTest`) and the Postman "Export" folder's; the + * button's visibility rules are the component spec's. + */ +test.describe('Content Drive export', () => { + test('downloads the filtered type as _contents_.csv @critical', async ({ + adminPage, + request, + testSuffix + }) => { + // Letters and digits only, so the sanitized type name in the file is this name unchanged. + const typeName = `CdExport${testSuffix.replace(/[^a-zA-Z0-9]/g, '')}`; + const contentType = await createFakeContentType(request, { + name: typeName, + variable: typeName, + fields: [createFakePayloadTextField({ name: 'Title', variable: 'title', sortOrder: 1 })] + }); + const contentletIds: string[] = []; + + try { + for (const title of [`${typeName} first`, `${typeName} second`]) { + const contentlet = await createContentlet(request, { + contentType: contentType.variable, + title + }); + contentletIds.push(contentlet.identifier); + } + + const drive = new ContentDrivePage(adminPage); + + // The address carries the filter, so the drive opens already narrowed to the one type. + await adminPage.goto( + `${Portlet.ContentDrive}?filters=${encodeURIComponent( + `contentType:${contentType.variable}` + )}` + ); + await expect(drive.toolbar).toBeVisible({ timeout: 20000 }); + await drive.expectListContainsTitle(`${typeName} first`); + + const exportButton = drive.toolbar.getByTestId('export-button').getByRole('button'); + await expect(exportButton).toBeEnabled({ timeout: 20000 }); + + // Armed before the click, or a fast server finishes before anything is listening. + const download = adminPage.waitForEvent('download', { timeout: 60000 }); + await exportButton.click(); + + expect((await download).suggestedFilename()).toMatch( + new RegExp(`^${typeName}_contents_\\d{1,2}_\\d{1,2}_\\d{4}\\.csv$`) + ); + } finally { + await deleteContentlets(request, contentletIds); + await deleteContentType(request, contentType.id); + } + }); +}); diff --git a/core-web/libs/data-access/src/index.ts b/core-web/libs/data-access/src/index.ts index b943d968c9ec..5c365519e4f5 100644 --- a/core-web/libs/data-access/src/index.ts +++ b/core-web/libs/data-access/src/index.ts @@ -20,6 +20,7 @@ export * from './lib/dot-categories/dot-categories.service'; export * from './lib/dot-company-configuration/dot-company-configuration.service'; export * from './lib/dot-containers/dot-containers.service'; export * from './lib/dot-content-drive/dot-content-drive.service'; +export * from './lib/dot-content-drive-export/dot-content-drive-export.service'; export * from './lib/dot-content-search/dot-content-search.service'; export * from './lib/dot-content-type/dot-content-type.service'; export * from './lib/dot-content-types-info/dot-content-types-info.service'; diff --git a/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.spec.ts b/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.spec.ts new file mode 100644 index 000000000000..1c07da8ae931 --- /dev/null +++ b/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.spec.ts @@ -0,0 +1,158 @@ +import { createServiceFactory, SpectatorService } from '@openng/spectator/vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { HttpClient, provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; + +import { DotContentDriveSearchRequest } from '@dotcms/dotcms-models'; + +import { + DotContentDriveExportRequest, + DotContentDriveExportResult, + DotContentDriveExportService +} from './dot-content-drive-export.service'; + +const EXPORT_URL = '/api/v1/drive/export'; + +/** The listing request as the store builds it, filtered to one content type. */ +const QUERY: DotContentDriveSearchRequest = { + assetPath: '//demo.dotcms.com/', + browseScope: 'ALL', + includeSystemHost: true, + contentTypes: ['Blog'], + language: ['1'], + filters: { text: '', filterFolders: true }, + contentCursor: 0, + folderCursor: 0, + maxResults: 40, + sortBy: 'modDate:desc', + showFolders: false +} as DotContentDriveSearchRequest; + +const BODY: DotContentDriveExportRequest = { query: QUERY }; + +/** The headers a successful filter-mode export carries, per contracts/drive-export-api.md. */ +const FILE_HEADERS = { + 'Content-Type': 'text/csv; charset=UTF-8', + 'Content-Disposition': + 'attachment; filename="Blog_contents_11_26_2026.csv"; filename*=UTF-8\'\'Blog_contents_11_26_2026.csv', + 'X-Export-Contentlets': '3', + 'X-Export-Files': '1' +}; + +describe('DotContentDriveExportService', () => { + let spectator: SpectatorService; + let httpMock: HttpTestingController; + + const createService = createServiceFactory({ + service: DotContentDriveExportService, + providers: [provideHttpClient(), provideHttpClientTesting()] + }); + + beforeEach(() => { + spectator = createService(); + httpMock = spectator.inject(HttpTestingController); + }); + + afterEach(() => { + httpMock.verify(); + vi.restoreAllMocks(); + }); + + /** Runs an export, answers it with the given headers, and returns what the service emitted. */ + const exportWith = ( + headers: Record + ): DotContentDriveExportResult | undefined => { + let result: DotContentDriveExportResult | undefined; + spectator.service.export(BODY).subscribe((value) => (result = value)); + + httpMock + .expectOne(EXPORT_URL) + .flush(new Blob(['Identifier,languageCode,countryCode,title\n']), { + status: 200, + statusText: 'OK', + headers + }); + + return result; + }; + + describe('the request', () => { + it('POSTs the listing query to /api/v1/drive/export', () => { + spectator.service.export(BODY).subscribe(); + + const req = httpMock.expectOne(EXPORT_URL); + expect(req.request.method).toBe('POST'); + expect(req.request.body).toEqual({ query: QUERY }); + req.flush(new Blob(['x']), { status: 200, statusText: 'OK', headers: FILE_HEADERS }); + }); + + it('asks for the whole response as a blob, so the headers can be read', () => { + // `observe` never reaches HttpRequest, so it is read off the call itself. The spy calls + // through, so the request still goes to the testing backend. + const postSpy = vi.spyOn(spectator.inject(HttpClient), 'post'); + + spectator.service.export(BODY).subscribe(); + + expect(postSpy).toHaveBeenCalledWith( + EXPORT_URL, + { query: QUERY }, + expect.objectContaining({ observe: 'response', responseType: 'blob' }) + ); + + const req = httpMock.expectOne(EXPORT_URL); + expect(req.request.responseType).toBe('blob'); + req.flush(new Blob(['x']), { status: 200, statusText: 'OK', headers: FILE_HEADERS }); + }); + }); + + describe('the result', () => { + it('emits { kind: "file", blob, fileName, contentlets, files }', () => { + const result = exportWith(FILE_HEADERS); + + expect(result).toEqual({ + kind: 'file', + blob: expect.any(Blob), + fileName: 'Blog_contents_11_26_2026.csv', + contentlets: 3, + files: 1 + }); + }); + + it('takes the file name from filename* and percent-decodes it', () => { + const result = exportWith({ + ...FILE_HEADERS, + 'Content-Disposition': + 'attachment; filename="Art_culo_contents_11_26_2026.csv"; filename*=UTF-8\'\'Art%C3%ADculo_contents_11_26_2026.csv' + }); + + expect(result).toMatchObject({ + kind: 'file', + fileName: 'Artículo_contents_11_26_2026.csv' + }); + }); + + it('falls back to filename, without its quotes, when filename* is absent', () => { + const result = exportWith({ + ...FILE_HEADERS, + 'Content-Disposition': 'attachment; filename="News_contents_11_26_2026.csv"' + }); + + expect(result).toMatchObject({ + kind: 'file', + fileName: 'News_contents_11_26_2026.csv' + }); + }); + + it('reads the X-Export-* headers as numbers', () => { + const result = exportWith({ + ...FILE_HEADERS, + 'X-Export-Contentlets': '2500', + 'X-Export-Files': '4' + }); + + // Strict equality on numbers: the raw header strings '2500' and '4' do not match. + expect(result).toMatchObject({ kind: 'file', contentlets: 2500, files: 4 }); + }); + }); +}); diff --git a/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts b/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts new file mode 100644 index 000000000000..14c8690b597a --- /dev/null +++ b/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts @@ -0,0 +1,56 @@ +import { EMPTY, Observable } from 'rxjs'; + +import { Injectable } from '@angular/core'; + +import { DotContentDriveSearchRequest } from '@dotcms/dotcms-models'; + +/** + * Body of `POST /api/v1/drive/export` in filter mode: the same request the listing sends to + * `/api/v1/drive/search`. The server ignores its paging, sorting and folder flags. + */ +export interface DotContentDriveExportRequest { + query: DotContentDriveSearchRequest; +} + +/** + * A 200 from the export endpoint: the file and what the server says it holds. + * + * `fileName` comes from `Content-Disposition` (`filename*` decoded when present, else `filename`); + * `contentlets` and `files` come from the `X-Export-Contentlets` and `X-Export-Files` headers. + */ +export interface DotContentDriveExportFile { + kind: 'file'; + blob: Blob; + fileName: string; + contentlets: number; + files: number; +} + +/** A 204 from the export endpoint: nothing readable matched, so there is no file. */ +export interface DotContentDriveExportEmpty { + kind: 'empty'; +} + +/** What an export resolves to. */ +export type DotContentDriveExportResult = DotContentDriveExportFile | DotContentDriveExportEmpty; + +/** + * Downloads Content Drive exports: one CSV for the content type the listing is filtered to. + */ +@Injectable({ + providedIn: 'root' +}) +export class DotContentDriveExportService { + /** + * Asks the server to build the export file for the given request. + * + * Not implemented yet (compile-only stub for the TDD Red step): it completes without a value + * and sends no request. + * + * @param _body The export request, carrying the listing query in filter mode. + * @returns The file and its counts once the server has built it. + */ + export(_body: DotContentDriveExportRequest): Observable { + return EMPTY; + } +} diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.html b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.html new file mode 100644 index 000000000000..b84b9e3d2965 --- /dev/null +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.html @@ -0,0 +1 @@ + diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts new file mode 100644 index 000000000000..f5bc65d5836a --- /dev/null +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts @@ -0,0 +1,318 @@ +import { + byTestId, + createComponentFactory, + mockProvider, + Spectator, + SpyObject +} from '@openng/spectator/vitest'; +import { of, Subject } from 'rxjs'; +import { afterEach, beforeEach, describe, expect, it, Mock, vi } from 'vitest'; + +vi.mock('@dotcms/utils', async () => ({ + ...(await vi.importActual('@dotcms/utils')), + getDownloadLink: vi.fn() +})); + +import { signal } from '@angular/core'; + +import { MessageService } from 'primeng/api'; + +import { + DotContentDriveExportResult, + DotContentDriveExportService, + DotContentTypeService, + DotMessageService +} from '@dotcms/data-access'; +import { + DotCMSBaseTypesContentTypes, + DotContentDriveItem, + DotContentDriveSearchRequest +} from '@dotcms/dotcms-models'; +import { getDownloadLink } from '@dotcms/utils'; +import { + createFakeContentlet, + createFakeContentType, + MockDotMessageService +} from '@dotcms/utils-testing'; + +import { DotContentDriveExportButtonComponent } from './dot-content-drive-export-button.component'; + +import { DEFAULT_PAGE, SUCCESS_MESSAGE_LIFE } from '../../../../shared/constants'; +import { + DotContentDriveFilters, + DotContentDrivePage, + DotContentDriveStatus +} from '../../../../shared/models'; +import { DotContentDriveStore } from '../../../../store/dot-content-drive.store'; + +/** A Form type's variable: fetching it answers with the FORM base type. */ +const FORM_VARIABLE = 'ContactForm'; + +/** The listing request the store would send to `/api/v1/drive/search`. */ +const REQUEST = { + assetPath: '//demo.dotcms.com/', + browseScope: 'ALL', + includeSystemHost: true, + contentTypes: ['Blog'], + language: ['1'], + filters: { text: '', filterFolders: true }, + contentCursor: 0, + folderCursor: 0, + maxResults: 40, + sortBy: 'modDate:desc', + showFolders: false +} as DotContentDriveSearchRequest; + +const CONTENTLET = createFakeContentlet({ identifier: 'contentlet-1', inode: 'inode-1' }); +const FOLDER = { + type: 'folder', + identifier: 'folder-1', + inode: 'folder-1', + title: 'blog', + name: 'blog', + path: '/blog/' +} as unknown as DotContentDriveItem; + +/** The last loaded page, reporting nothing more to load. */ +const LAST_PAGE: DotContentDrivePage = { ...DEFAULT_PAGE, hasMoreContent: false }; + +const FILE_RESULT: DotContentDriveExportResult = { + kind: 'file', + blob: new Blob(['Identifier,languageCode,countryCode,title\n']), + fileName: 'Blog_contents_11_26_2026.csv', + contentlets: 3, + files: 1 +}; + +describe('DotContentDriveExportButtonComponent (filter mode)', () => { + let spectator: Spectator; + let exportService: SpyObject; + let contentTypeService: SpyObject; + + // Real signals, so the component's computeds re-run when a test changes them. + const selectedItemsSignal = signal([]); + const filtersSignal = signal({ contentType: ['Blog'] }); + const statusSignal = signal(DotContentDriveStatus.LOADED); + const itemsSignal = signal([CONTENTLET]); + const pagesSignal = signal([LAST_PAGE]); + const requestSignal = signal(REQUEST); + + const messageServiceSpy = { add: vi.fn(), clear: vi.fn() }; + const anchorClick = vi.fn(); + + const createComponent = createComponentFactory({ + component: DotContentDriveExportButtonComponent, + providers: [ + mockProvider(DotContentDriveStore, { + selectedItems: selectedItemsSignal, + filters: filtersSignal, + status: statusSignal, + items: itemsSignal, + pages: pagesSignal, + $request: requestSignal + }), + mockProvider(DotContentTypeService, { + getContentType: vi.fn((variable: string) => + of( + createFakeContentType({ + variable, + baseType: + variable === FORM_VARIABLE + ? DotCMSBaseTypesContentTypes.FORM + : DotCMSBaseTypesContentTypes.CONTENT + }) + ) + ) + }), + mockProvider(DotContentDriveExportService, { + export: vi.fn().mockReturnValue(of(FILE_RESULT)) + }), + mockProvider(MessageService, messageServiceSpy), + { + provide: DotMessageService, + useValue: new MockDotMessageService({ + 'content-drive.export.button': 'Export', + 'content-drive.toast.export-success': 'Export ready', + 'content-drive.toast.export-success-detail': '{0} items exported in {1} file(s)' + }) + } + ], + detectChanges: false + }); + + /** The PrimeNG host of the Export button. */ + const exportButtonHost = () => spectator.query(byTestId('content-drive-export-button')); + + /** The native button inside it: the element that is disabled, busy, and clicked. */ + const exportButton = () => + exportButtonHost()?.querySelector('button') as HTMLButtonElement | null; + + /** + * Renders, lets the content-type fetch settle, and renders again: whether the button shows + * depends on the fetched type, which arrives after the first pass. + */ + const render = async () => { + spectator.detectChanges(); + await spectator.fixture.whenStable(); + spectator.detectChanges(); + }; + + beforeEach(() => { + (getDownloadLink as Mock).mockReturnValue({ click: anchorClick }); + spectator = createComponent(); + exportService = spectator.inject(DotContentDriveExportService); + contentTypeService = spectator.inject(DotContentTypeService); + }); + + afterEach(() => { + vi.clearAllMocks(); + selectedItemsSignal.set([]); + filtersSignal.set({ contentType: ['Blog'] }); + statusSignal.set(DotContentDriveStatus.LOADED); + itemsSignal.set([CONTENTLET]); + pagesSignal.set([LAST_PAGE]); + requestSignal.set(REQUEST); + }); + + describe('shown', () => { + it('should show when nothing is selected and the listing is filtered to one non-Form type', async () => { + await render(); + + expect(contentTypeService.getContentType).toHaveBeenCalledWith('Blog'); + expect(exportButtonHost()).toBeTruthy(); + expect(exportButtonHost()?.textContent).toContain('Export'); + }); + }); + + // Each case starts from the shown state and changes only the filter, so a button that never + // renders cannot pass them. + describe('not shown', () => { + beforeEach(async () => { + await render(); + expect(exportButtonHost()).toBeTruthy(); + }); + + it('should not show when no content type is filtered', async () => { + filtersSignal.set({}); + await render(); + + expect(exportButtonHost()).toBeNull(); + }); + + it('should not show when two content types are filtered', async () => { + filtersSignal.set({ contentType: ['Blog', 'News'] }); + await render(); + + expect(exportButtonHost()).toBeNull(); + }); + + it('should not show when the one filtered type is a Form', async () => { + filtersSignal.set({ contentType: [FORM_VARIABLE] }); + await render(); + + expect(contentTypeService.getContentType).toHaveBeenCalledWith(FORM_VARIABLE); + expect(exportButtonHost()).toBeNull(); + }); + }); + + describe('disabled', () => { + it('should be disabled when the loaded listing is empty and reports no more content', async () => { + itemsSignal.set([]); + await render(); + + expect(exportButton()).toBeTruthy(); + expect(exportButton()?.disabled).toBe(true); + }); + + it('should be disabled when the loaded listing holds only folders and reports no more content', async () => { + itemsSignal.set([FOLDER]); + await render(); + + expect(exportButton()).toBeTruthy(); + expect(exportButton()?.disabled).toBe(true); + }); + }); + + describe('enabled', () => { + it('should be enabled when the loaded listing holds a contentlet', async () => { + itemsSignal.set([FOLDER, CONTENTLET]); + await render(); + + expect(exportButton()).toBeTruthy(); + expect(exportButton()?.disabled).toBe(false); + }); + + it('should be enabled when only folders are loaded but a page reports more content', async () => { + itemsSignal.set([FOLDER]); + pagesSignal.set([{ ...DEFAULT_PAGE, hasMoreContent: true }]); + await render(); + + expect(exportButton()).toBeTruthy(); + expect(exportButton()?.disabled).toBe(false); + }); + + it('should be enabled while the listing is still loading', async () => { + itemsSignal.set([]); + statusSignal.set(DotContentDriveStatus.LOADING); + await render(); + + expect(exportButton()).toBeTruthy(); + expect(exportButton()?.disabled).toBe(false); + }); + }); + + describe('click', () => { + it('should export the listing request the store holds', async () => { + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(exportService.export).toHaveBeenCalledTimes(1); + expect(exportService.export).toHaveBeenCalledWith({ query: REQUEST }); + }); + }); + + describe('while running', () => { + it('should show loading, stay disabled, and ignore a second click', async () => { + // Never answers, so the export stays in flight for the whole test. + exportService.export.mockReturnValue(new Subject()); + await render(); + + spectator.click(exportButton() as HTMLElement); + spectator.detectChanges(); + + expect(exportButton()).toHaveClass('p-button-loading'); + expect(exportButton()?.disabled).toBe(true); + + spectator.click(exportButton() as HTMLElement); + + expect(exportService.export).toHaveBeenCalledTimes(1); + }); + }); + + describe('on success', () => { + it('should download the file under the name the server gave', async () => { + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(getDownloadLink).toHaveBeenCalledWith(FILE_RESULT.blob, FILE_RESULT.fileName); + expect(anchorClick).toHaveBeenCalledTimes(1); + }); + + it('should show a success toast with the number of exported items', async () => { + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(messageServiceSpy.add).toHaveBeenCalledWith( + expect.objectContaining({ + severity: 'success', + summary: 'Export ready', + detail: '3 items exported in 1 file(s)', + life: SUCCESS_MESSAGE_LIFE + }) + ); + }); + }); +}); diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts new file mode 100644 index 000000000000..72a26f694720 --- /dev/null +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts @@ -0,0 +1,15 @@ +import { ChangeDetectionStrategy, Component } from '@angular/core'; + +/** + * The toolbar's Export button: downloads the listing as a CSV when it is filtered to one content + * type and nothing is selected. + * + * Compile-only stub for the TDD Red step: it renders nothing yet. The behavior the specs describe + * lands with the implementation. + */ +@Component({ + selector: 'dot-content-drive-export-button', + templateUrl: './dot-content-drive-export-button.component.html', + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class DotContentDriveExportButtonComponent {} diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.spec.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.spec.ts index 5563fa4e80fc..3457c2f3a25c 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.spec.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.spec.ts @@ -5,7 +5,7 @@ import { createComponentFactory, mockProvider } from '@openng/spectator/vitest'; -import { of } from 'rxjs'; +import { EMPTY, of } from 'rxjs'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { provideHttpClient } from '@angular/common/http'; @@ -18,6 +18,7 @@ import { Tooltip } from 'primeng/tooltip'; import { DotCategoriesService, DotContentTypeService, + DotContentDriveExportService, DotContentletService, DotHttpErrorManagerService, DotLanguagesService, @@ -39,11 +40,12 @@ import { createFakeTextField, mockLocales, MockDotMessageService } from '@dotcms import { DotContentDriveToolbarComponent } from './dot-content-drive-toolbar.component'; -import { DIALOG_TYPE } from '../../shared/constants'; +import { DEFAULT_PAGE, DIALOG_TYPE } from '../../shared/constants'; import { MOCK_BASE_TYPES, MOCK_CONTENT_TYPES, MOCK_ITEMS } from '../../shared/mocks'; import { DotContentDriveActionExecution, DotContentDriveFilters, + DotContentDriveStatus, DotContentDriveViewType } from '../../shared/models'; import { DotContentDriveNavigationService } from '../../shared/services'; @@ -187,7 +189,13 @@ describe('DotContentDriveToolbarComponent', () => { languages: signal(mockLocales), defaultLanguageId: vi.fn().mockReturnValue(1), viewType: viewTypeSignal, - setViewType: vi.fn() + setViewType: vi.fn(), + // Read by the Export button this toolbar renders (#37900): whether the listing has + // anything to export, and the request it exports. + status: signal(DotContentDriveStatus.LOADED), + items: signal([]), + pages: signal([DEFAULT_PAGE]), + $request: signal({ assetPath: '//demo.dotcms.com/' }) }), mockProvider(DotContentTypeService, { getContentTypes: vi.fn().mockReturnValue(of(MOCK_CONTENT_TYPES)), @@ -201,7 +209,12 @@ describe('DotContentDriveToolbarComponent', () => { } }) ), - getAllContentTypes: vi.fn().mockReturnValue(of(MOCK_BASE_TYPES)) + getAllContentTypes: vi.fn().mockReturnValue(of(MOCK_BASE_TYPES)), + // The Export button fetches the one filtered type to rule out Forms. + getContentType: vi.fn().mockReturnValue(of(MOCK_CONTENT_TYPES[0])) + }), + mockProvider(DotContentDriveExportService, { + export: vi.fn().mockReturnValue(EMPTY) }), // The shared DotLanguageFilterComponent fetches the language list on init, so without // this the toolbar's render reaches for /api/v2/languages and the spec fails on a @@ -674,6 +687,21 @@ describe('DotContentDriveToolbarComponent', () => { }); }); + describe('Export button (#37900)', () => { + it('should sit in the Upload / Add New block when nothing is selected', async () => { + await settleToolbarAnimation(spectator); + + // The block is the row Upload and Add New share: the parent of their tooltip wrappers. + const block = spectator.query(byTestId('upload-asset-tooltip'))?.parentElement; + const exportButton = spectator.query(byTestId('export-button')); + + expect(block).toBeTruthy(); + expect(block?.contains(spectator.query(byTestId('add-new-tooltip')))).toBe(true); + expect(exportButton).toBeTruthy(); + expect(block?.contains(exportButton)).toBe(true); + }); + }); + describe('Workflow Center button', () => { it('should not offer it with no selection', async () => { selectedItemsSignal.set([]); diff --git a/dotCMS/src/main/java/com/dotcms/browser/BrowserAPI.java b/dotCMS/src/main/java/com/dotcms/browser/BrowserAPI.java index 91da7d360d21..445040be1af9 100644 --- a/dotCMS/src/main/java/com/dotcms/browser/BrowserAPI.java +++ b/dotCMS/src/main/java/com/dotcms/browser/BrowserAPI.java @@ -283,6 +283,26 @@ public default Map getFolderContent(final User user, final Strin PaginatedContents getPaginatedContents(final BrowserQuery browserQuery) throws DotSecurityException, DotDataException; + /** + * Returns every contentlet row a Content Drive export of this query writes: the working + * version of each contentlet in each language the listing would show, readable by the query's + * user, at most one row per identifier and language, ordered by identifier and then language. + *

+ * It runs the same structural query as {@link #getPaginatedContents(BrowserQuery)}, including + * the index narrowing of text and field filters, but ignores cursors, paging, sorting and the + * listing's time and row budgets. Folders and links are never returned, and neither are Form + * or Host content. + * + * @param browserQuery the listing query + * @param maxRows the most rows an export may hold; reading stops at the first row past it + * @return the rows, with {@link ExportCandidates#overLimit()} set when more than + * {@code maxRows} readable rows exist + * @throws DotSecurityException if the user cannot read the parent + * @throws DotDataException if the rows cannot be read + */ + ExportCandidates getContentForExport(BrowserQuery browserQuery, int maxRows) + throws DotSecurityException, DotDataException; + /** * Tells whether the index query this request would send leaves room, within the index's * maximum query-string length, for a useful batch of candidate inodes. A search term or filter diff --git a/dotCMS/src/main/java/com/dotcms/browser/BrowserAPIImpl.java b/dotCMS/src/main/java/com/dotcms/browser/BrowserAPIImpl.java index 89bacaee3088..c346bab047c2 100644 --- a/dotCMS/src/main/java/com/dotcms/browser/BrowserAPIImpl.java +++ b/dotCMS/src/main/java/com/dotcms/browser/BrowserAPIImpl.java @@ -2636,6 +2636,13 @@ public Map getFolderContent(final BrowserQuery browserQuery) thr return returnMap; } + @CloseDBIfOpened + @Override + public ExportCandidates getContentForExport(final BrowserQuery browserQuery, final int maxRows) + throws DotSecurityException, DotDataException { + throw new UnsupportedOperationException("not implemented"); + } + @Override @CloseDBIfOpened public PaginatedContents getPaginatedContents(final BrowserQuery browserQuery) diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java index d3a4a5ccd461..23f58fab3e46 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java @@ -4,6 +4,7 @@ import com.dotcms.rest.ResponseEntityView; import com.dotcms.rest.WebResource; import com.dotcms.rest.annotation.NoCache; +import com.dotcms.rest.api.v1.drive.export.DriveExportRequestForm; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.util.Logger; @@ -105,4 +106,26 @@ public Response search(@Context final HttpServletRequest request, return Response.ok(new ResponseEntityView<>(helper.driveSearch(form, user))).build(); } + /** + * Exports what the Drive shows, or what is selected in it, as a CSV or a zip of CSVs. + *

+ * Not implemented yet: it answers 501. It stays hidden from the OpenAPI document until it is. + * + * @param request the HTTP request + * @param response the HTTP response + * @param form the export request + * @return 501 Not Implemented + */ + @Hidden + @Path("/export") + @POST + @NoCache + @Consumes(MediaType.APPLICATION_JSON) + @Produces({"text/csv", "application/zip", MediaType.APPLICATION_JSON}) + public Response export(@Context final HttpServletRequest request, + @Context final HttpServletResponse response, + final DriveExportRequestForm form) { + return Response.status(Response.Status.NOT_IMPLEMENTED).build(); + } + } diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java new file mode 100644 index 000000000000..b44c5dea175a --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java @@ -0,0 +1,36 @@ +package com.dotcms.rest.api.v1.drive.export; + +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; +import com.liferay.portal.model.User; +import java.io.IOException; +import javax.servlet.http.HttpServletRequest; + +/** + * Runs a Content Drive export: resolves which rows the request exports and builds the file. + *

+ * In filter mode the rows are everything the Drive listing shows for the request's query, which + * must name exactly one content type; the result is one CSV. In selection mode the rows come from + * the selected folders and contentlets; the result is a zip with one CSV per content type. + */ +public class ContentDriveExportHelper { + + /** + * Builds the export a request asks for. + * + * @param form the request body + * @param user the {@link User} the export runs as + * @param request the HTTP request, used for the download links of binary fields + * @return the finished file; when nothing readable matched it reports zero rows and holds no + * file + * @throws com.dotcms.rest.exception.BadRequestException when the request is invalid + * @throws DotDataException if the rows cannot be read or the file cannot be written + * @throws DotSecurityException if the user cannot read the site or folder being exported + * @throws IOException if the temp file cannot be written + */ + public ExportFile export(final DriveExportRequestForm form, final User user, + final HttpServletRequest request) + throws DotDataException, DotSecurityException, IOException { + throw new UnsupportedOperationException("not implemented"); + } +} diff --git a/dotcms-integration/src/test/java/com/dotcms/MainSuite3a.java b/dotcms-integration/src/test/java/com/dotcms/MainSuite3a.java index 77b5e1cbc68c..54718069641c 100644 --- a/dotcms-integration/src/test/java/com/dotcms/MainSuite3a.java +++ b/dotcms-integration/src/test/java/com/dotcms/MainSuite3a.java @@ -98,6 +98,7 @@ com.dotcms.rest.api.v1.container.ContainerResourceCallerPermissionTest.class, com.dotcms.rest.api.v1.container.ContainerResourceContentReadAccessTest.class, ContentDriveBrowseScopeTest.class, + com.dotcms.rest.api.v1.drive.ContentDriveExportFilterModeTest.class, ContentDriveFieldFilterTest.class, ContentDriveHelperContentletAPIComparisonTest.class, ContentDriveKeywordSearchTest.class, @@ -111,6 +112,7 @@ AppsAPIImplTest.class, com.dotcms.content.elasticsearch.business.ESContentletAPIImplTest.class, com.dotcms.rendering.velocity.viewtools.content.util.ContentUtilsTest.class, + com.dotcms.browser.BrowserAPIExportTest.class, com.dotcms.browser.BrowserAPITest.class, com.dotmarketing.portlets.folders.business.FolderSearchPermissionsIT.class, com.dotcms.rest.api.v1.content.search.strategies.GlobalSearchAttributeStrategyMatchingTest.class, diff --git a/dotcms-integration/src/test/java/com/dotcms/browser/BrowserAPIExportTest.java b/dotcms-integration/src/test/java/com/dotcms/browser/BrowserAPIExportTest.java new file mode 100644 index 000000000000..fe745bfea743 --- /dev/null +++ b/dotcms-integration/src/test/java/com/dotcms/browser/BrowserAPIExportTest.java @@ -0,0 +1,496 @@ +package com.dotcms.browser; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import com.dotcms.IntegrationTestBase; +import com.dotcms.browser.BrowserAPIImpl.PaginatedContents; + +import com.dotcms.contenttype.model.field.CategoryField; +import com.dotcms.contenttype.model.field.TagField; +import com.dotcms.contenttype.model.field.TextField; +import com.dotcms.contenttype.model.type.BaseContentType; +import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.datagen.CategoryDataGen; +import com.dotcms.datagen.ContentTypeDataGen; +import com.dotcms.datagen.ContentletDataGen; +import com.dotcms.datagen.FieldDataGen; +import com.dotcms.datagen.FolderDataGen; +import com.dotcms.datagen.LanguageDataGen; +import com.dotcms.datagen.SiteDataGen; +import com.dotcms.datagen.WorkflowDataGen; +import com.dotcms.rest.api.v1.drive.BrowseScope; +import com.dotcms.rest.api.v1.drive.ContentDriveHelper; +import com.dotcms.rest.api.v1.drive.DriveRequestForm; +import com.dotcms.rest.api.v1.drive.QueryFilters; +import com.dotcms.rest.api.v1.drive.WorkflowFilterForm; +import com.dotcms.util.IntegrationTestInitService; +import com.dotmarketing.beans.Host; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.portlets.categories.model.Category; +import com.dotmarketing.portlets.contentlet.business.ContentletAPI; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.contentlet.model.IndexPolicy; +import com.dotmarketing.portlets.folders.model.Folder; +import com.dotmarketing.portlets.languagesmanager.model.Language; +import com.dotmarketing.portlets.workflows.business.WorkflowAPI; +import com.dotmarketing.portlets.workflows.model.WorkflowScheme; +import com.dotmarketing.portlets.workflows.model.WorkflowStep; +import com.dotmarketing.portlets.workflows.model.WorkflowTask; +import com.dotmarketing.util.Config; +import com.liferay.portal.model.User; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Integration tests for {@link BrowserAPI#getContentForExport(BrowserQuery, int)}: the rows a + * Content Drive export writes (research R1, FR-005, FR-011, FR-017, FR-017a). + *

+ * Every case builds the query the way the export does — through + * {@link ContentDriveHelper#toBrowserQueryBuilder} with folders and links off and working versions + * on — and compares the rows with what the listing shows for the same request, paged to the end + * through {@code nextContentCursor}. The listing is always read before any budget is lowered, so it + * is the full, unbudgeted answer. + */ +public class BrowserAPIExportTest extends IntegrationTestBase { + + private static final int NO_LIMIT = 100_000; + private static final int MAX_PAGES = 200; + + private static User systemUser; + private static ContentDriveHelper helper; + private static WorkflowAPI workflowAPI; + private static ContentletAPI contentletAPI; + + private static Host site; + private static Folder folder; + private static Language defaultLanguage; + private static Language secondLanguage; + private static WorkflowScheme scheme; + private static WorkflowStep stepOne; + private static Category categoryOne; + + /** Type with every state the listing filters on. */ + private static ContentType mixedType; + /** Type with 40 contentlets, for the scan-cap case. */ + private static ContentType bulkType; + /** Type with 6 contentlets, for the row limit. */ + private static ContentType sixType; + private static ContentType formType; + + private static Contentlet live; + private static Contentlet liveSecondLanguage; + private static Contentlet draft; + private static Contentlet archived; + private static Contentlet locked; + private static Contentlet publishedThenEdited; + private static Contentlet atSiteRoot; + private static Contentlet inSystemHost; + private static Contentlet formEntry; + private static final List bulk = new ArrayList<>(); + + @BeforeClass + public static void prepare() throws Exception { + IntegrationTestInitService.getInstance().init(); + systemUser = APILocator.systemUser(); + helper = ContentDriveHelper.newInstance(); + workflowAPI = APILocator.getWorkflowAPI(); + contentletAPI = APILocator.getContentletAPI(); + + final String unique = String.valueOf(System.currentTimeMillis()); + site = new SiteDataGen().name("browser-export-" + unique + ".local").nextPersisted(); + folder = new FolderDataGen().site(site).name("export-" + unique).nextPersisted(); + defaultLanguage = APILocator.getLanguageAPI().getDefaultLanguage(); + secondLanguage = new LanguageDataGen().nextPersisted(); + + scheme = new WorkflowDataGen().name("BrowserExportScheme_" + unique) + .nextPersistedWithDefaultStepsAndActions(); + final List steps = workflowAPI.findSteps(scheme); + stepOne = steps.get(0); + final WorkflowStep stepTwo = steps.get(1); + + final Category parent = new CategoryDataGen().setCategoryName("exportParent" + unique) + .setKey("exportParent" + unique).setCategoryVelocityVarName("exportParent" + unique) + .nextPersisted(); + categoryOne = new CategoryDataGen().setCategoryName("exportOne" + unique) + .setKey("exportOne" + unique).setCategoryVelocityVarName("exportOne" + unique) + .parent(parent).nextPersisted(); + final Category categoryTwo = new CategoryDataGen().setCategoryName("exportTwo" + unique) + .setKey("exportTwo" + unique).setCategoryVelocityVarName("exportTwo" + unique) + .parent(parent).nextPersisted(); + + // FieldDataGen gives every field a text default value, which would leak into the rows + // the filters see; every field here clears it. + mixedType = new ContentTypeDataGen().host(site) + .name("BrowserExportMixed " + unique).velocityVarName("browserExportMixed" + unique) + .workflowId(scheme.getId()) + .field(new FieldDataGen().defaultValue(null).type(TextField.class).name("title") + .velocityVarName("title").next()) + .field(new FieldDataGen().defaultValue(null).type(TagField.class).name("labels") + .velocityVarName("labels").next()) + .field(new FieldDataGen().defaultValue(null).type(CategoryField.class).name("cats") + .velocityVarName("cats").values(parent.getInode()).next()) + .nextPersisted(); + + live = ContentletDataGen.publish(mixed(folder, "alpha needle", "red", categoryOne)); + moveToStep(live, stepOne); + + final Contentlet secondLanguageDraft = ContentletDataGen.checkout(live); + secondLanguageDraft.setLanguageId(secondLanguage.getId()); + liveSecondLanguage = ContentletDataGen.checkin(secondLanguageDraft); + + draft = mixed(folder, "beta", "blue", categoryTwo); + moveToStep(draft, stepTwo); + + archived = ContentletDataGen.publish(mixed(folder, "gamma needle", "red", categoryTwo)); + ContentletDataGen.archive(archived); + + locked = ContentletDataGen.publish(mixed(folder, "delta", "blue", categoryOne)); + contentletAPI.lock(locked, systemUser, false); + + final Contentlet published = ContentletDataGen.publish(mixed(folder, "epsilon", "red", + categoryOne)); + final Contentlet checkout = contentletAPI.checkout(published.getInode(), systemUser, false); + checkout.setProperty("title", "epsilon edited"); + checkout.setIndexPolicy(IndexPolicy.FORCE); + publishedThenEdited = contentletAPI.checkin(checkout, systemUser, false); + + atSiteRoot = mixed(null, "root needle", "blue", categoryTwo); + inSystemHost = new ContentletDataGen(mixedType).host(APILocator.systemHost()) + .languageId(defaultLanguage.getId()).setProperty("title", "system needle") + .nextPersisted(); + + bulkType = simpleType("BrowserExportBulk", unique); + for (int i = 0; i < 40; i++) { + bulk.add(new ContentletDataGen(bulkType).host(site).folder(folder) + .setProperty("title", "bulk " + i).nextPersisted()); + } + + sixType = simpleType("BrowserExportSix", unique); + for (int i = 0; i < 6; i++) { + new ContentletDataGen(sixType).host(site).folder(folder) + .setProperty("title", "six " + i).nextPersisted(); + } + + formType = new ContentTypeDataGen().baseContentType(BaseContentType.FORM).host(site) + .name("BrowserExportForm" + unique).velocityVarName("browserExportForm" + unique) + .nextPersisted(); + formEntry = new ContentletDataGen(formType).host(site).nextPersistedWithSampleTextValues(); + } + + private static Contentlet mixed(final Folder target, final String title, final String tag, + final Category category) { + final ContentletDataGen dataGen = new ContentletDataGen(mixedType).host(site) + .languageId(defaultLanguage.getId()) + .setProperty("title", title).setProperty("labels", tag).addCategory(category); + if (target != null) { + dataGen.folder(target); + } + return dataGen.nextPersisted(); + } + + private static ContentType simpleType(final String name, final String unique) { + return new ContentTypeDataGen().host(site).name(name + " " + unique) + .velocityVarName(name + unique) + .field(new FieldDataGen().defaultValue(null).type(TextField.class).name("title") + .velocityVarName("title").next()) + .nextPersisted(); + } + + private static void moveToStep(final Contentlet contentlet, final WorkflowStep step) + throws Exception { + workflowAPI.deleteWorkflowTaskByContentletIdAnyLanguage(contentlet, systemUser); + final WorkflowTask task = workflowAPI.createWorkflowTask(contentlet, systemUser, step, + "browser-export-test", "browser-export-test"); + workflowAPI.saveWorkflowTask(task); + } + + // --------------------------------------------------------------------------------------------- + // helpers + // --------------------------------------------------------------------------------------------- + + /** The site at any depth, both languages, the mixed type. */ + private static DriveRequestForm.Builder siteRequest(final ContentType type) { + return DriveRequestForm.builder() + .assetPath("//" + site.getHostname() + "/") + .browseScope(BrowseScope.ALL) + .includeSystemHost(true) + .language(List.of(String.valueOf(defaultLanguage.getId()), + String.valueOf(secondLanguage.getId()))) + .contentTypes(List.of(type.variable())) + .showFolders(false) + .live(false) + .archived(false) + .maxResults(10); + } + + /** The working inodes the listing shows for a request, every page, read as the system user. */ + private static Set listingInodes(final DriveRequestForm request) throws Exception { + final Set inodes = new HashSet<>(); + int cursor = 0; + for (int page = 1; page <= MAX_PAGES; page++) { + final PaginatedContents result = helper.driveSearch( + DriveRequestForm.builder().from(request).contentCursor(cursor).build(), + systemUser); + result.list.forEach(item -> inodes.add((String) item.get("inode"))); + if (!result.hasMoreContent) { + return inodes; + } + cursor = result.nextContentCursor; + } + throw new AssertionError("The listing did not end after " + MAX_PAGES + " pages"); + } + + /** The query the export runs for a request: the listing's, without folders and links. */ + private static BrowserQuery exportQuery(final DriveRequestForm request) throws Exception { + return helper.toBrowserQueryBuilder(request, systemUser) + .showFolders(false).showLinks(false).showWorking(true).build(); + } + + private static ExportCandidates export(final BrowserAPI browserAPI, + final DriveRequestForm request, final int maxRows) throws Exception { + return browserAPI.getContentForExport(exportQuery(request), maxRows); + } + + private static Set inodes(final ExportCandidates candidates) { + return candidates.rows().stream().map(ExportRow::inode).collect(Collectors.toSet()); + } + + private static Set inodesOf(final List contentlets) { + return contentlets.stream().map(Contentlet::getInode).collect(Collectors.toSet()); + } + + /** + * Asserts the export returns exactly the listing's rows for a request, and that the listing is + * not empty, so the comparison cannot pass vacuously. + */ + private static void assertSameRowsAsListing(final String label, final DriveRequestForm request) + throws Exception { + final Set listing = listingInodes(request); + assertFalse(label + ": the listing must show rows, or the comparison proves nothing", + listing.isEmpty()); + final ExportCandidates candidates = export(APILocator.getBrowserAPI(), request, NO_LIMIT); + assertFalse(label, candidates.overLimit()); + assertEquals(label, listing, inodes(candidates)); + assertEquals(label + ": one row per identifier and language", + candidates.rows().size(), candidates.rows().stream().map(ExportRow::key) + .collect(Collectors.toSet()).size()); + } + + /** + * Runs an action with browser settings changed, restoring each to its default afterwards. + */ + private static void withSettings(final Map settings, final Action action) + throws Exception { + settings.forEach(Config::setProperty); + try { + action.run(); + } finally { + Config.setProperty(BrowserAPIImpl.BROWSER_DB_MAX_SCAN_ROWS_KEY, + BrowserAPIImpl.BROWSER_DB_MAX_SCAN_ROWS_DEFAULT); + Config.setProperty(BrowserAPIImpl.BROWSER_CONTENT_CHUNK_SIZE_KEY, + BrowserAPIImpl.BROWSER_CONTENT_CHUNK_SIZE_DEFAULT); + Config.setProperty(BrowserAPIImpl.BROWSER_DB_MAX_SCAN_TIME_MILLIS_KEY, + BrowserAPIImpl.BROWSER_DB_MAX_SCAN_TIME_MILLIS_DEFAULT); + Config.setProperty(BrowserAPIImpl.BROWSER_SINGLE_PASS_CHUNK_SIZE_KEY, + BrowserAPIImpl.BROWSER_SINGLE_PASS_CHUNK_SIZE_DEFAULT); + } + } + + @FunctionalInterface + private interface Action { + void run() throws Exception; + } + + // --------------------------------------------------------------------------------------------- + // tests + // --------------------------------------------------------------------------------------------- + + /** + * Method to test: {@link BrowserAPI#getContentForExport(BrowserQuery, int)} + * Given Scenario: (a) No text filter, 40 contentlets, and {@code BROWSER_DB_MAX_SCAN_ROWS} + * lowered to 15, far below them + * ExpectedResult: All 40 rows: the listing's scan cap does not apply to an export (FR-011) + */ + @Test + public void test_noTextFilter_ignoresTheScanCap() throws Exception { + final Map settings = new LinkedHashMap<>(); + settings.put(BrowserAPIImpl.BROWSER_DB_MAX_SCAN_ROWS_KEY, 15); + settings.put(BrowserAPIImpl.BROWSER_CONTENT_CHUNK_SIZE_KEY, 7); + withSettings(settings, () -> { + final ExportCandidates candidates = + export(new BrowserAPIImpl(), siteRequest(bulkType).build(), NO_LIMIT); + + assertFalse(candidates.overLimit()); + assertEquals(inodesOf(bulk), inodes(candidates)); + }); + } + + /** + * Method to test: {@link BrowserAPI#getContentForExport(BrowserQuery, int)} + * Given Scenario: (b) A text filter, with the scan rows and the chunk sizes lowered so the + * candidates span many chunks and exceed the listing's scan cap + * ExpectedResult: Exactly the rows the listing matches when it runs unbudgeted (US1 #11) + */ + @Test + public void test_textFilter_matchesTheListingAcrossChunks() throws Exception { + final DriveRequestForm request = siteRequest(mixedType) + .filters(QueryFilters.builder().text("needle").build()).build(); + final Set listing = listingInodes(request); + assertTrue("fixture: the text must match the site-root item", + listing.contains(atSiteRoot.getInode())); + assertFalse("fixture: the text must not match every row", listing.contains(draft.getInode())); + + final Map settings = new LinkedHashMap<>(); + settings.put(BrowserAPIImpl.BROWSER_DB_MAX_SCAN_ROWS_KEY, 2); + settings.put(BrowserAPIImpl.BROWSER_CONTENT_CHUNK_SIZE_KEY, 2); + settings.put(BrowserAPIImpl.BROWSER_SINGLE_PASS_CHUNK_SIZE_KEY, 2); + settings.put(BrowserAPIImpl.BROWSER_DB_MAX_SCAN_TIME_MILLIS_KEY, 1L); + withSettings(settings, () -> { + final ExportCandidates candidates = export(new BrowserAPIImpl(), request, NO_LIMIT); + assertEquals(listing, inodes(candidates)); + }); + } + + /** + * Method to test: {@link BrowserAPI#getContentForExport(BrowserQuery, int)} + * Given Scenario: (c) A contentlet published and then edited, so it has a live version and a + * newer working one + * ExpectedResult: One row for it, carrying the working inode (FR-017) + */ + @Test + public void test_publishedThenEdited_givesOneWorkingRow() throws Exception { + final ExportCandidates candidates = + export(APILocator.getBrowserAPI(), siteRequest(mixedType).build(), NO_LIMIT); + + final List rows = candidates.rows().stream() + .filter(row -> row.identifier().equals(publishedThenEdited.getIdentifier())) + .collect(Collectors.toList()); + assertEquals(1, rows.size()); + assertEquals(publishedThenEdited.getInode(), rows.get(0).inode()); + } + + /** + * Method to test: {@link BrowserAPI#getContentForExport(BrowserQuery, int)} + * Given Scenario: (d) Each listing filter on its own: language, workflow scheme, workflow step, + * each status, archived, and each System Host mode + * ExpectedResult: The same rows as the listing every time + */ + @Test + public void test_listingFilters_giveTheListingRows() throws Exception { + assertSameRowsAsListing("language", siteRequest(mixedType) + .language(List.of(String.valueOf(secondLanguage.getId()))).build()); + assertSameRowsAsListing("workflow scheme", siteRequest(mixedType) + .workflow(List.of(WorkflowFilterForm.builder().scheme(scheme.getId()).build())) + .build()); + assertSameRowsAsListing("workflow step", siteRequest(mixedType) + .workflow(List.of(WorkflowFilterForm.builder().scheme(scheme.getId()) + .step(stepOne.getId()).build())) + .build()); + assertSameRowsAsListing("status ARCHIVED", + siteRequest(mixedType).status(List.of("ARCHIVED")).build()); + assertSameRowsAsListing("status UNPUBLISHED", + siteRequest(mixedType).status(List.of("UNPUBLISHED")).build()); + assertSameRowsAsListing("status LOCKED", + siteRequest(mixedType).status(List.of("LOCKED")).build()); + assertSameRowsAsListing("archived", siteRequest(mixedType).archived(true).build()); + assertSameRowsAsListing("System Host INCLUDE", + siteRequest(mixedType).includeSystemHost(true).build()); + assertSameRowsAsListing("System Host EXCLUDE", + siteRequest(mixedType).includeSystemHost(false).build()); + assertSameRowsAsListing("System Host ONLY", + siteRequest(mixedType).browseScope(BrowseScope.SYSTEM_HOST).build()); + + assertTrue("fixture: System Host content is listed with INCLUDE", + listingInodes(siteRequest(mixedType).build()).contains(inSystemHost.getInode())); + assertTrue("fixture: archived content is listed when asked for", + listingInodes(siteRequest(mixedType).archived(true).build()) + .contains(archived.getInode())); + } + + /** + * Method to test: {@link BrowserAPI#getContentForExport(BrowserQuery, int)} + * Given Scenario: (e) A Tag field criterion, which the database resolves, and a Category field + * criterion, which the index resolves + * ExpectedResult: The same rows as the listing for each + */ + @Test + public void test_fieldCriteria_giveTheListingRows() throws Exception { + assertSameRowsAsListing("tag", siteRequest(mixedType) + .userSearchable(Map.of("labels", List.of("red"))).build()); + assertSameRowsAsListing("category", siteRequest(mixedType) + .userSearchable(Map.of("cats", List.of(categoryOne.getInode()))).build()); + } + + /** + * Method to test: {@link BrowserAPI#getContentForExport(BrowserQuery, int)} + * Given Scenario: (f) 6 readable rows, with a limit of 5 and then of 6 + * ExpectedResult: Over the limit at 5; all 6 rows and not over the limit at 6 + */ + @Test + public void test_limit_flagsOverLimit() throws Exception { + final DriveRequestForm request = siteRequest(sixType).build(); + + assertTrue(export(APILocator.getBrowserAPI(), request, 5).overLimit()); + + final ExportCandidates atLimit = export(APILocator.getBrowserAPI(), request, 6); + assertFalse(atLimit.overLimit()); + assertEquals(6, atLimit.rows().size()); + } + + /** + * Method to test: {@link BrowserAPI#getContentForExport(BrowserQuery, int)} + * Given Scenario: (g) Rows in two languages and several identifiers + * ExpectedResult: Ordered by identifier, then language + */ + @Test + public void test_rows_areOrderedByIdentifierThenLanguage() throws Exception { + final ExportCandidates candidates = + export(APILocator.getBrowserAPI(), siteRequest(mixedType).build(), NO_LIMIT); + assertTrue("fixture: both languages of one identifier are exported", + inodes(candidates).containsAll(Set.of(live.getInode(), + liveSecondLanguage.getInode()))); + + final List sorted = new ArrayList<>(candidates.rows()); + sorted.sort(Comparator.comparing(ExportRow::identifier) + .thenComparingLong(ExportRow::languageId)); + assertEquals(sorted, candidates.rows()); + } + + /** + * Method to test: {@link BrowserAPI#getContentForExport(BrowserQuery, int)} + * Given Scenario: (h) The whole site, every base type, with a Form entry on it, and the whole of + * System Host, where every site lives + * ExpectedResult: No Form entry and no Host row is ever returned (FR-007) + */ + @Test + public void test_formsAndHosts_areNeverReturned() throws Exception { + final ContentType hostType = APILocator.getContentTypeAPI(systemUser) + .find(Host.HOST_VELOCITY_VAR_NAME); + final DriveRequestForm wholeSite = DriveRequestForm.builder() + .assetPath("//" + site.getHostname() + "/") + .browseScope(BrowseScope.ALL).includeSystemHost(true) + .language(List.of(String.valueOf(defaultLanguage.getId()))) + .showFolders(false).live(false).archived(false).build(); + + final ExportCandidates candidates = export(APILocator.getBrowserAPI(), wholeSite, NO_LIMIT); + + assertTrue("fixture: the site's other content is exported", + inodes(candidates).contains(atSiteRoot.getInode())); + assertFalse("a Form entry is never exported", + inodes(candidates).contains(formEntry.getInode())); + for (final ExportRow row : candidates.rows()) { + assertFalse("no Host row: " + row, hostType.id().equals(row.contentTypeId())); + assertFalse("no Form row: " + row, formType.id().equals(row.contentTypeId())); + } + } +} diff --git a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java new file mode 100644 index 000000000000..2c8bd3d1ca3f --- /dev/null +++ b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java @@ -0,0 +1,484 @@ +package com.dotcms.rest.api.v1.drive; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +import com.dotcms.IntegrationTestBase; +import com.dotcms.browser.BrowserAPIImpl.PaginatedContents; +import com.dotcms.contenttype.model.field.HostFolderField; +import com.dotcms.contenttype.model.field.TextField; +import com.dotcms.contenttype.model.type.BaseContentType; +import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.datagen.ContentTypeDataGen; +import com.dotcms.datagen.ContentletDataGen; +import com.dotcms.datagen.FieldDataGen; +import com.dotcms.datagen.FolderDataGen; +import com.dotcms.datagen.LanguageDataGen; +import com.dotcms.datagen.RoleDataGen; +import com.dotcms.datagen.SiteDataGen; +import com.dotcms.datagen.UserDataGen; +import com.dotcms.datagen.WorkflowDataGen; +import com.dotcms.mock.request.MockAttributeRequest; +import com.dotcms.mock.request.MockHttpRequestIntegrationTest; +import com.dotcms.rest.ErrorEntity; +import com.dotcms.rest.ResponseEntityView; +import com.dotcms.rest.api.v1.drive.export.DriveExportRequestForm; +import com.dotcms.rest.api.v1.drive.export.ExportFileBuilder; +import com.dotcms.rest.api.v1.drive.export.ExportFileNames; +import com.dotcms.util.IntegrationTestInitService; +import com.dotmarketing.beans.Host; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.folders.model.Folder; +import com.dotmarketing.portlets.languagesmanager.model.Language; +import com.dotmarketing.portlets.workflows.model.WorkflowScheme; +import com.dotmarketing.util.ConfigUtils; +import com.liferay.portal.model.User; +import com.liferay.portal.util.WebKeys; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.StreamingOutput; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Integration tests for {@code POST /api/v1/drive/export} in filter mode + * ({@link ContentDriveResource#export}): nothing selected, the listing filtered to one content + * type, one CSV with everything the listing shows (User Story 1; FR-001, FR-004, FR-005, FR-016, + * FR-026, FR-034). + *

+ * Every row check compares the CSV with the listing for the same request, paged to the end, as + * identifier and language pairs. + */ +public class ContentDriveExportFilterModeTest extends IntegrationTestBase { + + private static final String ONE_TYPE = "Choose exactly one content type you can read to export."; + private static final String FORMS_AND_SITES = "Forms and sites can't be exported."; + private static final int MAX_PAGES = 200; + + /** + * Created in {@link #prepare()}: building it reaches the index API, which only exists once the + * test environment is initialized. + */ + private static ContentDriveHelper helper; + private static User systemUser; + private static User limitedUser; + + private static Host site; + private static Folder folder; + private static Folder subFolder; + private static Language defaultLanguage; + private static Language secondLanguage; + private static WorkflowScheme scheme; + + private static ContentType blog; + private static ContentType otherType; + private static ContentType formType; + + private static Contentlet inFolder; + private static Contentlet inSubFolder; + private static Contentlet atSiteRoot; + private static Contentlet inSystemHost; + + @BeforeClass + public static void prepare() throws Exception { + IntegrationTestInitService.getInstance().init(); + helper = ContentDriveHelper.newInstance(); + systemUser = APILocator.systemUser(); + + final String unique = String.valueOf(System.currentTimeMillis()); + site = new SiteDataGen().name("drive-export-" + unique + ".local").nextPersisted(); + folder = new FolderDataGen().site(site).name("blog-" + unique).nextPersisted(); + subFolder = new FolderDataGen().parent(folder).name("sub-" + unique).nextPersisted(); + defaultLanguage = APILocator.getLanguageAPI().getDefaultLanguage(); + secondLanguage = new LanguageDataGen().nextPersisted(); + scheme = new WorkflowDataGen().name("DriveExportScheme_" + unique) + .nextPersistedWithDefaultStepsAndActions(); + + // FieldDataGen gives every field a text default value; every field here clears it. + blog = new ContentTypeDataGen().host(site).workflowId(scheme.getId()) + .name("Blog" + unique).velocityVarName("driveExportBlog" + unique) + .field(new FieldDataGen().defaultValue(null).type(TextField.class).name("title") + .velocityVarName("title").next()) + .field(new FieldDataGen().defaultValue(null).type(HostFolderField.class) + .name("location").velocityVarName("location").next()) + .nextPersisted(); + otherType = new ContentTypeDataGen().host(site) + .name("Other" + unique).velocityVarName("driveExportOther" + unique) + .field(new FieldDataGen().defaultValue(null).type(TextField.class).name("title") + .velocityVarName("title").next()) + .nextPersisted(); + formType = new ContentTypeDataGen().baseContentType(BaseContentType.FORM).host(site) + .name("DriveExportForm" + unique).velocityVarName("driveExportForm" + unique) + .nextPersisted(); + + inFolder = ContentletDataGen.publish(blogEntry(folder, "summer needle")); + final Contentlet secondLanguageDraft = ContentletDataGen.checkout(inFolder); + secondLanguageDraft.setLanguageId(secondLanguage.getId()); + ContentletDataGen.checkin(secondLanguageDraft); + blogEntry(folder, "winter draft"); + final Contentlet archived = ContentletDataGen.publish(blogEntry(folder, "archived needle")); + ContentletDataGen.archive(archived); + inSubFolder = blogEntry(subFolder, "nested needle"); + atSiteRoot = blogEntry(null, "root entry"); + inSystemHost = new ContentletDataGen(blog).host(APILocator.systemHost()) + .languageId(defaultLanguage.getId()).setProperty("title", "shared needle") + .nextPersisted(); + new ContentletDataGen(otherType).host(site).folder(folder).setProperty("title", "other") + .nextPersisted(); + + // A back-end user (Drive users are) who can read none of this site's content types. + limitedUser = new UserDataGen().roles(new RoleDataGen().nextPersisted(), + APILocator.getRoleAPI().loadBackEndUserRole()).nextPersisted(); + } + + private static Contentlet blogEntry(final Folder target, final String title) { + final ContentletDataGen dataGen = new ContentletDataGen(blog).host(site) + .languageId(defaultLanguage.getId()).setProperty("title", title); + if (target != null) { + dataGen.folder(target); + } + return dataGen.nextPersisted(); + } + + // --------------------------------------------------------------------------------------------- + // helpers + // --------------------------------------------------------------------------------------------- + + private static String sitePath() { + return "//" + site.getHostname() + "/"; + } + + private static String folderPath() { + return "//" + site.getHostname() + folder.getPath(); + } + + /** A listing request for Blog in both languages, the way the Drive sends it. */ + private static DriveRequestForm.Builder query(final String assetPath) { + return DriveRequestForm.builder() + .assetPath(assetPath) + .language(List.of(String.valueOf(defaultLanguage.getId()), + String.valueOf(secondLanguage.getId()))) + .contentTypes(List.of(blog.variable())) + .showFolders(false) + .live(false) + .archived(false) + .maxResults(5); + } + + private static HttpServletRequest requestAs(final User user) { + final HttpServletRequest request = new MockAttributeRequest( + new MockHttpRequestIntegrationTest("localhost", "/api/v1/drive/export").request()) + .request(); + request.setAttribute(WebKeys.USER, user); + return request; + } + + private static Response export(final DriveRequestForm query, final User user) { + return new ContentDriveResource().export(requestAs(user), mock(HttpServletResponse.class), + DriveExportRequestForm.builder().query(query).build()); + } + + private static Response export(final DriveRequestForm query) { + return export(query, systemUser); + } + + private static String header(final Response response, final String name) { + final Object value = response.getMetadata().getFirst(name); + return value == null ? null : value.toString(); + } + + private static byte[] body(final Response response) throws Exception { + assertTrue("the body is streamed", response.getEntity() instanceof StreamingOutput); + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + ((StreamingOutput) response.getEntity()).write(out); + return out.toByteArray(); + } + + private static String errorMessage(final Response response) { + assertTrue("the error body is a ResponseEntityView", + response.getEntity() instanceof ResponseEntityView); + final List errors = ((ResponseEntityView) response.getEntity()).getErrors(); + assertNotNull(errors); + assertFalse(errors.isEmpty()); + return errors.get(0).getMessage(); + } + + /** {@code identifier|languageCode|countryCode} of every data row of a CSV. */ + private static Set csvKeys(final String csv) { + final List> rows = parseCsv(csv); + return rows.subList(1, rows.size()).stream() + .map(row -> row.get(0) + "|" + row.get(1) + "|" + row.get(2)) + .collect(Collectors.toSet()); + } + + /** The same keys for every row the listing shows for a request, every page. */ + private static Set listingKeys(final DriveRequestForm request) throws Exception { + final Map languages = new HashMap<>(); + final Set keys = new HashSet<>(); + int cursor = 0; + for (int page = 1; page <= MAX_PAGES; page++) { + final PaginatedContents result = helper.driveSearch( + DriveRequestForm.builder().from(request).showFolders(false).live(false) + .offset(0).contentCursor(cursor).build(), systemUser); + for (final Map item : result.list) { + final Contentlet contentlet = APILocator.getContentletAPI() + .find((String) item.get("inode"), systemUser, false); + final Language language = languages.computeIfAbsent(contentlet.getLanguageId(), + id -> APILocator.getLanguageAPI().getLanguage(id)); + keys.add(contentlet.getIdentifier() + "|" + language.getLanguageCode() + "|" + + language.getCountryCode()); + } + if (!result.hasMoreContent) { + return keys; + } + cursor = result.nextContentCursor; + } + throw new AssertionError("The listing did not end after " + MAX_PAGES + " pages"); + } + + private static String keyOf(final Contentlet contentlet) { + final Language language = APILocator.getLanguageAPI().getLanguage(contentlet.getLanguageId()); + return contentlet.getIdentifier() + "|" + language.getLanguageCode() + "|" + + language.getCountryCode(); + } + + /** + * Exports a request and asserts the CSV holds exactly the listing's rows, and that the listing + * is not empty, so the comparison cannot pass vacuously. + * + * @return the CSV's keys + */ + private static Set assertSameRowsAsListing(final String label, + final DriveRequestForm request) throws Exception { + final Set listing = listingKeys(request); + assertFalse(label + ": the listing must show rows, or the comparison proves nothing", + listing.isEmpty()); + final Response response = export(request); + assertEquals(label, 200, response.getStatus()); + final Set exported = csvKeys(new String(body(response), StandardCharsets.UTF_8)); + assertEquals(label, listing, exported); + return exported; + } + + private static Set exportDirectoryFiles() throws Exception { + final Path directory = Path.of(ConfigUtils.getAssetTempPath(), ExportFileBuilder.DIRECTORY_NAME); + if (!Files.exists(directory)) { + return Set.of(); + } + try (Stream files = Files.list(directory)) { + return files.collect(Collectors.toSet()); + } + } + + /** Parses the Content Search CSV format: CRLF rows, quoted cells with doubled quotes. */ + private static List> parseCsv(final String csv) { + final List> rows = new ArrayList<>(); + List row = new ArrayList<>(); + final StringBuilder cell = new StringBuilder(); + boolean quoted = false; + for (int i = 0; i < csv.length(); i++) { + final char c = csv.charAt(i); + if (quoted) { + if (c == '"' && i + 1 < csv.length() && csv.charAt(i + 1) == '"') { + cell.append('"'); + i++; + } else if (c == '"') { + quoted = false; + } else { + cell.append(c); + } + } else if (c == '"' && cell.length() == 0) { + quoted = true; + } else if (c == ',') { + row.add(cell.toString()); + cell.setLength(0); + } else if (c == '\r' && i + 1 < csv.length() && csv.charAt(i + 1) == '\n') { + row.add(cell.toString()); + cell.setLength(0); + rows.add(row); + row = new ArrayList<>(); + i++; + } else { + cell.append(c); + } + } + return rows; + } + + // --------------------------------------------------------------------------------------------- + // views + // --------------------------------------------------------------------------------------------- + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: Each Drive view: All Site Content with and without System Host, the site + * root, a folder, and System Host + * ExpectedResult: Exactly the rows the listing shows in that view, every page + */ + @Test + public void test_eachView_exportsTheListingRows() throws Exception { + final Set all = assertSameRowsAsListing("All Site Content with System Host", + query(sitePath()).browseScope(BrowseScope.ALL).includeSystemHost(true).build()); + assertTrue("any depth", all.contains(keyOf(inSubFolder))); + assertTrue("System Host included", all.contains(keyOf(inSystemHost))); + + final Set withoutSystemHost = assertSameRowsAsListing( + "All Site Content without System Host", + query(sitePath()).browseScope(BrowseScope.ALL).includeSystemHost(false).build()); + assertFalse("System Host excluded", withoutSystemHost.contains(keyOf(inSystemHost))); + + final Set root = assertSameRowsAsListing("site root", + query(sitePath()).browseScope(BrowseScope.ROOT).build()); + assertTrue(root.contains(keyOf(atSiteRoot))); + assertFalse("only what sits at the root", root.contains(keyOf(inFolder))); + + final Set inBlogFolder = assertSameRowsAsListing("folder", + query(folderPath()).build()); + assertTrue(inBlogFolder.contains(keyOf(inFolder))); + assertFalse("direct content only", inBlogFolder.contains(keyOf(inSubFolder))); + + final Set systemHost = assertSameRowsAsListing("System Host", + query(sitePath()).browseScope(BrowseScope.SYSTEM_HOST).build()); + assertEquals(Set.of(keyOf(inSystemHost)), systemHost); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: Each listing filter: language, workflow, status, text + * ExpectedResult: The same rows as the listing for each + */ + @Test + public void test_eachFilter_exportsTheListingRows() throws Exception { + final DriveRequestForm.Builder all = query(sitePath()).browseScope(BrowseScope.ALL); + + assertSameRowsAsListing("language", + all.build().withLanguage(List.of(String.valueOf(secondLanguage.getId())))); + assertSameRowsAsListing("workflow", query(sitePath()).browseScope(BrowseScope.ALL) + .workflow(List.of(WorkflowFilterForm.builder().scheme(scheme.getId()).build())) + .build()); + assertSameRowsAsListing("status", query(sitePath()).browseScope(BrowseScope.ALL) + .status(List.of("UNPUBLISHED")).build()); + final Set text = assertSameRowsAsListing("text", + query(sitePath()).browseScope(BrowseScope.ALL) + .filters(QueryFilters.builder().text("needle").build()).build()); + assertFalse("the text filter narrows", text.contains(keyOf(atSiteRoot))); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: A filter-mode export of a folder + * ExpectedResult: 200 with the CSV media type, the Content Search file name, the length of the + * body, the row count and one file; the body starts with the header row and writes the + * host/folder column as a readable location + */ + @Test + public void test_response_headersAndBody() throws Exception { + final Response response = export(query(folderPath()).build()); + + assertEquals(200, response.getStatus()); + final MediaType mediaType = MediaType.valueOf(header(response, "Content-Type")); + assertEquals("text", mediaType.getType()); + assertEquals("csv", mediaType.getSubtype()); + assertEquals("UTF-8", mediaType.getParameters().get("charset").toUpperCase()); + + final String fileName = ExportFileNames.csvName(blog.name(), blog.variable(), new Date()); + assertEquals(ExportFileNames.contentDisposition(fileName), + header(response, "Content-Disposition")); + + final byte[] body = body(response); + assertEquals(String.valueOf(body.length), header(response, "Content-Length")); + + final List> rows = parseCsv(new String(body, StandardCharsets.UTF_8)); + assertEquals(String.valueOf(rows.size() - 1), header(response, "X-Export-Contentlets")); + assertEquals("1", header(response, "X-Export-Files")); + + final List headerRow = rows.get(0); + assertEquals(List.of("Identifier", "languageCode", "countryCode"), headerRow.subList(0, 3)); + assertTrue(headerRow.contains("title")); + final int location = headerRow.indexOf("location"); + for (final List row : rows.subList(1, rows.size())) { + assertEquals("host/folder as a readable location", + "//" + site.getHostname() + folder.getPath(), row.get(location)); + } + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: The same request with the paging, sorting and display fields the export + * ignores: cursor, offset, page size, sort, showFolders, showLinks and live + * ExpectedResult: The same rows as without them + */ + @Test + public void test_ignoredFields_doNotChangeTheRows() throws Exception { + final DriveRequestForm plain = query(sitePath()).browseScope(BrowseScope.ALL).build(); + final Set expected = csvKeys(new String(body(export(plain)), StandardCharsets.UTF_8)); + assertTrue("fixture: the plain export has several rows", expected.size() > 3); + + final DriveRequestForm noisy = DriveRequestForm.builder().from(plain) + .contentCursor(3).offset(2).maxResults(1).sortBy("title:desc") + .showFolders(true).showLinks(true).live(true).build(); + final Response response = export(noisy); + + assertEquals(200, response.getStatus()); + assertEquals(expected, csvKeys(new String(body(response), StandardCharsets.UTF_8))); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: Zero content types, two, a variable that does not exist, and a type the + * limited user cannot read + * ExpectedResult: 400 with the same message every time, and no temp file left behind (FR-004, + * FR-010) + */ + @Test + public void test_notExactlyOneReadableType_isRejectedWithOneMessage() throws Exception { + final Set before = exportDirectoryFiles(); + final Map responses = new LinkedHashMap<>(); + responses.put("zero types", export(query(sitePath()).contentTypes(List.of()).build())); + responses.put("two types", export(query(sitePath()) + .contentTypes(List.of(blog.variable(), otherType.variable())).build())); + responses.put("unknown type", export(query(sitePath()) + .contentTypes(List.of("noSuchType" + System.currentTimeMillis())).build())); + responses.put("unreadable type", export(query(sitePath()).build(), limitedUser)); + + responses.forEach((label, response) -> { + assertEquals(label, 400, response.getStatus()); + assertEquals(label, ONE_TYPE, errorMessage(response)); + }); + assertEquals("no temp file is left", before, exportDirectoryFiles()); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: The listing filtered to a Form type + * ExpectedResult: 400 "Forms and sites can't be exported." (FR-007) + */ + @Test + public void test_formType_isRejected() { + final Response response = export(query(sitePath()) + .contentTypes(List.of(formType.variable())).build()); + + assertEquals(400, response.getStatus()); + assertEquals(FORMS_AND_SITES, errorMessage(response)); + } +} diff --git a/dotcms-postman/src/main/resources/postman/ContentDriveResource.postman_collection.json b/dotcms-postman/src/main/resources/postman/ContentDriveResource.postman_collection.json index 86055ab5f533..83d91a524f44 100644 --- a/dotcms-postman/src/main/resources/postman/ContentDriveResource.postman_collection.json +++ b/dotcms-postman/src/main/resources/postman/ContentDriveResource.postman_collection.json @@ -2739,6 +2739,324 @@ ], "description": "Coverage for the showLinks flag and the link pagination fields on POST /api/v1/drive/search (issue #36991)." }, + { + "name": "Export", + "item": [ + { + "name": "Export - Create Fresh Content Type", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code should be 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "var jsonData = pm.response.json();", + "pm.collectionVariables.set(\"exportContentTypeId\", jsonData.entity[0].id);", + "pm.collectionVariables.set(\"exportContentTypeVar\", jsonData.entity[0].variable);" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{serverURL}}/api/v1/contenttype", + "host": [ + "{{serverURL}}" + ], + "path": [ + "api", + "v1", + "contenttype" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"clazz\": \"com.dotcms.contenttype.model.type.SimpleContentType\",\n \"description\": \"Content Type for Drive Export Tests\",\n \"defaultType\": false,\n \"system\": false,\n \"folder\": \"SYSTEM_FOLDER\",\n \"name\": \"Drive Export Test {{$randomBankAccount}}\",\n \"variable\": \"driveExportTest{{$randomBankAccount}}\",\n \"host\": \"SYSTEM_HOST\",\n \"fixed\": false,\n \"fields\": [\n {\n \"clazz\": \"com.dotcms.contenttype.model.field.TextField\",\n \"indexed\": true,\n \"dataType\": \"TEXT\",\n \"readOnly\": false,\n \"required\": true,\n \"searchable\": true,\n \"listed\": true,\n \"sortOrder\": 1,\n \"unique\": false,\n \"name\": \"Title\",\n \"variable\": \"title\",\n \"fixed\": true\n }\n ],\n \"workflow\": [\n \"d61a59e1-a49c-46f2-a929-db2b4bfa88b2\"\n ]\n}", + "options": { + "raw": { + "language": "json" + } + } + } + }, + "response": [] + }, + { + "name": "Export - Create 3 Contentlets", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code should be 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "var jsonData = pm.response.json();", + "pm.test(\"Three contentlets created\", function () {", + " pm.expect(jsonData.errors.length).to.eql(0);", + " pm.expect(jsonData.entity.results.length).to.eql(3);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{serverURL}}/api/v1/workflow/actions/default/fire/PUBLISH", + "host": [ + "{{serverURL}}" + ], + "path": [ + "api", + "v1", + "workflow", + "actions", + "default", + "fire", + "PUBLISH" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"contentlets\": [\n {\n \"contentType\": \"{{exportContentTypeVar}}\",\n \"title\": \"Export item 1\",\n \"contentHost\": \"{{testSiteId}}\"\n },\n {\n \"contentType\": \"{{exportContentTypeVar}}\",\n \"title\": \"Export item 2\",\n \"contentHost\": \"{{testSiteId}}\"\n },\n {\n \"contentType\": \"{{exportContentTypeVar}}\",\n \"title\": \"Export item 3\",\n \"contentHost\": \"{{testSiteId}}\"\n }\n ]\n}", + "options": { + "raw": { + "language": "json" + } + } + } + }, + "response": [] + }, + { + "name": "Export - Filter Mode Returns One CSV", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code should be 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "pm.test(\"The body is a CSV\", function () {", + " pm.expect(pm.response.headers.get('Content-Type')).to.match(/^text\\/csv/);", + "});", + "", + "pm.test(\"The file is named as Content Search names it\", function () {", + " pm.expect(pm.response.headers.get('Content-Disposition')).to.include('_contents_');", + "});", + "", + "pm.test(\"The counts report 3 rows in 1 file\", function () {", + " pm.expect(pm.response.headers.get('X-Export-Contentlets')).to.eql('3');", + " pm.expect(pm.response.headers.get('X-Export-Files')).to.eql('1');", + "});", + "", + "pm.test(\"The CSV holds the header and 3 rows\", function () {", + " var lines = pm.response.text().split('\\r\\n').filter(function (line) { return line.length > 0; });", + " pm.expect(lines[0].indexOf('Identifier,languageCode,countryCode')).to.eql(0);", + " pm.expect(lines.length).to.eql(4);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{serverURL}}/api/v1/drive/export", + "host": [ + "{{serverURL}}" + ], + "path": [ + "api", + "v1", + "drive", + "export" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"query\": {\n \"assetPath\": \"//{{testSiteName}}/\",\n \"browseScope\": \"ALL\",\n \"contentTypes\": [\n \"{{exportContentTypeVar}}\"\n ]\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + } + }, + "response": [] + }, + { + "name": "Export - Two Content Types Are Rejected", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code should be 400\", function () {", + " pm.response.to.have.status(400);", + "});", + "", + "pm.test(\"The message asks for exactly one readable type\", function () {", + " pm.expect(pm.response.json().errors[0].message).to.eql('Choose exactly one content type you can read to export.');", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{serverURL}}/api/v1/drive/export", + "host": [ + "{{serverURL}}" + ], + "path": [ + "api", + "v1", + "drive", + "export" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"query\": {\n \"assetPath\": \"//{{testSiteName}}/\",\n \"browseScope\": \"ALL\",\n \"contentTypes\": [\n \"{{exportContentTypeVar}}\",\n \"{{testContentTypeVar}}\"\n ]\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + } + }, + "response": [] + }, + { + "name": "Export - Unknown Content Type Is Rejected", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code should be 400\", function () {", + " pm.response.to.have.status(400);", + "});", + "", + "pm.test(\"The message is the same as for two types\", function () {", + " pm.expect(pm.response.json().errors[0].message).to.eql('Choose exactly one content type you can read to export.');", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{serverURL}}/api/v1/drive/export", + "host": [ + "{{serverURL}}" + ], + "path": [ + "api", + "v1", + "drive", + "export" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"query\": {\n \"assetPath\": \"//{{testSiteName}}/\",\n \"browseScope\": \"ALL\",\n \"contentTypes\": [\n \"noSuchDriveExportType\"\n ]\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + } + }, + "response": [] + }, + { + "name": "Export - Delete Fresh Content Type", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code should be 200\", function () {", + " pm.response.to.have.status(200);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "DELETE", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{serverURL}}/api/v1/contenttype/id/{{exportContentTypeId}}", + "host": [ + "{{serverURL}}" + ], + "path": [ + "api", + "v1", + "contenttype", + "id", + "{{exportContentTypeId}}" + ] + } + }, + "response": [] + } + ] + }, { "name": "Cleanup", "item": [ From 60b3ac6957799c71e85f49eb4f6074031718c81d Mon Sep 17 00:00:00 2001 From: ddariod Date: Thu, 26 Nov 2026 19:20:05 -0500 Subject: [PATCH 12/28] feat(content-drive): export everything the listing shows for one content type Adds POST /api/v1/drive/export in filter mode (#37900): with nothing selected and the Drive listing filtered to one content type, Export downloads one CSV with every readable contentlet the listing's query matches, across all pages. - BrowserAPI#getContentForExport reuses the listing's SQL predicates with an export projection, pages by (identifier, language) keyset, narrows each chunk through the index when the query needs it, filters readable rows, and stops past CONTENT_DRIVE_EXPORT_MAX_ROWS. The listing SQL is unchanged. - The endpoint is documented in OpenAPI under the new "Content Drive" tag, answers 204 when nothing matches, and returns errors as ResponseEntityView. - The toolbar shows an Export button next to Upload / Add New. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- .../dot-content-drive-export.service.ts | 79 +++++- ...content-drive-export-button.component.html | 10 +- ...tent-drive-export-button.component.spec.ts | 3 + ...t-content-drive-export-button.component.ts | 136 ++++++++- .../dot-content-drive-toolbar.component.html | 5 + .../dot-content-drive-toolbar.component.ts | 2 + .../com/dotcms/browser/BrowserAPIImpl.java | 126 ++++++++- .../api/v1/drive/ContentDriveResource.java | 130 ++++++++- .../export/ContentDriveExportHelper.java | 165 ++++++++++- .../rest/config/DotRestApplication.java | 1 + .../WEB-INF/messages/Language.properties | 3 + .../main/webapp/WEB-INF/openapi/openapi.yaml | 262 ++++++++++++++++++ .../ContentDriveExportFilterModeTest.java | 31 ++- 13 files changed, 920 insertions(+), 33 deletions(-) diff --git a/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts b/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts index 14c8690b597a..b5c324a04065 100644 --- a/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts +++ b/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts @@ -1,9 +1,15 @@ -import { EMPTY, Observable } from 'rxjs'; +import { Observable } from 'rxjs'; -import { Injectable } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http'; +import { inject, Injectable } from '@angular/core'; + +import { map } from 'rxjs/operators'; import { DotContentDriveSearchRequest } from '@dotcms/dotcms-models'; +/** The endpoint that builds the export file. */ +const EXPORT_URL = '/api/v1/drive/export'; + /** * Body of `POST /api/v1/drive/export` in filter mode: the same request the listing sends to * `/api/v1/drive/search`. The server ignores its paging, sorting and folder flags. @@ -41,16 +47,73 @@ export type DotContentDriveExportResult = DotContentDriveExportFile | DotContent providedIn: 'root' }) export class DotContentDriveExportService { + readonly #http = inject(HttpClient); + /** * Asks the server to build the export file for the given request. * - * Not implemented yet (compile-only stub for the TDD Red step): it completes without a value - * and sends no request. + * The whole response is read as a blob, so the file name and the counts can be taken from its + * headers. A 204 (nothing readable matched) resolves to `{ kind: 'empty' }`. * - * @param _body The export request, carrying the listing query in filter mode. - * @returns The file and its counts once the server has built it. + * @param body The export request, carrying the listing query in filter mode. + * @returns The file and its counts once the server has built it, or `empty` when there is none. */ - export(_body: DotContentDriveExportRequest): Observable { - return EMPTY; + export(body: DotContentDriveExportRequest): Observable { + return this.#http + .post(EXPORT_URL, body, { observe: 'response', responseType: 'blob' }) + .pipe(map((response) => toExportResult(response))); + } +} + +/** + * Turns the HTTP response into an export result: `empty` for a 204 or a missing body, otherwise + * the file with the name and counts its headers carry. + */ +function toExportResult(response: HttpResponse): DotContentDriveExportResult { + if (response.status === 204 || !response.body) { + return { kind: 'empty' }; } + + const headers = response.headers; + + return { + kind: 'file', + blob: response.body, + fileName: parseFileName(headers.get('Content-Disposition')), + contentlets: readCount(headers, 'X-Export-Contentlets'), + files: readCount(headers, 'X-Export-Files') + }; +} + +/** + * Reads the file name out of a `Content-Disposition` header. + * + * The RFC 5987 `filename*=UTF-8''…` parameter wins, percent-decoded, because it carries names + * that are not ASCII; otherwise the plain `filename` is used without its quotes. Returns an empty + * string when the header is missing or names no file, which `getDownloadLink` still accepts. + */ +function parseFileName(header: string | null): string { + if (!header) { + return ''; + } + + const extended = header.match(/filename\*\s*=\s*(?:[\w-]+)?'[^']*'([^;]+)/i); + if (extended) { + try { + return decodeURIComponent(extended[1].trim()); + } catch { + // A malformed escape: fall back to the plain parameter below. + } + } + + const plain = header.match(/filename\s*=\s*("([^"]*)"|[^;]+)/i); + + return plain ? (plain[2] ?? plain[1]).trim() : ''; +} + +/** Reads a count header as a number; a missing or unparseable header counts as zero. */ +function readCount(headers: HttpHeaders, name: string): number { + const value = Number(headers.get(name)); + + return Number.isFinite(value) ? value : 0; } diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.html b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.html index b84b9e3d2965..3f665f56fbcd 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.html +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.html @@ -1 +1,9 @@ - +@if ($filterModeVisible()) { + +} diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts index f5bc65d5836a..ca689adf9cc7 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts @@ -161,6 +161,9 @@ describe('DotContentDriveExportButtonComponent (filter mode)', () => { (getDownloadLink as Mock).mockReturnValue({ click: anchorClick }); spectator = createComponent(); exportService = spectator.inject(DotContentDriveExportService); + // The mock is shared by every test and clearAllMocks keeps a return value a test set, so + // reset it here: otherwise the "while running" Subject leaks into the tests after it. + exportService.export.mockReturnValue(of(FILE_RESULT)); contentTypeService = spectator.inject(DotContentTypeService); }); diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts index 72a26f694720..b71133bb47c8 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts @@ -1,15 +1,137 @@ -import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { Component, computed, inject, signal } from '@angular/core'; +import { rxResource } from '@angular/core/rxjs-interop'; + +import { MessageService } from 'primeng/api'; +import { ButtonModule } from 'primeng/button'; + +import { finalize } from 'rxjs/operators'; + +import { + DotContentDriveExportService, + DotContentTypeService, + DotMessageService +} from '@dotcms/data-access'; +import { DotCMSBaseTypesContentTypes } from '@dotcms/dotcms-models'; +import { DotMessagePipe } from '@dotcms/ui'; +import { getDownloadLink } from '@dotcms/utils'; + +import { SUCCESS_MESSAGE_LIFE } from '../../../../shared/constants'; +import { DotContentDriveStatus } from '../../../../shared/models'; +import { DotContentDriveStore } from '../../../../store/dot-content-drive.store'; +import { isFolder } from '../../../../utils/functions'; /** * The toolbar's Export button: downloads the listing as a CSV when it is filtered to one content - * type and nothing is selected. + * type and nothing is selected (filter mode). * - * Compile-only stub for the TDD Red step: it renders nothing yet. The behavior the specs describe - * lands with the implementation. + * It reads the store and keeps its own in-flight state; it adds nothing to the store, which is at + * the `signalStore` feature limit. */ @Component({ selector: 'dot-content-drive-export-button', - templateUrl: './dot-content-drive-export-button.component.html', - changeDetection: ChangeDetectionStrategy.OnPush + imports: [ButtonModule, DotMessagePipe], + templateUrl: './dot-content-drive-export-button.component.html' }) -export class DotContentDriveExportButtonComponent {} +export class DotContentDriveExportButtonComponent { + readonly #store = inject(DotContentDriveStore); + readonly #exportService = inject(DotContentDriveExportService); + readonly #contentTypeService = inject(DotContentTypeService); + readonly #messageService = inject(MessageService); + readonly #dotMessageService = inject(DotMessageService); + + /** True from the click until the export answers, so a second click cannot start another. */ + protected readonly $exporting = signal(false); + + /** The one content type variable the listing is filtered to, or `undefined` for none or many. */ + readonly #filteredVariable = computed(() => { + const contentTypes = this.#store.filters()?.contentType ?? []; + + return contentTypes.length === 1 ? contentTypes[0] : undefined; + }); + + /** + * The filtered type, fetched to rule out Forms: they export through the Forms portlet, not + * here. Nothing is fetched unless exactly one type is filtered. + */ + readonly #contentType = rxResource({ + params: () => this.#filteredVariable(), + stream: ({ params }) => this.#contentTypeService.getContentType(params) + }); + + /** + * Filter mode is offered when nothing is selected and the listing is filtered to exactly one + * type that is not a Form. It stays hidden until that type has been fetched, and while a + * previous type's answer is still the one held. + */ + protected readonly $filterModeVisible = computed(() => { + const variable = this.#filteredVariable(); + + if (this.#store.selectedItems().length > 0 || !variable || !this.#contentType.hasValue()) { + return false; + } + + const contentType = this.#contentType.value(); + + return ( + contentType.variable === variable && + contentType.baseType !== DotCMSBaseTypesContentTypes.FORM + ); + }); + + /** + * Disabled while an export runs, and when the loaded listing has nothing to export: it holds no + * contentlet and no loaded page reports more content. A listing still loading keeps it enabled, + * since its items are not known yet. + */ + protected readonly $filterModeDisabled = computed(() => { + if (this.$exporting()) { + return true; + } + + if (this.#store.status() !== DotContentDriveStatus.LOADED) { + return false; + } + + const hasContentlet = this.#store.items().some((item) => !isFolder(item)); + const hasMoreContent = this.#store.pages().some((page) => page.hasMoreContent); + + return !hasContentlet && !hasMoreContent; + }); + + /** + * Exports the listing request the store holds and downloads the file under the name the server + * gave it, then confirms with a toast that carries the number of exported items. + * + * The request is not tied to this component's lifetime: the user may select a row while the + * file is being built, which removes the button, and the download should still arrive. + */ + protected onExport(): void { + if (this.$exporting()) { + return; + } + + this.$exporting.set(true); + + this.#exportService + .export({ query: this.#store.$request() }) + .pipe(finalize(() => this.$exporting.set(false))) + .subscribe((result) => { + if (result.kind !== 'file') { + return; + } + + getDownloadLink(result.blob, result.fileName).click(); + + this.#messageService.add({ + severity: 'success', + summary: this.#dotMessageService.get('content-drive.toast.export-success'), + detail: this.#dotMessageService.get( + 'content-drive.toast.export-success-detail', + String(result.contentlets), + String(result.files) + ), + life: SUCCESS_MESSAGE_LIFE + }); + }); + } +} diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.html b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.html index 8e915f68a3ed..daa80f022d22 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.html +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.html @@ -73,6 +73,11 @@ (click)="menu.toggle($event)" #button /> + + + } @if ($displayActions()) { diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.ts index bfb6bf7fbbd9..5f428b61145e 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.ts @@ -38,6 +38,7 @@ import { DotUploadButtonComponent } from '@dotcms/ui'; +import { DotContentDriveExportButtonComponent } from './components/dot-content-drive-export-button/dot-content-drive-export-button.component'; import { DotContentDriveSearchInputComponent } from './components/dot-content-drive-search-input/dot-content-drive-search-input.component'; import { DotContentDriveTreeTogglerComponent } from './components/dot-content-drive-tree-toggler/dot-content-drive-tree-toggler.component'; import { DotContentDriveWorkflowActionsComponent } from './components/dot-content-drive-workflow-actions/dot-content-drive-workflow-actions.component'; @@ -121,6 +122,7 @@ interface ToolbarAnimationState { DotMessagePipe, DotUploadButtonComponent, DotContentDriveTreeTogglerComponent, + DotContentDriveExportButtonComponent, DotContentTypeFilterChipComponent, DotContentDriveSearchInputComponent, DotLanguageFilterChipComponent, diff --git a/dotCMS/src/main/java/com/dotcms/browser/BrowserAPIImpl.java b/dotCMS/src/main/java/com/dotcms/browser/BrowserAPIImpl.java index c346bab047c2..e7c62e3223a4 100644 --- a/dotCMS/src/main/java/com/dotcms/browser/BrowserAPIImpl.java +++ b/dotCMS/src/main/java/com/dotcms/browser/BrowserAPIImpl.java @@ -86,6 +86,7 @@ import java.util.Date; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; @@ -2640,7 +2641,77 @@ public Map getFolderContent(final BrowserQuery browserQuery) thr @Override public ExportCandidates getContentForExport(final BrowserQuery browserQuery, final int maxRows) throws DotSecurityException, DotDataException { - throw new UnsupportedOperationException("not implemented"); + // The listing's budgets (scan rows, scan time, heuristic) are deliberately not read here: + // an export must hold every matching row, not as many as a page can afford (FR-011). + final SelectQuery sqlQuery = selectQuery(browserQuery, Projection.EXPORT); + final boolean narrowThroughIndex = isUseElasticSearchForFiltering(browserQuery); + final int chunkSize = Math.max(1, + Config.getIntProperty(BROWSER_CONTENT_CHUNK_SIZE_KEY, BROWSER_CONTENT_CHUNK_SIZE_DEFAULT)); + final ReadableRowFilter readableRowFilter = new ReadableRowFilter(); + + final Map rows = new LinkedHashMap<>(); + ExportRow last = null; + while (true) { + final List chunk = readExportChunk(sqlQuery, last, chunkSize); + if (chunk.isEmpty()) { + break; + } + last = chunk.get(chunk.size() - 1); + + List candidates = chunk; + if (narrowThroughIndex) { + final Set matched = processESDirectly(browserQuery, + chunk.stream().map(ExportRow::inode) + .collect(Collectors.toCollection(LinkedHashSet::new))); + candidates = chunk.stream().filter(row -> matched.contains(row.inode())) + .collect(Collectors.toList()); + } + for (final ExportRow row : readableRowFilter.filter(candidates, browserQuery.user)) { + rows.putIfAbsent(row.key(), row); + if (rows.size() > maxRows) { + return new ExportCandidates(new ArrayList<>(rows.values()), true); + } + } + if (chunk.size() < chunkSize) { + break; + } + } + return new ExportCandidates(new ArrayList<>(rows.values()), false); + } + + /** + * Reads the next chunk of export rows in {@code (identifier, language)} order, starting right + * after {@code after}. Keyset paging keeps every chunk as cheap as the first, however deep + * the export goes. + * + * @param sqlQuery the export select, built with {@link Projection#EXPORT} + * @param after the last row of the previous chunk, or {@code null} for the first chunk + * @param chunkSize the most rows to read + * @return the rows, in order + * @throws DotDataException if the query fails + */ + private static List readExportChunk(final SelectQuery sqlQuery, final ExportRow after, + final int chunkSize) throws DotDataException { + final StringBuilder sql = new StringBuilder(sqlQuery.selectQuery); + if (after != null) { + sql.append(" and (cvi.identifier, cvi.lang) > (?, ?) "); + } + sql.append(" order by cvi.identifier, cvi.lang limit ?"); + + final DotConnect dotConnect = new DotConnect().setSQL(sql.toString()); + sqlQuery.params.forEach(dotConnect::addParam); + if (after != null) { + dotConnect.addParam(after.identifier()); + dotConnect.addParam(after.languageId()); + } + dotConnect.addParam(chunkSize); + + final List chunk = new ArrayList<>(); + for (final Map row : dotConnect.loadObjectResults()) { + chunk.add(new ExportRow((String) row.get("inode"), (String) row.get("identifier"), + ((Number) row.get("lang")).longValue(), (String) row.get("structure_inode"))); + } + return chunk; } @Override @@ -2962,6 +3033,35 @@ private List> filterReturnList(final BrowserQuery browserQue * @return The {@link SelectQuery} object containing the select query string and its bound parameters. */ private SelectQuery selectQuery(final BrowserQuery browserQuery) { + return selectQuery(browserQuery, Projection.LISTING); + } + + /** + * What a select built by {@link #selectQuery(BrowserQuery, Projection)} returns. The WHERE + * clause is the same for both; only the selected columns, the ORDER BY and the export's + * exclusions differ. + */ + enum Projection { + /** The listing: one {@code inode} column, ordered as the request asks. */ + LISTING, + /** + * A Content Drive export: the working inode, identifier, language and content type of each + * row, with no ORDER BY (the caller adds its keyset order) and Form and Host content + * excluded. + */ + EXPORT + } + + /** + * Builds the SQL select for a {@link BrowserQuery} with the given projection. The structural + * predicates — site, folder, scope, languages, types, workflow, status, filters — are shared, + * so an export reads exactly the rows the listing reads. + * + * @param browserQuery The filtering criteria set via the {@link BrowserQuery}. + * @param projection What the select returns. + * @return The {@link SelectQuery} object containing the select query string and its bound parameters. + */ + private SelectQuery selectQuery(final BrowserQuery browserQuery, final Projection projection) { final String workingLiveInode = browserQuery.showWorking || browserQuery.showArchived ? "working_inode" : "live_inode"; @@ -3012,7 +3112,7 @@ private SelectQuery selectQuery(final BrowserQuery browserQuery) { } final StringBuilder selectQuery = new StringBuilder( - buildSelectBaseQuery(browserQuery, workingLiveInode, candidatesCte)); + buildSelectBaseQuery(browserQuery, workingLiveInode, candidatesCte, projection)); if (!browserQuery.languageIds.isEmpty()) { appendLanguageQuery(selectQuery, browserQuery.languageIds, @@ -3090,7 +3190,7 @@ private SelectQuery selectQuery(final BrowserQuery browserQuery) { if (UtilMethods.isSet(browserQuery.mimeTypes)) { appendMIMETypeQuery(selectQuery, browserQuery.mimeTypes, parameters); } - if (null != browserQuery.sortBy) { + if (Projection.LISTING == projection && null != browserQuery.sortBy) { appendOrderByQuery(selectQuery, browserQuery.sortByDesc, useFolderCte); } @@ -3123,10 +3223,11 @@ static class SelectQuery { * {@code contentlet} -- see {@link #selectQuery(BrowserQuery)}. When * blank, the query joins directly against {@code identifier} exactly * as before this fix (every non-folder-scoped caller is unaffected). + * @param projection What the select returns; see {@link Projection}. * @return The base SQL SELECT query string. */ private String buildSelectBaseQuery(final BrowserQuery browserQuery, final String workingLiveInode, - final String candidatesCte) { + final String candidatesCte, final Projection projection) { final String identifierSource = UtilMethods.isSet(candidatesCte) ? "candidates" : "identifier"; @@ -3136,8 +3237,19 @@ private String buildSelectBaseQuery(final BrowserQuery browserQuery, final Strin + " c.inode = cvi." + workingLiveInode + " and cvi.variant_id='" + DEFAULT_VARIANT.name() + "' "; - final StringBuilder baseQuery = new StringBuilder(candidatesCte) - .append("select cvi.").append(workingLiveInode).append(" as inode ").append(baseClause); + final StringBuilder baseQuery = new StringBuilder(candidatesCte); + if (Projection.EXPORT == projection) { + baseQuery.append("select cvi.").append(workingLiveInode).append(" as inode, ") + .append("cvi.identifier as identifier, cvi.lang as lang, ") + .append("struc.inode as structure_inode ").append(baseClause) + // Forms and sites are never exported (FR-007); both are constants, not input + .append(" and struc.structuretype <> ").append(BaseContentType.FORM.getType()) + .append(" and struc.velocity_var_name <> '").append(Host.HOST_VELOCITY_VAR_NAME) + .append("' "); + } else { + baseQuery.append("select cvi.").append(workingLiveInode).append(" as inode ") + .append(baseClause); + } final boolean showAllBaseTypes = browserQuery.baseTypes.contains(BaseContentType.ANY); if (!showAllBaseTypes) { @@ -3753,7 +3865,7 @@ private void appendOrderByQuery(StringBuilder sqlQuery, boolean orderByDesc, boo * * The match on the synthetic value is exact on purpose. A MIME Type that merely starts with it -- say, * {@code application/dotpage-foo} -- must still go through the metadata check. - *

The {@code struc} table is already joined by {@link #buildSelectBaseQuery(BrowserQuery, String)}, so the + *

The {@code struc} table is already joined by {@link #buildSelectBaseQuery(BrowserQuery, String, String, Projection)}, so the * base type condition needs no extra join and no bound parameter. * * @param sqlQuery The main SQL query. diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java index 23f58fab3e46..e226c68892b8 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java @@ -1,10 +1,16 @@ package com.dotcms.rest.api.v1.drive; +import com.dotcms.rest.ErrorEntity; import com.dotcms.rest.InitDataObject; import com.dotcms.rest.ResponseEntityView; import com.dotcms.rest.WebResource; import com.dotcms.rest.annotation.NoCache; +import com.dotcms.rest.api.v1.drive.export.ContentDriveExportHelper; import com.dotcms.rest.api.v1.drive.export.DriveExportRequestForm; +import com.dotcms.rest.api.v1.drive.export.ExportFile; +import com.dotcms.rest.api.v1.drive.export.ExportFileBuilder; +import com.dotcms.rest.api.v1.drive.export.ExportFileNames; +import com.dotcms.rest.exception.HttpStatusCodeException; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.util.Logger; @@ -17,6 +23,8 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import java.nio.file.Files; +import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; @@ -24,6 +32,7 @@ import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.glassfish.jersey.server.JSONP; @@ -36,7 +45,15 @@ @Path("/v1/drive") public class ContentDriveResource { + /** The number of data rows in an export file, over every CSV. */ + static final String EXPORT_CONTENTLETS_HEADER = "X-Export-Contentlets"; + /** The number of CSVs in an export file. */ + static final String EXPORT_FILES_HEADER = "X-Export-Files"; + private static final String EXPORT_FAILED_MESSAGE = + "The export failed. Try again, and contact your administrator if it keeps failing."; + private final ContentDriveHelper helper = ContentDriveHelper.newInstance(); + private final ContentDriveExportHelper exportHelper = new ContentDriveExportHelper(); /** * Search content assets using drive functionality @@ -107,16 +124,67 @@ public Response search(@Context final HttpServletRequest request, } /** - * Exports what the Drive shows, or what is selected in it, as a CSV or a zip of CSVs. - *

- * Not implemented yet: it answers 501. It stays hidden from the OpenAPI document until it is. + * Exports what the Drive shows, or what is selected in it, as a CSV or a zip of CSVs. The + * file is built completely before the first byte is sent, so a failure is an error status and + * never a truncated download. * * @param request the HTTP request * @param response the HTTP response * @param form the export request - * @return 501 Not Implemented + * @return 200 with the file, 204 when nothing readable matched, or 400, 404 or 500 with the + * reason in {@code errors[0].message} */ - @Hidden + @Operation( + operationId = "postDriveExport", + summary = "Export Content Drive content to CSV", + description = "Exports content from Content Drive in the CSV format the Content Search " + + "export writes and the content import reads.\n\n" + + "**Filter mode** (no `selection`): send `query`, the same body the Drive listing " + + "sends to `/api/v1/drive/search`, filtered to exactly one content type. Every " + + "contentlet the listing matches, across all pages, is returned as one CSV. " + + "Paging, sorting, `showFolders`, `showLinks` and `live` are ignored.\n\n" + + "**Selection mode** (`selection` with folders or contentlets, at most 60 in all, " + + "plus `siteId`): the selected contentlets in their selected language and every " + + "contentlet under the selected folders, in every language, as a zip with one CSV " + + "per content type.\n\n" + + "Only the working version of each contentlet is exported, and only what the user " + + "can read. Forms and sites are never exported. More than " + + "`CONTENT_DRIVE_EXPORT_MAX_ROWS` rows (default 100,000) is refused with a 400. " + + "The response headers `X-Export-Contentlets` and `X-Export-Files` give the rows " + + "and the CSVs written.", + tags = {"Content Drive"} + ) + @ApiResponses(value = { + @ApiResponse(responseCode = "200", + description = "The export file: one CSV in filter mode, a zip of CSVs in selection mode", + content = { + @Content(mediaType = "text/csv", + schema = @Schema(type = "string", format = "binary")), + @Content(mediaType = "application/zip", + schema = @Schema(type = "string", format = "binary")) + }), + @ApiResponse(responseCode = "204", + description = "Nothing readable matched the request; no file"), + @ApiResponse(responseCode = "400", + description = "Invalid request: nothing to export, not exactly one readable content " + + "type, a Form or Host type, too many selected items, an invalid entry, " + + "or more rows than the limit", + content = @Content(mediaType = "application/json", + schema = @Schema(type = "object", + description = "Error body: errors[0].message holds the reason"))), + @ApiResponse(responseCode = "401", description = "Unauthorized access", + content = @Content(mediaType = "application/json")), + @ApiResponse(responseCode = "404", + description = "The site or a selected folder was not found", + content = @Content(mediaType = "application/json", + schema = @Schema(type = "object", + description = "Error body: errors[0].message holds the reason"))), + @ApiResponse(responseCode = "500", + description = "The export failed", + content = @Content(mediaType = "application/json", + schema = @Schema(type = "object", + description = "Error body: errors[0].message holds a generic message"))) + }) @Path("/export") @POST @NoCache @@ -124,8 +192,58 @@ public Response search(@Context final HttpServletRequest request, @Produces({"text/csv", "application/zip", MediaType.APPLICATION_JSON}) public Response export(@Context final HttpServletRequest request, @Context final HttpServletResponse response, + @RequestBody(description = "What to export: a listing query (filter mode) or a " + + "selection of folders and contentlets", + required = true, + content = @Content(schema = @Schema(implementation = DriveExportRequestForm.class))) final DriveExportRequestForm form) { - return Response.status(Response.Status.NOT_IMPLEMENTED).build(); + + final InitDataObject initDataObject = new WebResource.InitBuilder() + .requiredBackendUser(true) + .requiredFrontendUser(false) + .requestAndResponse(request, response) + .rejectWhenNoUser(true).init(); + final User user = initDataObject.getUser(); + + try { + final DriveExportRequestForm body = + form == null ? DriveExportRequestForm.builder().build() : form; + final ExportFile file = exportHelper.export(body, user, request); + if (file.contentlets() == 0) { + return Response.noContent().build(); + } + return Response.ok(ExportFileBuilder.toStreamingOutput(file), file.mediaType()) + .header(HttpHeaders.CONTENT_DISPOSITION, + ExportFileNames.contentDisposition(file.fileName())) + .header(HttpHeaders.CONTENT_LENGTH, Files.size(file.path())) + .header(EXPORT_CONTENTLETS_HEADER, file.contentlets()) + .header(EXPORT_FILES_HEADER, file.files()) + .build(); + } catch (final HttpStatusCodeException e) { + return errorResponse(e.getResponse().getStatus(), + e.getResponse().getHeaderString("error-message")); + } catch (final Exception e) { + Logger.error(this, String.format("Content Drive export failed for user '%s': %s", + user.getUserId(), e.getMessage()), e); + return errorResponse(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + EXPORT_FAILED_MESSAGE); + } } + /** + * Builds an export error response in the one shape the Drive reads: + * {@code {"errors":[{"errorCode","message","fieldName":null}],"entity":null}}. + * + * @param status the HTTP status + * @param message the message for the user + * @return the response + */ + private static Response errorResponse(final int status, final String message) { + final Response.Status known = Response.Status.fromStatusCode(status); + final String errorCode = known == null ? String.valueOf(status) : known.name(); + return Response.status(status) + .type(MediaType.APPLICATION_JSON) + .entity(new ResponseEntityView<>(List.of(new ErrorEntity(errorCode, message, null)))) + .build(); + } } diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java index b44c5dea175a..a2cbfb32ef86 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java @@ -1,9 +1,30 @@ package com.dotcms.rest.api.v1.drive.export; +import com.dotcms.browser.BrowserAPI; +import com.dotcms.browser.BrowserQuery; +import com.dotcms.browser.ExportCandidates; +import com.dotcms.browser.ExportRow; +import com.dotcms.contenttype.exception.NotFoundInDbException; +import com.dotcms.contenttype.model.type.BaseContentType; +import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.rest.api.v1.drive.ContentDriveHelper; +import com.dotcms.rest.api.v1.drive.DriveRequestForm; +import com.dotcms.rest.api.v1.drive.export.AbstractDriveExportRequestForm.Mode; +import com.dotcms.rest.exception.BadRequestException; +import com.dotcms.rest.exception.NotFoundException; +import com.dotmarketing.beans.Host; +import com.dotmarketing.business.APILocator; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.util.Config; import com.liferay.portal.model.User; import java.io.IOException; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; /** @@ -15,6 +36,40 @@ */ public class ContentDriveExportHelper { + /** The configuration key of the most rows one export may hold. */ + public static final String MAX_ROWS_KEY = "CONTENT_DRIVE_EXPORT_MAX_ROWS"; + /** The most rows one export may hold when {@link #MAX_ROWS_KEY} is not set. */ + public static final int MAX_ROWS_DEFAULT = 100_000; + + static final String ONE_TYPE_MESSAGE = "Choose exactly one content type you can read to export."; + static final String FORMS_AND_SITES_MESSAGE = "Forms and sites can't be exported."; + static final String FOLDER_NOT_FOUND_MESSAGE = "Folder not found."; + + private final ContentDriveHelper driveHelper; + private final BrowserAPI browserAPI; + private final ExportFileBuilder fileBuilder; + + /** + * Creates a helper that uses the standard dotCMS APIs. + */ + public ContentDriveExportHelper() { + this(ContentDriveHelper.newInstance(), APILocator.getBrowserAPI(), new ExportFileBuilder()); + } + + /** + * Creates a helper with the given collaborators. + * + * @param driveHelper builds the listing query from the request + * @param browserAPI resolves the rows of a query + * @param fileBuilder writes the file + */ + ContentDriveExportHelper(final ContentDriveHelper driveHelper, final BrowserAPI browserAPI, + final ExportFileBuilder fileBuilder) { + this.driveHelper = driveHelper; + this.browserAPI = browserAPI; + this.fileBuilder = fileBuilder; + } + /** * Builds the export a request asks for. * @@ -23,7 +78,8 @@ public class ContentDriveExportHelper { * @param request the HTTP request, used for the download links of binary fields * @return the finished file; when nothing readable matched it reports zero rows and holds no * file - * @throws com.dotcms.rest.exception.BadRequestException when the request is invalid + * @throws BadRequestException when the request is invalid, or matches more rows than the limit + * @throws NotFoundException when the site or folder does not exist or cannot be read * @throws DotDataException if the rows cannot be read or the file cannot be written * @throws DotSecurityException if the user cannot read the site or folder being exported * @throws IOException if the temp file cannot be written @@ -31,6 +87,111 @@ public class ContentDriveExportHelper { public ExportFile export(final DriveExportRequestForm form, final User user, final HttpServletRequest request) throws DotDataException, DotSecurityException, IOException { - throw new UnsupportedOperationException("not implemented"); + if (form.validate() == Mode.FILTER) { + return exportFilter(form.query(), user, request); + } + throw new UnsupportedOperationException("Selection-mode export is not implemented yet"); + } + + /** + * Filter mode: every row the listing shows for the query, as one CSV (research R1–R3). + * + * @param query the listing request + * @param user the {@link User} the export runs as + * @param request the HTTP request + * @return the CSV + * @throws DotDataException if the rows cannot be read + * @throws DotSecurityException if the user cannot read the site or folder + * @throws IOException if the temp file cannot be written + */ + private ExportFile exportFilter(final DriveRequestForm query, final User user, + final HttpServletRequest request) + throws DotDataException, DotSecurityException, IOException { + final ContentType contentType = resolveOneContentType(query, user); + + // Every override goes before build(): build() snapshots the builder + final BrowserQuery browserQuery = listingQueryBuilder(query, user) + .withContentTypes(Set.of(contentType.id())) + .showFolders(false) + .showLinks(false) + .showWorking(true) + .build(); + driveHelper.checkSearchable(browserQuery); + + final int maxRows = Config.getIntProperty(MAX_ROWS_KEY, MAX_ROWS_DEFAULT); + final ExportCandidates candidates = browserAPI.getContentForExport(browserQuery, maxRows); + if (candidates.overLimit()) { + throw new BadRequestException(overLimitMessage(maxRows)); + } + final List inodes = candidates.rows().stream().map(ExportRow::inode) + .collect(Collectors.toList()); + return fileBuilder.buildCsv(contentType, inodes, user, request); + } + + /** + * Builds the listing query for a request. A site or folder in {@code assetPath} that does not + * exist and one the user cannot read give the same 404, so the response never tells which + * applied (FR-014). + * + * @param query the listing request + * @param user the {@link User} the export runs as + * @return the builder, unbuilt + * @throws NotFoundException when the site or folder does not exist or cannot be read + * @throws DotDataException if the query cannot be built for another reason + */ + private BrowserQuery.Builder listingQueryBuilder(final DriveRequestForm query, final User user) + throws DotDataException { + try { + return driveHelper.toBrowserQueryBuilder(query, user); + } catch (final DotSecurityException | NotFoundInDbException | NotFoundException e) { + throw new NotFoundException(FOLDER_NOT_FOUND_MESSAGE); + } + } + + /** + * Resolves the one content type a filter-mode export is for. Zero or several types, a type + * that does not exist and a type the user cannot read all give the same message, so the + * response never tells which applied (FR-004). + * + * @param query the listing request + * @param user the {@link User} the export runs as + * @return the content type + * @throws BadRequestException when there is not exactly one readable type, or it is a Form or + * the Host type + * @throws DotDataException if the content type cannot be read for another reason + */ + private static ContentType resolveOneContentType(final DriveRequestForm query, final User user) + throws DotDataException { + final List requested = query.contentTypes(); + if (requested == null || requested.size() != 1) { + throw new BadRequestException(ONE_TYPE_MESSAGE); + } + final ContentType contentType; + try { + contentType = APILocator.getContentTypeAPI(user).find(requested.get(0)); + } catch (final NotFoundInDbException | DotSecurityException e) { + throw new BadRequestException(ONE_TYPE_MESSAGE); + } + if (contentType == null) { + throw new BadRequestException(ONE_TYPE_MESSAGE); + } + if (BaseContentType.FORM == contentType.baseType() + || Host.HOST_VELOCITY_VAR_NAME.equals(contentType.variable())) { + throw new BadRequestException(FORMS_AND_SITES_MESSAGE); + } + return contentType; + } + + /** + * The message for an export over the row limit (FR-010). + * + * @param maxRows the limit + * @return the message, with the limit written with thousands separators + */ + static String overLimitMessage(final int maxRows) { + final String limit = new DecimalFormat("#,###", DecimalFormatSymbols.getInstance(Locale.US)) + .format(maxRows); + return "This export has more than " + limit + " rows; " + limit + + " is the limit. Narrow the filters or the selection and try again."; } } diff --git a/dotCMS/src/main/java/com/dotcms/rest/config/DotRestApplication.java b/dotCMS/src/main/java/com/dotcms/rest/config/DotRestApplication.java index 4553cf063d8a..549370358144 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/config/DotRestApplication.java +++ b/dotCMS/src/main/java/com/dotcms/rest/config/DotRestApplication.java @@ -62,6 +62,7 @@ @Tag(name = "Content", description = "Endpoints for managing content and contentlets"), @Tag(name = "Content Analytics", description = "Content performance analytics and reporting"), @Tag(name = "Content Delivery", description = "Content delivery and rendering"), + @Tag(name = "Content Drive", description = "Content Drive browsing and export"), @Tag(name = "Content Report", description = "Content reporting and analytics"), @Tag(name = "Content Type", description = "Content type definitions and schema management", externalDocs = @ExternalDocumentation(description = "Additional Content Type API information", diff --git a/dotCMS/src/main/webapp/WEB-INF/messages/Language.properties b/dotCMS/src/main/webapp/WEB-INF/messages/Language.properties index ec5a0601a1bc..344388b02049 100644 --- a/dotCMS/src/main/webapp/WEB-INF/messages/Language.properties +++ b/dotCMS/src/main/webapp/WEB-INF/messages/Language.properties @@ -7558,6 +7558,9 @@ content-drive.tree.expand=Expand folder tree content-drive.toast.download-success=Downloading {0} content-drive.toast.download-success-detail=The download has started. +content-drive.export.button=Export +content-drive.toast.export-success=Export ready +content-drive.toast.export-success-detail={0} items exported in {1} file(s) content-drive.chip-filter.overflow-label={0} and {1} more content-drive.filters.clear-all=Clear all diff --git a/dotCMS/src/main/webapp/WEB-INF/openapi/openapi.yaml b/dotCMS/src/main/webapp/WEB-INF/openapi/openapi.yaml index b9279d32a9f5..0f19a4afe4b5 100644 --- a/dotCMS/src/main/webapp/WEB-INF/openapi/openapi.yaml +++ b/dotCMS/src/main/webapp/WEB-INF/openapi/openapi.yaml @@ -113,6 +113,8 @@ tags: name: Categories - description: Cluster nodes and distributed system management name: Cluster Management +- description: Content Drive browsing and export + name: Content Drive - description: Content reporting and analytics name: Content Report - description: Publishing environment management and configuration @@ -10654,6 +10656,70 @@ paths: summary: Save (upsert) the dotAuth configuration for a site tags: - dotAuth + /v1/drive/export: + post: + description: |- + Exports content from Content Drive in the CSV format the Content Search export writes and the content import reads. + + **Filter mode** (no `selection`): send `query`, the same body the Drive listing sends to `/api/v1/drive/search`, filtered to exactly one content type. Every contentlet the listing matches, across all pages, is returned as one CSV. Paging, sorting, `showFolders`, `showLinks` and `live` are ignored. + + **Selection mode** (`selection` with folders or contentlets, at most 60 in all, plus `siteId`): the selected contentlets in their selected language and every contentlet under the selected folders, in every language, as a zip with one CSV per content type. + + Only the working version of each contentlet is exported, and only what the user can read. Forms and sites are never exported. More than `CONTENT_DRIVE_EXPORT_MAX_ROWS` rows (default 100,000) is refused with a 400. The response headers `X-Export-Contentlets` and `X-Export-Files` give the rows and the CSVs written. + operationId: postDriveExport + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/DriveExportRequestForm" + description: "What to export: a listing query (filter mode) or a selection\ + \ of folders and contentlets" + required: true + responses: + "200": + content: + application/zip: + schema: + type: string + format: binary + text/csv: + schema: + type: string + format: binary + description: "The export file: one CSV in filter mode, a zip of CSVs in\ + \ selection mode" + "204": + description: Nothing readable matched the request; no file + "400": + content: + application/json: + schema: + type: object + description: "Error body: errors[0].message holds the reason" + description: "Invalid request: nothing to export, not exactly one readable\ + \ content type, a Form or Host type, too many selected items, an invalid\ + \ entry, or more rows than the limit" + "401": + content: + application/json: {} + description: Unauthorized access + "404": + content: + application/json: + schema: + type: object + description: "Error body: errors[0].message holds the reason" + description: The site or a selected folder was not found + "500": + content: + application/json: + schema: + type: object + description: "Error body: errors[0].message holds a generic message" + description: The export failed + summary: Export Content Drive content to CSV + tags: + - Content Drive /v1/ema: get: operationId: getDetails @@ -29467,6 +29533,128 @@ components: type: string thumbnailUrl: type: string + DriveExportRequestForm: + type: object + properties: + query: + $ref: "#/components/schemas/DriveRequestForm" + selection: + $ref: "#/components/schemas/ExportSelectionForm" + siteId: + type: string + DriveRequestForm: + type: object + properties: + archived: + type: boolean + assetPath: + type: string + baseTypes: + type: array + items: + type: string + properties: + empty: + type: boolean + first: + type: string + last: + type: string + browseScope: + type: string + enum: + - ALL + - ROOT + - SYSTEM_HOST + contentCursor: + type: integer + format: int32 + contentTypes: + type: array + items: + type: string + properties: + empty: + type: boolean + first: + type: string + last: + type: string + filters: + $ref: "#/components/schemas/QueryFilters" + folderCursor: + type: integer + format: int32 + includeSystemHost: + type: boolean + language: + type: array + items: + type: string + properties: + empty: + type: boolean + first: + type: string + last: + type: string + linkCursor: + type: integer + format: int32 + live: + type: boolean + maxResults: + type: integer + format: int32 + mimeTypes: + type: array + items: + type: string + properties: + empty: + type: boolean + first: + type: string + last: + type: string + offset: + type: integer + format: int32 + showFolders: + type: boolean + showLinks: + type: boolean + sortBy: + type: string + status: + type: array + items: + type: string + properties: + empty: + type: boolean + first: + type: string + last: + type: string + userSearchable: + type: object + additionalProperties: + type: object + properties: + empty: + type: boolean + workflow: + type: array + items: + $ref: "#/components/schemas/WorkflowFilterForm" + properties: + empty: + type: boolean + first: + $ref: "#/components/schemas/WorkflowFilterForm" + last: + $ref: "#/components/schemas/WorkflowFilterForm" DropOldVersionsResultView: type: object properties: @@ -30040,6 +30228,14 @@ components: for the site. Absent when configured. enum: - analytics_disabled + ExportContentletRefForm: + type: object + properties: + identifier: + type: string + languageId: + type: integer + format: int64 ExportSecretForm: type: object properties: @@ -30066,6 +30262,31 @@ components: - appKeysBySite - exportAll - password + ExportSelectionForm: + type: object + properties: + contentlets: + type: array + items: + $ref: "#/components/schemas/ExportContentletRefForm" + properties: + empty: + type: boolean + first: + $ref: "#/components/schemas/ExportContentletRefForm" + last: + $ref: "#/components/schemas/ExportContentletRefForm" + folders: + type: array + items: + type: string + properties: + empty: + type: boolean + first: + type: string + last: + type: string ExtraPackagesForm: type: object properties: @@ -32196,6 +32417,17 @@ components: $ref: "#/components/schemas/EnvironmentDetailView" last: $ref: "#/components/schemas/EnvironmentDetailView" + ImmutableListExportContentletRefForm: + type: array + items: + $ref: "#/components/schemas/ExportContentletRefForm" + properties: + empty: + type: boolean + first: + $ref: "#/components/schemas/ExportContentletRefForm" + last: + $ref: "#/components/schemas/ExportContentletRefForm" ImmutableListJob: type: array items: @@ -32308,6 +32540,17 @@ components: $ref: "#/components/schemas/VariantResult" last: $ref: "#/components/schemas/VariantResult" + ImmutableListWorkflowFilterForm: + type: array + items: + $ref: "#/components/schemas/WorkflowFilterForm" + properties: + empty: + type: boolean + first: + $ref: "#/components/schemas/WorkflowFilterForm" + last: + $ref: "#/components/schemas/WorkflowFilterForm" ImmutableListWorkflowScheme: type: array description: Workflow schemes associated with the content type @@ -34496,6 +34739,18 @@ components: quantile: type: number format: double + QueryFilters: + type: object + properties: + filterFolders: + type: boolean + searchScope: + type: string + enum: + - ALL_FIELDS + - TITLE + text: + type: string RadioField: type: object allOf: @@ -43667,6 +43922,13 @@ components: $ref: "#/components/schemas/WorkflowStep" scheme: $ref: "#/components/schemas/WorkflowScheme" + WorkflowFilterForm: + type: object + properties: + scheme: + type: string + step: + type: string WorkflowFormEntry: type: object properties: diff --git a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java index 2c8bd3d1ca3f..61cefb065aab 100644 --- a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java +++ b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java @@ -3,6 +3,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; @@ -30,7 +31,10 @@ import com.dotcms.rest.api.v1.drive.export.ExportFileNames; import com.dotcms.util.IntegrationTestInitService; import com.dotmarketing.beans.Host; +import com.dotmarketing.beans.Permission; import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.PermissionAPI; +import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.folders.model.Folder; import com.dotmarketing.portlets.languagesmanager.model.Language; @@ -81,6 +85,11 @@ public class ContentDriveExportFilterModeTest extends IntegrationTestBase { */ private static ContentDriveHelper helper; private static User systemUser; + /** + * Calls the endpoint. A REST request never runs as the system user (InteractiveUserPolicy + * refuses it), so the export runs as a CMS Administrator, who also reads everything. + */ + private static User adminUser; private static User limitedUser; private static Host site; @@ -93,6 +102,8 @@ public class ContentDriveExportFilterModeTest extends IntegrationTestBase { private static ContentType blog; private static ContentType otherType; private static ContentType formType; + /** A type the limited user cannot read: its only permission is READ for an unrelated role. */ + private static ContentType unreadableType; private static Contentlet inFolder; private static Contentlet inSubFolder; @@ -127,6 +138,16 @@ public static void prepare() throws Exception { .field(new FieldDataGen().defaultValue(null).type(TextField.class).name("title") .velocityVarName("title").next()) .nextPersisted(); + // Content type READ is checked with front-end roles, so a new type inherits a READ any + // user passes; an individual permission for another role replaces what it inherits. + unreadableType = new ContentTypeDataGen().host(site) + .name("Unreadable" + unique).velocityVarName("driveExportUnreadable" + unique) + .field(new FieldDataGen().defaultValue(null).type(TextField.class).name("title") + .velocityVarName("title").next()) + .nextPersisted(); + APILocator.getPermissionAPI().save(new Permission(unreadableType.getPermissionId(), + new RoleDataGen().nextPersisted().getId(), PermissionAPI.PERMISSION_READ), + unreadableType, systemUser, false); formType = new ContentTypeDataGen().baseContentType(BaseContentType.FORM).host(site) .name("DriveExportForm" + unique).velocityVarName("driveExportForm" + unique) .nextPersisted(); @@ -146,9 +167,14 @@ public static void prepare() throws Exception { new ContentletDataGen(otherType).host(site).folder(folder).setProperty("title", "other") .nextPersisted(); + adminUser = new UserDataGen().roles(APILocator.getRoleAPI().loadCMSAdminRole(), + APILocator.getRoleAPI().loadBackEndUserRole()).nextPersisted(); // A back-end user (Drive users are) who can read none of this site's content types. limitedUser = new UserDataGen().roles(new RoleDataGen().nextPersisted(), APILocator.getRoleAPI().loadBackEndUserRole()).nextPersisted(); + assertThrows("Fixture error: the limited user must not be able to read this type", + DotSecurityException.class, + () -> APILocator.getContentTypeAPI(limitedUser).find(unreadableType.variable())); } private static Contentlet blogEntry(final Folder target, final String title) { @@ -199,7 +225,7 @@ private static Response export(final DriveRequestForm query, final User user) { } private static Response export(final DriveRequestForm query) { - return export(query, systemUser); + return export(query, adminUser); } private static String header(final Response response, final String name) { @@ -459,7 +485,8 @@ public void test_notExactlyOneReadableType_isRejectedWithOneMessage() throws Exc .contentTypes(List.of(blog.variable(), otherType.variable())).build())); responses.put("unknown type", export(query(sitePath()) .contentTypes(List.of("noSuchType" + System.currentTimeMillis())).build())); - responses.put("unreadable type", export(query(sitePath()).build(), limitedUser)); + responses.put("unreadable type", export(query(sitePath()) + .contentTypes(List.of(unreadableType.variable())).build(), limitedUser)); responses.forEach((label, response) -> { assertEquals(label, 400, response.getStatus()); From c56664aebe7dd0a06013b50528a8834401e0edaa Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 09:24:12 -0500 Subject: [PATCH 13/28] test(content-drive): cover empty, failed and not-found export outcomes Tests approved before the implementation for the Content Drive export outcomes (#37900): 204 when nothing readable matches, a generic 500 that leaks no cause and leaves no temp file when writing fails, and one 404 for a missing or unreadable site or folder. The frontend specs cover reading the server's error message from the blob body and the empty and error toasts. Adds the seams the failure test needs to inject a failing CSV writer. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- .../dot-content-drive-export.service.spec.ts | 116 ++++++++++++++- ...tent-drive-export-button.component.spec.ts | 136 +++++++++++++++++- .../api/v1/drive/ContentDriveResource.java | 18 ++- .../export/ContentDriveExportHelper.java | 14 ++ .../v1/drive/export/ExportFileBuilder.java | 11 +- .../ContentDriveExportFilterModeTest.java | 135 +++++++++++++++++ 6 files changed, 424 insertions(+), 6 deletions(-) diff --git a/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.spec.ts b/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.spec.ts index 1c07da8ae931..62cd52ddbb55 100644 --- a/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.spec.ts +++ b/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.spec.ts @@ -1,8 +1,13 @@ import { createServiceFactory, SpectatorService } from '@openng/spectator/vitest'; +import { firstValueFrom } from 'rxjs'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { HttpClient, provideHttpClient } from '@angular/common/http'; -import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { + HttpTestingController, + provideHttpClientTesting, + TestRequest +} from '@angular/common/http/testing'; import { DotContentDriveSearchRequest } from '@dotcms/dotcms-models'; @@ -40,6 +45,26 @@ const FILE_HEADERS = { 'X-Export-Files': '1' }; +/** + * What the export rejects with when the error body carries no message it can read. It is the + * same sentence the server sends for an unexpected failure, so the user reads one wording for + * "something went wrong" whichever side noticed it. + */ +const GENERIC_EXPORT_ERROR = + 'The export failed. Try again, and contact your administrator if it keeps failing.'; + +/** An error body as the server writes it (contracts/drive-export-api.md), carrying `message`. */ +const errorBody = (errorCode: string, message: string): Blob => + new Blob( + [ + JSON.stringify({ + errors: [{ errorCode, message, fieldName: null }], + entity: null + }) + ], + { type: 'application/json' } + ); + describe('DotContentDriveExportService', () => { let spectator: SpectatorService; let httpMock: HttpTestingController; @@ -154,5 +179,94 @@ describe('DotContentDriveExportService', () => { // Strict equality on numbers: the raw header strings '2500' and '4' do not match. expect(result).toMatchObject({ kind: 'file', contentlets: 2500, files: 4 }); }); + + it('emits { kind: "empty" } for a 204', async () => { + const result = firstValueFrom(spectator.service.export(BODY)); + + httpMock.expectOne(EXPORT_URL).flush(null, { status: 204, statusText: 'No Content' }); + + expect(await result).toEqual({ kind: 'empty' }); + }); + }); + + describe('a failed export', () => { + /** + * Runs an export, fails it with `fail`, and returns what the observable errored with. + * Reading a Blob body is asynchronous, so the error is awaited rather than caught inline. + * An export that succeeds instead resolves to `undefined`, which fails every assertion below. + */ + const exportFailingWith = (fail: (req: TestRequest) => void): Promise => { + const result = firstValueFrom(spectator.service.export(BODY)); + + fail(httpMock.expectOne(EXPORT_URL)); + + return result.then( + () => undefined, + (error: unknown) => error + ); + }; + + it.each([ + { status: 400, statusText: 'Bad Request', errorCode: 'BAD_REQUEST' }, + { status: 404, statusText: 'Not Found', errorCode: 'NOT_FOUND' }, + { status: 500, statusText: 'Internal Server Error', errorCode: 'INTERNAL_SERVER_ERROR' } + ])( + 'errors with the server message from the Blob body of a $status', + async ({ status, statusText, errorCode }) => { + const message = `The server refused the export (${status})`; + + const error = await exportFailingWith((req) => + req.flush(errorBody(errorCode, message), { status, statusText }) + ); + + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toBe(message); + } + ); + + it.each([ + { + body: 'a Blob body that is not JSON', + fail: (req: TestRequest) => + req.flush(new Blob(['Bad Gateway'], { type: 'text/html' }), { + status: 500, + statusText: 'Internal Server Error' + }) + }, + { + body: 'a JSON body with no errors array', + fail: (req: TestRequest) => + req.flush( + new Blob([JSON.stringify({ entity: null })], { + type: 'application/json' + }), + { status: 400, statusText: 'Bad Request' } + ) + }, + { + body: 'a JSON body whose errors array is empty', + fail: (req: TestRequest) => + req.flush( + new Blob([JSON.stringify({ errors: [], entity: null })], { + type: 'application/json' + }), + { status: 404, statusText: 'Not Found' } + ) + }, + { + body: 'no body at all', + fail: (req: TestRequest) => + req.flush(null, { status: 500, statusText: 'Internal Server Error' }) + }, + { + body: 'a network error (no response, status 0)', + fail: (req: TestRequest) => req.error(new ProgressEvent('error')) + } + ])(`errors with "${GENERIC_EXPORT_ERROR}" for $body`, async ({ fail }) => { + const error = await exportFailingWith(fail); + + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toBe(GENERIC_EXPORT_ERROR); + }); }); }); diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts index ca689adf9cc7..0d4e7916b1dd 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts @@ -5,7 +5,7 @@ import { Spectator, SpyObject } from '@openng/spectator/vitest'; -import { of, Subject } from 'rxjs'; +import { of, Subject, throwError } from 'rxjs'; import { afterEach, beforeEach, describe, expect, it, Mock, vi } from 'vitest'; vi.mock('@dotcms/utils', async () => ({ @@ -37,7 +37,12 @@ import { import { DotContentDriveExportButtonComponent } from './dot-content-drive-export-button.component'; -import { DEFAULT_PAGE, SUCCESS_MESSAGE_LIFE } from '../../../../shared/constants'; +import { + DEFAULT_PAGE, + ERROR_MESSAGE_LIFE, + SUCCESS_MESSAGE_LIFE, + WARNING_MESSAGE_LIFE +} from '../../../../shared/constants'; import { DotContentDriveFilters, DotContentDrivePage, @@ -84,6 +89,11 @@ const FILE_RESULT: DotContentDriveExportResult = { files: 1 }; +const EMPTY_RESULT: DotContentDriveExportResult = { kind: 'empty' }; + +/** The message the service errors with once it has read the server's error body. */ +const SERVER_MESSAGE = 'Server says no'; + describe('DotContentDriveExportButtonComponent (filter mode)', () => { let spectator: Spectator; let exportService: SpyObject; @@ -133,7 +143,10 @@ describe('DotContentDriveExportButtonComponent (filter mode)', () => { useValue: new MockDotMessageService({ 'content-drive.export.button': 'Export', 'content-drive.toast.export-success': 'Export ready', - 'content-drive.toast.export-success-detail': '{0} items exported in {1} file(s)' + 'content-drive.toast.export-success-detail': + '{0} items exported in {1} file(s)', + 'content-drive.toast.export-empty': 'There is nothing to export', + 'content-drive.toast.export-error': 'Export failed' }) } ], @@ -318,4 +331,121 @@ describe('DotContentDriveExportButtonComponent (filter mode)', () => { ); }); }); + + describe('on empty', () => { + beforeEach(() => { + exportService.export.mockReturnValue(of(EMPTY_RESULT)); + }); + + it('should show a warning toast that there is nothing to export', async () => { + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(messageServiceSpy.add).toHaveBeenCalledTimes(1); + expect(messageServiceSpy.add).toHaveBeenCalledWith( + expect.objectContaining({ + severity: 'warn', + summary: 'There is nothing to export', + life: WARNING_MESSAGE_LIFE + }) + ); + }); + + it('should not download anything', async () => { + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(getDownloadLink).not.toHaveBeenCalled(); + expect(anchorClick).not.toHaveBeenCalled(); + }); + }); + + describe('on error', () => { + beforeEach(() => { + exportService.export.mockReturnValue(throwError(() => new Error(SERVER_MESSAGE))); + }); + + it('should show an error toast with the server message', async () => { + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(messageServiceSpy.add).toHaveBeenCalledTimes(1); + expect(messageServiceSpy.add).toHaveBeenCalledWith( + expect.objectContaining({ + severity: 'error', + summary: 'Export failed', + detail: SERVER_MESSAGE, + life: ERROR_MESSAGE_LIFE + }) + ); + }); + + it('should not download anything', async () => { + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(getDownloadLink).not.toHaveBeenCalled(); + expect(anchorClick).not.toHaveBeenCalled(); + }); + }); + + // Each case holds the answer back until the button has shown it is loading, so the button is + // seen both loading and cleared: an answer that arrived synchronously could not prove that. + describe('loading is cleared', () => { + let answer: Subject; + + /** Clicks Export and checks the button is loading while the answer is held back. */ + const clickAndExpectLoading = async () => { + await render(); + + spectator.click(exportButton() as HTMLElement); + spectator.detectChanges(); + + expect(exportButton()).toHaveClass('p-button-loading'); + expect(exportButton()?.disabled).toBe(true); + }; + + /** Checks the button is back to its idle state, ready for another export. */ + const expectNotLoading = () => { + spectator.detectChanges(); + + expect(exportButton()).not.toHaveClass('p-button-loading'); + expect(exportButton()?.disabled).toBe(false); + }; + + beforeEach(() => { + answer = new Subject(); + exportService.export.mockReturnValue(answer); + }); + + it('should clear loading after a file is downloaded', async () => { + await clickAndExpectLoading(); + + answer.next(FILE_RESULT); + answer.complete(); + + expectNotLoading(); + }); + + it('should clear loading when there is nothing to export', async () => { + await clickAndExpectLoading(); + + answer.next(EMPTY_RESULT); + answer.complete(); + + expectNotLoading(); + }); + + it('should clear loading when the export fails', async () => { + await clickAndExpectLoading(); + + answer.error(new Error(SERVER_MESSAGE)); + + expectNotLoading(); + }); + }); }); diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java index e226c68892b8..4a6bef0aeced 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java @@ -53,7 +53,23 @@ public class ContentDriveResource { "The export failed. Try again, and contact your administrator if it keeps failing."; private final ContentDriveHelper helper = ContentDriveHelper.newInstance(); - private final ContentDriveExportHelper exportHelper = new ContentDriveExportHelper(); + private final ContentDriveExportHelper exportHelper; + + /** + * Creates the resource with the standard export helper. + */ + public ContentDriveResource() { + this(new ContentDriveExportHelper()); + } + + /** + * Creates the resource with the given export helper. Tests use it to make an export fail. + * + * @param exportHelper runs the exports + */ + ContentDriveResource(final ContentDriveExportHelper exportHelper) { + this.exportHelper = exportHelper; + } /** * Search content assets using drive functionality diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java index a2cbfb32ef86..c21081a74610 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java @@ -1,6 +1,7 @@ package com.dotcms.rest.api.v1.drive.export; import com.dotcms.browser.BrowserAPI; +import com.dotcms.content.export.ContentletCsvWriter; import com.dotcms.browser.BrowserQuery; import com.dotcms.browser.ExportCandidates; import com.dotcms.browser.ExportRow; @@ -17,6 +18,7 @@ import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.util.Config; +import com.google.common.annotations.VisibleForTesting; import com.liferay.portal.model.User; import java.io.IOException; import java.text.DecimalFormat; @@ -56,6 +58,18 @@ public ContentDriveExportHelper() { this(ContentDriveHelper.newInstance(), APILocator.getBrowserAPI(), new ExportFileBuilder()); } + /** + * Creates a helper that writes with the given CSV writer, into the standard export directory. + * Tests outside this package use it to make the writing fail. + * + * @param writer writes each content type's CSV + */ + @VisibleForTesting + public ContentDriveExportHelper(final ContentletCsvWriter writer) { + this(ContentDriveHelper.newInstance(), APILocator.getBrowserAPI(), + new ExportFileBuilder(writer, ExportFileBuilder.defaultDirectory())); + } + /** * Creates a helper with the given collaborators. * diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilder.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilder.java index 09209b7b9592..1c44befee835 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilder.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ExportFileBuilder.java @@ -50,7 +50,16 @@ public class ExportFileBuilder { * Creates a builder that writes with the shared CSV writer under the asset temp path. */ public ExportFileBuilder() { - this(new ContentletCsvWriter(), Path.of(ConfigUtils.getAssetTempPath(), DIRECTORY_NAME)); + this(new ContentletCsvWriter(), defaultDirectory()); + } + + /** + * The directory export files are written to: {@link #DIRECTORY_NAME} under the asset temp path. + * + * @return the export directory + */ + public static Path defaultDirectory() { + return Path.of(ConfigUtils.getAssetTempPath(), DIRECTORY_NAME); } /** diff --git a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java index 61cefb065aab..06476ba37b47 100644 --- a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java +++ b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java @@ -3,12 +3,15 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import com.dotcms.IntegrationTestBase; import com.dotcms.browser.BrowserAPIImpl.PaginatedContents; +import com.dotcms.content.export.ContentletCsvWriter; +import com.dotcms.content.export.HostFolderMode; import com.dotcms.contenttype.model.field.HostFolderField; import com.dotcms.contenttype.model.field.TextField; import com.dotcms.contenttype.model.type.BaseContentType; @@ -26,6 +29,8 @@ import com.dotcms.mock.request.MockHttpRequestIntegrationTest; import com.dotcms.rest.ErrorEntity; import com.dotcms.rest.ResponseEntityView; +import com.dotcms.rest.api.v1.DotObjectMapperProvider; +import com.dotcms.rest.api.v1.drive.export.ContentDriveExportHelper; import com.dotcms.rest.api.v1.drive.export.DriveExportRequestForm; import com.dotcms.rest.api.v1.drive.export.ExportFileBuilder; import com.dotcms.rest.api.v1.drive.export.ExportFileNames; @@ -34,6 +39,8 @@ import com.dotmarketing.beans.Permission; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.PermissionAPI; +import com.dotmarketing.business.Role; +import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.folders.model.Folder; @@ -43,6 +50,8 @@ import com.liferay.portal.model.User; import com.liferay.portal.util.WebKeys; import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -77,6 +86,9 @@ public class ContentDriveExportFilterModeTest extends IntegrationTestBase { private static final String ONE_TYPE = "Choose exactly one content type you can read to export."; private static final String FORMS_AND_SITES = "Forms and sites can't be exported."; + private static final String EXPORT_FAILED = + "The export failed. Try again, and contact your administrator if it keeps failing."; + private static final String FOLDER_NOT_FOUND = "Folder not found."; private static final int MAX_PAGES = 200; /** @@ -91,6 +103,8 @@ public class ContentDriveExportFilterModeTest extends IntegrationTestBase { */ private static User adminUser; private static User limitedUser; + /** A back-end user who can read the site and the Blog type but none of the Blog rows. */ + private static User siteReader; private static Host site; private static Folder folder; @@ -172,6 +186,19 @@ public static void prepare() throws Exception { // A back-end user (Drive users are) who can read none of this site's content types. limitedUser = new UserDataGen().roles(new RoleDataGen().nextPersisted(), APILocator.getRoleAPI().loadBackEndUserRole()).nextPersisted(); + final Role siteReaderRole = new RoleDataGen().nextPersisted(); + siteReader = new UserDataGen().roles(siteReaderRole, + APILocator.getRoleAPI().loadBackEndUserRole()).nextPersisted(); + APILocator.getPermissionAPI().save(new Permission(site.getPermissionId(), + siteReaderRole.getId(), PermissionAPI.PERMISSION_READ), site, systemUser, false); + assertNotNull("Fixture error: the site reader must read the site", + APILocator.getHostAPI().find(site.getIdentifier(), siteReader, false)); + assertNotNull("Fixture error: the site reader must read the Blog type", + APILocator.getContentTypeAPI(siteReader).find(blog.variable())); + assertFalse("Fixture error: the site reader must not read the Blog rows", + APILocator.getPermissionAPI().doesUserHavePermission(inFolder, + PermissionAPI.PERMISSION_READ, siteReader, false)); + assertThrows("Fixture error: the limited user must not be able to read this type", DotSecurityException.class, () -> APILocator.getContentTypeAPI(limitedUser).find(unreadableType.variable())); @@ -224,6 +251,43 @@ private static Response export(final DriveRequestForm query, final User user) { DriveExportRequestForm.builder().query(query).build()); } + private static Response export(final ContentDriveResource resource, + final DriveRequestForm query, final User user) { + return resource.export(requestAs(user), mock(HttpServletResponse.class), + DriveExportRequestForm.builder().query(query).build()); + } + + /** The files that appeared in the export directory since {@code before}. */ + private static Set newFilesSince(final Set before) throws Exception { + final Set added = new HashSet<>(exportDirectoryFiles()); + added.removeAll(before); + return added; + } + + /** The response entity as the client receives it. */ + private static String entityJson(final Response response) throws Exception { + return DotObjectMapperProvider.getInstance().getDefaultObjectMapper() + .writeValueAsString(response.getEntity()); + } + + /** + * Writes the header row and then fails, as a disk or database failure halfway through a file + * would. + */ + private static final class FailingWriter extends ContentletCsvWriter { + + static final String SECRET = "internal detail that must never reach the client"; + + @Override + public int write(final ContentType contentType, final List inodes, + final User user, final HttpServletRequest request, + final HostFolderMode hostFolderMode, final Writer out) + throws DotDataException, IOException { + out.write("Identifier,languageCode,countryCode\r\n"); + throw new DotDataException(SECRET); + } + } + private static Response export(final DriveRequestForm query) { return export(query, adminUser); } @@ -508,4 +572,75 @@ public void test_formType_isRejected() { assertEquals(400, response.getStatus()); assertEquals(FORMS_AND_SITES, errorMessage(response)); } + // --------------------------------------------------------------------------------------------- + // outcomes: nothing to export, failure, not found (User Story 7) + // --------------------------------------------------------------------------------------------- + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (a) A user who can read the site and the type, exporting the whole site + * (without System Host), none of whose Blog rows they can read + * ExpectedResult: 204 with no body, and no file left in the export directory (FR-027, FR-032) + */ + @Test + public void test_nothingReadable_isNoContent() throws Exception { + final Set before = exportDirectoryFiles(); + + // The site, not a folder: the site reader's READ is on the site only, which its folders do + // not inherit, so a folder path would be a 404 rather than an empty export. + final Response response = export(query(sitePath()).browseScope(BrowseScope.ALL) + .includeSystemHost(false).build(), siteReader); + + assertEquals(204, response.getStatus()); + assertNull(response.getEntity()); + assertEquals("no temp file is left", Set.of(), newFilesSince(before)); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (b) The CSV writer fails halfway through the file + * ExpectedResult: 500 with the generic message; neither the cause nor a stack trace reaches the + * client, and no file is left in the export directory (FR-029, FR-031, FR-032) + */ + @Test + public void test_writerFailure_isAGenericServerError() throws Exception { + final Set before = exportDirectoryFiles(); + final ContentDriveResource failing = + new ContentDriveResource(new ContentDriveExportHelper(new FailingWriter())); + + final Response response = export(failing, query(folderPath()).build(), adminUser); + + assertEquals(500, response.getStatus()); + assertEquals(EXPORT_FAILED, errorMessage(response)); + final String body = entityJson(response); + assertFalse("the cause is not returned", body.contains(FailingWriter.SECRET)); + assertFalse("no stack trace is returned", body.contains("Exception")); + assertFalse("no stack trace is returned", body.contains("\tat ")); + assertEquals("no temp file is left", Set.of(), newFilesSince(before)); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (c) A site the user cannot read, a site that does not exist, and a folder that + * does not exist in a real site + * ExpectedResult: 404 "Folder not found." each time, with identical bodies, so the response never + * tells which applied (FR-014) + */ + @Test + public void test_missingOrUnreadableLocation_isNotFound() throws Exception { + final Map responses = new LinkedHashMap<>(); + responses.put("unreadable site", export(query(sitePath()).build(), limitedUser)); + responses.put("missing site", export(query("//no-such-site-" + System.currentTimeMillis() + + ".local/").build(), adminUser)); + responses.put("missing folder", export(query(sitePath() + "no-such-folder-" + + System.currentTimeMillis() + "/").build(), adminUser)); + + final Set bodies = new HashSet<>(); + for (final Map.Entry entry : responses.entrySet()) { + assertEquals(entry.getKey(), 404, entry.getValue().getStatus()); + assertEquals(entry.getKey(), FOLDER_NOT_FOUND, errorMessage(entry.getValue())); + bodies.add(entityJson(entry.getValue())); + } + assertEquals("identical bodies", 1, bodies.size()); + } } From 007df8f2055237ed5184ffe6afe5bde27d678afd Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 09:24:20 -0500 Subject: [PATCH 14/28] feat(content-drive): show why an export produced no file When an export has nothing readable to write, the Drive shows a warning toast; when it fails, an error toast with the server's message, read from the JSON error body the endpoint returns as a blob (#37900). Neither downloads anything, and the button leaves its loading state in every case. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- .../dot-content-drive-export.service.ts | 48 +++++++++++++-- ...t-content-drive-export-button.component.ts | 61 +++++++++++++------ .../WEB-INF/messages/Language.properties | 2 + 3 files changed, 89 insertions(+), 22 deletions(-) diff --git a/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts b/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts index b5c324a04065..9d1aaed6bd9d 100644 --- a/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts +++ b/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts @@ -1,15 +1,22 @@ -import { Observable } from 'rxjs'; +import { from, Observable, throwError } from 'rxjs'; -import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http'; +import { HttpClient, HttpErrorResponse, HttpHeaders, HttpResponse } from '@angular/common/http'; import { inject, Injectable } from '@angular/core'; -import { map } from 'rxjs/operators'; +import { catchError, map, switchMap } from 'rxjs/operators'; import { DotContentDriveSearchRequest } from '@dotcms/dotcms-models'; /** The endpoint that builds the export file. */ const EXPORT_URL = '/api/v1/drive/export'; +/** + * Shown when an error carries no message the user can read: the same sentence the server sends for + * an unexpected failure, so the user reads one wording whichever side noticed it. + */ +const GENERIC_EXPORT_ERROR = + 'The export failed. Try again, and contact your administrator if it keeps failing.'; + /** * Body of `POST /api/v1/drive/export` in filter mode: the same request the listing sends to * `/api/v1/drive/search`. The server ignores its paging, sorting and folder flags. @@ -56,12 +63,23 @@ export class DotContentDriveExportService { * headers. A 204 (nothing readable matched) resolves to `{ kind: 'empty' }`. * * @param body The export request, carrying the listing query in filter mode. + * An error response (400, 404, 500) arrives as a blob too, so its JSON body is read to error + * with the server's `errors[0].message`; a body with no readable message errors with a generic + * one. + * * @returns The file and its counts once the server has built it, or `empty` when there is none. */ export(body: DotContentDriveExportRequest): Observable { return this.#http .post(EXPORT_URL, body, { observe: 'response', responseType: 'blob' }) - .pipe(map((response) => toExportResult(response))); + .pipe( + map((response) => toExportResult(response)), + catchError((error: unknown) => + from(readErrorMessage(error)).pipe( + switchMap((message) => throwError(() => new Error(message))) + ) + ) + ); } } @@ -117,3 +135,25 @@ function readCount(headers: HttpHeaders, name: string): number { return Number.isFinite(value) ? value : 0; } + +/** + * Reads the message out of an export error: the `errors[0].message` of the JSON body the server + * sends as a blob. A network error, a body that is not JSON, or JSON without a message gives the + * generic message. + */ +async function readErrorMessage(error: unknown): Promise { + if (!(error instanceof HttpErrorResponse) || !(error.error instanceof Blob)) { + return GENERIC_EXPORT_ERROR; + } + + try { + const parsed = JSON.parse(await error.error.text()) as { + errors?: { message?: unknown }[]; + }; + const message = parsed?.errors?.[0]?.message; + + return typeof message === 'string' && message.trim() ? message : GENERIC_EXPORT_ERROR; + } catch { + return GENERIC_EXPORT_ERROR; + } +} diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts index b71133bb47c8..b8df73c08fd4 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts @@ -15,7 +15,11 @@ import { DotCMSBaseTypesContentTypes } from '@dotcms/dotcms-models'; import { DotMessagePipe } from '@dotcms/ui'; import { getDownloadLink } from '@dotcms/utils'; -import { SUCCESS_MESSAGE_LIFE } from '../../../../shared/constants'; +import { + ERROR_MESSAGE_LIFE, + SUCCESS_MESSAGE_LIFE, + WARNING_MESSAGE_LIFE +} from '../../../../shared/constants'; import { DotContentDriveStatus } from '../../../../shared/models'; import { DotContentDriveStore } from '../../../../store/dot-content-drive.store'; import { isFolder } from '../../../../utils/functions'; @@ -100,7 +104,9 @@ export class DotContentDriveExportButtonComponent { /** * Exports the listing request the store holds and downloads the file under the name the server - * gave it, then confirms with a toast that carries the number of exported items. + * gave it, then confirms with a toast that carries the number of exported items. When nothing + * readable matched, a warning toast says so; when the export fails, an error toast shows the + * server's message. Neither downloads anything. * * The request is not tied to this component's lifetime: the user may select a row while the * file is being built, which removes the button, and the download should still arrive. @@ -115,23 +121,42 @@ export class DotContentDriveExportButtonComponent { this.#exportService .export({ query: this.#store.$request() }) .pipe(finalize(() => this.$exporting.set(false))) - .subscribe((result) => { - if (result.kind !== 'file') { - return; + .subscribe({ + next: (result) => { + if (result.kind !== 'file') { + this.#messageService.add({ + severity: 'warn', + summary: this.#dotMessageService.get( + 'content-drive.toast.export-empty' + ), + life: WARNING_MESSAGE_LIFE + }); + + return; + } + + getDownloadLink(result.blob, result.fileName).click(); + + this.#messageService.add({ + severity: 'success', + summary: this.#dotMessageService.get('content-drive.toast.export-success'), + detail: this.#dotMessageService.get( + 'content-drive.toast.export-success-detail', + String(result.contentlets), + String(result.files) + ), + life: SUCCESS_MESSAGE_LIFE + }); + }, + // The service already turned the response into the server's message + error: (error: Error) => { + this.#messageService.add({ + severity: 'error', + summary: this.#dotMessageService.get('content-drive.toast.export-error'), + detail: error.message, + life: ERROR_MESSAGE_LIFE + }); } - - getDownloadLink(result.blob, result.fileName).click(); - - this.#messageService.add({ - severity: 'success', - summary: this.#dotMessageService.get('content-drive.toast.export-success'), - detail: this.#dotMessageService.get( - 'content-drive.toast.export-success-detail', - String(result.contentlets), - String(result.files) - ), - life: SUCCESS_MESSAGE_LIFE - }); }); } } diff --git a/dotCMS/src/main/webapp/WEB-INF/messages/Language.properties b/dotCMS/src/main/webapp/WEB-INF/messages/Language.properties index 344388b02049..01f07ef90c87 100644 --- a/dotCMS/src/main/webapp/WEB-INF/messages/Language.properties +++ b/dotCMS/src/main/webapp/WEB-INF/messages/Language.properties @@ -7561,6 +7561,8 @@ content-drive.toast.download-success-detail=The download has started. content-drive.export.button=Export content-drive.toast.export-success=Export ready content-drive.toast.export-success-detail={0} items exported in {1} file(s) +content-drive.toast.export-empty=There is nothing to export +content-drive.toast.export-error=Export failed content-drive.chip-filter.overflow-label={0} and {1} more content-drive.filters.clear-all=Clear all From 71aa3cdbfe64b30a8f3827f73a1e07a3961acd07 Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 09:54:12 -0500 Subject: [PATCH 15/28] test(content-drive): cover the export row limit Tests for refusing a Content Drive export over CONTENT_DRIVE_EXPORT_MAX_ROWS (#37900): one row over the limit is a 400 with the limit in the message and leaves no file, the limit itself is allowed, only readable rows count, the default limit is written as 100,000, and resolving rows stops at the chunk that passes the limit. The chunk reader becomes a package-visible instance method so the test can count chunks, and the message builder is public. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- .../com/dotcms/browser/BrowserAPIImpl.java | 4 +- .../export/ContentDriveExportHelper.java | 2 +- .../dotcms/browser/BrowserAPIExportTest.java | 33 +++++ .../ContentDriveExportFilterModeTest.java | 137 ++++++++++++++++++ 4 files changed, 173 insertions(+), 3 deletions(-) diff --git a/dotCMS/src/main/java/com/dotcms/browser/BrowserAPIImpl.java b/dotCMS/src/main/java/com/dotcms/browser/BrowserAPIImpl.java index e7c62e3223a4..f1d0529c162e 100644 --- a/dotCMS/src/main/java/com/dotcms/browser/BrowserAPIImpl.java +++ b/dotCMS/src/main/java/com/dotcms/browser/BrowserAPIImpl.java @@ -2682,7 +2682,7 @@ public ExportCandidates getContentForExport(final BrowserQuery browserQuery, fin /** * Reads the next chunk of export rows in {@code (identifier, language)} order, starting right * after {@code after}. Keyset paging keeps every chunk as cheap as the first, however deep - * the export goes. + * the export goes. Package-visible so tests can count the chunks an export reads. * * @param sqlQuery the export select, built with {@link Projection#EXPORT} * @param after the last row of the previous chunk, or {@code null} for the first chunk @@ -2690,7 +2690,7 @@ public ExportCandidates getContentForExport(final BrowserQuery browserQuery, fin * @return the rows, in order * @throws DotDataException if the query fails */ - private static List readExportChunk(final SelectQuery sqlQuery, final ExportRow after, + List readExportChunk(final SelectQuery sqlQuery, final ExportRow after, final int chunkSize) throws DotDataException { final StringBuilder sql = new StringBuilder(sqlQuery.selectQuery); if (after != null) { diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java index c21081a74610..3195f004ce7f 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java @@ -202,7 +202,7 @@ private static ContentType resolveOneContentType(final DriveRequestForm query, f * @param maxRows the limit * @return the message, with the limit written with thousands separators */ - static String overLimitMessage(final int maxRows) { + public static String overLimitMessage(final int maxRows) { final String limit = new DecimalFormat("#,###", DecimalFormatSymbols.getInstance(Locale.US)) .format(maxRows); return "This export has more than " + limit + " rows; " + limit diff --git a/dotcms-integration/src/test/java/com/dotcms/browser/BrowserAPIExportTest.java b/dotcms-integration/src/test/java/com/dotcms/browser/BrowserAPIExportTest.java index fe745bfea743..442af7f63073 100644 --- a/dotcms-integration/src/test/java/com/dotcms/browser/BrowserAPIExportTest.java +++ b/dotcms-integration/src/test/java/com/dotcms/browser/BrowserAPIExportTest.java @@ -3,6 +3,11 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import com.dotcms.IntegrationTestBase; import com.dotcms.browser.BrowserAPIImpl.PaginatedContents; @@ -85,6 +90,8 @@ public class BrowserAPIExportTest extends IntegrationTestBase { private static ContentType bulkType; /** Type with 6 contentlets, for the row limit. */ private static ContentType sixType; + /** Type with 30 contentlets, to show the walk stops early. */ + private static ContentType thirtyType; private static ContentType formType; private static Contentlet live; @@ -181,6 +188,12 @@ public static void prepare() throws Exception { .setProperty("title", "six " + i).nextPersisted(); } + thirtyType = simpleType("BrowserExportThirty", unique); + for (int i = 0; i < 30; i++) { + new ContentletDataGen(thirtyType).host(site).folder(folder) + .setProperty("title", "thirty " + i).nextPersisted(); + } + formType = new ContentTypeDataGen().baseContentType(BaseContentType.FORM).host(site) .name("BrowserExportForm" + unique).velocityVarName("browserExportForm" + unique) .nextPersisted(); @@ -493,4 +506,24 @@ public void test_formsAndHosts_areNeverReturned() throws Exception { assertFalse("no Form row: " + row, formType.id().equals(row.contentTypeId())); } } + /** + * Method to test: {@link BrowserAPI#getContentForExport(BrowserQuery, int)} + * Given Scenario: 30 readable rows, a limit of 5 and chunks of 3 + * ExpectedResult: Over the limit, and only 2 chunks read: the walk stops after the chunk that + * produced the 6th row instead of reading all 10 (FR-010) + */ + @Test + public void test_overLimit_stopsReadingAtTheChunkPastTheLimit() throws Exception { + final Map settings = new LinkedHashMap<>(); + settings.put(BrowserAPIImpl.BROWSER_CONTENT_CHUNK_SIZE_KEY, 3); + withSettings(settings, () -> { + final BrowserAPIImpl browserAPI = spy(new BrowserAPIImpl()); + + final ExportCandidates candidates = + export(browserAPI, siteRequest(thirtyType).build(), 5); + + assertTrue(candidates.overLimit()); + verify(browserAPI, times(2)).readExportChunk(any(), any(), anyInt()); + }); + } } diff --git a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java index 06476ba37b47..a9083bcdeac3 100644 --- a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java +++ b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java @@ -46,9 +46,11 @@ import com.dotmarketing.portlets.folders.model.Folder; import com.dotmarketing.portlets.languagesmanager.model.Language; import com.dotmarketing.portlets.workflows.model.WorkflowScheme; +import com.dotmarketing.util.Config; import com.dotmarketing.util.ConfigUtils; import com.liferay.portal.model.User; import com.liferay.portal.util.WebKeys; +import io.vavr.control.Try; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.Writer; @@ -72,6 +74,7 @@ import javax.ws.rs.core.StreamingOutput; import org.junit.BeforeClass; import org.junit.Test; +import org.junit.function.ThrowingRunnable; /** * Integration tests for {@code POST /api/v1/drive/export} in filter mode @@ -116,6 +119,12 @@ public class ContentDriveExportFilterModeTest extends IntegrationTestBase { private static ContentType blog; private static ContentType otherType; private static ContentType formType; + /** Types with 5, 6 and 7 contentlets at the site root, for the row limit. */ + private static ContentType fiveRows; + private static ContentType sixRows; + private static ContentType sevenRows; + /** A back-end user who can read the site and 5 of the 7 {@link #sevenRows} contentlets. */ + private static User limitReader; /** A type the limited user cannot read: its only permission is READ for an unrelated role. */ private static ContentType unreadableType; @@ -199,11 +208,48 @@ public static void prepare() throws Exception { APILocator.getPermissionAPI().doesUserHavePermission(inFolder, PermissionAPI.PERMISSION_READ, siteReader, false)); + fiveRows = rowsType("Five", unique, 5); + sixRows = rowsType("Six", unique, 6); + sevenRows = rowsType("Seven", unique, 7); + final Role limitReaderRole = new RoleDataGen().nextPersisted(); + limitReader = new UserDataGen().roles(limitReaderRole, + APILocator.getRoleAPI().loadBackEndUserRole()).nextPersisted(); + APILocator.getPermissionAPI().save(new Permission(site.getPermissionId(), + limitReaderRole.getId(), PermissionAPI.PERMISSION_READ), site, systemUser, false); + final List sevenContentlets = APILocator.getContentletAPI().search( + "+contentType:" + sevenRows.variable() + " +working:true", 0, 0, null, systemUser, + false); + assertEquals("Fixture error: seven contentlets", 7, sevenContentlets.size()); + for (final Contentlet contentlet : sevenContentlets.subList(0, 5)) { + APILocator.getPermissionAPI().save(new Permission(contentlet.getPermissionId(), + limitReaderRole.getId(), PermissionAPI.PERMISSION_READ), contentlet, + systemUser, false); + } + assertEquals("Fixture error: the limit reader must read exactly 5 of the 7", 5, + sevenContentlets.stream().filter(contentlet -> Try.of(() -> + APILocator.getPermissionAPI().doesUserHavePermission(contentlet, + PermissionAPI.PERMISSION_READ, limitReader, false)).get()) + .count()); + assertThrows("Fixture error: the limited user must not be able to read this type", DotSecurityException.class, () -> APILocator.getContentTypeAPI(limitedUser).find(unreadableType.variable())); } + /** A type with a title field and {@code rows} contentlets at the site root. */ + private static ContentType rowsType(final String name, final String unique, final int rows) { + final ContentType type = new ContentTypeDataGen().host(site) + .name(name + "Rows" + unique).velocityVarName("driveExport" + name + "Rows" + unique) + .field(new FieldDataGen().defaultValue(null).type(TextField.class).name("title") + .velocityVarName("title").next()) + .nextPersisted(); + for (int i = 0; i < rows; i++) { + new ContentletDataGen(type).host(site).languageId(defaultLanguage.getId()) + .setProperty("title", name + " " + i).nextPersisted(); + } + return type; + } + private static Contentlet blogEntry(final Folder target, final String title) { final ContentletDataGen dataGen = new ContentletDataGen(blog).host(site) .languageId(defaultLanguage.getId()).setProperty("title", title); @@ -643,4 +689,95 @@ public void test_missingOrUnreadableLocation_isNotFound() throws Exception { } assertEquals("identical bodies", 1, bodies.size()); } + // --------------------------------------------------------------------------------------------- + // the row limit (User Story 5) + // --------------------------------------------------------------------------------------------- + + /** The whole site, without System Host, for one type. */ + private static DriveRequestForm wholeSite(final ContentType type) { + return query(sitePath()).browseScope(BrowseScope.ALL).includeSystemHost(false) + .contentTypes(List.of(type.variable())).build(); + } + + private static int csvRows(final Response response) throws Exception { + return parseCsv(new String(body(response), StandardCharsets.UTF_8)).size() - 1; + } + + /** + * Runs an action with {@code CONTENT_DRIVE_EXPORT_MAX_ROWS} set to 5, restoring it afterwards. + */ + private static void withLimitOfFive(final ThrowingRunnable action) throws Throwable { + final int previous = Config.getIntProperty(ContentDriveExportHelper.MAX_ROWS_KEY, + ContentDriveExportHelper.MAX_ROWS_DEFAULT); + Config.setProperty(ContentDriveExportHelper.MAX_ROWS_KEY, 5); + try { + action.run(); + } finally { + Config.setProperty(ContentDriveExportHelper.MAX_ROWS_KEY, previous); + } + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (a) A limit of 5 and 6 readable rows + * ExpectedResult: 400 with the limit message, and no file left (FR-010) + */ + @Test + public void test_overTheLimit_isRefused() throws Throwable { + withLimitOfFive(() -> { + final Set before = exportDirectoryFiles(); + + final Response response = export(wholeSite(sixRows)); + + assertEquals(400, response.getStatus()); + assertEquals("This export has more than 5 rows; 5 is the limit. Narrow the filters or " + + "the selection and try again.", errorMessage(response)); + assertEquals("no temp file is left", Set.of(), newFilesSince(before)); + }); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (b) A limit of 5 and exactly 5 readable rows + * ExpectedResult: 200 with the 5 rows: the limit itself is allowed + */ + @Test + public void test_atTheLimit_isExported() throws Throwable { + withLimitOfFive(() -> { + final Response response = export(wholeSite(fiveRows)); + + assertEquals(200, response.getStatus()); + assertEquals("5", header(response, "X-Export-Contentlets")); + assertEquals(5, csvRows(response)); + }); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (c) A limit of 5, and a user who can read 5 of 7 rows + * ExpectedResult: 200 with the 5 readable rows: only readable rows count toward the limit + * (FR-015) + */ + @Test + public void test_onlyReadableRows_countTowardTheLimit() throws Throwable { + withLimitOfFive(() -> { + final Response response = export(wholeSite(sevenRows), limitReader); + + assertEquals(200, response.getStatus()); + assertEquals("5", header(response, "X-Export-Contentlets")); + assertEquals(5, csvRows(response)); + }); + } + + /** + * Method to test: {@link ContentDriveExportHelper#overLimitMessage(int)} + * Given Scenario: (d) The default limit, 100000 + * ExpectedResult: The number is written with a comma as the thousands separator + */ + @Test + public void test_overLimitMessage_formatsTheDefaultLimit() { + assertEquals("This export has more than 100,000 rows; 100,000 is the limit. Narrow the " + + "filters or the selection and try again.", + ContentDriveExportHelper.overLimitMessage(100_000)); + } } From f70bd8393fa9dcf24f0eb27053ec1a223f91c2ff Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 10:51:18 -0500 Subject: [PATCH 16/28] feat(content-drive): never reveal unreadable content in an export Covers what a limited user's filter-mode export shows (#37900): content they cannot read is absent, the response carries only the contract's headers so nothing reveals how many rows were skipped, and a row that becomes unreadable between resolving and writing is skipped and not counted. Splits the filter-mode export into a resolve step and a write step so that last case can be tested. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- .../export/ContentDriveExportHelper.java | 50 +++- .../src/test/java/com/dotcms/MainSuite2a.java | 1 + .../ContentDriveExportPermissionTest.java | 275 ++++++++++++++++++ 3 files changed, 314 insertions(+), 12 deletions(-) create mode 100644 dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportPermissionTest.java diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java index 3195f004ce7f..e487da8e07c5 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java @@ -102,25 +102,35 @@ public ExportFile export(final DriveExportRequestForm form, final User user, final HttpServletRequest request) throws DotDataException, DotSecurityException, IOException { if (form.validate() == Mode.FILTER) { - return exportFilter(form.query(), user, request); + return write(resolveFilterMode(form.query(), user), user, request); } throw new UnsupportedOperationException("Selection-mode export is not implemented yet"); } /** - * Filter mode: every row the listing shows for the query, as one CSV (research R1–R3). + * The rows a filter-mode export resolved for one content type, before anything is written. * - * @param query the listing request - * @param user the {@link User} the export runs as - * @param request the HTTP request - * @return the CSV + * @param contentType the content type every row belongs to + * @param candidates the readable rows, in output order + */ + record FilterResolution(ContentType contentType, ExportCandidates candidates) { + } + + /** + * Filter mode, first step: checks the request and resolves its readable rows (research R1–R3). + * Nothing is written. + * + * @param query the listing request + * @param user the {@link User} the export runs as + * @return the content type and its readable rows + * @throws BadRequestException when there is not exactly one readable type, it is a Form or Host + * type, or more rows match than the limit + * @throws NotFoundException when the site or folder does not exist or cannot be read * @throws DotDataException if the rows cannot be read * @throws DotSecurityException if the user cannot read the site or folder - * @throws IOException if the temp file cannot be written */ - private ExportFile exportFilter(final DriveRequestForm query, final User user, - final HttpServletRequest request) - throws DotDataException, DotSecurityException, IOException { + FilterResolution resolveFilterMode(final DriveRequestForm query, final User user) + throws DotDataException, DotSecurityException { final ContentType contentType = resolveOneContentType(query, user); // Every override goes before build(): build() snapshots the builder @@ -137,9 +147,25 @@ private ExportFile exportFilter(final DriveRequestForm query, final User user, if (candidates.overLimit()) { throw new BadRequestException(overLimitMessage(maxRows)); } - final List inodes = candidates.rows().stream().map(ExportRow::inode) + return new FilterResolution(contentType, candidates); + } + + /** + * Filter mode, second step: writes the resolved rows as one CSV. A row the user can no longer + * read by now is skipped and not counted (FR-026a). + * + * @param resolution what {@link #resolveFilterMode} returned + * @param user the {@link User} the export runs as + * @param request the HTTP request, used for the download links of binary fields + * @return the CSV; it reports zero rows, and holds no file, when no row was written + * @throws DotDataException if the file cannot be written + * @throws IOException if the temp file cannot be written + */ + ExportFile write(final FilterResolution resolution, final User user, + final HttpServletRequest request) throws DotDataException, IOException { + final List inodes = resolution.candidates().rows().stream().map(ExportRow::inode) .collect(Collectors.toList()); - return fileBuilder.buildCsv(contentType, inodes, user, request); + return fileBuilder.buildCsv(resolution.contentType(), inodes, user, request); } /** diff --git a/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java b/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java index 107522968086..723a426e739b 100644 --- a/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java +++ b/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java @@ -147,6 +147,7 @@ GenericBundleActivatorIntegrationTest.class, com.dotcms.enterprise.publishing.remote.handler.OSGIHandlerTest.class, com.dotcms.publisher.receiver.BundlePluginDeploymentTest.class, + com.dotcms.rest.api.v1.drive.export.ContentDriveExportPermissionTest.class, com.dotmarketing.portlets.contentlet.transform.ContentMapWidgetFieldRenderTest.class, ApiTokenResourceTest.class, AuthCredentialPushPublishUtilTest.class, diff --git a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportPermissionTest.java b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportPermissionTest.java new file mode 100644 index 000000000000..b9acd031e354 --- /dev/null +++ b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportPermissionTest.java @@ -0,0 +1,275 @@ +package com.dotcms.rest.api.v1.drive.export; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +import com.dotcms.IntegrationTestBase; +import com.dotcms.contenttype.model.field.TextField; +import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.datagen.ContentTypeDataGen; +import com.dotcms.datagen.ContentletDataGen; +import com.dotcms.datagen.FieldDataGen; +import com.dotcms.datagen.RoleDataGen; +import com.dotcms.datagen.SiteDataGen; +import com.dotcms.datagen.UserDataGen; +import com.dotcms.mock.request.MockAttributeRequest; +import com.dotcms.mock.request.MockHttpRequestIntegrationTest; +import com.dotcms.rest.api.v1.drive.BrowseScope; +import com.dotcms.rest.api.v1.drive.ContentDriveResource; +import com.dotcms.rest.api.v1.drive.DriveRequestForm; +import com.dotcms.util.IntegrationTestInitService; +import com.dotmarketing.beans.Host; +import com.dotmarketing.beans.Permission; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.PermissionAPI; +import com.dotmarketing.business.Role; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.util.Config; +import com.liferay.portal.model.User; +import com.liferay.portal.util.WebKeys; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.StreamingOutput; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Integration tests for what a Content Drive export reveals to a user with limited permissions, + * in filter mode (User Story 4; FR-012, FR-015, FR-026a). + *

+ * It sits in the helper's package so case (c) can call the resolve and write steps one at a time + * and change a permission in between. + */ +public class ContentDriveExportPermissionTest extends IntegrationTestBase { + + /** Every header the contract allows on a 200; anything else could leak a skipped count. */ + private static final Set CONTRACT_HEADERS = Set.of("Content-Type", + "Content-Disposition", "Content-Length", "X-Export-Contentlets", "X-Export-Files"); + + private static boolean asyncReferencesOldValue; + private static User systemUser; + private static User limitedUser; + private static Role limitedRole; + private static Host site; + + /** Z is readable by another user, not by the limited one; A, B and C are readable by it. */ + private static ContentType zType; + private static Contentlet z; + private static List readableSiblings; + + /** Three rows the limited user can read, one of which loses READ between the two steps. */ + private static ContentType revokeType; + private static List revokeRows; + + @BeforeClass + public static void prepare() throws Exception { + IntegrationTestInitService.getInstance().init(); + systemUser = APILocator.systemUser(); + final PermissionAPI permissionAPI = APILocator.getPermissionAPI(); + + // Permission references are written asynchronously by default; the grants below must be in + // place before the assertions. ContentDriveLinksTest pins the same flag for the same reason. + asyncReferencesOldValue = Config.getBooleanProperty("PERMISSION_REFERENCES_UPDATE_ASYNC", true); + Config.setProperty("PERMISSION_REFERENCES_UPDATE_ASYNC", false); + + final String unique = String.valueOf(System.currentTimeMillis()); + site = new SiteDataGen().name("drive-export-perm-" + unique + ".local").nextPersisted(); + + // A back-end user (Drive users are) with READ on the site, so its path resolves, and on + // no content except what is granted below one row at a time. + limitedRole = new RoleDataGen().nextPersisted(); + limitedUser = new UserDataGen().roles(limitedRole, + APILocator.getRoleAPI().loadBackEndUserRole()).nextPersisted(); + permissionAPI.save(new Permission(site.getPermissionId(), limitedRole.getId(), + PermissionAPI.PERMISSION_READ), site, systemUser, false); + + zType = titledType("PermZ", unique); + z = titled(zType, "Z"); + readableSiblings = new ArrayList<>(); + for (final String title : List.of("A", "B", "C")) { + final Contentlet sibling = titled(zType, title); + grantRead(sibling); + readableSiblings.add(sibling); + } + + // Z is readable, just not by the limited user. + final Role otherRole = new RoleDataGen().nextPersisted(); + final User otherReader = new UserDataGen().roles(otherRole, + APILocator.getRoleAPI().loadBackEndUserRole()).nextPersisted(); + permissionAPI.save(new Permission(z.getPermissionId(), otherRole.getId(), + PermissionAPI.PERMISSION_READ), z, systemUser, false); + assertTrue("Fixture error: another user must read Z", + permissionAPI.doesUserHavePermission(z, PermissionAPI.PERMISSION_READ, otherReader, + false)); + assertFalse("Fixture error: the limited user must not read Z", + permissionAPI.doesUserHavePermission(z, PermissionAPI.PERMISSION_READ, limitedUser, + false)); + for (final Contentlet sibling : readableSiblings) { + assertTrue("Fixture error: the limited user must read " + sibling.getTitle(), + permissionAPI.doesUserHavePermission(sibling, PermissionAPI.PERMISSION_READ, + limitedUser, false)); + } + + revokeType = titledType("PermRevoke", unique); + revokeRows = new ArrayList<>(); + for (final String title : List.of("R1", "R2", "R3")) { + final Contentlet row = titled(revokeType, title); + grantRead(row); + revokeRows.add(row); + } + } + + @AfterClass + public static void restore() { + Config.setProperty("PERMISSION_REFERENCES_UPDATE_ASYNC", asyncReferencesOldValue); + } + + private static ContentType titledType(final String name, final String unique) { + return new ContentTypeDataGen().host(site) + .name(name + unique).velocityVarName("driveExport" + name + unique) + .field(new FieldDataGen().defaultValue(null).type(TextField.class).name("title") + .velocityVarName("title").next()) + .nextPersisted(); + } + + private static Contentlet titled(final ContentType type, final String title) { + return new ContentletDataGen(type).host(site) + .languageId(APILocator.getLanguageAPI().getDefaultLanguage().getId()) + .setProperty("title", title).nextPersisted(); + } + + private static void grantRead(final Contentlet contentlet) throws Exception { + APILocator.getPermissionAPI().save(new Permission(contentlet.getPermissionId(), + limitedRole.getId(), PermissionAPI.PERMISSION_READ), contentlet, systemUser, false); + } + + /** The whole site, without System Host, for one type, as the Drive sends it. */ + private static DriveRequestForm wholeSite(final ContentType type) { + return DriveRequestForm.builder() + .assetPath("//" + site.getHostname() + "/") + .browseScope(BrowseScope.ALL) + .includeSystemHost(false) + .language(List.of(String.valueOf( + APILocator.getLanguageAPI().getDefaultLanguage().getId()))) + .contentTypes(List.of(type.variable())) + .showFolders(false) + .live(false) + .archived(false) + .build(); + } + + private static HttpServletRequest requestAs(final User user) { + final HttpServletRequest request = new MockAttributeRequest( + new MockHttpRequestIntegrationTest("localhost", "/api/v1/drive/export").request()) + .request(); + request.setAttribute(WebKeys.USER, user); + return request; + } + + private static Response export(final DriveRequestForm query, final User user) { + return new ContentDriveResource().export(requestAs(user), mock(HttpServletResponse.class), + DriveExportRequestForm.builder().query(query).build()); + } + + private static String body(final Response response) throws Exception { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + ((StreamingOutput) response.getEntity()).write(out); + return out.toString(StandardCharsets.UTF_8); + } + + /** The first cell of every data row: the identifiers, in file order. */ + private static List identifiers(final String csv) { + final String[] lines = csv.split("\r\n"); + final List identifiers = new ArrayList<>(); + for (int i = 1; i < lines.length; i++) { + if (!lines[i].isEmpty()) { + identifiers.add(lines[i].split(",", -1)[0]); + } + } + return identifiers; + } + + private static Set identifiersOf(final List contentlets) { + return contentlets.stream().map(Contentlet::getIdentifier).collect(Collectors.toSet()); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (a) A limited user exports a type in which they can read A, B and C but not + * Z, which another user can read + * ExpectedResult: The CSV holds A, B and C, and not Z (FR-012) + */ + @Test + public void test_unreadableRow_isNotExported() throws Exception { + final Response response = export(wholeSite(zType), limitedUser); + + assertEquals(200, response.getStatus()); + final List exported = identifiers(body(response)); + assertEquals(identifiersOf(readableSiblings), Set.copyOf(exported)); + assertFalse(exported.contains(z.getIdentifier())); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (b) The same export + * ExpectedResult: Only the contract's headers are sent, and {@code X-Export-Contentlets} equals + * the data rows, so nothing tells how many rows were skipped (FR-015) + */ + @Test + public void test_response_revealsNothingAboutSkippedRows() throws Exception { + final Response response = export(wholeSite(zType), limitedUser); + + assertEquals(200, response.getStatus()); + for (final String header : response.getMetadata().keySet()) { + assertTrue("unexpected header " + header, CONTRACT_HEADERS.contains(header)); + } + final int rows = identifiers(body(response)).size(); + assertEquals(String.valueOf(rows), + String.valueOf(response.getMetadata().getFirst("X-Export-Contentlets"))); + assertEquals(readableSiblings.size(), rows); + } + + /** + * Method to test: {@link ContentDriveExportHelper#resolveFilterMode} then + * {@link ContentDriveExportHelper#write} + * Given Scenario: (c) Three readable rows are resolved; READ on one of them is revoked before + * they are written + * ExpectedResult: That row is skipped, the file holds the other two, and the reported count + * equals the rows written (US4 #8, FR-026a) + */ + @Test + public void test_rowUnreadableBeforeWriting_isSkippedAndNotCounted() throws Exception { + final ContentDriveExportHelper helper = new ContentDriveExportHelper(); + final ContentDriveExportHelper.FilterResolution resolution = + helper.resolveFilterMode(wholeSite(revokeType), limitedUser); + assertEquals("fixture: all three rows resolve", 3, resolution.candidates().rows().size()); + + final Contentlet revoked = revokeRows.get(1); + APILocator.getPermissionAPI().removePermissions(revoked); + assertFalse("fixture: READ is gone", APILocator.getPermissionAPI() + .doesUserHavePermission(revoked, PermissionAPI.PERMISSION_READ, limitedUser, + false)); + + final ExportFile file = helper.write(resolution, limitedUser, requestAs(limitedUser)); + try { + final List written = identifiers(Files.readString(file.path(), + StandardCharsets.UTF_8)); + assertEquals(2, file.contentlets()); + assertEquals(file.contentlets(), written.size()); + assertFalse(written.contains(revoked.getIdentifier())); + } finally { + Files.deleteIfExists(file.path()); + } + } +} From 96d3a3812bafe2cd6e1c7186e5ab6c1f770ad3f6 Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 11:09:42 -0500 Subject: [PATCH 17/28] test(content-drive): prove an exported CSV imports back in place Round-trip test for the Content Drive filter-mode export (#37900): content in a folder, at a site root and in System Host is exported, edited and imported with the identifier as the key, with no row errors, every value updated and nothing moved. Also checks the Drive CSV equals the Content Search CSV column by column except host/folder. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- .../src/test/java/com/dotcms/MainSuite2a.java | 1 + .../ContentDriveExportRoundTripTest.java | 298 ++++++++++++++++++ 2 files changed, 299 insertions(+) create mode 100644 dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportRoundTripTest.java diff --git a/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java b/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java index 723a426e739b..70917328a284 100644 --- a/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java +++ b/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java @@ -148,6 +148,7 @@ com.dotcms.enterprise.publishing.remote.handler.OSGIHandlerTest.class, com.dotcms.publisher.receiver.BundlePluginDeploymentTest.class, com.dotcms.rest.api.v1.drive.export.ContentDriveExportPermissionTest.class, + com.dotcms.rest.api.v1.drive.ContentDriveExportRoundTripTest.class, com.dotmarketing.portlets.contentlet.transform.ContentMapWidgetFieldRenderTest.class, ApiTokenResourceTest.class, AuthCredentialPushPublishUtilTest.class, diff --git a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportRoundTripTest.java b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportRoundTripTest.java new file mode 100644 index 000000000000..e3acb7794f17 --- /dev/null +++ b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportRoundTripTest.java @@ -0,0 +1,298 @@ +package com.dotcms.rest.api.v1.drive; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.dotcms.repackage.com.csvreader.CsvReader; +import com.dotcms.IntegrationTestBase; +import com.dotcms.contenttype.model.field.HostFolderField; +import com.dotcms.contenttype.model.field.TextField; +import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.datagen.ContentTypeDataGen; +import com.dotcms.datagen.ContentletDataGen; +import com.dotcms.datagen.FieldDataGen; +import com.dotcms.datagen.FolderDataGen; +import com.dotcms.datagen.SiteDataGen; +import com.dotcms.datagen.UserDataGen; +import com.dotcms.mock.request.MockAttributeRequest; +import com.dotcms.mock.request.MockHttpRequestIntegrationTest; +import com.dotcms.rest.api.v1.drive.export.DriveExportRequestForm; +import com.dotcms.util.IntegrationTestInitService; +import com.dotmarketing.beans.Host; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.portlets.contentlet.action.EditContentletAction; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.folders.business.FolderAPI; +import com.dotmarketing.portlets.folders.model.Folder; +import com.dotmarketing.portlets.workflows.business.SystemWorkflowConstants; +import com.dotmarketing.util.ImportUtil; +import com.liferay.portal.model.User; +import com.liferay.portal.util.WebKeys; +import java.io.ByteArrayOutputStream; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.StringWriter; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.StreamingOutput; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Integration tests proving a Content Drive filter-mode CSV can be imported back (User Story 6; + * FR-021, FR-022, SC-003, SC-004): the import updates the same contentlets in the same place, and + * the file equals the Content Search CSV except for the host/folder column. + */ +public class ContentDriveExportRoundTripTest extends IntegrationTestBase { + + private static final String LOCATION = "location"; + + private static User systemUser; + /** Calls the endpoint: a REST request never runs as the system user. */ + private static User adminUser; + private static Host site; + private static Folder folder; + private static ContentType type; + + private static Contentlet inFolder; + private static Contentlet atSiteRoot; + private static Contentlet inSystemHost; + + @BeforeClass + public static void prepare() throws Exception { + IntegrationTestInitService.getInstance().init(); + systemUser = APILocator.systemUser(); + adminUser = new UserDataGen().roles(APILocator.getRoleAPI().loadCMSAdminRole(), + APILocator.getRoleAPI().loadBackEndUserRole()).nextPersisted(); + + final String unique = String.valueOf(System.currentTimeMillis()); + site = new SiteDataGen().name("drive-roundtrip-" + unique + ".local").nextPersisted(); + folder = new FolderDataGen().site(site).name("rt").nextPersisted(); + + // FieldDataGen gives every field a text default value; every field here clears it. + type = new ContentTypeDataGen().host(site) + .workflowId(SystemWorkflowConstants.SYSTEM_WORKFLOW_ID) + .name("RoundTrip" + unique).velocityVarName("driveRoundTrip" + unique) + .field(new FieldDataGen().defaultValue(null).type(TextField.class).name("title") + .velocityVarName("title").next()) + .field(new FieldDataGen().defaultValue(null).type(HostFolderField.class) + .name(LOCATION).velocityVarName(LOCATION).next()) + .nextPersisted(); + + inFolder = new ContentletDataGen(type).host(site).folder(folder) + .setProperty("title", "rt-folder").nextPersisted(); + atSiteRoot = new ContentletDataGen(type).host(site) + .setProperty("title", "rt-root").nextPersisted(); + inSystemHost = new ContentletDataGen(type).host(APILocator.systemHost()) + .setProperty("title", "rt-system").nextPersisted(); + } + + // --------------------------------------------------------------------------------------------- + // helpers + // --------------------------------------------------------------------------------------------- + + /** The Drive's filter-mode export of the type: All Site Content, System Host included. */ + private static String driveCsv() throws Exception { + final HttpServletRequest request = new MockAttributeRequest( + new MockHttpRequestIntegrationTest("localhost", "/api/v1/drive/export").request()) + .request(); + request.setAttribute(WebKeys.USER, adminUser); + final DriveRequestForm query = DriveRequestForm.builder() + .assetPath("//" + site.getHostname() + "/") + .browseScope(BrowseScope.ALL) + .includeSystemHost(true) + .language(List.of(String.valueOf( + APILocator.getLanguageAPI().getDefaultLanguage().getId()))) + .contentTypes(List.of(type.variable())) + .build(); + + final Response response = new ContentDriveResource().export(request, + mock(HttpServletResponse.class), DriveExportRequestForm.builder().query(query).build()); + assertEquals(200, response.getStatus()); + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + ((StreamingOutput) response.getEntity()).write(out); + return out.toString(StandardCharsets.UTF_8); + } + + /** Content Search's export of the same contentlets. */ + private static String contentSearchCsv(final List contentlets) throws Exception { + final StringWriter out = new StringWriter(); + final HttpServletResponse response = mock(HttpServletResponse.class); + when(response.getWriter()).thenReturn(new PrintWriter(out)); + // The list in the shape Content Search hands over: two leading entries it skips + final List> list = new ArrayList<>(); + list.add(new HashMap<>()); + list.add(new HashMap<>()); + for (final Contentlet contentlet : contentlets) { + final Map entry = new HashMap<>(); + entry.put("inode", contentlet.getInode()); + list.add(entry); + } + new EditContentletAction().downloadToExcel(response, systemUser, list, type.inode()); + return out.toString(); + } + + /** Every data row of a CSV as column name to value, keyed by identifier and language. */ + private static Map> rowsByKey(final String csv) throws Exception { + final CsvReader reader = new CsvReader(new StringReader(csv)); + reader.setSafetySwitch(false); + reader.readHeaders(); + final String[] headers = reader.getHeaders(); + final Map> rows = new LinkedHashMap<>(); + while (reader.readRecord()) { + final Map row = new LinkedHashMap<>(); + for (int i = 0; i < headers.length; i++) { + row.put(headers[i], reader.get(i)); + } + rows.put(row.get("Identifier") + "|" + row.get("languageCode") + "|" + + row.get("countryCode"), row); + } + reader.close(); + return rows; + } + + /** + * Imports a CSV the way the Content Search import does with a multilingual file and no key + * fields: the identifier column picks the contentlet to update, the language and country + * columns its language. + */ + private static Map> importCsv(final String csv) throws Exception { + final StringReader reader = new StringReader(csv); + final CsvReader csvReader = new CsvReader(reader); + csvReader.setSafetySwitch(false); + csvReader.readHeaders(); + final String[] headers = csvReader.getHeaders(); + int languageColumn = -1; + int countryColumn = -1; + for (int column = 0; column < headers.length; column++) { + if ("languageCode".equals(headers[column])) { + languageColumn = column; + } + if ("countryCode".equals(headers[column])) { + countryColumn = column; + } + } + final HttpServletRequest request = new MockAttributeRequest( + new MockHttpRequestIntegrationTest("localhost", "/").request()).request(); + request.setAttribute(WebKeys.USER, systemUser); + + return ImportUtil.importFile(0L, site.getIdentifier(), type.inode(), new String[]{}, + false, true, systemUser, -1, headers, csvReader, languageColumn, countryColumn, + reader, SystemWorkflowConstants.WORKFLOW_SAVE_ACTION_ID, request); + } + + /** + * Rewrites a CSV with the title column changed as given, leaving every other cell as it was. + * Cells are written back in the format the export uses: quoted only when they hold a comma or + * a line feed, rows ending with CRLF. + */ + private static String withTitlesChanged(final String csv, final Map newTitles) + throws Exception { + final CsvReader reader = new CsvReader(new StringReader(csv)); + reader.setSafetySwitch(false); + reader.readHeaders(); + final String[] headers = reader.getHeaders(); + final StringBuilder out = new StringBuilder(String.join(",", headers)).append("\r\n"); + while (reader.readRecord()) { + final List cells = new ArrayList<>(); + for (int i = 0; i < headers.length; i++) { + String value = reader.get(i); + if ("title".equals(headers[i])) { + value = newTitles.getOrDefault(value, value); + } + cells.add(value.contains(",") || value.contains("\n") + ? "\"" + value.replace("\"", "\"\"") + "\"" : value); + } + out.append(String.join(",", cells)).append("\r\n"); + } + reader.close(); + return out.toString(); + } + + private static Contentlet working(final Contentlet contentlet) throws Exception { + return APILocator.getContentletAPI().findContentletByIdentifier( + contentlet.getIdentifier(), false, contentlet.getLanguageId(), systemUser, false); + } + + // --------------------------------------------------------------------------------------------- + // tests + // --------------------------------------------------------------------------------------------- + + /** + * Method to test: {@link ContentDriveResource#export} then {@link ImportUtil#importFile} + * Given Scenario: (a) Contentlets in folder {@code /rt/}, at the site root and in System Host, + * exported in filter mode, one text value changed per row, and imported back + * with the identifier as the key + * ExpectedResult: No row errors, every value updated, and every contentlet still in its host + * and folder (SC-003, SC-004) + */ + @Test + public void test_exportedCsv_importsBackInPlace() throws Exception { + final String exported = driveCsv(); + final Map newTitles = Map.of("rt-folder", "rt-folder edited", + "rt-root", "rt-root edited", "rt-system", "rt-system edited"); + final String edited = withTitlesChanged(exported, newTitles); + assertEquals("fixture: the three rows are exported and edited", 3, + rowsByKey(edited).values().stream() + .filter(row -> newTitles.containsValue(row.get("title"))).count()); + + final Map> results = importCsv(edited); + + assertEquals("row errors: " + results.get("errors"), 0, results.get("errors").size()); + + final Map expectedTitles = new LinkedHashMap<>(); + expectedTitles.put(inFolder, "rt-folder edited"); + expectedTitles.put(atSiteRoot, "rt-root edited"); + expectedTitles.put(inSystemHost, "rt-system edited"); + for (final Map.Entry entry : expectedTitles.entrySet()) { + final Contentlet before = entry.getKey(); + final Contentlet after = working(before); + assertNotNull(after); + assertEquals(entry.getValue(), after.getStringProperty("title")); + assertEquals(entry.getValue() + ": same host", before.getHost(), after.getHost()); + assertEquals(entry.getValue() + ": same folder", before.getFolder(), after.getFolder()); + } + assertEquals("the folder row stays in /rt/", folder.getInode(), working(inFolder).getFolder()); + assertEquals("the root row stays on the site", site.getIdentifier(), + working(atSiteRoot).getHost()); + assertEquals("the root row stays at the root", FolderAPI.SYSTEM_FOLDER, + working(atSiteRoot).getFolder()); + assertEquals("the System Host row stays in System Host", Host.SYSTEM_HOST, + working(inSystemHost).getHost()); + } + + /** + * Method to test: {@link ContentDriveResource#export} against + * {@link EditContentletAction#downloadToExcel} + * Given Scenario: (b) The same contentlets exported by the Drive and by Content Search + * ExpectedResult: The same header, the same rows, and every column equal except host/folder + * (FR-021) + */ + @Test + public void test_driveCsv_equalsContentSearchExceptHostFolder() throws Exception { + final Map> drive = rowsByKey(driveCsv()); + final Map> contentSearch = rowsByKey( + contentSearchCsv(List.of(inFolder, atSiteRoot, inSystemHost))); + + assertEquals("the same rows", contentSearch.keySet(), drive.keySet()); + for (final String key : contentSearch.keySet()) { + final Map driveRow = new LinkedHashMap<>(drive.get(key)); + final Map contentSearchRow = new LinkedHashMap<>(contentSearch.get(key)); + assertEquals("the same columns in the same order", + new ArrayList<>(contentSearchRow.keySet()), new ArrayList<>(driveRow.keySet())); + driveRow.remove(LOCATION); + contentSearchRow.remove(LOCATION); + assertEquals(key, contentSearchRow, driveRow); + } + } +} From aaf56fff31dfa2f17b79e885fa4982b899404ede Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 12:06:03 -0500 Subject: [PATCH 18/28] test(content-drive): cover exporting selected contentlets as a zip Tests approved before the implementation for selection-mode export of contentlets (#37900): one CSV per content type in a zip named after the site, each contentlet in its selected language, archived and System Host content included, the selection winning over the listing's filters, repeated or edited entries exported once, unexportable entries dropped without a trace, distinct and safe entry names, the 60-item limit and the site 404. Postman, button, toolbar, action center and Playwright tests cover the same flow. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- .../content-drive-export.spec.ts | 86 ++++ ...tent-drive-action-center.component.spec.ts | 39 ++ ...tent-drive-export-button.component.spec.ts | 224 ++++++++- ...ot-content-drive-toolbar.component.spec.ts | 25 +- .../src/test/java/com/dotcms/MainSuite2a.java | 1 + .../ContentDriveExportSelectionModeTest.java | 458 ++++++++++++++++++ ...ntentDriveResource.postman_collection.json | 112 ++++- 7 files changed, 939 insertions(+), 6 deletions(-) create mode 100644 dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportSelectionModeTest.java diff --git a/core-web/apps/dotcms-ui-e2e/src/tests/content-drive/content-drive-export.spec.ts b/core-web/apps/dotcms-ui-e2e/src/tests/content-drive/content-drive-export.spec.ts index 6f3f93b0f35d..2e14d5209992 100644 --- a/core-web/apps/dotcms-ui-e2e/src/tests/content-drive/content-drive-export.spec.ts +++ b/core-web/apps/dotcms-ui-e2e/src/tests/content-drive/content-drive-export.spec.ts @@ -68,4 +68,90 @@ test.describe('Content Drive export', () => { await deleteContentType(request, contentType.id); } }); + + /** + * Selection mode (US2): selected contentlets of several types export as one zip, named after + * the site: `_export_.zip`. Which CSVs the zip holds, and their rows, are + * `ContentDriveExportSelectionModeTest`'s; the body the button sends is the component spec's. + */ + test('downloads selected contentlets of two types as _export_.zip @critical', async ({ + adminPage, + request, + testSuffix + }) => { + const suffix = testSuffix.replace(/[^a-zA-Z0-9]/g, ''); + const typeNames = [`CdExportBlog${suffix}`, `CdExportNews${suffix}`]; + const contentTypes: { id: string; variable: string }[] = []; + const contentletIds: string[] = []; + const titles: string[] = []; + + try { + for (const typeName of typeNames) { + const contentType = await createFakeContentType(request, { + name: typeName, + variable: typeName, + fields: [ + createFakePayloadTextField({ + name: 'Title', + variable: 'title', + sortOrder: 1 + }) + ] + }); + contentTypes.push(contentType); + + const title = `${typeName} selected`; + const contentlet = await createContentlet(request, { + contentType: contentType.variable, + title + }); + contentletIds.push(contentlet.identifier); + titles.push(title); + } + + const drive = new ContentDrivePage(adminPage); + + // Narrowed to the two new types so both rows are on the first page; the selection, not + // this filter, is what gets exported. + await adminPage.goto( + `${Portlet.ContentDrive}?filters=${encodeURIComponent( + `contentType:${contentTypes.map((type) => type.variable).join(',')}` + )}` + ); + await expect(drive.toolbar).toBeVisible({ timeout: 20000 }); + + for (const title of titles) { + await drive.expectListContainsTitle(title); + await adminPage + .getByTestId('item-row') + .filter({ + has: adminPage.getByTestId('item-title-text').getByText(title, { + exact: true + }) + }) + .getByTestId('item-checkbox') + .click(); + } + + // With a selection the button sits beside the workflow actions. + await expect(drive.toolbar.getByTestId('workflow-actions')).toBeVisible({ + timeout: 20000 + }); + const exportButton = drive.toolbar.getByTestId('export-button').getByRole('button'); + await expect(exportButton).toBeEnabled({ timeout: 20000 }); + + // Armed before the click, or a fast server finishes before anything is listening. + const download = adminPage.waitForEvent('download', { timeout: 60000 }); + await exportButton.click(); + + expect((await download).suggestedFilename()).toMatch( + /^.+_export_\d{1,2}_\d{1,2}_\d{4}\.zip$/ + ); + } finally { + await deleteContentlets(request, contentletIds); + for (const contentType of contentTypes) { + await deleteContentType(request, contentType.id); + } + } + }); }); diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dialogs/dot-content-drive-action-center/dot-content-drive-action-center.component.spec.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dialogs/dot-content-drive-action-center/dot-content-drive-action-center.component.spec.ts index 218294ccdfd4..93fe30231e8b 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dialogs/dot-content-drive-action-center/dot-content-drive-action-center.component.spec.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dialogs/dot-content-drive-action-center/dot-content-drive-action-center.component.spec.ts @@ -1003,6 +1003,45 @@ describe('DotContentDriveActionCenterComponent', () => { }); }); + // Export (#37900) is a toolbar button beside the workflow actions, not an Action Center row: it + // has no preview, no eligible subset and nothing to run over the selection (T074). + describe('export is not offered here', () => { + beforeEach(() => { + // Every row the dialog can show: an admin, with an environment to push to, over + // contentlets and a folder. + mockCurrentUserIsAdmin.set(true); + mockHasPushPublishEnvironments.set(true); + mockSelectedItems.set([ + contentlet({ inode: 'inode-1' }), + contentlet({ inode: 'inode-2', live: true }), + folderRow('folder-1', '/blogs/folder-1/') + ]); + spectator.detectChanges(); + }); + + it('should label no quick action Export', () => { + // The row buttons only: the warning icon and coming-soon badge share the prefix. + const rows = spectator.queryAll( + 'button[data-testid^="quick-action-"]' + ); + + expect(rows.length).toBeGreaterThan(0); + expect(spectator.query('[data-testid="quick-action-EXPORT"]')).toBeNull(); + + // The message mock echoes keys, so a row labeled from any export key reads "export". + for (const row of rows) { + expect(row.textContent).not.toMatch(/\bexport\b/i); + } + }); + + it('should label no row in the dialog Export', () => { + const dialog = spectator.query('[data-testid="action-center"]'); + + expect(dialog).toBeTruthy(); + expect(dialog?.textContent).not.toMatch(/\bexport\b/i); + }); + }); + describe('lock and unlock quick actions', () => { it('should fire LOCK with only the unlocked inodes', () => { mockSelectedItems.set([ diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts index 0d4e7916b1dd..63721129b6d7 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts @@ -16,6 +16,7 @@ vi.mock('@dotcms/utils', async () => ({ import { signal } from '@angular/core'; import { MessageService } from 'primeng/api'; +import { Tooltip } from 'primeng/tooltip'; import { DotContentDriveExportResult, @@ -26,7 +27,8 @@ import { import { DotCMSBaseTypesContentTypes, DotContentDriveItem, - DotContentDriveSearchRequest + DotContentDriveSearchRequest, + DotSite } from '@dotcms/dotcms-models'; import { getDownloadLink } from '@dotcms/utils'; import { @@ -94,7 +96,45 @@ const EMPTY_RESULT: DotContentDriveExportResult = { kind: 'empty' }; /** The message the service errors with once it has read the server's error body. */ const SERVER_MESSAGE = 'Server says no'; -describe('DotContentDriveExportButtonComponent (filter mode)', () => { +/** + * The most items selection mode exports at once (FR-002a). + * + * Declared here until T082 adds `MAX_SELECTION_ITEMS` to `shared/constants.ts`; once it exists, + * import it instead so the spec and the button cannot drift apart. + */ +const MAX_SELECTION_ITEMS = 60; + +/** The site Content Drive is browsing: selection mode sends its identifier as `siteId`. */ +const CURRENT_SITE: DotSite = { + aliases: '', + archived: false, + hostname: 'demo.dotcms.com', + identifier: 'site-001' +}; + +/** Copy for the limit tooltip, so the test reads the sentence the user sees. */ +const MAX_ITEMS_TOOLTIP = 'You can export at most 60 items at once'; + +/** A selected contentlet, carrying the two values selection mode sends for it. */ +const selectedContentlet = (identifier: string, languageId: number): DotContentDriveItem => + createFakeContentlet({ identifier, inode: `inode-${identifier}-${languageId}`, languageId }); + +/** `count` distinct selected contentlets, all in English. */ +const selectedContentlets = (count: number): DotContentDriveItem[] => + Array.from({ length: count }, (_, index) => selectedContentlet(`contentlet-${index}`, 1)); + +/** A selection-mode 200: the zip, holding one CSV per content type. */ +const ZIP_RESULT: DotContentDriveExportResult = { + kind: 'file', + blob: new Blob(['zip']), + fileName: 'demo.dotcms.com_export_11_26_2026.zip', + contentlets: 3, + files: 2 +}; + +// The describes at this level are filter mode (nothing selected); selection mode has its own block +// at the end. +describe('DotContentDriveExportButtonComponent', () => { let spectator: Spectator; let exportService: SpyObject; let contentTypeService: SpyObject; @@ -106,6 +146,7 @@ describe('DotContentDriveExportButtonComponent (filter mode)', () => { const itemsSignal = signal([CONTENTLET]); const pagesSignal = signal([LAST_PAGE]); const requestSignal = signal(REQUEST); + const currentSiteSignal = signal(CURRENT_SITE); const messageServiceSpy = { add: vi.fn(), clear: vi.fn() }; const anchorClick = vi.fn(); @@ -119,7 +160,8 @@ describe('DotContentDriveExportButtonComponent (filter mode)', () => { status: statusSignal, items: itemsSignal, pages: pagesSignal, - $request: requestSignal + $request: requestSignal, + currentSite: currentSiteSignal }), mockProvider(DotContentTypeService, { getContentType: vi.fn((variable: string) => @@ -146,7 +188,8 @@ describe('DotContentDriveExportButtonComponent (filter mode)', () => { 'content-drive.toast.export-success-detail': '{0} items exported in {1} file(s)', 'content-drive.toast.export-empty': 'There is nothing to export', - 'content-drive.toast.export-error': 'Export failed' + 'content-drive.toast.export-error': 'Export failed', + 'content-drive.export.tooltip.max-items': MAX_ITEMS_TOOLTIP }) } ], @@ -188,6 +231,7 @@ describe('DotContentDriveExportButtonComponent (filter mode)', () => { itemsSignal.set([CONTENTLET]); pagesSignal.set([LAST_PAGE]); requestSignal.set(REQUEST); + currentSiteSignal.set(CURRENT_SITE); }); describe('shown', () => { @@ -448,4 +492,176 @@ describe('DotContentDriveExportButtonComponent (filter mode)', () => { expectNotLoading(); }); }); + + // Selection mode (#37900, US2): with anything selected, the button exports the selected + // contentlets as a zip, whatever the listing is filtered to. Folders are Phase 9's (T085). + describe('selection mode', () => { + /** The wrapper the limit tooltip hangs off: a disabled button fires no tooltip itself. */ + const exportTooltipWrapper = () => + spectator.query(byTestId('content-drive-export-tooltip')); + + /** The tooltip directive on that wrapper, read for the text it would show. */ + // A string selector, not byTestId: Spectator ignores `read` for DOM selectors and would + // return the span instead of the Tooltip directive. + const exportTooltip = () => + spectator.query('[data-testid="content-drive-export-tooltip"]', { read: Tooltip }); + + describe('shown', () => { + it('should show when something is selected and no content type is filtered', async () => { + filtersSignal.set({}); + selectedItemsSignal.set([selectedContentlet('blog-1', 1)]); + await render(); + + expect(exportButtonHost()).toBeTruthy(); + expect(exportButtonHost()?.textContent).toContain('Export'); + }); + + it('should show when something is selected and several content types are filtered', async () => { + filtersSignal.set({ contentType: ['Blog', 'News'] }); + selectedItemsSignal.set([selectedContentlet('blog-1', 1)]); + await render(); + + expect(exportButtonHost()).toBeTruthy(); + }); + + it('should show when something is selected and the one filtered type is a Form', async () => { + // The Form rule is filter mode's: the server drops Form contentlets from a + // selection itself, so the button does not hide over the filter. + filtersSignal.set({ contentType: [FORM_VARIABLE] }); + selectedItemsSignal.set([selectedContentlet('blog-1', 1)]); + await render(); + + expect(exportButtonHost()).toBeTruthy(); + }); + }); + + describe('item limit', () => { + it(`should be enabled with exactly ${MAX_SELECTION_ITEMS} items selected`, async () => { + selectedItemsSignal.set(selectedContentlets(MAX_SELECTION_ITEMS)); + await render(); + + expect(exportButton()).toBeTruthy(); + expect(exportButton()?.disabled).toBe(false); + expect(exportTooltip()?.content ?? '').toBe(''); + }); + + it(`should be disabled with more than ${MAX_SELECTION_ITEMS} items selected`, async () => { + selectedItemsSignal.set(selectedContentlets(MAX_SELECTION_ITEMS + 1)); + await render(); + + expect(exportButton()).toBeTruthy(); + expect(exportButton()?.disabled).toBe(true); + }); + + it('should say why it is disabled on a wrapper, not on the disabled button', async () => { + selectedItemsSignal.set(selectedContentlets(MAX_SELECTION_ITEMS + 1)); + await render(); + + const wrapper = exportTooltipWrapper(); + + expect(wrapper?.tagName).toBe('SPAN'); + expect(wrapper?.contains(exportButtonHost())).toBe(true); + expect(exportTooltip()?.content).toBe(MAX_ITEMS_TOOLTIP); + }); + }); + + describe('click', () => { + it('should send the selected contentlets with the current site, and no query', async () => { + // Two language versions of one Blog and a News: each entry is its own row. + selectedItemsSignal.set([ + selectedContentlet('blog-1', 1), + selectedContentlet('blog-1', 2), + selectedContentlet('news-1', 1) + ]); + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(exportService.export).toHaveBeenCalledTimes(1); + expect(exportService.export).toHaveBeenCalledWith({ + siteId: CURRENT_SITE.identifier, + selection: { + folders: [], + contentlets: [ + { identifier: 'blog-1', languageId: 1 }, + { identifier: 'blog-1', languageId: 2 }, + { identifier: 'news-1', languageId: 1 } + ] + } + }); + }); + + it('should not send a selected folder as a contentlet', async () => { + selectedItemsSignal.set([selectedContentlet('blog-1', 1), FOLDER]); + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(exportService.export).toHaveBeenCalledTimes(1); + expect(exportService.export).toHaveBeenCalledWith( + expect.objectContaining({ + siteId: CURRENT_SITE.identifier, + selection: expect.objectContaining({ + contentlets: [{ identifier: 'blog-1', languageId: 1 }] + }) + }) + ); + }); + }); + + describe('on success', () => { + beforeEach(() => { + exportService.export.mockReturnValue(of(ZIP_RESULT)); + selectedItemsSignal.set([ + selectedContentlet('blog-1', 1), + selectedContentlet('blog-2', 1), + selectedContentlet('news-1', 1) + ]); + }); + + it('should download the zip under the name the server gave', async () => { + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(getDownloadLink).toHaveBeenCalledWith(ZIP_RESULT.blob, ZIP_RESULT.fileName); + expect(anchorClick).toHaveBeenCalledTimes(1); + }); + + it('should show a success toast with the exported items and files', async () => { + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(messageServiceSpy.add).toHaveBeenCalledWith( + expect.objectContaining({ + severity: 'success', + summary: 'Export ready', + detail: '3 items exported in 2 file(s)', + life: SUCCESS_MESSAGE_LIFE + }) + ); + }); + }); + + describe('on error', () => { + it('should show an error toast with the server message and download nothing', async () => { + exportService.export.mockReturnValue(throwError(() => new Error(SERVER_MESSAGE))); + selectedItemsSignal.set([selectedContentlet('blog-1', 1)]); + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(messageServiceSpy.add).toHaveBeenCalledWith( + expect.objectContaining({ + severity: 'error', + summary: 'Export failed', + detail: SERVER_MESSAGE, + life: ERROR_MESSAGE_LIFE + }) + ); + expect(getDownloadLink).not.toHaveBeenCalled(); + }); + }); + }); }); diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.spec.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.spec.ts index 3457c2f3a25c..6f7d4c1c098b 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.spec.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.spec.ts @@ -195,7 +195,9 @@ describe('DotContentDriveToolbarComponent', () => { status: signal(DotContentDriveStatus.LOADED), items: signal([]), pages: signal([DEFAULT_PAGE]), - $request: signal({ assetPath: '//demo.dotcms.com/' }) + $request: signal({ assetPath: '//demo.dotcms.com/' }), + // Selection mode sends the browsed site's identifier as `siteId`. + currentSite: signal({ identifier: 'site-001', hostname: 'demo.dotcms.com' }) }), mockProvider(DotContentTypeService, { getContentTypes: vi.fn().mockReturnValue(of(MOCK_CONTENT_TYPES)), @@ -700,6 +702,27 @@ describe('DotContentDriveToolbarComponent', () => { expect(exportButton).toBeTruthy(); expect(block?.contains(exportButton)).toBe(true); }); + + // Selection mode (US2): the same button moves beside the workflow actions, since Upload + // and Add New are hidden while anything is selected. + it('should sit next to the workflow actions when something is selected', async () => { + selectedItemsSignal.set([MOCK_ITEMS[0], MOCK_ITEMS[1]]); + await settleToolbarAnimation(spectator); + + const workflowActions = spectator.query(byTestId('workflow-actions')); + const exportButtons = spectator.queryAll(byTestId('export-button')); + const exportButton = exportButtons[0]; + + expect(workflowActions).toBeTruthy(); + expect(exportButtons).toHaveLength(1); + expect(exportButton.parentElement).toBe(workflowActions?.parentElement); + expect([ + exportButton.previousElementSibling, + exportButton.nextElementSibling + ]).toContain(workflowActions); + // The creation block is gone, so the button cannot be sitting in it. + expect(spectator.query(byTestId('upload-asset-tooltip'))).toBeNull(); + }); }); describe('Workflow Center button', () => { diff --git a/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java b/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java index 70917328a284..4030ebce0d36 100644 --- a/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java +++ b/dotcms-integration/src/test/java/com/dotcms/MainSuite2a.java @@ -149,6 +149,7 @@ com.dotcms.publisher.receiver.BundlePluginDeploymentTest.class, com.dotcms.rest.api.v1.drive.export.ContentDriveExportPermissionTest.class, com.dotcms.rest.api.v1.drive.ContentDriveExportRoundTripTest.class, + com.dotcms.rest.api.v1.drive.ContentDriveExportSelectionModeTest.class, com.dotmarketing.portlets.contentlet.transform.ContentMapWidgetFieldRenderTest.class, ApiTokenResourceTest.class, AuthCredentialPushPublishUtilTest.class, diff --git a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportSelectionModeTest.java b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportSelectionModeTest.java new file mode 100644 index 000000000000..1f9c128b4251 --- /dev/null +++ b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportSelectionModeTest.java @@ -0,0 +1,458 @@ +package com.dotcms.rest.api.v1.drive; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +import com.dotcms.IntegrationTestBase; +import com.dotcms.contenttype.model.field.TextField; +import com.dotcms.contenttype.model.type.BaseContentType; +import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.datagen.ContentTypeDataGen; +import com.dotcms.datagen.ContentletDataGen; +import com.dotcms.datagen.FieldDataGen; +import com.dotcms.datagen.LanguageDataGen; +import com.dotcms.datagen.RoleDataGen; +import com.dotcms.datagen.SiteDataGen; +import com.dotcms.datagen.UserDataGen; +import com.dotcms.mock.request.MockAttributeRequest; +import com.dotcms.mock.request.MockHttpRequestIntegrationTest; +import com.dotcms.rest.ErrorEntity; +import com.dotcms.rest.ResponseEntityView; +import com.dotcms.rest.api.v1.drive.export.DriveExportRequestForm; +import com.dotcms.rest.api.v1.drive.export.ExportContentletRefForm; +import com.dotcms.rest.api.v1.drive.export.ExportFileBuilder; +import com.dotcms.rest.api.v1.drive.export.ExportFileNames; +import com.dotcms.rest.api.v1.drive.export.ExportSelectionForm; +import com.dotcms.util.IntegrationTestInitService; +import com.dotmarketing.beans.Host; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.languagesmanager.model.Language; +import com.liferay.portal.model.User; +import com.liferay.portal.util.WebKeys; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.StreamingOutput; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Integration tests for {@code POST /api/v1/drive/export} in selection mode, contentlet part + * (User Story 2; FR-002, FR-002a, FR-003, FR-004a, FR-008, FR-016 – FR-019): the selected + * contentlets, each in its selected language, as a zip with one CSV per content type. + */ +public class ContentDriveExportSelectionModeTest extends IntegrationTestBase { + + private static final String TOO_MANY = "You can export at most 60 items at once."; + private static final String FOLDER_NOT_FOUND = "Folder not found."; + + /** Calls the endpoint: a REST request never runs as the system user. */ + private static User adminUser; + /** A back-end user who can read nothing on the site. */ + private static User limitedUser; + private static Host site; + private static Language defaultLanguage; + private static Language secondLanguage; + + private static ContentType blog; + private static ContentType news; + private static ContentType twinOne; + private static ContentType twinTwo; + private static ContentType unsafeName; + + private static Contentlet blogOne; + private static Contentlet blogOneSecondLanguage; + private static Contentlet blogTwo; + private static Contentlet newsOne; + private static Contentlet archivedBlog; + private static Contentlet editedBlog; + private static Contentlet newsInSystemHost; + private static Contentlet inOtherSite; + private static Contentlet formEntry; + private static Contentlet twinOneEntry; + private static Contentlet twinTwoEntry; + private static Contentlet unsafeNameEntry; + + @BeforeClass + public static void prepare() throws Exception { + IntegrationTestInitService.getInstance().init(); + adminUser = new UserDataGen().roles(APILocator.getRoleAPI().loadCMSAdminRole(), + APILocator.getRoleAPI().loadBackEndUserRole()).nextPersisted(); + limitedUser = new UserDataGen().roles(new RoleDataGen().nextPersisted(), + APILocator.getRoleAPI().loadBackEndUserRole()).nextPersisted(); + + final String unique = String.valueOf(System.currentTimeMillis()); + site = new SiteDataGen().name("drive-selection-" + unique + ".local").nextPersisted(); + final Host otherSite = new SiteDataGen().name("drive-selection-other-" + unique + ".local") + .nextPersisted(); + defaultLanguage = APILocator.getLanguageAPI().getDefaultLanguage(); + secondLanguage = new LanguageDataGen().nextPersisted(); + + blog = titledType("Blog" + unique, "driveSelBlog" + unique); + news = titledType("News" + unique, "driveSelNews" + unique); + twinOne = titledType("Twin " + unique, "driveSelTwinOne" + unique); + twinTwo = titledType("Twin " + unique, "driveSelTwinTwo" + unique); + unsafeName = titledType("A/B: C", "driveSelUnsafe" + unique); + + blogOne = entry(blog, site, "blog one"); + final Contentlet secondLanguageDraft = ContentletDataGen.checkout(blogOne); + secondLanguageDraft.setLanguageId(secondLanguage.getId()); + blogOneSecondLanguage = ContentletDataGen.checkin(secondLanguageDraft); + blogTwo = entry(blog, site, "blog two"); + newsOne = entry(news, site, "news one"); + + archivedBlog = ContentletDataGen.publish(entry(blog, site, "archived blog")); + ContentletDataGen.archive(archivedBlog); + + editedBlog = entry(blog, site, "before edit"); + newsInSystemHost = entry(news, APILocator.systemHost(), "shared news"); + inOtherSite = entry(blog, otherSite, "other site blog"); + + final ContentType formType = new ContentTypeDataGen() + .baseContentType(BaseContentType.FORM).host(site) + .name("DriveSelForm" + unique).velocityVarName("driveSelForm" + unique) + .nextPersisted(); + formEntry = new ContentletDataGen(formType).host(site).nextPersistedWithSampleTextValues(); + + twinOneEntry = entry(twinOne, site, "twin one"); + twinTwoEntry = entry(twinTwo, site, "twin two"); + unsafeNameEntry = entry(unsafeName, site, "unsafe"); + } + + private static ContentType titledType(final String name, final String variable) { + return new ContentTypeDataGen().host(site).name(name).velocityVarName(variable) + .field(new FieldDataGen().defaultValue(null).type(TextField.class).name("title") + .velocityVarName("title").next()) + .nextPersisted(); + } + + private static Contentlet entry(final ContentType type, final Host host, final String title) { + return new ContentletDataGen(type).host(host).languageId(defaultLanguage.getId()) + .setProperty("title", title).nextPersisted(); + } + + // --------------------------------------------------------------------------------------------- + // helpers + // --------------------------------------------------------------------------------------------- + + private static ExportContentletRefForm ref(final Contentlet contentlet) { + return ExportContentletRefForm.builder().identifier(contentlet.getIdentifier()) + .languageId(contentlet.getLanguageId()).build(); + } + + private static DriveExportRequestForm.Builder selection(final String siteId, + final List contentlets) { + return DriveExportRequestForm.builder().siteId(siteId) + .selection(ExportSelectionForm.builder().contentlets(contentlets).build()); + } + + private static DriveExportRequestForm selectionOf(final Contentlet... contentlets) { + return selection(site.getIdentifier(), Stream.of(contentlets) + .map(ContentDriveExportSelectionModeTest::ref).collect(Collectors.toList())) + .build(); + } + + private static HttpServletRequest requestAs(final User user) { + final HttpServletRequest request = new MockAttributeRequest( + new MockHttpRequestIntegrationTest("localhost", "/api/v1/drive/export").request()) + .request(); + request.setAttribute(WebKeys.USER, user); + return request; + } + + private static Response export(final DriveExportRequestForm form, final User user) { + return new ContentDriveResource().export(requestAs(user), mock(HttpServletResponse.class), + form); + } + + private static Response export(final DriveExportRequestForm form) { + return export(form, adminUser); + } + + private static String header(final Response response, final String name) { + final Object value = response.getMetadata().getFirst(name); + return value == null ? null : value.toString(); + } + + private static String errorMessage(final Response response) { + assertTrue("the error body is a ResponseEntityView", + response.getEntity() instanceof ResponseEntityView); + final List errors = ((ResponseEntityView) response.getEntity()).getErrors(); + return errors.get(0).getMessage(); + } + + /** The zip's entries, name to CSV text, in entry order. */ + private static Map zipEntries(final Response response) throws Exception { + assertEquals(200, response.getStatus()); + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + ((StreamingOutput) response.getEntity()).write(out); + final Map entries = new LinkedHashMap<>(); + try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()))) { + for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { + entries.put(entry.getName(), new String(zip.readAllBytes(), StandardCharsets.UTF_8)); + } + } + return entries; + } + + /** The data rows of a CSV, split on commas (the fixtures hold no comma in any value). */ + private static List> dataRows(final String csv) { + final String[] lines = csv.split("\r\n"); + final List> rows = new ArrayList<>(); + for (int i = 1; i < lines.length; i++) { + if (!lines[i].isEmpty()) { + rows.add(List.of(lines[i].split(",", -1))); + } + } + return rows; + } + + /** {@code identifier|languageCode|countryCode} of every row of every entry. */ + private static Set rowKeys(final Map entries) { + final Set keys = new HashSet<>(); + entries.values().forEach(csv -> dataRows(csv) + .forEach(row -> keys.add(row.get(0) + "|" + row.get(1) + "|" + row.get(2)))); + return keys; + } + + private static String keyOf(final Contentlet contentlet) { + final Language language = APILocator.getLanguageAPI().getLanguage(contentlet.getLanguageId()); + return contentlet.getIdentifier() + "|" + language.getLanguageCode() + "|" + + language.getCountryCode(); + } + + private static String csvName(final ContentType type) { + return ExportFileNames.csvName(type.name(), type.variable(), new Date()); + } + + private static Set exportDirectoryFiles() throws Exception { + final Path directory = ExportFileBuilder.defaultDirectory(); + if (!Files.exists(directory)) { + return Set.of(); + } + try (Stream files = Files.list(directory)) { + return files.collect(Collectors.toSet()); + } + } + + // --------------------------------------------------------------------------------------------- + // tests + // --------------------------------------------------------------------------------------------- + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (a) Two Blog contentlets in the default language (one also has an unselected + * second-language version) and one News contentlet are selected + * ExpectedResult: A zip named after the site with one CSV per type: Blog with the 2 selected + * rows only, News with 1; 3 rows in 2 files + */ + @Test + public void test_selectedContentlets_exportOneCsvPerType() throws Exception { + final Response response = export(selectionOf(blogOne, blogTwo, newsOne)); + + assertEquals(200, response.getStatus()); + assertEquals("application/zip", header(response, "Content-Type")); + assertEquals(ExportFileNames.contentDisposition( + ExportFileNames.zipName(site.getHostname(), new Date())), + header(response, "Content-Disposition")); + assertEquals("3", header(response, "X-Export-Contentlets")); + assertEquals("2", header(response, "X-Export-Files")); + + final Map entries = zipEntries(response); + assertEquals(Set.of(csvName(blog), csvName(news)), entries.keySet()); + final Set blogRows = rowKeys(Map.of("blog", entries.get(csvName(blog)))); + assertEquals(Set.of(keyOf(blogOne), keyOf(blogTwo)), blogRows); + assertFalse("the unselected language is not exported", + blogRows.contains(keyOf(blogOneSecondLanguage))); + assertEquals(Set.of(keyOf(newsOne)), rowKeys(Map.of("news", entries.get(csvName(news))))); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (b) Both language versions of one contentlet are selected + * ExpectedResult: Both rows, each with its own language and country code + */ + @Test + public void test_bothLanguagesSelected_giveBothRows() throws Exception { + final Map entries = + zipEntries(export(selectionOf(blogOne, blogOneSecondLanguage))); + + assertEquals(Set.of(keyOf(blogOne), keyOf(blogOneSecondLanguage)), rowKeys(entries)); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (c) An archived contentlet is selected; (h) a System Host contentlet is + * selected + * ExpectedResult: Both are exported + */ + @Test + public void test_archivedAndSystemHostSelections_areExported() throws Exception { + final Map entries = + zipEntries(export(selectionOf(archivedBlog, newsInSystemHost))); + + assertEquals(Set.of(keyOf(archivedBlog), keyOf(newsInSystemHost)), rowKeys(entries)); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (d) The selection of (a), sent with a query naming another content type, a + * text, a workflow, a status and another language + * ExpectedResult: The same rows as without the query: the selection wins (FR-003, FR-008) + */ + @Test + public void test_query_doesNotChangeASelection() throws Exception { + final Set plain = rowKeys(zipEntries(export(selectionOf(blogOne, blogTwo, newsOne)))); + + final DriveRequestForm query = DriveRequestForm.builder() + .assetPath("//" + site.getHostname() + "/") + .contentTypes(List.of(twinOne.variable())) + .language(List.of(String.valueOf(secondLanguage.getId()))) + .status(List.of("ARCHIVED")) + .workflow(List.of(WorkflowFilterForm.builder() + .scheme(UUID.randomUUID().toString()).build())) + .filters(QueryFilters.builder().text("nothing matches this").build()) + .build(); + final DriveExportRequestForm withQuery = DriveExportRequestForm.builder() + .from(selectionOf(blogOne, blogTwo, newsOne)).query(query).build(); + + assertEquals(plain, rowKeys(zipEntries(export(withQuery)))); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (e) A contentlet is edited after it was selected, so it has a new working + * inode + * ExpectedResult: It is exported once, with the edited values + */ + @Test + public void test_editedAfterSelection_exportsTheEditedValuesOnce() throws Exception { + final DriveExportRequestForm form = selectionOf(editedBlog); + + final Contentlet checkout = ContentletDataGen.checkout(editedBlog); + checkout.setProperty("title", "after edit"); + ContentletDataGen.checkin(checkout); + + final List> rows = dataRows(zipEntries(export(form)).get(csvName(blog))); + assertEquals(1, rows.size()); + assertTrue(rows.get(0).contains("after edit")); + assertFalse(rows.get(0).contains("before edit")); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (f) The same entry is sent twice + * ExpectedResult: It is exported once + */ + @Test + public void test_repeatedEntry_isExportedOnce() throws Exception { + final Response response = export(selectionOf(blogTwo, blogTwo)); + + assertEquals("1", header(response, "X-Export-Contentlets")); + assertEquals(1, dataRows(zipEntries(response).get(csvName(blog))).size()); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (g) A selection with a missing identifier, a contentlet of another site and a + * Form entry besides a valid contentlet + * ExpectedResult: They are dropped silently: the response equals the one for the valid + * contentlet alone (FR-002a) + */ + @Test + public void test_unexportableEntries_areDroppedSilently() throws Exception { + final Response alone = export(selectionOf(blogOne)); + final List mixed = new ArrayList<>(List.of(ref(blogOne), + ExportContentletRefForm.builder().identifier(UUID.randomUUID().toString()) + .languageId(defaultLanguage.getId()).build(), + ref(inOtherSite), ref(formEntry))); + final Response withDropped = export(selection(site.getIdentifier(), mixed).build()); + + assertEquals(alone.getStatus(), withDropped.getStatus()); + assertEquals(header(alone, "X-Export-Contentlets"), + header(withDropped, "X-Export-Contentlets")); + assertEquals(header(alone, "X-Export-Files"), header(withDropped, "X-Export-Files")); + assertEquals(header(alone, "Content-Disposition"), + header(withDropped, "Content-Disposition")); + assertEquals(zipEntries(alone), zipEntries(withDropped)); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (i) Two content types with the same name; (j) a content type named + * {@code A/B: C} + * ExpectedResult: Two CSVs, the second ending {@code -2}; the unsafe name becomes + * {@code A_B_ C} (FR-019) + */ + @Test + public void test_entryNames_areDistinctAndSafe() throws Exception { + final Map entries = + zipEntries(export(selectionOf(twinOneEntry, twinTwoEntry, unsafeNameEntry))); + + // "_contents_.csv", today + final String suffix = ExportFileNames.csvName("x", "x", new Date()).substring(1); + assertTrue(entries.containsKey(twinOne.name() + suffix)); + assertTrue(entries.containsKey(twinOne.name() + suffix.replace(".csv", "-2.csv"))); + assertTrue(entries.containsKey("A_B_ C" + suffix)); + assertEquals(3, entries.size()); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (k) 61 entries + * ExpectedResult: 400 with the 60-item message, and no file left (FR-004a) + */ + @Test + public void test_moreThanSixtyEntries_isRefused() throws Exception { + final Set before = exportDirectoryFiles(); + final List refs = new ArrayList<>(); + for (int i = 0; i < 61; i++) { + refs.add(ref(blogOne)); + } + + final Response response = export(selection(site.getIdentifier(), refs).build()); + + assertEquals(400, response.getStatus()); + assertEquals(TOO_MANY, errorMessage(response)); + final Set added = new HashSet<>(exportDirectoryFiles()); + added.removeAll(before); + assertEquals("no temp file is left", Set.of(), added); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (l) A {@code siteId} that does not exist, and one the user cannot read + * ExpectedResult: 404 "Folder not found." both times, with the same message (FR-014) + */ + @Test + public void test_missingOrUnreadableSite_isNotFound() { + final Response missing = export(selection(UUID.randomUUID().toString(), + List.of(ref(blogOne))).build()); + final Response unreadable = export(selectionOf(blogOne), limitedUser); + + assertEquals(404, missing.getStatus()); + assertEquals(FOLDER_NOT_FOUND, errorMessage(missing)); + assertEquals(404, unreadable.getStatus()); + assertEquals(FOLDER_NOT_FOUND, errorMessage(unreadable)); + } +} diff --git a/dotcms-postman/src/main/resources/postman/ContentDriveResource.postman_collection.json b/dotcms-postman/src/main/resources/postman/ContentDriveResource.postman_collection.json index 83d91a524f44..36aa99790dbf 100644 --- a/dotcms-postman/src/main/resources/postman/ContentDriveResource.postman_collection.json +++ b/dotcms-postman/src/main/resources/postman/ContentDriveResource.postman_collection.json @@ -2807,7 +2807,11 @@ "pm.test(\"Three contentlets created\", function () {", " pm.expect(jsonData.errors.length).to.eql(0);", " pm.expect(jsonData.entity.results.length).to.eql(3);", - "});" + "});", + "", + "// Kept for the selection-mode requests below", + "var firstResult = jsonData.entity.results[0];", + "pm.collectionVariables.set(\"exportContentlet1Id\", firstResult[Object.keys(firstResult)[0]].identifier);" ], "type": "text/javascript" } @@ -3016,6 +3020,112 @@ }, "response": [] }, + { + "name": "Export - Selection Of Two Types Returns A Zip", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code should be 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "pm.test(\"The body is a zip\", function () {", + " pm.expect(pm.response.headers.get('Content-Type')).to.match(/^application\\/zip/);", + "});", + "", + "pm.test(\"One CSV per content type\", function () {", + " pm.expect(pm.response.headers.get('X-Export-Files')).to.eql('2');", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"siteId\": \"{{testSiteId}}\",\n \"selection\": {\n \"contentlets\": [\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{alphaContentlet1Id}}\",\n \"languageId\": 1\n }\n ]\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{serverURL}}/api/v1/drive/export", + "host": [ + "{{serverURL}}" + ], + "path": [ + "api", + "v1", + "drive", + "export" + ] + } + }, + "response": [] + }, + { + "name": "Export - More Than 60 Selected Items Are Rejected", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code should be 400\", function () {", + " pm.response.to.have.status(400);", + "});", + "", + "pm.test(\"The message gives the limit\", function () {", + " pm.expect(pm.response.json().errors[0].message).to.eql('You can export at most 60 items at once.');", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"siteId\": \"{{testSiteId}}\",\n \"selection\": {\n \"contentlets\": [\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n },\n {\n \"identifier\": \"{{exportContentlet1Id}}\",\n \"languageId\": 1\n }\n ]\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{serverURL}}/api/v1/drive/export", + "host": [ + "{{serverURL}}" + ], + "path": [ + "api", + "v1", + "drive", + "export" + ] + } + }, + "response": [] + }, { "name": "Export - Delete Fresh Content Type", "event": [ From a9cbae2ba011d4025609a0ffb066bd94e33f7f39 Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 12:06:12 -0500 Subject: [PATCH 19/28] feat(content-drive): export selected contentlets of several types With contentlets selected in Content Drive, Export downloads a zip named after the site with one CSV per content type (#37900). Each contentlet is exported in the language it was selected in, as its working version, and only if the user can read it; missing, other-site, Form and Host entries are dropped silently. The selection wins over the listing's filters. The button sits next to the workflow actions and is disabled above 60 selected items. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- .../dot-content-drive-export.service.ts | 31 +++- ...content-drive-export-button.component.html | 23 ++- ...t-content-drive-export-button.component.ts | 90 +++++++++-- .../dot-content-drive-toolbar.component.html | 5 + .../portlet/src/lib/shared/constants.ts | 6 + .../export/ContentDriveExportHelper.java | 73 ++++++++- .../v1/drive/export/SelectionResolver.java | 144 ++++++++++++++++++ .../WEB-INF/messages/Language.properties | 1 + 8 files changed, 352 insertions(+), 21 deletions(-) create mode 100644 dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/SelectionResolver.java diff --git a/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts b/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts index 9d1aaed6bd9d..c1690c50492a 100644 --- a/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts +++ b/core-web/libs/data-access/src/lib/dot-content-drive-export/dot-content-drive-export.service.ts @@ -21,10 +21,33 @@ const GENERIC_EXPORT_ERROR = * Body of `POST /api/v1/drive/export` in filter mode: the same request the listing sends to * `/api/v1/drive/search`. The server ignores its paging, sorting and folder flags. */ -export interface DotContentDriveExportRequest { +export interface DotContentDriveExportFilterRequest { query: DotContentDriveSearchRequest; } +/** One selected contentlet: a language version, so the same identifier may appear once per language. */ +export interface DotContentDriveExportContentlet { + identifier: string; + languageId: number; +} + +/** + * Body of `POST /api/v1/drive/export` in selection mode: the selected items of the site being + * browsed. Folders are sent as `//host/path/` paths; contentlets as identifier and language. + */ +export interface DotContentDriveExportSelectionRequest { + siteId: string; + selection: { + folders: string[]; + contentlets: DotContentDriveExportContentlet[]; + }; +} + +/** Body of `POST /api/v1/drive/export`: filter mode or selection mode. */ +export type DotContentDriveExportRequest = + | DotContentDriveExportFilterRequest + | DotContentDriveExportSelectionRequest; + /** * A 200 from the export endpoint: the file and what the server says it holds. * @@ -48,7 +71,8 @@ export interface DotContentDriveExportEmpty { export type DotContentDriveExportResult = DotContentDriveExportFile | DotContentDriveExportEmpty; /** - * Downloads Content Drive exports: one CSV for the content type the listing is filtered to. + * Downloads Content Drive exports: one CSV for the content type the listing is filtered to, or a + * zip with one CSV per content type for a selection. */ @Injectable({ providedIn: 'root' @@ -62,11 +86,12 @@ export class DotContentDriveExportService { * The whole response is read as a blob, so the file name and the counts can be taken from its * headers. A 204 (nothing readable matched) resolves to `{ kind: 'empty' }`. * - * @param body The export request, carrying the listing query in filter mode. * An error response (400, 404, 500) arrives as a blob too, so its JSON body is read to error * with the server's `errors[0].message`; a body with no readable message errors with a generic * one. * + * @param body The export request: the listing query in filter mode, or the site and the + * selected items in selection mode. * @returns The file and its counts once the server has built it, or `empty` when there is none. */ export(body: DotContentDriveExportRequest): Observable { diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.html b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.html index 3f665f56fbcd..3d90c5557894 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.html +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.html @@ -1,9 +1,16 @@ -@if ($filterModeVisible()) { - +@if ($visible()) { + + + + } diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts index b8df73c08fd4..e792156e4390 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts @@ -3,10 +3,12 @@ import { rxResource } from '@angular/core/rxjs-interop'; import { MessageService } from 'primeng/api'; import { ButtonModule } from 'primeng/button'; +import { TooltipModule } from 'primeng/tooltip'; import { finalize } from 'rxjs/operators'; import { + DotContentDriveExportRequest, DotContentDriveExportService, DotContentTypeService, DotMessageService @@ -17,23 +19,26 @@ import { getDownloadLink } from '@dotcms/utils'; import { ERROR_MESSAGE_LIFE, + MAX_SELECTION_ITEMS, SUCCESS_MESSAGE_LIFE, WARNING_MESSAGE_LIFE } from '../../../../shared/constants'; import { DotContentDriveStatus } from '../../../../shared/models'; import { DotContentDriveStore } from '../../../../store/dot-content-drive.store'; +import { excludeFolders } from '../../../../utils/action-center'; import { isFolder } from '../../../../utils/functions'; /** - * The toolbar's Export button: downloads the listing as a CSV when it is filtered to one content - * type and nothing is selected (filter mode). + * The toolbar's Export button. With nothing selected it downloads the listing as a CSV when the + * listing is filtered to one content type (filter mode); with anything selected it downloads the + * selected contentlets as a zip with one CSV per content type (selection mode). * * It reads the store and keeps its own in-flight state; it adds nothing to the store, which is at * the `signalStore` feature limit. */ @Component({ selector: 'dot-content-drive-export-button', - imports: [ButtonModule, DotMessagePipe], + imports: [ButtonModule, TooltipModule, DotMessagePipe], templateUrl: './dot-content-drive-export-button.component.html' }) export class DotContentDriveExportButtonComponent { @@ -46,6 +51,19 @@ export class DotContentDriveExportButtonComponent { /** True from the click until the export answers, so a second click cannot start another. */ protected readonly $exporting = signal(false); + /** + * Selection mode applies whenever anything is selected, whatever the listing is filtered to: + * the Form rule is filter mode's, and the server drops Form contentlets from a selection. + */ + protected readonly $selectionMode = computed( + () => this.#store.selectedItems().length > 0 + ); + + /** More items are selected than the server accepts in one export. */ + readonly #selectionTooLarge = computed( + () => this.#store.selectedItems().length > MAX_SELECTION_ITEMS + ); + /** The one content type variable the listing is filtered to, or `undefined` for none or many. */ readonly #filteredVariable = computed(() => { const contentTypes = this.#store.filters()?.contentType ?? []; @@ -102,24 +120,58 @@ export class DotContentDriveExportButtonComponent { return !hasContentlet && !hasMoreContent; }); + /** Whether the button shows: in selection mode always, in filter mode on its own rule. */ + protected readonly $visible = computed( + () => this.$selectionMode() || this.$filterModeVisible() + ); + + /** + * Disabled while an export runs. In selection mode, also when more items are selected than the + * server accepts; in filter mode, when the loaded listing has nothing to export. + */ + protected readonly $disabled = computed(() => { + if (!this.$selectionMode()) { + return this.$filterModeDisabled(); + } + + return this.$exporting() || this.#selectionTooLarge(); + }); + /** - * Exports the listing request the store holds and downloads the file under the name the server - * gave it, then confirms with a toast that carries the number of exported items. When nothing + * The message key that says why the button is disabled, or an empty string when there is + * nothing to say. Only the selection limit is explained: the other disabled states are either + * brief (an export running) or visible in the listing itself (nothing to export). + */ + protected readonly $tooltip = computed(() => + this.$selectionMode() && this.#selectionTooLarge() + ? 'content-drive.export.tooltip.max-items' + : '' + ); + + /** + * Exports what the button stands for and downloads the file under the name the server gave it, + * then confirms with a toast that carries the number of exported items and files. When nothing * readable matched, a warning toast says so; when the export fails, an error toast shows the * server's message. Neither downloads anything. * - * The request is not tied to this component's lifetime: the user may select a row while the - * file is being built, which removes the button, and the download should still arrive. + * In selection mode the request carries the browsed site and the selected contentlets; in + * filter mode, the listing request the store holds. + * + * The request is not tied to this component's lifetime: the user may change the selection + * while the file is being built, which can remove the button, and the download should still + * arrive. */ protected onExport(): void { - if (this.$exporting()) { + if (this.$disabled()) { return; } + const body = this.#buildRequest(); + this.$exporting.set(true); this.#exportService - .export({ query: this.#store.$request() }) + .export(body) .pipe(finalize(() => this.$exporting.set(false))) .subscribe({ next: (result) => { @@ -159,4 +211,24 @@ export class DotContentDriveExportButtonComponent { } }); } + + /** + * The export body for the current mode. Selection mode sends contentlets only, one entry per + * selected language version; selected folders are not exported yet, so `folders` stays empty. + */ + #buildRequest(): DotContentDriveExportRequest { + if (!this.$selectionMode()) { + return { query: this.#store.$request() }; + } + + return { + siteId: this.#store.currentSite()?.identifier ?? '', + selection: { + folders: [], + contentlets: excludeFolders(this.#store.selectedItems()).map( + ({ identifier, languageId }) => ({ identifier, languageId }) + ) + } + }; + } } diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.html b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.html index daa80f022d22..53f3d6302d5d 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.html +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.html @@ -89,6 +89,11 @@ animate.leave="toolbar-leave" data-testid="workflow-actions" /> + + + @if ($displayActionCenter()) { diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/shared/constants.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/shared/constants.ts index 0c774262e047..fd999e990362 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/shared/constants.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/shared/constants.ts @@ -315,6 +315,12 @@ export const SUCCESS_MESSAGE_LIFE = 4500; */ export const WARNING_MESSAGE_LIFE = 7000; export const ERROR_MESSAGE_LIFE = 4500; + +/** + * The most items a selection-mode export sends at once. Matches the server's limit on selection + * entries, which rejects more with a 400. + */ +export const MAX_SELECTION_ITEMS = 60; export const MOVE_TO_FOLDER_WORKFLOW_ACTION_ID = 'dd4c4b7c-e9d3-4dc0-8fbf-36102f9c6324'; /** diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java index e487da8e07c5..3008a1d82e13 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java @@ -6,6 +6,13 @@ import com.dotcms.browser.ExportCandidates; import com.dotcms.browser.ExportRow; import com.dotcms.contenttype.exception.NotFoundInDbException; +import com.dotcms.contenttype.business.ContentTypeAPI; +import com.dotmarketing.portlets.contentlet.business.HostAPI; +import com.dotmarketing.util.UtilMethods; +import io.vavr.control.Try; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.Map; import com.dotcms.contenttype.model.type.BaseContentType; import com.dotcms.contenttype.model.type.ContentType; import com.dotcms.rest.api.v1.drive.ContentDriveHelper; @@ -50,6 +57,8 @@ public class ContentDriveExportHelper { private final ContentDriveHelper driveHelper; private final BrowserAPI browserAPI; private final ExportFileBuilder fileBuilder; + private final HostAPI hostAPI = APILocator.getHostAPI(); + private final SelectionResolver selectionResolver = new SelectionResolver(); /** * Creates a helper that uses the standard dotCMS APIs. @@ -104,7 +113,69 @@ public ExportFile export(final DriveExportRequestForm form, final User user, if (form.validate() == Mode.FILTER) { return write(resolveFilterMode(form.query(), user), user, request); } - throw new UnsupportedOperationException("Selection-mode export is not implemented yet"); + return exportSelection(form, user, request); + } + + /** + * Selection mode: the selected contentlets, and the content of the selected folders, as a zip + * with one CSV per content type (research R5, R6). + * + * @param form the request, already validated + * @param user the {@link User} the export runs as + * @param request the HTTP request, used for the download links of binary fields + * @return the zip; it reports zero rows, and holds no file, when nothing readable was selected + * @throws NotFoundException when the site does not exist or cannot be read + * @throws BadRequestException when more rows are selected than the limit + * @throws DotDataException if the rows cannot be read or the file cannot be written + * @throws IOException if the temp file cannot be written + */ + private ExportFile exportSelection(final DriveExportRequestForm form, final User user, + final HttpServletRequest request) throws DotDataException, IOException { + final Host site = browsedSite(form.siteId(), user); + + final int maxRows = Config.getIntProperty(MAX_ROWS_KEY, MAX_ROWS_DEFAULT); + final ExportCandidates candidates = selectionResolver.resolve(form, site, user, maxRows); + if (candidates.overLimit()) { + throw new BadRequestException(overLimitMessage(maxRows)); + } + + // One CSV per content type, in the order the types first appear + final Map> inodesByTypeId = new LinkedHashMap<>(); + for (final ExportRow row : candidates.rows()) { + inodesByTypeId.computeIfAbsent(row.contentTypeId(), id -> new ArrayList<>()) + .add(row.inode()); + } + final ContentTypeAPI systemContentTypeAPI = + APILocator.getContentTypeAPI(APILocator.systemUser()); + final Map> inodesByType = new LinkedHashMap<>(); + for (final Map.Entry> entry : inodesByTypeId.entrySet()) { + try { + inodesByType.put(systemContentTypeAPI.find(entry.getKey()), entry.getValue()); + } catch (final DotSecurityException e) { + throw new DotDataException(e.getMessage(), e); + } + } + return fileBuilder.buildZip(site.getHostname(), inodesByType, user, request); + } + + /** + * Resolves the site a selection was made in. A site that does not exist and one the user + * cannot read give the same 404, so the response never tells which applied (FR-014). + * + * @param siteId the site identifier from the request + * @param user the {@link User} the export runs as + * @return the site + * @throws NotFoundException when the site is missing, does not exist or cannot be read + */ + private Host browsedSite(final String siteId, final User user) { + if (!UtilMethods.isSet(siteId)) { + throw new NotFoundException(FOLDER_NOT_FOUND_MESSAGE); + } + final Host site = Try.of(() -> hostAPI.find(siteId, user, false)).getOrNull(); + if (site == null || !UtilMethods.isSet(site.getIdentifier())) { + throw new NotFoundException(FOLDER_NOT_FOUND_MESSAGE); + } + return site; } /** diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/SelectionResolver.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/SelectionResolver.java new file mode 100644 index 000000000000..74c1818c434d --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/SelectionResolver.java @@ -0,0 +1,144 @@ +package com.dotcms.rest.api.v1.drive.export; + +import com.dotcms.browser.ExportCandidates; +import com.dotcms.browser.ExportRow; +import com.dotcms.browser.ReadableRowFilter; +import com.dotcms.contenttype.business.ContentTypeAPI; +import com.dotcms.contenttype.model.type.BaseContentType; +import com.dotcms.contenttype.model.type.ContentType; +import com.dotmarketing.beans.Host; +import com.dotmarketing.beans.Identifier; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.IdentifierAPI; +import com.dotmarketing.business.VersionableAPI; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.portlets.contentlet.model.ContentletVersionInfo; +import com.dotmarketing.util.UtilMethods; +import com.liferay.portal.model.User; +import io.vavr.control.Try; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * Resolves the rows of a selection-mode export: the selected contentlets, each in the language + * that was selected, and the content of the selected folders (research R5, R6). + *

+ * An entry that does not resolve to an exportable row is dropped silently, with no difference in + * the response, so an export never tells whether something exists that the user cannot see. + */ +public class SelectionResolver { + + private final VersionableAPI versionableAPI; + private final IdentifierAPI identifierAPI; + private final ContentTypeAPI contentTypeAPI; + private final ReadableRowFilter readableRowFilter; + + /** + * Creates a resolver that uses the standard dotCMS APIs. Content types are read as the system + * user: whether the user may read a row is decided per row by {@link ReadableRowFilter}. + */ + public SelectionResolver() { + this(APILocator.getVersionableAPI(), APILocator.getIdentifierAPI(), + APILocator.getContentTypeAPI(APILocator.systemUser()), new ReadableRowFilter()); + } + + /** + * Creates a resolver with the given APIs. + * + * @param versionableAPI finds the working version of a contentlet in a language + * @param identifierAPI finds the site and type of an identifier + * @param contentTypeAPI finds content types, as the system user + * @param readableRowFilter keeps the rows the user can read + */ + SelectionResolver(final VersionableAPI versionableAPI, final IdentifierAPI identifierAPI, + final ContentTypeAPI contentTypeAPI, final ReadableRowFilter readableRowFilter) { + this.versionableAPI = versionableAPI; + this.identifierAPI = identifierAPI; + this.contentTypeAPI = contentTypeAPI; + this.readableRowFilter = readableRowFilter; + } + + /** + * Resolves the readable rows of a selection. + *

+ * Each selected contentlet gives the working version of its identifier in its selected + * language. It is dropped when that version does not exist, when the identifier belongs to a + * site other than {@code site} or System Host, or when its type is a Form or the Host type. + * Rows are deduplicated by identifier and language, then kept only when the user can read them. + * + * @param form the request; its selection is resolved + * @param site the site being browsed + * @param user the {@link User} the export runs as + * @param maxRows the most rows the export may hold + * @return the readable rows, one per identifier and language, in selection order, with + * {@link ExportCandidates#overLimit()} set when more than {@code maxRows} exist + * @throws DotDataException if the rows cannot be read + */ + public ExportCandidates resolve(final DriveExportRequestForm form, final Host site, + final User user, final int maxRows) throws DotDataException { + final Map> typesByVariable = new HashMap<>(); + final Map candidates = new LinkedHashMap<>(); + if (form.selection() != null) { + for (final ExportContentletRefForm ref : form.selection().contentlets()) { + contentletRow(ref, site, typesByVariable) + .ifPresent(row -> candidates.putIfAbsent(row.key(), row)); + } + } + + final List readable = + readableRowFilter.filter(new ArrayList<>(candidates.values()), user); + if (readable.size() > maxRows) { + return new ExportCandidates(new ArrayList<>(readable.subList(0, maxRows + 1)), true); + } + return new ExportCandidates(readable, false); + } + + /** + * The row of one selected contentlet, or empty when it must be dropped. + * + * @param ref the selected identifier and language + * @param site the site being browsed + * @param typesByVariable content types already looked up, by variable + * @return the row + * @throws DotDataException if the identifier cannot be read + */ + private Optional contentletRow(final ExportContentletRefForm ref, final Host site, + final Map> typesByVariable) throws DotDataException { + final Optional versionInfo = + versionableAPI.getContentletVersionInfo(ref.identifier(), ref.languageId()); + if (versionInfo.isEmpty() || !UtilMethods.isSet(versionInfo.get().getWorkingInode())) { + return Optional.empty(); + } + final Identifier identifier = identifierAPI.find(ref.identifier()); + if (identifier == null || !UtilMethods.isSet(identifier.getId())) { + return Optional.empty(); + } + final String hostId = identifier.getHostId(); + if (!site.getIdentifier().equals(hostId) && !Host.SYSTEM_HOST.equals(hostId)) { + return Optional.empty(); + } + final Optional contentType = typesByVariable.computeIfAbsent( + identifier.getAssetSubType(), + variable -> Try.of(() -> contentTypeAPI.find(variable)).toJavaOptional()); + if (contentType.isEmpty() || !isExportable(contentType.get())) { + return Optional.empty(); + } + return Optional.of(new ExportRow(versionInfo.get().getWorkingInode(), ref.identifier(), + ref.languageId(), contentType.get().id())); + } + + /** + * Whether a content type's content can be exported: never a Form or the Host type (FR-007). + * + * @param contentType the content type + * @return {@code true} when its content is exported + */ + static boolean isExportable(final ContentType contentType) { + return BaseContentType.FORM != contentType.baseType() + && !Host.HOST_VELOCITY_VAR_NAME.equals(contentType.variable()); + } +} diff --git a/dotCMS/src/main/webapp/WEB-INF/messages/Language.properties b/dotCMS/src/main/webapp/WEB-INF/messages/Language.properties index 01f07ef90c87..6ec00a96f95a 100644 --- a/dotCMS/src/main/webapp/WEB-INF/messages/Language.properties +++ b/dotCMS/src/main/webapp/WEB-INF/messages/Language.properties @@ -7563,6 +7563,7 @@ content-drive.toast.export-success=Export ready content-drive.toast.export-success-detail={0} items exported in {1} file(s) content-drive.toast.export-empty=There is nothing to export content-drive.toast.export-error=Export failed +content-drive.export.tooltip.max-items=You can export at most 60 items at once content-drive.chip-filter.overflow-label={0} and {1} more content-drive.filters.clear-all=Clear all From 8a3dfa2e51f2d0d822427193f2dd152243e73c2b Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 13:35:29 -0500 Subject: [PATCH 20/28] test(content-drive): cover exporting whole folders Tests approved before the implementation for selecting folders in a Content Drive export (#37900): every contentlet below a folder at any depth, in every language and archived, each once even when nested folders and their content are selected together; assets and pages in their own CSVs; Form content skipped; 400 for an unparseable path or a site root and one 404 for a missing path, a file or another site's folder, leaving no file. The button spec covers sending folders and counting them toward the 60-item limit. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- ...tent-drive-export-button.component.spec.ts | 104 +++++++- .../ContentDriveExportSelectionModeTest.java | 226 +++++++++++++++++- 2 files changed, 328 insertions(+), 2 deletions(-) diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts index 63721129b6d7..b24833645ffc 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts @@ -123,6 +123,19 @@ const selectedContentlet = (identifier: string, languageId: number): DotContentD const selectedContentlets = (count: number): DotContentDriveItem[] => Array.from({ length: count }, (_, index) => selectedContentlet(`contentlet-${index}`, 1)); +/** A selected folder at `path`, shaped like the folders the listing holds. */ +const selectedFolder = (path: string): DotContentDriveItem => + ({ + ...FOLDER, + identifier: `folder${path}`, + inode: `folder${path}`, + path + }) as DotContentDriveItem; + +/** `count` distinct selected folders, each at the site root. */ +const selectedFolders = (count: number): DotContentDriveItem[] => + Array.from({ length: count }, (_, index) => selectedFolder(`/folder-${index}/`)); + /** A selection-mode 200: the zip, holding one CSV per content type. */ const ZIP_RESULT: DotContentDriveExportResult = { kind: 'file', @@ -494,7 +507,8 @@ describe('DotContentDriveExportButtonComponent', () => { }); // Selection mode (#37900, US2): with anything selected, the button exports the selected - // contentlets as a zip, whatever the listing is filtered to. Folders are Phase 9's (T085). + // contentlets and folders as a zip, whatever the listing is filtered to. Folders go as + // `//` asset paths (US3). describe('selection mode', () => { /** The wrapper the limit tooltip hangs off: a disabled button fires no tooltip itself. */ const exportTooltipWrapper = () => @@ -609,6 +623,94 @@ describe('DotContentDriveExportButtonComponent', () => { }); }); + // US3: a selected folder exports everything below it, so it is sent as the folder's asset + // path on the browsed site, and it counts toward the item limit like a contentlet. + describe('folders', () => { + it('should send the selected folders as asset paths on the browsed site, with the contentlets', async () => { + selectedItemsSignal.set([ + selectedFolder('/blog/'), + selectedContentlet('blog-1', 1), + selectedFolder('/a/b/'), + selectedContentlet('news-1', 2) + ]); + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(exportService.export).toHaveBeenCalledTimes(1); + expect(exportService.export).toHaveBeenCalledWith({ + siteId: CURRENT_SITE.identifier, + selection: { + folders: ['//demo.dotcms.com/blog/', '//demo.dotcms.com/a/b/'], + contentlets: [ + { identifier: 'blog-1', languageId: 1 }, + { identifier: 'news-1', languageId: 2 } + ] + } + }); + }); + + it('should send only folders when no contentlet is selected', async () => { + selectedItemsSignal.set([selectedFolder('/blog/')]); + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(exportService.export).toHaveBeenCalledTimes(1); + expect(exportService.export).toHaveBeenCalledWith({ + siteId: CURRENT_SITE.identifier, + selection: { + folders: ['//demo.dotcms.com/blog/'], + contentlets: [] + } + }); + }); + + it("should build the folder paths with the browsed site's hostname", async () => { + currentSiteSignal.set({ + ...CURRENT_SITE, + identifier: 'site-002', + hostname: 'other.example.com' + }); + selectedItemsSignal.set([selectedFolder('/blog/')]); + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(exportService.export).toHaveBeenCalledWith({ + siteId: 'site-002', + selection: { + folders: ['//other.example.com/blog/'], + contentlets: [] + } + }); + }); + + it(`should count folders and contentlets together: ${MAX_SELECTION_ITEMS / 2} of each is enabled`, async () => { + selectedItemsSignal.set([ + ...selectedFolders(MAX_SELECTION_ITEMS / 2), + ...selectedContentlets(MAX_SELECTION_ITEMS / 2) + ]); + await render(); + + expect(exportButton()).toBeTruthy(); + expect(exportButton()?.disabled).toBe(false); + expect(exportTooltip()?.content ?? '').toBe(''); + }); + + it(`should count folders and contentlets together: one past ${MAX_SELECTION_ITEMS} is disabled with the limit tooltip`, async () => { + selectedItemsSignal.set([ + ...selectedFolders(MAX_SELECTION_ITEMS / 2), + ...selectedContentlets(MAX_SELECTION_ITEMS / 2 + 1) + ]); + await render(); + + expect(exportButton()).toBeTruthy(); + expect(exportButton()?.disabled).toBe(true); + expect(exportTooltip()?.content).toBe(MAX_ITEMS_TOOLTIP); + }); + }); + describe('on success', () => { beforeEach(() => { exportService.export.mockReturnValue(of(ZIP_RESULT)); diff --git a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportSelectionModeTest.java b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportSelectionModeTest.java index 1f9c128b4251..3760c5d25cfd 100644 --- a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportSelectionModeTest.java +++ b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportSelectionModeTest.java @@ -2,6 +2,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; @@ -11,15 +12,21 @@ import com.dotcms.contenttype.model.type.ContentType; import com.dotcms.datagen.ContentTypeDataGen; import com.dotcms.datagen.ContentletDataGen; +import com.dotcms.datagen.DotAssetDataGen; import com.dotcms.datagen.FieldDataGen; +import com.dotcms.datagen.FileAssetDataGen; +import com.dotcms.datagen.FolderDataGen; +import com.dotcms.datagen.HTMLPageDataGen; import com.dotcms.datagen.LanguageDataGen; import com.dotcms.datagen.RoleDataGen; import com.dotcms.datagen.SiteDataGen; +import com.dotcms.datagen.TemplateDataGen; import com.dotcms.datagen.UserDataGen; import com.dotcms.mock.request.MockAttributeRequest; import com.dotcms.mock.request.MockHttpRequestIntegrationTest; import com.dotcms.rest.ErrorEntity; import com.dotcms.rest.ResponseEntityView; +import com.dotcms.rest.api.v1.DotObjectMapperProvider; import com.dotcms.rest.api.v1.drive.export.DriveExportRequestForm; import com.dotcms.rest.api.v1.drive.export.ExportContentletRefForm; import com.dotcms.rest.api.v1.drive.export.ExportFileBuilder; @@ -29,10 +36,12 @@ import com.dotmarketing.beans.Host; import com.dotmarketing.business.APILocator; import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.folders.model.Folder; import com.dotmarketing.portlets.languagesmanager.model.Language; import com.liferay.portal.model.User; import com.liferay.portal.util.WebKeys; import java.io.ByteArrayInputStream; +import java.io.File; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -93,6 +102,30 @@ public class ContentDriveExportSelectionModeTest extends IntegrationTestBase { private static Contentlet twinTwoEntry; private static Contentlet unsafeNameEntry; + // Folder part (User Story 3) + private static final String INVALID_PATH = "Invalid folder path."; + private static Host otherSite; + /** {@code /a/} holds X; {@code /a/b/c/} holds Y. */ + private static Folder folderA; + private static Folder folderAB; + private static Contentlet x; + private static Contentlet y; + /** Holds one contentlet in two languages and an archived one. */ + private static Folder languagesFolder; + private static Contentlet bilingual; + private static Contentlet bilingualSecondLanguage; + private static Contentlet archivedInFolder; + /** Holds a file asset, a dotAsset and a page. */ + private static Folder assetsFolder; + private static Contentlet fileAsset; + private static Contentlet dotAsset; + private static Contentlet page; + /** Holds a Form entry and a Blog entry. */ + private static Folder formFolder; + private static Contentlet formInFolder; + private static Contentlet blogInFormFolder; + private static Folder otherSiteFolder; + @BeforeClass public static void prepare() throws Exception { IntegrationTestInitService.getInstance().init(); @@ -103,7 +136,7 @@ public static void prepare() throws Exception { final String unique = String.valueOf(System.currentTimeMillis()); site = new SiteDataGen().name("drive-selection-" + unique + ".local").nextPersisted(); - final Host otherSite = new SiteDataGen().name("drive-selection-other-" + unique + ".local") + otherSite = new SiteDataGen().name("drive-selection-other-" + unique + ".local") .nextPersisted(); defaultLanguage = APILocator.getLanguageAPI().getDefaultLanguage(); secondLanguage = new LanguageDataGen().nextPersisted(); @@ -137,6 +170,44 @@ public static void prepare() throws Exception { twinOneEntry = entry(twinOne, site, "twin one"); twinTwoEntry = entry(twinTwo, site, "twin two"); unsafeNameEntry = entry(unsafeName, site, "unsafe"); + + folderA = new FolderDataGen().site(site).name("a").nextPersisted(); + folderAB = new FolderDataGen().parent(folderA).name("b").nextPersisted(); + final Folder folderABC = new FolderDataGen().parent(folderAB).name("c").nextPersisted(); + x = entryIn(blog, folderA, "x"); + y = entryIn(news, folderABC, "y"); + + languagesFolder = new FolderDataGen().site(site).name("languages").nextPersisted(); + bilingual = entryIn(blog, languagesFolder, "bilingual"); + final Contentlet bilingualDraft = ContentletDataGen.checkout(bilingual); + bilingualDraft.setLanguageId(secondLanguage.getId()); + bilingualSecondLanguage = ContentletDataGen.checkin(bilingualDraft); + archivedInFolder = ContentletDataGen.publish(entryIn(blog, languagesFolder, "archived")); + ContentletDataGen.archive(archivedInFolder); + + // "assets" is a reserved folder name + assetsFolder = new FolderDataGen().site(site).name("media").nextPersisted(); + final File text = File.createTempFile("drive-export-file", ".txt"); + Files.writeString(text.toPath(), "file asset body"); + fileAsset = new FileAssetDataGen(assetsFolder, text).nextPersisted(); + final File image = File.createTempFile("drive-export-dotasset", ".png"); + Files.write(image.toPath(), new byte[]{1, 2, 3}); + dotAsset = new DotAssetDataGen(site, assetsFolder, image).nextPersisted(); + page = new HTMLPageDataGen(assetsFolder, new TemplateDataGen().nextPersisted()) + .nextPersisted(); + + formFolder = new FolderDataGen().site(site).name("forms").nextPersisted(); + formInFolder = new ContentletDataGen(formType).host(site).folder(formFolder) + .nextPersistedWithSampleTextValues(); + blogInFormFolder = entryIn(blog, formFolder, "beside the form"); + + otherSiteFolder = new FolderDataGen().site(otherSite).name("elsewhere").nextPersisted(); + } + + private static Contentlet entryIn(final ContentType type, final Folder folder, + final String title) { + return new ContentletDataGen(type).host(site).folder(folder) + .languageId(defaultLanguage.getId()).setProperty("title", title).nextPersisted(); } private static ContentType titledType(final String name, final String variable) { @@ -172,6 +243,22 @@ private static DriveExportRequestForm selectionOf(final Contentlet... contentlet .build(); } + private static String pathOf(final Folder folder) { + return "//" + site.getHostname() + folder.getPath(); + } + + /** A selection of folder paths and contentlets in the browsed site. */ + private static DriveExportRequestForm folderSelection(final List folders, + final Contentlet... contentlets) { + return DriveExportRequestForm.builder().siteId(site.getIdentifier()) + .selection(ExportSelectionForm.builder().folders(folders) + .contentlets(Stream.of(contentlets) + .map(ContentDriveExportSelectionModeTest::ref) + .collect(Collectors.toList())) + .build()) + .build(); + } + private static HttpServletRequest requestAs(final User user) { final HttpServletRequest request = new MockAttributeRequest( new MockHttpRequestIntegrationTest("localhost", "/api/v1/drive/export").request()) @@ -455,4 +542,141 @@ public void test_missingOrUnreadableSite_isNotFound() { assertEquals(404, unreadable.getStatus()); assertEquals(FOLDER_NOT_FOUND, errorMessage(unreadable)); } + // --------------------------------------------------------------------------------------------- + // folders (User Story 3) + // --------------------------------------------------------------------------------------------- + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (a) {@code /a/} holds X and {@code /a/b/c/} holds Y; {@code /a/}, + * {@code /a/b/} and X are selected + * ExpectedResult: X and Y once each, at any depth, and no row for a folder (FR-006, FR-017) + */ + @Test + public void test_nestedFolderSelection_exportsEachContentletOnce() throws Exception { + final Response response = export( + folderSelection(List.of(pathOf(folderA), pathOf(folderAB)), x)); + + assertEquals("2", header(response, "X-Export-Contentlets")); + final Map entries = zipEntries(response); + assertEquals(Set.of(keyOf(x), keyOf(y)), rowKeys(entries)); + final List identifiers = new ArrayList<>(); + entries.values().forEach(csv -> dataRows(csv).forEach(row -> identifiers.add(row.get(0)))); + assertEquals("each contentlet once", 2, identifiers.size()); + assertFalse("no row for a folder", identifiers.contains(folderA.getIdentifier())); + assertFalse("no row for a folder", identifiers.contains(folderAB.getIdentifier())); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (b) A folder holding a contentlet in two languages and an archived contentlet + * ExpectedResult: All three rows: every language and archived content (FR-006) + */ + @Test + public void test_folder_exportsEveryLanguageAndArchivedContent() throws Exception { + final Map entries = + zipEntries(export(folderSelection(List.of(pathOf(languagesFolder))))); + + assertEquals(Set.of(keyOf(bilingual), keyOf(bilingualSecondLanguage), + keyOf(archivedInFolder)), rowKeys(entries)); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (c) A folder holding a file asset, a dotAsset and a page + * ExpectedResult: Each in its own type's CSV; the file asset's binary field is a download URL + */ + @Test + public void test_folderAssets_exportInTheirOwnTypeCsv() throws Exception { + final Map entries = + zipEntries(export(folderSelection(List.of(pathOf(assetsFolder))))); + + for (final Contentlet asset : List.of(fileAsset, dotAsset, page)) { + final String csv = entries.get(csvName(asset.getContentType())); + assertNotNull("a CSV for " + asset.getContentType().variable(), csv); + assertEquals(Set.of(keyOf(asset)), rowKeys(Map.of("csv", csv))); + } + final String fileCsv = entries.get(csvName(fileAsset.getContentType())); + final String[] lines = fileCsv.split("\r\n"); + final List header = List.of(lines[0].split(",")); + final List row = List.of(lines[1].split(",", -1)); + final String binary = row.get(header.indexOf("fileAsset")); + assertTrue("binary as a download URL: " + binary, binary.startsWith("http")); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (d) A folder and a contentlet outside it are selected + * ExpectedResult: Both end up in the same zip + */ + @Test + public void test_folderAndOutsideContentlet_shareOneZip() throws Exception { + final Map entries = + zipEntries(export(folderSelection(List.of(pathOf(folderA)), newsOne))); + + assertTrue(rowKeys(entries).containsAll(Set.of(keyOf(x), keyOf(y), keyOf(newsOne)))); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (e) A folder holding a Form entry and a Blog entry + * ExpectedResult: The Blog entry only: Form content is never exported (FR-007). Sites live in + * System Host, never in a site folder, so the Host exclusion is covered by the + * filter-mode and BrowserAPI tests + */ + @Test + public void test_folderForm_isNotExported() throws Exception { + final Map entries = + zipEntries(export(folderSelection(List.of(pathOf(formFolder))))); + + assertEquals(Set.of(keyOf(blogInFormFolder)), rowKeys(entries)); + assertFalse(rowKeys(entries).contains(keyOf(formInFolder))); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (f) A path that does not parse, {@code //}, and the site root; (h) no file + * ExpectedResult: 400 "Invalid folder path." each time, and no file left + */ + @Test + public void test_invalidFolderPaths_areRejected() throws Exception { + final Set before = exportDirectoryFiles(); + for (final String path : List.of("not a path", "//", "//" + site.getHostname() + "/")) { + final Response response = export(folderSelection(List.of(path))); + + assertEquals(path, 400, response.getStatus()); + assertEquals(path, INVALID_PATH, errorMessage(response)); + } + final Set added = new HashSet<>(exportDirectoryFiles()); + added.removeAll(before); + assertEquals("no temp file is left", Set.of(), added); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (g) A path that does not exist, a path naming a file, and a folder of another + * site; (h) no file + * ExpectedResult: 404 "Folder not found." each time, with identical bodies, and no file left + * (FR-014) + */ + @Test + public void test_unresolvableFolders_areNotFound() throws Exception { + final Set before = exportDirectoryFiles(); + final String filePath = "//" + site.getHostname() + + APILocator.getIdentifierAPI().find(fileAsset.getIdentifier()).getPath(); + final Set bodies = new HashSet<>(); + for (final String path : List.of(pathOf(folderA) + "no-such-folder/", filePath, + "//" + otherSite.getHostname() + otherSiteFolder.getPath())) { + final Response response = export(folderSelection(List.of(path))); + + assertEquals(path, 404, response.getStatus()); + assertEquals(path, FOLDER_NOT_FOUND, errorMessage(response)); + bodies.add(DotObjectMapperProvider.getInstance().getDefaultObjectMapper() + .writeValueAsString(response.getEntity())); + } + assertEquals("identical bodies", 1, bodies.size()); + final Set added = new HashSet<>(exportDirectoryFiles()); + added.removeAll(before); + assertEquals("no temp file is left", Set.of(), added); + } } From 3139bdaf08675f06aadc8f0410ae1f7127084779 Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 13:35:38 -0500 Subject: [PATCH 21/28] feat(content-drive): export whole folders Selected folders now export every contentlet below them, at any depth, in every language, archived included, skipping subfolders the user cannot read (#37900). Folders are validated before any content is read: an unparseable path or a site root is a 400, and a missing path, a file, another site's folder or an unreadable one is the same 404. The button sends the selected folders as site-qualified paths. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- ...t-content-drive-export-button.component.ts | 23 +- .../v1/drive/export/SelectionResolver.java | 216 +++++++++++++++++- 2 files changed, 219 insertions(+), 20 deletions(-) diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts index e792156e4390..eb2c20b4271a 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts @@ -25,7 +25,7 @@ import { } from '../../../../shared/constants'; import { DotContentDriveStatus } from '../../../../shared/models'; import { DotContentDriveStore } from '../../../../store/dot-content-drive.store'; -import { excludeFolders } from '../../../../utils/action-center'; +import { excludeFolders, toFolderAssetPaths } from '../../../../utils/action-center'; import { isFolder } from '../../../../utils/functions'; /** @@ -154,7 +154,7 @@ export class DotContentDriveExportButtonComponent { * readable matched, a warning toast says so; when the export fails, an error toast shows the * server's message. Neither downloads anything. * - * In selection mode the request carries the browsed site and the selected contentlets; in + * In selection mode the request carries the browsed site and the selected folders and contentlets; in * filter mode, the listing request the store holds. * * The request is not tied to this component's lifetime: the user may change the selection @@ -213,21 +213,26 @@ export class DotContentDriveExportButtonComponent { } /** - * The export body for the current mode. Selection mode sends contentlets only, one entry per - * selected language version; selected folders are not exported yet, so `folders` stays empty. + * The export body for the current mode. Selection mode sends the selected folders as asset + * paths on the browsed site, such as `//demo.dotcms.com/blog/`, so each exports everything + * below it, and the selected contentlets with one entry per selected language version. */ #buildRequest(): DotContentDriveExportRequest { if (!this.$selectionMode()) { return { query: this.#store.$request() }; } + const site = this.#store.currentSite(); + const selectedItems = this.#store.selectedItems(); + return { - siteId: this.#store.currentSite()?.identifier ?? '', + siteId: site?.identifier ?? '', selection: { - folders: [], - contentlets: excludeFolders(this.#store.selectedItems()).map( - ({ identifier, languageId }) => ({ identifier, languageId }) - ) + folders: toFolderAssetPaths(selectedItems, site?.hostname ?? ''), + contentlets: excludeFolders(selectedItems).map(({ identifier, languageId }) => ({ + identifier, + languageId + })) } }; } diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/SelectionResolver.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/SelectionResolver.java index 74c1818c434d..05f1a46bb94b 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/SelectionResolver.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/SelectionResolver.java @@ -4,6 +4,19 @@ import com.dotcms.browser.ExportRow; import com.dotcms.browser.ReadableRowFilter; import com.dotcms.contenttype.business.ContentTypeAPI; +import com.dotcms.contenttype.exception.NotFoundInDbException; +import com.dotcms.rest.api.v1.asset.AssetPathResolver; +import com.dotcms.rest.api.v1.asset.ResolvedAssetAndPath; +import com.dotcms.rest.exception.BadRequestException; +import com.dotcms.rest.exception.NotFoundException; +import com.dotcms.variant.VariantAPI; +import com.dotmarketing.business.PermissionAPI; +import com.dotmarketing.common.db.DotConnect; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.portlets.folders.business.FolderAPI; +import com.dotmarketing.portlets.folders.model.Folder; +import java.util.Collections; +import java.util.regex.Pattern; import com.dotcms.contenttype.model.type.BaseContentType; import com.dotcms.contenttype.model.type.ContentType; import com.dotmarketing.beans.Host; @@ -32,10 +45,22 @@ */ public class SelectionResolver { + static final String INVALID_FOLDER_PATH = "Invalid folder path."; + static final String FOLDER_NOT_FOUND = "Folder not found."; + + /** A folder path: {@code //}, a host name, then a non-empty path; a site root is not one. */ + private static final Pattern FOLDER_PATH = Pattern.compile("^//[^/\\s]+/.+$"); + /** Folder paths per content query, well under any database's parameter limit. */ + static final int FOLDER_PATH_BATCH = 500; + /** Rows per content query. */ + static final int FOLDER_ROWS_CHUNK = 1000; + private final VersionableAPI versionableAPI; private final IdentifierAPI identifierAPI; private final ContentTypeAPI contentTypeAPI; private final ReadableRowFilter readableRowFilter; + private final PermissionAPI permissionAPI = APILocator.getPermissionAPI(); + private final FolderAPI folderAPI = APILocator.getFolderAPI(); /** * Creates a resolver that uses the standard dotCMS APIs. Content types are read as the system @@ -68,7 +93,10 @@ public SelectionResolver() { * Each selected contentlet gives the working version of its identifier in its selected * language. It is dropped when that version does not exist, when the identifier belongs to a * site other than {@code site} or System Host, or when its type is a Form or the Host type. - * Rows are deduplicated by identifier and language, then kept only when the user can read them. + * Each selected folder gives every contentlet below it, at any depth, in every language, + * archived included, skipping subfolders the user cannot read. Rows are kept only when the + * user can read them, and appear once per identifier and language: the selected contentlets + * first, then the folders' content. * * @param form the request; its selection is resolved * @param site the site being browsed @@ -76,25 +104,191 @@ public SelectionResolver() { * @param maxRows the most rows the export may hold * @return the readable rows, one per identifier and language, in selection order, with * {@link ExportCandidates#overLimit()} set when more than {@code maxRows} exist - * @throws DotDataException if the rows cannot be read + * @throws BadRequestException when a folder path does not parse or names a site root + * @throws NotFoundException when a folder does not resolve, names a file, belongs to another + * site, or cannot be read + * @throws DotDataException if the rows cannot be read */ public ExportCandidates resolve(final DriveExportRequestForm form, final Host site, final User user, final int maxRows) throws DotDataException { + final ExportSelectionForm selection = form.selection(); + // Every folder is validated before any content is read, so an error never comes with a + // partial result + final List selectedFolders = selection == null ? List.of() + : resolveFolders(selection.folders(), site, user); + final Map> typesByVariable = new HashMap<>(); - final Map candidates = new LinkedHashMap<>(); - if (form.selection() != null) { - for (final ExportContentletRefForm ref : form.selection().contentlets()) { + final Map selected = new LinkedHashMap<>(); + if (selection != null) { + for (final ExportContentletRefForm ref : selection.contentlets()) { contentletRow(ref, site, typesByVariable) - .ifPresent(row -> candidates.putIfAbsent(row.key(), row)); + .ifPresent(row -> selected.putIfAbsent(row.key(), row)); + } + } + + final Map rows = new LinkedHashMap<>(); + if (addAll(rows, readableRowFilter.filter(new ArrayList<>(selected.values()), user), + maxRows)) { + return overLimit(rows); + } + final List folderPaths = readableFolderPaths(selectedFolders, user); + for (int start = 0; start < folderPaths.size(); start += FOLDER_PATH_BATCH) { + final List batch = + folderPaths.subList(start, Math.min(start + FOLDER_PATH_BATCH, folderPaths.size())); + ExportRow last = null; + while (true) { + final List chunk = readFolderChunk(site, batch, last); + if (chunk.isEmpty()) { + break; + } + last = chunk.get(chunk.size() - 1); + if (addAll(rows, readableRowFilter.filter(chunk, user), maxRows)) { + return overLimit(rows); + } + if (chunk.size() < FOLDER_ROWS_CHUNK) { + break; + } + } + } + return new ExportCandidates(new ArrayList<>(rows.values()), false); + } + + /** + * Adds rows not seen yet, by identifier and language, in order. + * + * @param rows the rows so far + * @param toAdd the rows to add + * @param maxRows the limit + * @return {@code true} as soon as there are more than {@code maxRows} rows + */ + private static boolean addAll(final Map rows, final List toAdd, + final int maxRows) { + for (final ExportRow row : toAdd) { + rows.putIfAbsent(row.key(), row); + if (rows.size() > maxRows) { + return true; + } + } + return false; + } + + private static ExportCandidates overLimit(final Map rows) { + return new ExportCandidates(new ArrayList<>(rows.values()), true); + } + + /** + * Resolves the selected folder paths, as the system user so that "missing" and "unreadable" + * cannot be told apart, then checks READ for the user. + * + * @param paths the selected paths, {@code ////} + * @param site the site being browsed + * @param user the {@link User} the export runs as + * @return the folders, in selection order + * @throws BadRequestException when a path does not parse or names a site root + * @throws NotFoundException when a path does not resolve, names a file, belongs to another + * site, or the user cannot read the folder + * @throws DotDataException if a folder cannot be read + */ + private List resolveFolders(final List paths, final Host site, final User user) + throws DotDataException { + final List folders = new ArrayList<>(); + for (final String path : paths) { + if (path == null || !FOLDER_PATH.matcher(path).matches()) { + throw new BadRequestException(INVALID_FOLDER_PATH); + } + final ResolvedAssetAndPath resolved; + try { + resolved = AssetPathResolver.newInstance().resolve(path, APILocator.systemUser()); + } catch (final IllegalArgumentException e) { + throw new BadRequestException(INVALID_FOLDER_PATH); + } catch (final NotFoundException | NotFoundInDbException | DotSecurityException e) { + throw new NotFoundException(FOLDER_NOT_FOUND); + } + final Folder folder = resolved.resolvedFolder(); + if (UtilMethods.isSet(resolved.asset()) || folder == null || folder.isSystemFolder() + || resolved.resolvedHost() == null + || !site.getIdentifier().equals(resolved.resolvedHost().getIdentifier()) + || !permissionAPI.doesUserHavePermission(folder, PermissionAPI.PERMISSION_READ, + user, false)) { + throw new NotFoundException(FOLDER_NOT_FOUND); + } + folders.add(folder); + } + return folders; + } + + /** + * The paths of every folder whose content is exported: each selected folder and every readable + * folder below it. The folder API prunes below an unreadable folder, so content under it is + * never read (FR-013). + * + * @param selectedFolders the selected folders, already readable + * @param user the {@link User} the export runs as + * @return the folder paths, each once + * @throws DotDataException if the subfolders cannot be read + */ + private List readableFolderPaths(final List selectedFolders, final User user) + throws DotDataException { + final Map pathsByInode = new LinkedHashMap<>(); + for (final Folder folder : selectedFolders) { + pathsByInode.putIfAbsent(folder.getInode(), folder.getPath()); + final List subFolders; + try { + subFolders = folderAPI.findSubFoldersRecursively(folder, user, false); + } catch (final DotSecurityException e) { + throw new DotDataException(e.getMessage(), e); } + subFolders.forEach(sub -> pathsByInode.putIfAbsent(sub.getInode(), sub.getPath())); + } + return new ArrayList<>(pathsByInode.values()); + } + + /** + * Reads the next chunk of contentlet rows directly in the given folders, in + * {@code (identifier, language)} order: the working version in every language, archived + * included, never a Form or the Host type. + * + * @param site the site the folders belong to + * @param folderPaths at most {@link #FOLDER_PATH_BATCH} folder paths + * @param after the last row of the previous chunk, or {@code null} + * @return the rows, in order + * @throws DotDataException if the query fails + */ + private static List readFolderChunk(final Host site, final List folderPaths, + final ExportRow after) throws DotDataException { + final StringBuilder sql = new StringBuilder("select cvi.working_inode as inode, " + + "cvi.identifier as identifier, cvi.lang as lang, " + + "struc.inode as structure_inode " + + "from identifier id " + + "join contentlet_version_info cvi on cvi.identifier = id.id " + + "and cvi.variant_id = '" + VariantAPI.DEFAULT_VARIANT.name() + "' " + + "join structure struc on struc.velocity_var_name = id.asset_subtype " + + "where id.host_inode = ? and id.asset_type = 'contentlet' " + + "and struc.structuretype <> " + BaseContentType.FORM.getType() + " " + + "and struc.velocity_var_name <> '" + Host.HOST_VELOCITY_VAR_NAME + "' " + + "and id.parent_path in (") + .append(String.join(",", Collections.nCopies(folderPaths.size(), "?"))) + .append(") "); + if (after != null) { + sql.append("and (cvi.identifier, cvi.lang) > (?, ?) "); + } + sql.append("order by cvi.identifier, cvi.lang limit ?"); + + final DotConnect dotConnect = new DotConnect().setSQL(sql.toString()); + dotConnect.addParam(site.getIdentifier()); + folderPaths.forEach(dotConnect::addParam); + if (after != null) { + dotConnect.addParam(after.identifier()); + dotConnect.addParam(after.languageId()); } + dotConnect.addParam(FOLDER_ROWS_CHUNK); - final List readable = - readableRowFilter.filter(new ArrayList<>(candidates.values()), user); - if (readable.size() > maxRows) { - return new ExportCandidates(new ArrayList<>(readable.subList(0, maxRows + 1)), true); + final List chunk = new ArrayList<>(); + for (final Map row : dotConnect.loadObjectResults()) { + chunk.add(new ExportRow((String) row.get("inode"), (String) row.get("identifier"), + ((Number) row.get("lang")).longValue(), (String) row.get("structure_inode"))); } - return new ExportCandidates(readable, false); + return chunk; } /** From 56cd050611928f98bbc6da1ee8e97cac4b93a674 Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 14:09:26 -0500 Subject: [PATCH 22/28] test(content-drive): prove selection-mode exports keep every guarantee Extends the Content Drive export tests to selections (#37900): unreadable subfolders and rows are left out while a readable contentlet selected inside an unreadable folder is exported; unreadable, missing and other-site folders give identical 404s and dropped contentlets leave no trace; folder rows count toward the row limit while a folder counts as one selected item; a selection zip imports back in place; and an empty selection result is a 204 with the empty toast. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- ...tent-drive-export-button.component.spec.ts | 20 ++ .../ContentDriveExportRoundTripTest.java | 83 +++++++- .../ContentDriveExportSelectionModeTest.java | 110 ++++++++++ .../ContentDriveExportPermissionTest.java | 196 ++++++++++++++++++ 4 files changed, 403 insertions(+), 6 deletions(-) diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts index b24833645ffc..1238656cb9f4 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts @@ -765,5 +765,25 @@ describe('DotContentDriveExportButtonComponent', () => { expect(getDownloadLink).not.toHaveBeenCalled(); }); }); + + describe('on empty', () => { + it('should show the nothing-to-export toast and download nothing (#37900 T095)', async () => { + exportService.export.mockReturnValue(of(EMPTY_RESULT)); + selectedItemsSignal.set([selectedFolder('/locked/')]); + await render(); + + spectator.click(exportButton() as HTMLElement); + + expect(messageServiceSpy.add).toHaveBeenCalledTimes(1); + expect(messageServiceSpy.add).toHaveBeenCalledWith( + expect.objectContaining({ + severity: 'warn', + summary: 'There is nothing to export', + life: WARNING_MESSAGE_LIFE + }) + ); + expect(getDownloadLink).not.toHaveBeenCalled(); + }); + }); }); }); diff --git a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportRoundTripTest.java b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportRoundTripTest.java index e3acb7794f17..5dfa13680add 100644 --- a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportRoundTripTest.java +++ b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportRoundTripTest.java @@ -20,6 +20,8 @@ import com.dotcms.mock.request.MockAttributeRequest; import com.dotcms.mock.request.MockHttpRequestIntegrationTest; import com.dotcms.rest.api.v1.drive.export.DriveExportRequestForm; +import com.dotcms.rest.api.v1.drive.export.ExportContentletRefForm; +import com.dotcms.rest.api.v1.drive.export.ExportSelectionForm; import com.dotcms.util.IntegrationTestInitService; import com.dotmarketing.beans.Host; import com.dotmarketing.business.APILocator; @@ -31,6 +33,7 @@ import com.dotmarketing.util.ImportUtil; import com.liferay.portal.model.User; import com.liferay.portal.util.WebKeys; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.io.StringReader; @@ -41,6 +44,8 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Response; @@ -124,6 +129,43 @@ private static String driveCsv() throws Exception { return out.toString(StandardCharsets.UTF_8); } + /** + * The CSV of the Drive's selection-mode zip for {@code /rt/}, the site-root contentlet and the + * System Host contentlet; all three are of one type, so the zip holds one entry. + */ + private static String selectionCsv() throws Exception { + final HttpServletRequest request = new MockAttributeRequest( + new MockHttpRequestIntegrationTest("localhost", "/api/v1/drive/export").request()) + .request(); + request.setAttribute(WebKeys.USER, adminUser); + final DriveExportRequestForm form = DriveExportRequestForm.builder() + .siteId(site.getIdentifier()) + .selection(ExportSelectionForm.builder() + .addFolders("//" + site.getHostname() + folder.getPath()) + .addContentlets(ExportContentletRefForm.builder() + .identifier(atSiteRoot.getIdentifier()) + .languageId(atSiteRoot.getLanguageId()).build()) + .addContentlets(ExportContentletRefForm.builder() + .identifier(inSystemHost.getIdentifier()) + .languageId(inSystemHost.getLanguageId()).build()) + .build()) + .build(); + + final Response response = new ContentDriveResource().export(request, + mock(HttpServletResponse.class), form); + assertEquals(200, response.getStatus()); + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + ((StreamingOutput) response.getEntity()).write(out); + final List csvs = new ArrayList<>(); + try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()))) { + for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { + csvs.add(new String(zip.readAllBytes(), StandardCharsets.UTF_8)); + } + } + assertEquals("one type, one CSV", 1, csvs.size()); + return csvs.get(0); + } + /** Content Search's export of the same contentlets. */ private static String contentSearchCsv(final List contentlets) throws Exception { final StringWriter out = new StringWriter(); @@ -238,9 +280,15 @@ private static Contentlet working(final Contentlet contentlet) throws Exception */ @Test public void test_exportedCsv_importsBackInPlace() throws Exception { + // Titles are read now, not assumed: the other round-trip test edits them too + final Map expectedTitles = new LinkedHashMap<>(); + final Map newTitles = new HashMap<>(); + for (final Contentlet contentlet : List.of(inFolder, atSiteRoot, inSystemHost)) { + final String title = working(contentlet).getStringProperty("title"); + expectedTitles.put(contentlet, title + " edited"); + newTitles.put(title, title + " edited"); + } final String exported = driveCsv(); - final Map newTitles = Map.of("rt-folder", "rt-folder edited", - "rt-root", "rt-root edited", "rt-system", "rt-system edited"); final String edited = withTitlesChanged(exported, newTitles); assertEquals("fixture: the three rows are exported and edited", 3, rowsByKey(edited).values().stream() @@ -250,10 +298,6 @@ public void test_exportedCsv_importsBackInPlace() throws Exception { assertEquals("row errors: " + results.get("errors"), 0, results.get("errors").size()); - final Map expectedTitles = new LinkedHashMap<>(); - expectedTitles.put(inFolder, "rt-folder edited"); - expectedTitles.put(atSiteRoot, "rt-root edited"); - expectedTitles.put(inSystemHost, "rt-system edited"); for (final Map.Entry entry : expectedTitles.entrySet()) { final Contentlet before = entry.getKey(); final Contentlet after = working(before); @@ -295,4 +339,31 @@ public void test_driveCsv_equalsContentSearchExceptHostFolder() throws Exception assertEquals(key, contentSearchRow, driveRow); } } + /** + * Method to test: {@link ContentDriveResource#export} in selection mode, then + * {@link ImportUtil#importFile} + * Given Scenario: The CSV of the zip from selecting {@code /rt/}, the site-root contentlet and + * the System Host contentlet, with each title changed, imported back + * ExpectedResult: No row errors, the new titles, and every contentlet in its host and folder + * (SC-003, SC-004) + */ + @Test + public void test_selectionZipCsv_importsBackInPlace() throws Exception { + final Map newTitles = new HashMap<>(); + for (final Contentlet contentlet : List.of(inFolder, atSiteRoot, inSystemHost)) { + final String title = working(contentlet).getStringProperty("title"); + newTitles.put(title, title + " via selection"); + } + final String edited = withTitlesChanged(selectionCsv(), newTitles); + + final Map> results = importCsv(edited); + + assertEquals("row errors: " + results.get("errors"), 0, results.get("errors").size()); + for (final Contentlet before : List.of(inFolder, atSiteRoot, inSystemHost)) { + final Contentlet after = working(before); + assertTrue(after.getStringProperty("title").endsWith(" via selection")); + assertEquals(before.getHost(), after.getHost()); + assertEquals(before.getFolder(), after.getFolder()); + } + } } diff --git a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportSelectionModeTest.java b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportSelectionModeTest.java index 3760c5d25cfd..041ce702fc0b 100644 --- a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportSelectionModeTest.java +++ b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportSelectionModeTest.java @@ -27,6 +27,7 @@ import com.dotcms.rest.ErrorEntity; import com.dotcms.rest.ResponseEntityView; import com.dotcms.rest.api.v1.DotObjectMapperProvider; +import com.dotcms.rest.api.v1.drive.export.ContentDriveExportHelper; import com.dotcms.rest.api.v1.drive.export.DriveExportRequestForm; import com.dotcms.rest.api.v1.drive.export.ExportContentletRefForm; import com.dotcms.rest.api.v1.drive.export.ExportFileBuilder; @@ -34,12 +35,18 @@ import com.dotcms.rest.api.v1.drive.export.ExportSelectionForm; import com.dotcms.util.IntegrationTestInitService; import com.dotmarketing.beans.Host; +import com.dotmarketing.beans.Permission; import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.PermissionAPI; +import com.dotmarketing.business.Permissionable; +import com.dotmarketing.business.Role; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.folders.model.Folder; import com.dotmarketing.portlets.languagesmanager.model.Language; +import com.dotmarketing.util.Config; import com.liferay.portal.model.User; import com.liferay.portal.util.WebKeys; +import io.vavr.control.Try; import java.io.ByteArrayInputStream; import java.io.File; import java.io.ByteArrayOutputStream; @@ -126,6 +133,15 @@ public class ContentDriveExportSelectionModeTest extends IntegrationTestBase { private static Contentlet blogInFormFolder; private static Folder otherSiteFolder; + // Limits and outcomes (Phase 10) + private static Folder fiveRowsFolder; + private static Folder sixRowsFolder; + /** Holds 61 contentlets: more rows than selection entries allow, as one entry. */ + private static Folder largeFolder; + /** Readable as a folder by {@link #folderReader}, whose content they cannot read. */ + private static Folder lockedContentFolder; + private static User folderReader; + @BeforeClass public static void prepare() throws Exception { IntegrationTestInitService.getInstance().init(); @@ -202,6 +218,39 @@ public static void prepare() throws Exception { blogInFormFolder = entryIn(blog, formFolder, "beside the form"); otherSiteFolder = new FolderDataGen().site(otherSite).name("elsewhere").nextPersisted(); + + fiveRowsFolder = folderWith("five", 5); + sixRowsFolder = folderWith("six", 6); + largeFolder = folderWith("large", 61); + + // READ on the site and on the folder itself, which its content does not inherit + lockedContentFolder = folderWith("locked", 2); + final Role folderReaderRole = new RoleDataGen().nextPersisted(); + folderReader = new UserDataGen().roles(folderReaderRole, + APILocator.getRoleAPI().loadBackEndUserRole()).nextPersisted(); + for (final Permissionable permissionable : List.of(site, lockedContentFolder)) { + APILocator.getPermissionAPI().save(new Permission(permissionable.getPermissionId(), + folderReaderRole.getId(), PermissionAPI.PERMISSION_READ), permissionable, + APILocator.systemUser(), false); + } + assertTrue("Fixture error: the folder reader must read the folder", + APILocator.getPermissionAPI().doesUserHavePermission(lockedContentFolder, + PermissionAPI.PERMISSION_READ, folderReader, false)); + assertTrue("Fixture error: the folder reader must read none of its content", + APILocator.getContentletAPI().findContentletsByFolder(lockedContentFolder, + APILocator.systemUser(), false).stream() + .noneMatch(contentlet -> Try.of(() -> APILocator.getPermissionAPI() + .doesUserHavePermission(contentlet, PermissionAPI.PERMISSION_READ, + folderReader, false)).get())); + } + + /** A folder at the site root holding {@code rows} Blog contentlets. */ + private static Folder folderWith(final String name, final int rows) { + final Folder folder = new FolderDataGen().site(site).name(name).nextPersisted(); + for (int i = 0; i < rows; i++) { + entryIn(blog, folder, name + " " + i); + } + return folder; } private static Contentlet entryIn(final ContentType type, final Folder folder, @@ -679,4 +728,65 @@ public void test_unresolvableFolders_areNotFound() throws Exception { added.removeAll(before); assertEquals("no temp file is left", Set.of(), added); } + // --------------------------------------------------------------------------------------------- + // limits and outcomes in selection mode (Phase 10) + // --------------------------------------------------------------------------------------------- + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: {@code CONTENT_DRIVE_EXPORT_MAX_ROWS} set to 5; a folder with 6 readable + * rows, then one with 5 + * ExpectedResult: 400 with the limit message, then 200 with 5 rows (FR-010) + */ + @Test + public void test_folderRows_countTowardTheRowLimit() throws Exception { + final int previous = Config.getIntProperty(ContentDriveExportHelper.MAX_ROWS_KEY, + ContentDriveExportHelper.MAX_ROWS_DEFAULT); + Config.setProperty(ContentDriveExportHelper.MAX_ROWS_KEY, 5); + try { + final Set before = exportDirectoryFiles(); + final Response over = export(folderSelection(List.of(pathOf(sixRowsFolder)))); + assertEquals(400, over.getStatus()); + assertEquals(ContentDriveExportHelper.overLimitMessage(5), errorMessage(over)); + final Set added = new HashSet<>(exportDirectoryFiles()); + added.removeAll(before); + assertEquals("no temp file is left", Set.of(), added); + + final Response atLimit = export(folderSelection(List.of(pathOf(fiveRowsFolder)))); + assertEquals("5", header(atLimit, "X-Export-Contentlets")); + } finally { + Config.setProperty(ContentDriveExportHelper.MAX_ROWS_KEY, previous); + } + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: One folder holding 61 contentlets + * ExpectedResult: 200 with 61 rows: the folder is one selected item, not 61 (FR-004a) + */ + @Test + public void test_largeFolder_countsAsOneSelectedItem() throws Exception { + final Response response = export(folderSelection(List.of(pathOf(largeFolder)))); + + assertEquals(200, response.getStatus()); + assertEquals("61", header(response, "X-Export-Contentlets")); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: A user who can read a folder but none of its content selects it + * ExpectedResult: 204, and no file left (FR-027, FR-032) + */ + @Test + public void test_readableFolderWithNothingReadable_isNoContent() throws Exception { + final Set before = exportDirectoryFiles(); + + final Response response = + export(folderSelection(List.of(pathOf(lockedContentFolder))), folderReader); + + assertEquals(204, response.getStatus()); + final Set added = new HashSet<>(exportDirectoryFiles()); + added.removeAll(before); + assertEquals("no temp file is left", Set.of(), added); + } } diff --git a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportPermissionTest.java b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportPermissionTest.java index b9acd031e354..6a4f4b93267e 100644 --- a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportPermissionTest.java +++ b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportPermissionTest.java @@ -11,11 +11,13 @@ import com.dotcms.datagen.ContentTypeDataGen; import com.dotcms.datagen.ContentletDataGen; import com.dotcms.datagen.FieldDataGen; +import com.dotcms.datagen.FolderDataGen; import com.dotcms.datagen.RoleDataGen; import com.dotcms.datagen.SiteDataGen; import com.dotcms.datagen.UserDataGen; import com.dotcms.mock.request.MockAttributeRequest; import com.dotcms.mock.request.MockHttpRequestIntegrationTest; +import com.dotcms.rest.api.v1.DotObjectMapperProvider; import com.dotcms.rest.api.v1.drive.BrowseScope; import com.dotcms.rest.api.v1.drive.ContentDriveResource; import com.dotcms.rest.api.v1.drive.DriveRequestForm; @@ -26,16 +28,22 @@ import com.dotmarketing.business.PermissionAPI; import com.dotmarketing.business.Role; import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.folders.model.Folder; import com.dotmarketing.util.Config; import com.liferay.portal.model.User; import com.liferay.portal.util.WebKeys; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; +import java.util.HashSet; import java.util.Set; +import java.util.UUID; import java.util.stream.Collectors; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Response; @@ -68,6 +76,19 @@ public class ContentDriveExportPermissionTest extends IntegrationTestBase { private static Contentlet z; private static List readableSiblings; + // Selection part + /** Readable by the limited user, with readable A1 and A2 and unreadable Z1 in it. */ + private static Folder folderA; + /** Under {@link #folderA}, not readable; holds S1 and, deeper, S2, both readable themselves. */ + private static Folder secretFolder; + private static Contentlet a1; + private static Contentlet a2; + private static Contentlet z1; + private static Contentlet s1; + private static Contentlet s2; + private static Contentlet inOtherSite; + private static Folder otherSiteFolder; + /** Three rows the limited user can read, one of which loses READ between the two steps. */ private static ContentType revokeType; private static List revokeRows; @@ -121,6 +142,43 @@ public static void prepare() throws Exception { limitedUser, false)); } + // /a/ is readable through an individual grant on the folder itself, which its subfolders + // do not inherit, so /a/secret/ and everything below it stays unreadable. + final ContentType selectionType = titledType("PermSelection", unique); + folderA = new FolderDataGen().site(site).name("a").nextPersisted(); + secretFolder = new FolderDataGen().parent(folderA).name("secret").nextPersisted(); + final Folder deepFolder = new FolderDataGen().parent(secretFolder).name("deep") + .nextPersisted(); + permissionAPI.save(new Permission(folderA.getPermissionId(), limitedRole.getId(), + PermissionAPI.PERMISSION_READ), folderA, systemUser, false); + a1 = titledIn(selectionType, folderA, "A1"); + a2 = titledIn(selectionType, folderA, "A2"); + z1 = titledIn(selectionType, folderA, "Z1"); + s1 = titledIn(selectionType, secretFolder, "S1"); + s2 = titledIn(selectionType, deepFolder, "S2"); + for (final Contentlet readable : List.of(a1, a2, s1, s2)) { + grantRead(readable); + } + final Host otherSite = new SiteDataGen().name("drive-export-perm-other-" + unique + ".local") + .nextPersisted(); + otherSiteFolder = new FolderDataGen().site(otherSite).name("elsewhere").nextPersisted(); + inOtherSite = new ContentletDataGen(selectionType).host(otherSite) + .setProperty("title", "other site").nextPersisted(); + grantRead(inOtherSite); + + assertTrue("Fixture error: the limited user must read /a/", permissionAPI + .doesUserHavePermission(folderA, PermissionAPI.PERMISSION_READ, limitedUser, false)); + assertFalse("Fixture error: the limited user must not read /a/secret/", permissionAPI + .doesUserHavePermission(secretFolder, PermissionAPI.PERMISSION_READ, limitedUser, + false)); + assertFalse("Fixture error: the limited user must not read Z1", permissionAPI + .doesUserHavePermission(z1, PermissionAPI.PERMISSION_READ, limitedUser, false)); + for (final Contentlet readable : List.of(a1, a2, s1, s2)) { + assertTrue("Fixture error: the limited user must read " + readable.getTitle(), + permissionAPI.doesUserHavePermission(readable, PermissionAPI.PERMISSION_READ, + limitedUser, false)); + } + revokeType = titledType("PermRevoke", unique); revokeRows = new ArrayList<>(); for (final String title : List.of("R1", "R2", "R3")) { @@ -149,6 +207,13 @@ private static Contentlet titled(final ContentType type, final String title) { .setProperty("title", title).nextPersisted(); } + private static Contentlet titledIn(final ContentType type, final Folder folder, + final String title) { + return new ContentletDataGen(type).host(site).folder(folder) + .languageId(APILocator.getLanguageAPI().getDefaultLanguage().getId()) + .setProperty("title", title).nextPersisted(); + } + private static void grantRead(final Contentlet contentlet) throws Exception { APILocator.getPermissionAPI().save(new Permission(contentlet.getPermissionId(), limitedRole.getId(), PermissionAPI.PERMISSION_READ), contentlet, systemUser, false); @@ -272,4 +337,135 @@ public void test_rowUnreadableBeforeWriting_isSkippedAndNotCounted() throws Exce Files.deleteIfExists(file.path()); } } + // --------------------------------------------------------------------------------------------- + // selection mode + // --------------------------------------------------------------------------------------------- + + private static ExportContentletRefForm ref(final String identifier) { + return ExportContentletRefForm.builder().identifier(identifier) + .languageId(APILocator.getLanguageAPI().getDefaultLanguage().getId()).build(); + } + + private static DriveExportRequestForm selection(final List folders, + final List contentlets) { + return DriveExportRequestForm.builder().siteId(site.getIdentifier()) + .selection(ExportSelectionForm.builder().folders(folders).contentlets(contentlets) + .build()) + .build(); + } + + private static Response exportSelection(final DriveExportRequestForm form) { + return new ContentDriveResource().export(requestAs(limitedUser), + mock(HttpServletResponse.class), form); + } + + private static String pathOf(final Host host, final Folder folder) { + return "//" + host.getHostname() + folder.getPath(); + } + + /** The identifiers in every CSV of a zip response. */ + private static Set zipIdentifiers(final Response response) throws Exception { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + ((StreamingOutput) response.getEntity()).write(out); + final Set identifiers = new HashSet<>(); + try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()))) { + for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { + identifiers.addAll(identifiers(new String(zip.readAllBytes(), + StandardCharsets.UTF_8))); + } + } + return identifiers; + } + + private static String entityJson(final Response response) throws Exception { + return DotObjectMapperProvider.getInstance().getDefaultObjectMapper() + .writeValueAsString(response.getEntity()); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (a) The limited user exports /a/, which holds A1, A2 and the unreadable Z1, + * and the unreadable /a/secret/ (with S1, and S2 deeper, both readable + * themselves); (e) the same response's headers + * ExpectedResult: A1 and A2 only: nothing under the unreadable folder at any depth, and not Z1 + * (FR-013); only the contract's headers, with the count equal to the rows (FR-015) + */ + @Test + public void test_selectedFolder_leavesOutUnreadableFoldersAndRows() throws Exception { + final Response response = exportSelection( + selection(List.of(pathOf(site, folderA)), List.of())); + + assertEquals(200, response.getStatus()); + for (final String header : response.getMetadata().keySet()) { + assertTrue("unexpected header " + header, CONTRACT_HEADERS.contains(header)); + } + assertEquals("2", String.valueOf(response.getMetadata().getFirst("X-Export-Contentlets"))); + assertEquals(Set.of(a1.getIdentifier(), a2.getIdentifier()), zipIdentifiers(response)); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (b) S1, readable, sits in the unreadable /a/secret/ and is selected directly + * ExpectedResult: S1 is exported: a contentlet's own READ decides, not its folder's (FR-009) + */ + @Test + public void test_readableContentletInUnreadableFolder_isExportedWhenSelected() + throws Exception { + final Response response = exportSelection( + selection(List.of(), List.of(ref(s1.getIdentifier())))); + + assertEquals(200, response.getStatus()); + assertEquals(Set.of(s1.getIdentifier()), zipIdentifiers(response)); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (c) An unreadable folder, a missing folder and another site's folder + * ExpectedResult: 404 each time, with byte-identical bodies (FR-014) + */ + @Test + public void test_unreadableMissingAndOtherSiteFolders_lookTheSame() throws Exception { + final Set bodies = new HashSet<>(); + for (final String path : List.of(pathOf(site, secretFolder), + pathOf(site, folderA) + "missing-" + System.currentTimeMillis() + "/", + "//" + otherSiteFolder.getHost().getHostname() + otherSiteFolder.getPath())) { + final Response response = exportSelection(selection(List.of(path), List.of())); + assertEquals(path, 404, response.getStatus()); + bodies.add(entityJson(response)); + } + assertEquals("byte-identical bodies", 1, bodies.size()); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: (d) A1 with a missing contentlet, the unreadable Z1 and another site's + * contentlet; then those three alone, together and one at a time + * ExpectedResult: The same response as A1 alone; with nothing else left, 204 every time + * (FR-002a, FR-015) + */ + @Test + public void test_droppedContentlets_leaveNoTrace() throws Exception { + final List dropped = List.of( + ref(UUID.randomUUID().toString()), ref(z1.getIdentifier()), + ref(inOtherSite.getIdentifier())); + + final Response alone = exportSelection( + selection(List.of(), List.of(ref(a1.getIdentifier())))); + final List mixed = new ArrayList<>(List.of(ref(a1.getIdentifier()))); + mixed.addAll(dropped); + final Response withDropped = exportSelection(selection(List.of(), mixed)); + + assertEquals(alone.getStatus(), withDropped.getStatus()); + for (final String header : CONTRACT_HEADERS) { + assertEquals(header, String.valueOf(alone.getMetadata().getFirst(header)), + String.valueOf(withDropped.getMetadata().getFirst(header))); + } + assertEquals(zipIdentifiers(alone), zipIdentifiers(withDropped)); + + assertEquals(204, exportSelection(selection(List.of(), dropped)).getStatus()); + for (final ExportContentletRefForm one : dropped) { + assertEquals(one.identifier(), 204, + exportSelection(selection(List.of(), List.of(one))).getStatus()); + } + } } From e4509d7d81dc04cfd8853c9c066ba8a9eda1419e Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 16:41:19 -0500 Subject: [PATCH 23/28] fix(content-drive): compile the export form on a clean build DriveExportRequestForm is generated by Immutables in the same round as DriveRequestForm, so on a clean build the imported simple name was not resolved yet and the generated class referred to it without an import, failing `just build-no-cache` (#37900). The query attribute now declares the type fully qualified. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- .../api/v1/drive/export/AbstractDriveExportRequestForm.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractDriveExportRequestForm.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractDriveExportRequestForm.java index 73498302584a..0d61537cfc74 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractDriveExportRequestForm.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/AbstractDriveExportRequestForm.java @@ -1,6 +1,5 @@ package com.dotcms.rest.api.v1.drive.export; -import com.dotcms.rest.api.v1.drive.DriveRequestForm; import com.dotcms.rest.exception.BadRequestException; import com.dotmarketing.util.UtilMethods; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -64,7 +63,10 @@ enum Mode { */ @Nullable @JsonProperty("query") - DriveRequestForm query(); + // Fully qualified on purpose: DriveRequestForm is generated by Immutables in the same round as + // this form's own class, so on a clean build an imported simple name is not resolved yet and + // the generated code would refer to it without an import. + com.dotcms.rest.api.v1.drive.DriveRequestForm query(); /** * Checks the request and tells which export it asks for. From 0d98f3322c4dae4132fe242ab9598705a82bd687 Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 16:41:21 -0500 Subject: [PATCH 24/28] refactor(content-drive): close the Content Search writer and document helpers downloadToExcel takes its writer in a try-with-resources, after setting the headers as before, and drops the branch that printed through a null writer; empty input still writes nothing (#37900). Adds the missing Javadoc to the new private helpers of the CSV writer and the selection resolver. The Content Search characterization tests still pass. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- .../content/export/ContentletCsvWriter.java | 21 +++++++++++++++++++ .../v1/drive/export/SelectionResolver.java | 7 +++++++ .../action/EditContentletAction.java | 19 ++++++++--------- 3 files changed, 37 insertions(+), 10 deletions(-) diff --git a/dotCMS/src/main/java/com/dotcms/content/export/ContentletCsvWriter.java b/dotCMS/src/main/java/com/dotcms/content/export/ContentletCsvWriter.java index 9ec3cd8bddda..ce1b3871ee43 100644 --- a/dotCMS/src/main/java/com/dotcms/content/export/ContentletCsvWriter.java +++ b/dotCMS/src/main/java/com/dotcms/content/export/ContentletCsvWriter.java @@ -348,6 +348,15 @@ private final class RowContext { private final Map> hosts = new HashMap<>(); private final Map> folders = new HashMap<>(); + /** + * Starts the context of one {@link ContentletCsvWriter#write} call, with empty host and + * folder caches. + * + * @param contentType the content type being written + * @param user the user the rows are loaded as + * @param request the request used for binary download links + * @param hostFolderMode how the host/folder column is written + */ private RowContext(final ContentType contentType, final User user, final HttpServletRequest request, final HostFolderMode hostFolderMode) { this.contentType = contentType; @@ -387,6 +396,12 @@ private Optional location(final Contentlet content) { return Optional.of("//" + host.get().getHostname() + folder.get().getPath()); } + /** + * Reads a host as the system user, for the location column only. + * + * @param hostId the host identifier + * @return the host, or empty when it cannot be read; the failure is logged + */ private Optional findHost(final String hostId) { try { return Optional.ofNullable( @@ -398,6 +413,12 @@ private Optional findHost(final String hostId) { } } + /** + * Reads a folder as the system user, for the location column only. + * + * @param folderInode the folder inode + * @return the folder, or empty when it cannot be read; the failure is logged + */ private Optional findFolder(final String folderInode) { try { return Optional.ofNullable(folderAPI.find(folderInode, APILocator.systemUser(), diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/SelectionResolver.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/SelectionResolver.java index 05f1a46bb94b..4b7f5d1e60b7 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/SelectionResolver.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/SelectionResolver.java @@ -172,6 +172,13 @@ private static boolean addAll(final Map rows, final List rows) { return new ExportCandidates(new ArrayList<>(rows.values()), true); } diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/action/EditContentletAction.java b/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/action/EditContentletAction.java index ad07f493a95c..6805d31330f0 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/action/EditContentletAction.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/action/EditContentletAction.java @@ -1916,7 +1916,7 @@ private void _loadForm(ActionRequest req, ActionResponse res, PortletConfig conf * The Content Type could not be read. */ public void downloadToExcel(final HttpServletResponse response, final User user, final List> contentletsToExport, final String contentTypeInode) throws DotSecurityException, DotDataException { - PrintWriter writer = null; + // Empty input writes nothing, not even a header row, as it always has if (!contentletsToExport.isEmpty()) { Logger.info(this, String.format("Generating CSV data. Mapping content list of type '%s'", contentTypeInode)); final List contentletInodes = new ArrayList<>(); @@ -1935,12 +1935,13 @@ public void downloadToExcel(final HttpServletResponse response, final User user, response.setContentType(MediaType.APPLICATION_OCTET_STREAM + "; " + MediaType.CHARSET_PARAMETER + "=" + StandardCharsets.UTF_8.name()); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + csvFileName +"\""); - writer = response.getWriter(); - // The Content Drive export writes the same file through the same writer - totalSize = new ContentletCsvWriter().write(contentType, contentletInodes, user, - HttpServletRequestThreadLocal.INSTANCE.getRequest(), HostFolderMode.IDENTIFIER, - writer); - writer.close(); + // The headers are set before the writer is taken, so its charset is UTF-8 + try (final PrintWriter writer = response.getWriter()) { + // The Content Drive export writes the same file through the same writer + totalSize = new ContentletCsvWriter().write(contentType, contentletInodes, user, + HttpServletRequestThreadLocal.INSTANCE.getRequest(), HostFolderMode.IDENTIFIER, + writer); + } HibernateUtil.closeSession(); } catch (final Exception p) { final String errorMsg = String.format("An error occurred when exporting contents of type '%s' [%s] to" + @@ -1960,9 +1961,7 @@ public void downloadToExcel(final HttpServletResponse response, final User user, .SIMPLE_MESSAGE).setSeverity(MessageSeverity.INFO).setLife(10000).create(); SystemMessageEventUtil.getInstance().pushMessage(systemMessage, ImmutableList.of(user.getUserId())); Logger.info(this, endMsg); - } else { - try {writer.print("\r\n");} catch (Exception e) { Logger.debug(this,"Error: download to excel "+e); } - } + } } /** From 38239b92f10a049f49a08a2807e43e7fc5fd3ba3 Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 16:41:22 -0500 Subject: [PATCH 25/28] test(content-drive): cover the export gaps found by convergence Tests approved before the fixes (#37900): a search text too complex for the index is the same 400 as the listing gives, a file built before a failure is deleted at once, error bodies carry a null entity as the contract shows, and an export started from one Export button blocks the other one that appears when the selection changes. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- ...tent-drive-export-button.component.spec.ts | 97 ++++++++++++++++++ ...ot-content-drive-toolbar.component.spec.ts | 98 ++++++++++++++++++- .../ContentDriveExportFilterModeTest.java | 84 ++++++++++++++++ 3 files changed, 277 insertions(+), 2 deletions(-) diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts index 1238656cb9f4..d2952d8fcb12 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.spec.ts @@ -14,6 +14,7 @@ vi.mock('@dotcms/utils', async () => ({ })); import { signal } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; import { MessageService } from 'primeng/api'; import { Tooltip } from 'primeng/tooltip'; @@ -50,6 +51,7 @@ import { DotContentDrivePage, DotContentDriveStatus } from '../../../../shared/models'; +import { DotContentDriveExportStateService } from '../../../../shared/services/dot-content-drive-export-state.service'; import { DotContentDriveStore } from '../../../../store/dot-content-drive.store'; /** A Form type's variable: fetching it answers with the FORM base type. */ @@ -167,6 +169,9 @@ describe('DotContentDriveExportButtonComponent', () => { const createComponent = createComponentFactory({ component: DotContentDriveExportButtonComponent, providers: [ + // The real shared in-flight flag, provided per test so a test that leaves an export + // running cannot leave the next test's buttons disabled. + DotContentDriveExportStateService, mockProvider(DotContentDriveStore, { selectedItems: selectedItemsSignal, filters: filtersSignal, @@ -506,6 +511,98 @@ describe('DotContentDriveExportButtonComponent', () => { }); }); + // The toolbar renders one Export button with nothing selected and another beside the workflow + // actions. Selecting while an export runs removes the first and mounts the second, which must + // not offer a second export until the first one ends (#37900 T106, FR-036, US1 scenario 10). + describe('while another Export button is exporting', () => { + let answer: Subject; + let otherFixture: ComponentFixture; + + /** The native button of the instance mounted after the selection changed. */ + const otherExportButton = () => + otherFixture.nativeElement.querySelector( + '[data-testid="content-drive-export-button"] button' + ) as HTMLButtonElement | null; + + /** + * Starts a filter-mode export from this instance, then does what the toolbar does when the + * user selects something meanwhile: removes this instance and mounts a new one, which is + * in selection mode. The answer is held back, so the export is still running afterwards. + */ + const exportThenSelect = async () => { + await render(); + spectator.click(exportButton() as HTMLElement); + + selectedItemsSignal.set([selectedContentlet('blog-1', 1)]); + spectator.fixture.destroy(); + + otherFixture = TestBed.createComponent(DotContentDriveExportButtonComponent); + otherFixture.detectChanges(); + await otherFixture.whenStable(); + otherFixture.detectChanges(); + }; + + /** Checks the new instance shows the running export: loading, and not clickable. */ + const expectOtherLoading = () => { + expect(otherExportButton()).toBeTruthy(); + expect(otherExportButton()).toHaveClass('p-button-loading'); + expect(otherExportButton()?.disabled).toBe(true); + }; + + beforeEach(() => { + answer = new Subject(); + exportService.export.mockReturnValue(answer); + }); + + it('should show the new button loading and disabled while the export runs', async () => { + await exportThenSelect(); + + expectOtherLoading(); + }); + + it('should not start a second export when the new button is clicked', async () => { + await exportThenSelect(); + + spectator.click(otherExportButton() as HTMLElement); + + expect(exportService.export).toHaveBeenCalledTimes(1); + }); + + // Each case first sees the new button loading, so an instance that was never blocked + // cannot pass by being enabled from the start. + describe('once the export ends', () => { + it.each([ + { + outcome: 'a file is downloaded', + end: () => { + answer.next(FILE_RESULT); + answer.complete(); + } + }, + { + outcome: 'there is nothing to export', + end: () => { + answer.next(EMPTY_RESULT); + answer.complete(); + } + }, + { + outcome: 'the export fails', + end: () => answer.error(new Error(SERVER_MESSAGE)) + } + ])('should enable the new button again when $outcome', async ({ end }) => { + await exportThenSelect(); + expectOtherLoading(); + + end(); + otherFixture.detectChanges(); + + expect(otherExportButton()).not.toHaveClass('p-button-loading'); + expect(otherExportButton()?.disabled).toBe(false); + }); + }); + }); + // Selection mode (#37900, US2): with anything selected, the button exports the selected // contentlets and folders as a zip, whatever the listing is filtered to. Folders go as // `//` asset paths (US3). diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.spec.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.spec.ts index a72be3642316..f5560814ef95 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.spec.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/dot-content-drive-toolbar.component.spec.ts @@ -5,7 +5,7 @@ import { createComponentFactory, mockProvider } from '@openng/spectator/vitest'; -import { EMPTY, of } from 'rxjs'; +import { EMPTY, of, Subject } from 'rxjs'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { provideHttpClient } from '@angular/common/http'; @@ -18,6 +18,7 @@ import { Tooltip } from 'primeng/tooltip'; import { DotCategoriesService, DotContentTypeService, + DotContentDriveExportResult, DotContentDriveExportService, DotContentletService, DotHttpErrorManagerService, @@ -49,7 +50,10 @@ import { DotContentDriveStatus, DotContentDriveViewType } from '../../shared/models'; -import { DotContentDriveNavigationService } from '../../shared/services'; +import { + DotContentDriveExportStateService, + DotContentDriveNavigationService +} from '../../shared/services'; import { DotContentDriveStore } from '../../store/dot-content-drive.store'; import { hasNonDefaultFilters } from '../../utils/functions'; @@ -219,6 +223,9 @@ describe('DotContentDriveToolbarComponent', () => { mockProvider(DotContentDriveExportService, { export: vi.fn().mockReturnValue(EMPTY) }), + // The real flag both Export buttons share, provided per test so an export a test leaves + // running cannot disable the next test's buttons. + DotContentDriveExportStateService, // The shared DotLanguageFilterComponent fetches the language list on init, so without // this the toolbar's render reaches for /api/v2/languages and the spec fails on a // NetworkError rather than on anything it is testing. @@ -264,6 +271,9 @@ describe('DotContentDriveToolbarComponent', () => { messageServiceSpy.clear.mockClear(); spectator = createComponent(); store = spectator.inject(DotContentDriveStore, true); + // The mock is shared by every test and clearAllMocks keeps a return value a test set, so + // reset it here: otherwise a test's never-answering export leaks into the tests after it. + spectator.inject(DotContentDriveExportService).export.mockReturnValue(EMPTY); spectator.detectChanges(); }); @@ -734,6 +744,90 @@ describe('DotContentDriveToolbarComponent', () => { // The creation block is gone, so the button cannot be sitting in it. expect(spectator.query(byTestId('upload-asset-tooltip'))).toBeNull(); }); + + // Changing the selection swaps one Export button for the other while an export may still + // be running; the one that appears must not start a second export until the first ends + // (#37900 T106, FR-036, US1 scenario 10). + describe('while an export runs and the selection changes', () => { + let answer: Subject; + let exportService: SpyObject; + + /** The native button of the Export button showing now: the toolbar shows one at a time. */ + const exportButton = () => + spectator + .query(byTestId('content-drive-export-button')) + ?.querySelector('button') as HTMLButtonElement | null; + + /** Settles the toolbar and lets the Export button's content type fetch answer. */ + const settle = async () => { + await settleToolbarAnimation(spectator); + await spectator.fixture.whenStable(); + spectator.detectChanges(); + }; + + /** Checks the Export button showing now is loading and cannot be clicked. */ + const expectExportBlocked = () => { + expect(exportButton()).toBeTruthy(); + expect(exportButton()).toHaveClass('p-button-loading'); + expect(exportButton()?.disabled).toBe(true); + }; + + beforeEach(() => { + // Filtered to one non-Form type, so the button shows with nothing selected too. + filtersSignal.set({ contentType: [MOCK_CONTENT_TYPES[0].variable] }); + exportService = spectator.inject(DotContentDriveExportService); + answer = new Subject(); + exportService.export.mockReturnValue(answer); + }); + + it('should block the button beside the workflow actions when something is selected', async () => { + await settle(); + expect(exportButton()?.disabled).toBe(false); + spectator.click(exportButton() as HTMLElement); + + selectedItemsSignal.set([MOCK_ITEMS[0]]); + await settle(); + + expect(spectator.query(byTestId('workflow-actions'))).toBeTruthy(); + expectExportBlocked(); + + spectator.click(exportButton() as HTMLElement); + + expect(exportService.export).toHaveBeenCalledTimes(1); + }); + + it('should block the button in the Upload / Add New block when the selection is cleared', async () => { + selectedItemsSignal.set([MOCK_ITEMS[0]]); + await settle(); + expect(exportButton()?.disabled).toBe(false); + spectator.click(exportButton() as HTMLElement); + + selectedItemsSignal.set([]); + await settle(); + + expect(spectator.query(byTestId('upload-asset-tooltip'))).toBeTruthy(); + expectExportBlocked(); + + spectator.click(exportButton() as HTMLElement); + + expect(exportService.export).toHaveBeenCalledTimes(1); + }); + + it('should enable the button again once the export ends', async () => { + await settle(); + spectator.click(exportButton() as HTMLElement); + selectedItemsSignal.set([MOCK_ITEMS[0]]); + await settle(); + expectExportBlocked(); + + answer.next({ kind: 'empty' }); + answer.complete(); + spectator.detectChanges(); + + expect(exportButton()).not.toHaveClass('p-button-loading'); + expect(exportButton()?.disabled).toBe(false); + }); + }); }); describe('Workflow Center button', () => { diff --git a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java index a9083bcdeac3..eccbab0143c6 100644 --- a/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java +++ b/dotcms-integration/src/test/java/com/dotcms/rest/api/v1/drive/ContentDriveExportFilterModeTest.java @@ -32,6 +32,7 @@ import com.dotcms.rest.api.v1.DotObjectMapperProvider; import com.dotcms.rest.api.v1.drive.export.ContentDriveExportHelper; import com.dotcms.rest.api.v1.drive.export.DriveExportRequestForm; +import com.dotcms.rest.api.v1.drive.export.ExportFile; import com.dotcms.rest.api.v1.drive.export.ExportFileBuilder; import com.dotcms.rest.api.v1.drive.export.ExportFileNames; import com.dotcms.util.IntegrationTestInitService; @@ -92,6 +93,9 @@ public class ContentDriveExportFilterModeTest extends IntegrationTestBase { private static final String EXPORT_FAILED = "The export failed. Try again, and contact your administrator if it keeps failing."; private static final String FOLDER_NOT_FOUND = "Folder not found."; + /** The message {@code /search} gives for a search text the index cannot build a query from. */ + private static final String TOO_COMPLEX = "The search text or filter values are too complex to " + + "search for; simplify or shorten them and try again."; private static final int MAX_PAGES = 200; /** @@ -780,4 +784,84 @@ public void test_overLimitMessage_formatsTheDefaultLimit() { + "filters or the selection and try again.", ContentDriveExportHelper.overLimitMessage(100_000)); } + // --------------------------------------------------------------------------------------------- + // convergence (Phase 12) + // --------------------------------------------------------------------------------------------- + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: A search text the index cannot build a query from (a long, self-repeating + * term, as {@code ContentDriveFieldFilterTest#testTooComplexSearchTermIsRejected} + * uses), over a type with rows, so the index narrowing runs (T104) + * ExpectedResult: 400 with the same message {@code /search} gives, not the generic 500 + * (contract § 400, FR-028) + */ + @Test + public void test_tooComplexSearchText_isABadRequestLikeSearch() throws Exception { + final Response response = export(query(sitePath()).browseScope(BrowseScope.ALL) + .filters(QueryFilters.builder().text("x".repeat(501)).build()).build()); + + assertEquals(400, response.getStatus()); + assertEquals(TOO_COMPLEX, errorMessage(response)); + } + + /** + * Returns a real, finished file in the export directory, with no file name, so building the + * response fails after the file exists, the way a failure while sending the headers would. + */ + private static final class FileThenFailingHelper extends ContentDriveExportHelper { + + Path built; + + @Override + public ExportFile export(final DriveExportRequestForm form, final User user, + final HttpServletRequest request) throws IOException { + Files.createDirectories(ExportFileBuilder.defaultDirectory()); + built = Files.createTempFile(ExportFileBuilder.defaultDirectory(), "export-", ".csv"); + Files.writeString(built, "Identifier,languageCode,countryCode\r\nx,en,US\r\n"); + return new ExportFile(built, null, "text/csv; charset=UTF-8", 1, 1); + } + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: The file is built, then building the response fails (T105) + * ExpectedResult: 500 with the generic message, and the built file is deleted at once rather + * than left for the hourly sweep (FR-032, SC-008) + */ + @Test + public void test_failureAfterTheFileIsBuilt_deletesIt() throws Exception { + final FileThenFailingHelper helper = new FileThenFailingHelper(); + + final Response response = export(new ContentDriveResource(helper), + query(folderPath()).build(), adminUser); + + assertEquals(500, response.getStatus()); + assertEquals(EXPORT_FAILED, errorMessage(response)); + assertNotNull("fixture: the helper built a file", helper.built); + assertFalse("the built file is deleted", Files.exists(helper.built)); + } + + /** + * Method to test: {@link ContentDriveResource#export} + * Given Scenario: A 400, a 404 and a 500 (T108) + * ExpectedResult: Each error body carries {@code "entity": null}, as the contract's error body + * shows + */ + @Test + public void test_errorBodies_carryANullEntity() throws Exception { + final List errors = List.of( + export(query(sitePath()).contentTypes(List.of()).build()), + export(query("//no-such-site-" + System.currentTimeMillis() + ".local/").build()), + export(new ContentDriveResource(new ContentDriveExportHelper(new FailingWriter())), + query(folderPath()).build(), adminUser)); + + for (final Response response : errors) { + assertTrue(response.getEntity() instanceof ResponseEntityView); + assertNull("status " + response.getStatus(), + ((ResponseEntityView) response.getEntity()).getEntity()); + assertTrue("status " + response.getStatus(), + entityJson(response).contains("\"entity\":null")); + } + } } From cdd3da6b959b6d8a5891f0513bc50afe1ac2d490 Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 16:41:31 -0500 Subject: [PATCH 26/28] fix(content-drive): close the export gaps found by convergence A filter-mode export whose search text the index rejects as too complex now answers the listing's 400 instead of a generic 500; the endpoint deletes a file it built before failing; error bodies carry `entity: null`; and both Export buttons share whether an export is running, so changing the selection mid-export cannot start a second one (#37900). Refs #37900 Co-Authored-By: Claude Opus 5.5 --- ...t-content-drive-export-button.component.ts | 20 +++++++----- .../dot-content-drive-export-state.service.ts | 31 +++++++++++++++++++ .../portlet/src/lib/shared/services/index.ts | 1 + .../rest/api/v1/drive/ContentDriveHelper.java | 11 +++++-- .../api/v1/drive/ContentDriveResource.java | 27 ++++++++++++++-- .../export/ContentDriveExportHelper.java | 17 ++++++++-- 6 files changed, 93 insertions(+), 14 deletions(-) create mode 100644 core-web/libs/portlets/dot-content-drive/portlet/src/lib/shared/services/dot-content-drive-export-state.service.ts diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts index eb2c20b4271a..4f00ce994af1 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/components/dot-content-drive-toolbar/components/dot-content-drive-export-button/dot-content-drive-export-button.component.ts @@ -1,4 +1,4 @@ -import { Component, computed, inject, signal } from '@angular/core'; +import { Component, computed, inject } from '@angular/core'; import { rxResource } from '@angular/core/rxjs-interop'; import { MessageService } from 'primeng/api'; @@ -24,6 +24,7 @@ import { WARNING_MESSAGE_LIFE } from '../../../../shared/constants'; import { DotContentDriveStatus } from '../../../../shared/models'; +import { DotContentDriveExportStateService } from '../../../../shared/services'; import { DotContentDriveStore } from '../../../../store/dot-content-drive.store'; import { excludeFolders, toFolderAssetPaths } from '../../../../utils/action-center'; import { isFolder } from '../../../../utils/functions'; @@ -33,8 +34,9 @@ import { isFolder } from '../../../../utils/functions'; * listing is filtered to one content type (filter mode); with anything selected it downloads the * selected contentlets as a zip with one CSV per content type (selection mode). * - * It reads the store and keeps its own in-flight state; it adds nothing to the store, which is at - * the `signalStore` feature limit. + * It reads the store, and shares whether an export is running with the other Export button + * through `DotContentDriveExportStateService`; it adds nothing to the store, which is at the + * `signalStore` feature limit. */ @Component({ selector: 'dot-content-drive-export-button', @@ -47,9 +49,13 @@ export class DotContentDriveExportButtonComponent { readonly #contentTypeService = inject(DotContentTypeService); readonly #messageService = inject(MessageService); readonly #dotMessageService = inject(DotMessageService); + readonly #exportState = inject(DotContentDriveExportStateService); - /** True from the click until the export answers, so a second click cannot start another. */ - protected readonly $exporting = signal(false); + /** + * True from a click on either Export button until that export answers, so neither button can + * start another one meanwhile, even the one that appears when the selection changes. + */ + protected readonly $exporting = this.#exportState.$exporting; /** * Selection mode applies whenever anything is selected, whatever the listing is filtered to: @@ -168,11 +174,11 @@ export class DotContentDriveExportButtonComponent { const body = this.#buildRequest(); - this.$exporting.set(true); + this.#exportState.start(); this.#exportService .export(body) - .pipe(finalize(() => this.$exporting.set(false))) + .pipe(finalize(() => this.#exportState.end())) .subscribe({ next: (result) => { if (result.kind !== 'file') { diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/shared/services/dot-content-drive-export-state.service.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/shared/services/dot-content-drive-export-state.service.ts new file mode 100644 index 000000000000..e9c6f4fb156a --- /dev/null +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/shared/services/dot-content-drive-export-state.service.ts @@ -0,0 +1,31 @@ +import { Injectable, Signal, signal } from '@angular/core'; + +/** + * Whether a Content Drive export is running, shared by every Export button (#37900, FR-036). + * + * The toolbar renders two Export buttons, one with nothing selected and one beside the workflow + * actions, and changing the selection swaps one for the other while an export may still be + * running. Each button reads this flag rather than keeping its own, so the one that appears + * cannot start a second export until the first one ends. + * + * Provided in `root` because the export request is not tied to any component: it keeps running + * when the button that started it is removed, so the flag has to outlive that button as well. It + * is not part of `DotContentDriveStore`, which is at the `signalStore` feature limit. + */ +@Injectable({ providedIn: 'root' }) +export class DotContentDriveExportStateService { + readonly #exporting = signal(false); + + /** True from the moment an export starts until it answers, whichever button started it. */ + readonly $exporting: Signal = this.#exporting.asReadonly(); + + /** Marks an export as running. */ + start(): void { + this.#exporting.set(true); + } + + /** Marks the running export as ended, whether it downloaded a file, found nothing or failed. */ + end(): void { + this.#exporting.set(false); + } +} diff --git a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/shared/services/index.ts b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/shared/services/index.ts index aa6655d614b2..24403c41adc3 100644 --- a/core-web/libs/portlets/dot-content-drive/portlet/src/lib/shared/services/index.ts +++ b/core-web/libs/portlets/dot-content-drive/portlet/src/lib/shared/services/index.ts @@ -1 +1,2 @@ +export * from './dot-content-drive-export-state.service'; export * from './dot-content-drive-navigation.service'; diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveHelper.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveHelper.java index de614565d20c..c63450881f66 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveHelper.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveHelper.java @@ -45,6 +45,13 @@ */ public class ContentDriveHelper { + /** + * The 400 message for search text or filter values the index cannot build a query from. The + * listing and the Content Drive export give the same one. + */ + public static final String TOO_COMPLEX_MESSAGE = "The search text or filter values are too " + + "complex to search for; simplify or shorten them and try again."; + private final BrowserAPI browserAPI; private final ContentDriveFieldFilterResolver fieldFilterResolver = new ContentDriveFieldFilterResolver(); @@ -112,9 +119,7 @@ public PaginatedContents driveSearch(final DriveRequestForm requestForm, final U return browserAPI.getPaginatedContents(browserQuery); } catch (final DotDataException | DotRuntimeException e) { if (ExceptionUtil.causedBy(e, ESQueryTooComplexException.class)) { - throw new BadRequestException(e, - "The search text or filter values are too complex to search for; simplify " - + "or shorten them and try again."); + throw new BadRequestException(e, TOO_COMPLEX_MESSAGE); } throw e; } diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java index 4a6bef0aeced..2791b6118df8 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/ContentDriveResource.java @@ -221,10 +221,11 @@ public Response export(@Context final HttpServletRequest request, .rejectWhenNoUser(true).init(); final User user = initDataObject.getUser(); + ExportFile file = null; try { final DriveExportRequestForm body = form == null ? DriveExportRequestForm.builder().build() : form; - final ExportFile file = exportHelper.export(body, user, request); + file = exportHelper.export(body, user, request); if (file.contentlets() == 0) { return Response.noContent().build(); } @@ -241,11 +242,30 @@ public Response export(@Context final HttpServletRequest request, } catch (final Exception e) { Logger.error(this, String.format("Content Drive export failed for user '%s': %s", user.getUserId(), e.getMessage()), e); + // A file built before the failure is never sent, so nothing else would delete it + if (file != null) { + deleteQuietly(file.path()); + } return errorResponse(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), EXPORT_FAILED_MESSAGE); } } + /** + * Deletes an export file that will not be sent, logging instead of throwing when it cannot be + * deleted; the export directory's hourly sweep removes it then. + * + * @param path the file to delete + */ + private void deleteQuietly(final java.nio.file.Path path) { + try { + Files.deleteIfExists(path); + } catch (final Exception e) { + Logger.warn(this, String.format("Unable to delete export file '%s': %s", path, + e.getMessage())); + } + } + /** * Builds an export error response in the one shape the Drive reads: * {@code {"errors":[{"errorCode","message","fieldName":null}],"entity":null}}. @@ -259,7 +279,10 @@ private static Response errorResponse(final int status, final String message) { final String errorCode = known == null ? String.valueOf(status) : known.name(); return Response.status(status) .type(MediaType.APPLICATION_JSON) - .entity(new ResponseEntityView<>(List.of(new ErrorEntity(errorCode, message, null)))) + // entity null, as the contract's error body shows; the errors-only constructor + // would write "" + .entity(new ResponseEntityView( + List.of(new ErrorEntity(errorCode, message, null)), (Object) null)) .build(); } } diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java index 3008a1d82e13..4fd8346a4e2e 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/drive/export/ContentDriveExportHelper.java @@ -3,10 +3,12 @@ import com.dotcms.browser.BrowserAPI; import com.dotcms.content.export.ContentletCsvWriter; import com.dotcms.browser.BrowserQuery; +import com.dotcms.browser.ESQueryTooComplexException; import com.dotcms.browser.ExportCandidates; import com.dotcms.browser.ExportRow; import com.dotcms.contenttype.exception.NotFoundInDbException; import com.dotcms.contenttype.business.ContentTypeAPI; +import com.dotcms.exception.ExceptionUtil; import com.dotmarketing.portlets.contentlet.business.HostAPI; import com.dotmarketing.util.UtilMethods; import io.vavr.control.Try; @@ -23,6 +25,7 @@ import com.dotmarketing.beans.Host; import com.dotmarketing.business.APILocator; import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotRuntimeException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.util.Config; import com.google.common.annotations.VisibleForTesting; @@ -195,7 +198,8 @@ record FilterResolution(ContentType contentType, ExportCandidates candidates) { * @param user the {@link User} the export runs as * @return the content type and its readable rows * @throws BadRequestException when there is not exactly one readable type, it is a Form or Host - * type, or more rows match than the limit + * type, the search text is too complex for the index, or more + * rows match than the limit * @throws NotFoundException when the site or folder does not exist or cannot be read * @throws DotDataException if the rows cannot be read * @throws DotSecurityException if the user cannot read the site or folder @@ -214,7 +218,16 @@ FilterResolution resolveFilterMode(final DriveRequestForm query, final User user driveHelper.checkSearchable(browserQuery); final int maxRows = Config.getIntProperty(MAX_ROWS_KEY, MAX_ROWS_DEFAULT); - final ExportCandidates candidates = browserAPI.getContentForExport(browserQuery, maxRows); + final ExportCandidates candidates; + try { + candidates = browserAPI.getContentForExport(browserQuery, maxRows); + } catch (final DotDataException | DotRuntimeException e) { + // Search input the index cannot build a query from is bad input, as in the listing + if (ExceptionUtil.causedBy(e, ESQueryTooComplexException.class)) { + throw new BadRequestException(e, ContentDriveHelper.TOO_COMPLEX_MESSAGE); + } + throw e; + } if (candidates.overLimit()) { throw new BadRequestException(overLimitMessage(maxRows)); } From c31380c7e6689636d3dbfef35ee572a6874e0560 Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 20:59:08 -0500 Subject: [PATCH 27/28] test(content-drive): stop the selection e2e waiting on hidden workflow actions For two contentlets of different types the workflow actions component has no shared action and renders hidden, so the wait for it timed out before the Export click (#37900). The wait only located the button; the test still checks the button is enabled with a selection and the zip download name. Refs #37900 Co-Authored-By: Claude Opus 5.5 --- .../src/tests/content-drive/content-drive-export.spec.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/core-web/apps/dotcms-ui-e2e/src/tests/content-drive/content-drive-export.spec.ts b/core-web/apps/dotcms-ui-e2e/src/tests/content-drive/content-drive-export.spec.ts index 2e14d5209992..1d4b0cc22e9f 100644 --- a/core-web/apps/dotcms-ui-e2e/src/tests/content-drive/content-drive-export.spec.ts +++ b/core-web/apps/dotcms-ui-e2e/src/tests/content-drive/content-drive-export.spec.ts @@ -133,10 +133,9 @@ test.describe('Content Drive export', () => { .click(); } - // With a selection the button sits beside the workflow actions. - await expect(drive.toolbar.getByTestId('workflow-actions')).toBeVisible({ - timeout: 20000 - }); + // With a selection the button sits in the selection block, beside the workflow actions. + // The actions themselves are not awaited: for contentlets of two types there may be no + // action they share, and the component then renders hidden. const exportButton = drive.toolbar.getByTestId('export-button').getByRole('button'); await expect(exportButton).toBeEnabled({ timeout: 20000 }); From b59a8a62f5fa9714dc67257ed16248499024ec9c Mon Sep 17 00:00:00 2001 From: ddariod Date: Fri, 27 Nov 2026 22:20:00 -0500 Subject: [PATCH 28/28] docs(spec): content drive export changes after the manual check Three changes to the approved spec for #37900, decided after checking the implementation by hand: - A selection whose rows are all of one content type exports that single CSV, named as in filter mode, instead of a zip holding it (FR-016, US2). - The Export button sits in the same place in both modes: last in the toolbar (FR-035, US2). - The selection limit becomes configurable, CONTENT_DRIVE_EXPORT_MAX_SELECTED_ITEMS (default 60), selection mode only; the UI reads the same value. The 100,000-row limit is unchanged and applies in both modes (FR-004a, FR-028, SC-002, US2). Refs #37900 Co-Authored-By: Claude Opus 5.5 --- specs/37900-content-drive-export/spec.md | 87 ++++++++++++++---------- 1 file changed, 51 insertions(+), 36 deletions(-) diff --git a/specs/37900-content-drive-export/spec.md b/specs/37900-content-drive-export/spec.md index a91c015a4d97..b3e8e573aad5 100644 --- a/specs/37900-content-drive-export/spec.md +++ b/specs/37900-content-drive-export/spec.md @@ -13,9 +13,10 @@ **Input**: [#37900](https://github.com/dotCMS/core/issues/37900) — Content Drive: Add content export. Bring the Content Search CSV export to Content Drive with feature parity first (filter mode: exactly one content type, every result of the listing's location and filters, as one CSV), then add -selection as new capability (selection mode: up to 60 folders and contentlets of any content types, -as a zip with one CSV per content type). Both reuse the Content Search CSV writer and file names -(`_contents_.csv`; the zip is `_export_.zip`), keep the +selection as new capability (selection mode: up to a configurable number of folders and contentlets, +60 by default, of any content types, as one CSV when they resolve to a single content type and +otherwise a zip with one CSV per content type). Both reuse the Content Search CSV writer and file +names (`_contents_.csv`; the zip is `_export_.zip`), keep the 100,000-row limit but refuse bigger exports instead of truncating them, and let the selection win over the filter. @@ -37,7 +38,8 @@ This feature brings that export to Drive, through one new endpoint, in two modes - **Selection mode (new).** The user selects folders and contentlets, of any content types. A selected contentlet is exported in the language version the user selected, and only that one. A selected folder brings every contentlet below it, at any depth, in every language version and - including archived ones. Folders themselves are never rows. The result is a zip with one CSV per content type. Drive's filters do not apply: **what you + including archived ones. Folders themselves are never rows. The result is one CSV when every row + is of a single content type, and otherwise a zip with one CSV per content type. Drive's filters do not apply: **what you select is what you export.** Each CSV has the same columns, values and file name as the Content Search export, so it can be @@ -100,7 +102,7 @@ CSV. ### User Story 2 - Export selected contentlets of several content types (Priority: P2) An editor selects contentlets in Drive and clicks **Export**. A zip downloads with one CSV per -content type among them. Each selected row is exported as it was selected: the contentlet in that +content type among them; when they are all of one content type, that single CSV downloads instead. Each selected row is exported as it was selected: the contentlet in that language, and no other language version of it. **Why this priority**: It is new capability beyond Content Search. It reuses the CSV writer, the @@ -116,11 +118,14 @@ data row. The toast reports 3 items and 2 files. **Acceptance Scenarios**: 1. **Given** one or more items are selected in Drive, **When** the toolbar renders, **Then** an - Export button is shown beside the workflow actions, and the Action Center does not list an - Export row. + Export button is shown as the last button of the toolbar, where filter mode shows it, and the + Action Center does not list an Export row. 2. **Given** contentlets of two content types are selected, **When** the user clicks Export, **Then** a zip downloads that holds one CSV per content type, and the toast reports the number of rows and CSV files exported. +2a. **Given** the selected items resolve to rows of a single content type (contentlets of one type, + or folders whose content is all of one type), **When** the user clicks Export, **Then** that one + CSV downloads, named as in filter mode, not a zip holding it. 3. **Given** a contentlet has versions in two languages and only its English row is selected, **When** it is exported, **Then** its CSV has only the English row. **Given** both language rows are selected, **Then** both are exported, each with its languageCode and countryCode. @@ -130,19 +135,19 @@ data row. The toast reports 3 items and 2 files. the user exports a selection, **Then** the filters do not change which items are exported. 6. **Given** items are selected and the listing is filtered to one content type, **When** the user exports, **Then** the selection is exported and the filter is ignored. -7. **Given** more than 60 items are selected (folders and contentlets together), **When** the - toolbar renders, **Then** the Export button is disabled and explains that at most 60 items can be - exported at once. -8. **Given** a request whose selection has more than 60 entries, **When** it reaches the server, - **Then** it is refused as a bad request and no file is produced. +7. **Given** more items are selected than the configured selection limit (folders and contentlets + together; 60 by default), **When** the toolbar renders, **Then** the Export button is disabled + and explains that at most that many items can be exported at once. +8. **Given** a request whose selection has more entries than the configured selection limit, + **When** it reaches the server, **Then** it is refused as a bad request and no file is produced. --- ### User Story 3 - Export whole folders (Priority: P2) An editor selects one or more folders, optionally together with contentlets, and exports them. The -zip holds every contentlet inside the folders at any depth, plus the selected contentlets, each -exported once. Folders are only walked to reach their content; they are never rows. +file (a zip, or one CSV when everything is of one content type) holds every contentlet inside the +folders at any depth, plus the selected contentlets, each exported once. Folders are only walked to reach their content; they are never rows. **Why this priority**: Exporting a whole section of a site, of every content type, is what selection adds over Content Search, which has no recursive folder export. @@ -161,7 +166,7 @@ and no row stands for a folder. 3. **Given** a selected folder holds files and pages, **When** it is exported, **Then** they are exported in their own content types' CSVs, with binary fields as a download URL. 4. **Given** a folder and a contentlet outside it are selected, **When** they are exported, **Then** - both are in the same zip. + both are in the same file. 5. **Given** a contentlet is selected directly and is also inside a selected folder, **When** they are exported, **Then** the contentlet appears in its CSV once. 6. **Given** a folder and one of its subfolders are both selected, **When** they are exported, @@ -242,7 +247,7 @@ An editor exports content, edits a CSV, and imports it back to update the same c moves the CSV writer and changes one column (host/folder), and neither may break importing. It is checked as part of this ticket, without waiting for the Drive import ticket (#37896). -**Independent Test**: Export a filter-mode CSV and a selection-mode zip that together hold content in +**Independent Test**: Export a filter-mode CSV and a selection-mode file that together hold content in a folder, content at a site root and content in System Host. Import one CSV of each with Identifier as the key field and no language (multilingual file). The same contentlets are updated with no row errors, and each one is still on the same site and in the same folder. @@ -305,9 +310,9 @@ file. a Form type filter (FR-007). - **Listing changes while it is being exported.** Content created or deleted during a filter-mode export may or may not be in the file; the export does not lock the listing. -- **60 items selected, one of them a large folder.** The 60-item limit counts what the user selected, - not what is below it: a folder is one item. The 100,000-row limit still applies to what the - selection expands to (FR-010). +- **The selection limit reached, one of them a large folder.** The selection limit counts what the + user selected, not what is below it: a folder is one item. The 100,000-row limit still applies to + what the selection expands to (FR-010). - **Content at a site root.** Its host/folder column is the bare hostname, not `//site/`. Written as `//site/`, the import would resolve the path `/` to the system folder and silently move the contentlet to System Host, with no row error (FR-022). @@ -353,9 +358,12 @@ file. resolved for the user, before any content is read: a content type that does not exist and one the user cannot read MUST both be refused, with the same bad-request message. An unresolved type MUST never fall through to a query with no content type restriction. -- **FR-004a**: A selection MUST hold at most 60 items, counting folders and contentlets together. A - folder counts as one item, whatever it contains. A request whose selection has more than 60 - entries MUST be refused as a bad request. +- **FR-004a**: A selection MUST hold at most a configurable number of items + (`CONTENT_DRIVE_EXPORT_MAX_SELECTED_ITEMS`, 60 by default), counting folders and contentlets + together. A folder counts as one item, whatever it contains. The limit applies to selection mode + only. A request whose selection has more entries than the limit MUST be refused as a bad request + whose message says at most that many items can be exported at once. The UI MUST read the same + configured value, so the button and the server never disagree. **What gets exported** @@ -403,9 +411,12 @@ file. **Files and names** -- **FR-016**: A filter-mode export MUST produce a single CSV, not a zip. A selection-mode export MUST - produce a zip named `_export_.zip`, where `` is the site the user is - browsing in Drive and the date is the export date. +- **FR-016**: A filter-mode export MUST produce a single CSV, not a zip. A selection-mode export whose + rows are all of one content type MUST produce that single CSV as well, named as in filter mode + (FR-019). A selection-mode export with rows of two or more content types MUST produce a zip named + `_export_.zip`, where `` is the site the user is browsing in Drive + and the date is the export date. Which applies is decided by the rows resolved, not by what was + selected: a folder may hold content of several types. - **FR-017**: Each contentlet MUST appear at most once per language: duplicates are removed by identifier and language, not by inode. This applies when a contentlet is selected and also inside a selected folder, when nested folders are both selected, when the same entry is sent twice, and @@ -480,7 +491,7 @@ file. - **FR-027**: When there is nothing the user can read to export, the system MUST return "no content" (204) and no file. - **FR-028**: An empty selection with no listing query, a malformed folder path, a filter-mode query - not naming exactly one readable content type, a selection of more than 60 entries, and an export + not naming exactly one readable content type, a selection over the configured selection limit, and an export over 100,000 rows MUST return "bad request" (400) with a message the UI can show. A folder that does not resolve is "not found" (404), as an unreadable one is (FR-014). - **FR-029**: When the export fails, the system MUST return a server error (500) with a JSON error @@ -499,10 +510,11 @@ file. is not a Form, Drive MUST show the Export button in the toolbar, which exports in filter mode. If the listing shows no contentlets for the current filters, the button MUST be disabled. Otherwise, with nothing selected, it MUST NOT be shown. -- **FR-035**: When one or more items are selected, Drive MUST show the Export button beside the - workflow actions in the toolbar, which exports the selection. The Action Center MUST NOT list an - Export row. With more than 60 items selected, the button MUST be disabled and tell the user that - at most 60 items can be exported at once. +- **FR-035**: When one or more items are selected, Drive MUST show the Export button in the toolbar, + which exports the selection. In both modes the button MUST sit in the same place: last, after + every other toolbar button. The Action Center MUST NOT list an Export row. With more items + selected than the configured selection limit (FR-004a), the button MUST be disabled and tell the + user that at most that many items can be exported at once. - **FR-036**: While an export runs, the Export button MUST show a loading state and be disabled. - **FR-037**: On success, the browser MUST download the file under the server's file name, and a toast MUST report the number of items and CSV files exported. @@ -522,8 +534,9 @@ file. identifier and language. - **Content-type CSV**: All export rows of one content type, with one header row, named `_contents_.csv`. -- **Export file**: A single content-type CSV (filter mode) or a zip of content-type CSVs (selection - mode), with its row and file counts. +- **Export file**: A single content-type CSV (filter mode, or a selection whose rows are of one + content type) or a zip of content-type CSVs (a selection with rows of several content types), with + its row and file counts. ## Success Criteria *(mandatory)* @@ -532,8 +545,9 @@ file. - **SC-001**: Every export an editor can make today from Content Search (one content type, filtered by site or folder, language, workflow, text and System Host) can be made from Drive in one action, without paging through the listing first. -- **SC-002**: A user can export any mix of up to 60 selected folders and contentlets they can read, - of any number of content types, in one action, up to 100,000 rows. +- **SC-002**: A user can export any mix of selected folders and contentlets they can read, up to the + configured selection limit (60 by default), of any number of content types, in one action, up to + 100,000 rows. - **SC-003**: For the same content, 100% of columns and values in a Drive CSV match the Content Search export, except the host/folder column. - **SC-004**: A CSV from either mode, imported back with Identifier as key and no language, updates @@ -562,8 +576,9 @@ file. - **Known related decisions**: - Feature parity with Content Search is the first goal; selection is additional (team decision, 2026-10-14). - - The Export button sits in the toolbar, beside the workflow actions when there is a selection, - not in the Action Center. This was decided in the team meeting. + - The Export button sits in the toolbar, not in the Action Center. This was decided in the team + meeting. After the manual check (2026-11-27) the developer asked for the same place in both + modes: last in the toolbar. - The relationship column keeps legacy behavior and is not filtered by the user's permissions (FR-024). This was decided explicitly in the spec review, as feature parity: today's Content Search export already writes every related identifier unchecked (`loadRelationships`, with