> For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt.

# Groovy Console — Batch sửa JCR Node: Asset Name, Property và Dry Run an toàn

> Bài này dùng **AEM Groovy Console 15.1.0** (ICF Next) trên **AEM 6.5.24 Author** local. Quy trình đã được chạy thử từ audit, dry run, apply đến verify và rollback; các đoạn code bên dưới là code đã dùng để test.
>
> Script chạy trong Groovy Console dùng `Session` JCR của user đang đăng nhập. Console không có `undo`, không có transaction bao phủ nhiều lần `save()`, và DSL `rename` có thể tự commit. Do đó nên tách bước đọc và bước ghi: audit, dry run, apply theo batch nhỏ, rồi verify và chuẩn bị sẵn mapping để rollback.

***

## 0. TL;DR — quy trình 5 pha

```text
1. HIỂU    node nào là asset, property nào là tên, reference nào đang trỏ tới
2. SEARCH  query rộng theo path + node type, filter bằng Groovy
3. DRY RUN lập plan JSON/CSV, không setProperty, không move, không save
4. APPLY   đọc plan, kiểm tra precondition, move/setProperty, save theo batch
5. VERIFY  path cũ 404, path mới 200, UUID giữ nguyên, reference đã đổi
```

Điểm quan trọng nhất là **không tìm node và sửa JCR trong cùng một script**. Dùng một script read-only để tạo plan, sau đó dùng script khác để ghi theo plan đã review.

***

## 1. Groovy Console trên AEM 6.5

### 1.1. Cài đặt và truy cập

AEM 6.5 không có sẵn Groovy Console. Bản dùng trong bài là package **AEM Groovy Console 15.1.0** của ICF Next:

```text
https://github.com/icfnext/aem-groovy-console/releases
```

Cài qua Package Manager (`/crx/packmgr/index.jsp`) hoặc `curl`:

```powershell
curl.exe -sS -u admin:admin `
  -F "file=@C:\path\to\aem-groovy-console-15.1.0.zip" `
  -F "cmd=upload" -F "install=true" `
  http://localhost:4502/crx/packmgr/service.jsp
```

Sau khi cài, kiểm tra bundle tại `/system/console/bundles`:

```text
AEM Groovy Console            15.1.0   Active
AEM Groovy Extension Bundle   7.0.0    Active
Groovy Runtime                2.4.15   Active
```

Truy cập:

```text
http://localhost:4502/groovyconsole
```

Với package 15.1.0 trong bài, URL này hoạt động. Một số tài liệu cũ dùng `/etc/groovyconsole.html`; trên instance 6.5.24 được test, path đó trả `404`.

> **Quyền truy cập:** Groovy Console chạy code tùy ý trong JVM và có `Session` của user đang đăng nhập. Chỉ cấp cho admin hoặc nhóm vận hành/dev thực sự tin cậy. Không mở `/groovyconsole` và `/bin/groovyconsole/post.json` ra ngoài qua Dispatcher.

### 1.2. Các binding có sẵn

Khi mở console, script có các biến sau:

| Binding                          | Kiểu                      | Dùng để                                                    |
| -------------------------------- | ------------------------- | ---------------------------------------------------------- |
| `session`                        | `javax.jcr.Session`       | đọc/ghi JCR, `save()`, `move()`                            |
| `resourceResolver`               | `ResourceResolver`        | đọc Resource, `adaptTo`, `commit()`                        |
| `pageManager`                    | `PageManager`             | lấy page, list children                                    |
| `queryBuilder`                   | `QueryBuilder`            | query theo predicate                                       |
| `log`                            | `org.slf4j.Logger`        | ghi log                                                    |
| `out`                            | `PrintStream`             | output thay cho `println`                                  |
| `data`                           | `List` / `Map` / `String` | dữ liệu từ panel **Data**                                  |
| `nodeBuilder`                    | `NodeBuilder`             | tạo cây node bằng DSL                                      |
| `pageBuilder`                    | `PageBuilder`             | tạo page bằng DSL                                          |
| `bundleContext`                  | `BundleContext`           | lấy OSGi service nếu thật cần                              |
| `slingRequest` / `slingResponse` | Sling request/response    | chỉ có khi chạy trực tiếp, không có khi chạy scheduled job |

Một số method tiện dụng:

```groovy
getNode("/content/dam/myproject")        // Node, throw nếu không tồn tại
getResource("/content/dam/myproject")    // Resource, null nếu không tồn tại
getPage("/content/myproject/en")         // Page, null nếu không tồn tại
save()                                   // session.save()
createQuery([path: "...", type: "..."])  // QueryBuilder
rename node to "new-name"                // DSL, tự save
move " /old/path" to "/new/path"         // DSL, tự save
```

### 1.3. Script chạy bằng session nào?

Phần này thường gây nhầm lẫn:

- **Chạy tay trên UI:** `session` và `resourceResolver` là của **user đang đăng nhập**. Trong bài test, `session.userID` là `admin`.
- **Scheduled job:** console dùng `ResourceResolverFactory.getServiceResourceResolver(null)`, tức là chạy bằng service user theo mapping của package. Với package 15.1.0, mapping là:

```text
aem-groovy-console = groovy-console-system-user
```

Trên instance test, `groovy-console-system-user` chỉ thuộc group `everyone`. Vì vậy scheduled job **không tự có quyền admin**; nếu script cần ghi, phải cấp ACL phù hợp hoặc dùng một service user riêng. Đừng dùng scheduled job để “lách” quyền của user tương tác.

Kiểm tra nhanh:

```groovy
println "session.userID       = " + session.userID
println "resourceResolver ID  = " + resourceResolver.userID
println "hasPendingChanges    = " + session.hasPendingChanges()
```

### 1.4. Save, commit và cái bẫy “tự save”

Console **không tự save** khi script kết thúc. `setProperty()` mà không đi kèm `save()` chỉ tạo thay đổi tạm thời; request tiếp theo sẽ không thấy dữ liệu đó. Trong test, node tạo không `save()` trả `404`, còn node được `save()` trả `200`.

| Thao tác                    | Có tự save? | Ghi chú                        |
| --------------------------- | ----------- | ------------------------------ |
| `node.setProperty(...)`     | Không       | chỉ là transient change        |
| `session.removeItem(...)`   | Không       | phải `save()`                  |
| `session.move(...)`         | Không       | phải `save()`                  |
| `save()` / `session.save()` | Có          | commit toàn bộ pending changes |
| `resourceResolver.commit()` | Có          | commit thay đổi qua Sling API  |
| `rename node to "..."`      | **Có**      | DSL tự gọi save                |
| `move "src" to "dst"`       | **Có**      | DSL tự gọi save                |

Vì vậy:

- Trong **dry run**, tuyệt đối không gọi `setProperty`, `removeItem`, `session.move`, `rename`, `move` hay `save`.
- Trong **apply**, dùng `session.move` + `save()` theo batch để kiểm soát commit. Không dùng `rename node to ...` cho batch lớn vì mỗi lần rename là một lần commit riêng.
- Nếu script lỗi giữa chừng, các `save()` trước đó **vẫn đã ghi**. Plan, batch nhỏ và mapping là cơ sở để rollback những thay đổi đó.

### 1.5. Audit và history

Console ghi lại script và output tại:

```text
/var/groovyconsole/audit/<user>/<yyyy>/<MM>/<dd>/record*
```

Mỗi record có các property đáng chú ý:

```text
script        toàn bộ source code
output        output của println
result        giá trị return
runningTime   thời gian chạy
jcr:createdBy thường là groovy-console-system-user
```

Lưu ý:

- Audit rất hữu ích để truy vết “ai chạy script gì, lúc nào”.
- Nhưng audit lưu **toàn bộ script**, nên không được hardcode mật khẩu, token, connection string trong script.
- Nếu script in ra dữ liệu nhạy cảm, output cũng nằm trong `/var`. Cần chính sách lưu trữ/xoá phù hợp.
- Nút xoá history trong UI chỉ xoá audit record, không hoàn tác thay đổi JCR.

***

## 2. Hiểu node trước khi sửa

### 2.1. Một asset DAM gồm những gì?

Với một image asset, cấu trúc thực tế trên AEM 6.5.24:

```text
/content/dam/myproject/hero/Ảnh Bìa (1).PNG        <- dam:Asset, đây là "tên asset"
  jcr:content                                     <- dam:AssetContent
    metadata                                      <- nt:unstructured
      dc:format        = image/png
      dam:MIMEtype     = image/png
      dam:Fileformat   = PNG
      dam:size         = 68
      dam:sha1         = ...
      tiff:ImageWidth  = ...
      tiff:ImageLength = ...
      dam:extracted    = ...
    renditions
      original
        jcr:content
          jcr:data     <- binary gốc
          jcr:mimeType = image/png
      cq5dam.thumbnail.48.48.png
      cq5dam.thumbnail.140.100.png
      cq5dam.web.1280.1280.png
```

Các điểm cần nhớ:

- **Tên asset = tên node `dam:Asset`**, không phải `dc:title`.
- `dc:title` / `dc:description` là metadata hiển thị; đổi title **không** đổi path, không làm broken link.
- `dam:sha1` là checksum; trong test, nó **đổi** sau khi metadata được cập nhật. Đừng dùng `dam:sha1` làm định danh duy nhất. `jcr:uuid` ổn định hơn.
- `jcr:content/metadata` có thể chưa có `dc:title`; đừng giả định property luôn tồn tại.
- `jcr:mixinTypes`, `cq:tags` là multi-value. Gọi `.string` trên property multi-value sẽ ném `ValueFormatException`.
- `Node` JCR **không có** `adaptTo(Asset)`. Muốn lấy `Asset`, đi qua Resource:

```groovy
def asset = resourceResolver.getResource(node.path)?.adaptTo(com.day.cq.dam.api.Asset)
```

### 2.2. Đổi tên asset và đổi property khác nhau thế nào?

| Thay đổi                 | Đối tượng        | Ảnh hưởng                                        |
| ------------------------ | ---------------- | ------------------------------------------------ |
| Đổi tên node asset       | `dam:Asset` name | Đổi URL/path; mọi reference theo path có thể gãy |
| Đổi `dc:title`           | metadata         | Chỉ đổi hiển thị; path giữ nguyên                |
| Đổi `dc:description`     | metadata         | Chỉ đổi mô tả                                    |
| Đổi `cq:tags`            | metadata         | Đổi phân loại; phải là `String[]`                |
| Đổi `jcr:lastModified`   | metadata/node    | Không nên set tay; AEM tự cập nhật               |
| Đổi `dam:sha1`           | metadata         | Không nên set tay; AEM tính lại                  |
| Đổi `jcr:uuid`           | node             | Tuyệt đối không                                  |
| Đổi `jcr:primaryType`    | node             | Tuyệt đối không trong batch                      |
| Đổi `sling:resourceType` | component node   | Có thể làm page không render được                |
| Đổi `cq:template`        | page             | Có thể làm page mất cấu trúc                     |

### 2.3. Property type và multi-value

Trước khi update, kiểm tra type:

```groovy
def prop = node.getProperty("cq:tags")
println prop.isMultiple()          // true
println prop.values*.string        // đọc multi-value
```

Ghi multi-value:

```groovy
node.setProperty("cq:tags", ["myproject:hero", "myproject:image"] as String[])
```

Ghi số/ngày:

```groovy
node.setProperty("myNumber", 42L)
node.setProperty("myDate", java.util.Calendar.instance)
```

Xoá property:

```groovy
if (node.hasProperty("obsolete")) {
    node.getProperty("obsolete").remove()
}
```

### 2.4. Nên và không nên batch

| Nên batch                      | Cần cực kỳ cẩn thận      | Không nên batch      |
| ------------------------------ | ------------------------ | -------------------- |
| `dc:title`, `dc:description`   | Đổi tên asset/page       | `/libs`, `/apps`     |
| `cq:tags`                      | Đổi `sling:resourceType` | `/home` (user/group) |
| Custom property trên component | Đổi `cq:template`        | `/oak:index`         |
| Alt text / text phụ            | Đổi `jcr:primaryType`    | `rep:policy` / ACL   |
| Metadata theo folder           | Đổi binary/rendition     | `jcr:system`         |
| Chuẩn hoá tên asset            | Xoá asset                | `jcr:uuid`           |

***

## 3. Chiến lược search node cần sửa

### 3.1. Viết rule kiểm tra format

Không nên tìm theo cảm tính. Với image asset, có thể bắt đầu bằng các rule sau:

```text
- Chỉ dùng: a-z, 0-9, dấu gạch ngang, một dấu chấm trước extension
- Không dùng: khoảng trắng, chữ hoa, dấu tiếng Việt, ngoặc, %, #, ?, &, dấu nháy
- Không bắt đầu/kết thúc bằng "-" hoặc "."
- Không có "--"
- Extension thuộc whitelist: jpg, jpeg, png, gif, webp, svg, tif, tiff
- Extension phải khớp MIME (image/jpeg -> jpg/jpeg, image/png -> png, ...)
- Tên sau chuẩn hoá không trùng trong cùng folder (so sánh case-insensitive)
- Độ dài <= 80 ký tự (đây là convention, không phải giới hạn cứng của JCR)
```

Regex tham khảo cho tên đã chuẩn hoá:

```groovy
def clean = name ==~ /^[a-z0-9]+(?:-[a-z0-9]+)*\.[a-z0-9]+$/
```

Bảng reason code dùng trong plan:

| Reason                    | Nghĩa                                          |
| ------------------------- | ---------------------------------------------- |
| `whitespace`              | có khoảng trắng                                |
| `uppercase`               | có chữ hoa                                     |
| `non-ascii`               | có ký tự ngoài ASCII (tiếng Việt, CJK, emoji…) |
| `invalid-char`            | có ký tự ngoài `[A-Za-z0-9._-]`                |
| `edge-space`              | space ở đầu/cuối                               |
| `edge-dot`                | bắt đầu/kết thúc bằng dấu chấm                 |
| `edge-hyphen`             | bắt đầu/kết thúc bằng gạch ngang               |
| `double-dot`              | có `..`                                        |
| `extension-case`          | extension viết hoa (`.PNG`)                    |
| `extension-not-allowed`   | extension ngoài whitelist                      |
| `extension-mime-mismatch` | extension không khớp `dc:format`               |
| `looks-url-encoded`       | tên chứa `%20`, `%28`…                         |
| `name-too-long`           | vượt convention                                |
| `duplicate-proposed`      | nhiều asset cùng cho ra một tên mới            |
| `target-exists`           | tên mới đã tồn tại trong folder                |
| `zero-bytes`              | `dam:size = 0`                                 |
| `missing-original`        | không có rendition `original`                  |

### 3.2. Query rộng theo path + node type, filter bằng Groovy

JCR-SQL2/Oak **không** hỗ trợ regex, tìm không phân biệt hoa thường hoặc normalize Unicode. Cách làm phù hợp là:

```text
Query rộng: đúng scope + đúng node type + có limit
Filter hẹp: regex, Unicode, MIME, collision, reference... bằng Groovy
```

Query nền:

```groovy
def scope = "/content/dam/myproject"
def sql = "SELECT * FROM [dam:Asset] AS a WHERE ISDESCENDANTNODE(a, '" +
    scope.replace("'", "''") + "')"

def q = session.workspace.queryManager.createQuery(sql, "JCR-SQL2")
q.limit = 500
def result = q.execute()

println "count=" + result.rows.size()
result.nodes.each { node ->
    println node.path
}
```

Không nên query toàn bộ `/content/dam` vì:

- Dễ traversal, chậm, tốn memory.
- Kéo theo asset ngoài scope, subasset, file không liên quan.
- Không kiểm soát được số lượng.

Với subasset (PDF page, layer của file AI…), lọc thêm:

```groovy
def asset = resourceResolver.getResource(node.path)?.adaptTo(com.day.cq.dam.api.Asset)
if (asset?.subAsset) return
```

### 3.3. Query theo property — chỉ khi biết index

Chỉ query theo property khi property đã có index hoặc scope đủ nhỏ. Ví dụ tìm image PNG:

```groovy
def q = createQuery([
    path        : "/content/dam/myproject",
    type        : "dam:Asset",
    property    : "jcr:content/metadata/dc:format",
    "property.value": "image/png",
    "p.limit"   : 500
])

def result = q.result
println "hits=" + result.hits.size()
result.hits.each { println it.resource.path }
```

Trước khi dùng, mở QueryBuilder Debug:

```text
http://localhost:4502/libs/cq/search/content/querydebug.html
```

Kiểm tra:

- Query có dùng index không, hay đang traversal.
- Số node bị scan có vượt ngưỡng không.
- Có cần thêm custom Oak index không.

Quy tắc:

- `property = value` hoặc `LIKE 'prefix%'`: có thể dùng index nếu index tồn tại.
- `LIKE '%substring%'`: gần như chắc chắn traversal; tránh trên cây lớn.
- Kết hợp `path` + `type` + `property` để giảm scan.
- Luôn set `p.limit` hoặc `q.limit`.

### 3.4. Query theo tên node

QueryBuilder có predicate `nodename` cho wildcard đơn giản, nhưng không thay thế regex:

```groovy
def q = createQuery([
    path    : "/content/dam/myproject",
    type    : "dam:Asset",
    nodename: "*Ảnh*",
    "p.limit": 200
])
```

Với rule phức tạp (Unicode, khoảng trắng, chữ hoa, extension, collision), query rộng rồi filter bằng Groovy; JCR-SQL2 không phải nơi để xử lý regex.

### 3.5. Search reference trước khi đổi tên asset

Đổi tên asset cần kiểm tra reference trước. Những nơi thường chứa reference gồm:

Các nơi thường chứa reference:

| Nơi chứa                    | Property / cách tìm                                                            | Ghi chú                              |
| --------------------------- | ------------------------------------------------------------------------------ | ------------------------------------ |
| Image, Download, PDF Viewer | `fileReference`                                                                | Dạng phổ biến nhất                   |
| Teaser / CTA / link         | `linkURL`, `ctaLink`, `pageLink`, `href`                                       | Có thể trỏ page hoặc asset           |
| Rich text (RTE)             | `text` (HTML)                                                                  | Đường dẫn nằm trong chuỗi HTML       |
| Content Fragment            | `fileReference`, `assetPath`, `path` trong `jcr:content/data/...`              | Tùy model                            |
| Experience Fragment         | `sling:resource`, property của component                                       | Kiểm tra từng loại                   |
| Asset metadata              | `dam:references`, `dam:originalPath`, `dam:resolvedPath`, XMP `stRef:filePath` | AEM quản lý một phần                 |
| Dynamic Media               | `dam:scene7File`, `dam:scene7Publish`                                          | Kiểm tra riêng                       |
| Trang / navigation          | `cq:redirectTarget`, link properties                                           | Không phải asset reference trực tiếp |

Query exact cho `fileReference`:

```groovy
def target = "/content/dam/myproject/hero/Ảnh Bìa (1).PNG"
def escaped = target.replace("'", "''")
def sql = """
SELECT * FROM [nt:base] AS r
WHERE ISDESCENDANTNODE(r, '/content')
  AND r.[fileReference] = '$escaped'
"""

def q = session.workspace.queryManager.createQuery(sql, "JCR-SQL2")
q.limit = 1000
println "refs=" + q.execute().rows.size()
```

Query prefix cho cả folder:

```groovy
def sql = """
SELECT * FROM [nt:base] AS r
WHERE ISDESCENDANTNODE(r, '/content')
  AND r.[fileReference] LIKE '/content/dam/myproject/%'
"""
```

Lưu ý:

- Prefix `LIKE` vẫn có thể traversal nếu `fileReference` không có index; kiểm tra query plan.
- Leading wildcard `LIKE '%...%'` càng chậm; chỉ dùng trên scope nhỏ.
- `[fileReference]` có thể là `String` hoặc `String[]`; xử lý cả hai.
- Asset name có dấu nháy `'` phải escape khi build JCR-SQL2.

#### AEM có tự update reference khi move asset không?

Trong AEM 6.5.24, job `com/adobe/cq/dam/assetmove` (`AssetMoveEventHandler`) có xử lý một số reference:

- `sling:resource`
- `dam:originalPath`
- `dam:resolvedPath`
- XMP `stRef:filePath`

Nó **không** query và cũng **không** sửa `fileReference`. Đã test thực tế:

```text
1. Tạo node ref-a với fileReference = /content/dam/.../ui-moved.png
2. session.move(asset) sang /content/dam/.../hero-image.png + save()
3. ref-a vẫn giữ fileReference = /content/dam/.../ui-moved.png
4. Phải chạy script riêng set lại fileReference = /content/dam/.../hero-image.png
```

Do đó:

- Không được tin rằng “move asset là AEM tự sửa hết link”.
- Phải scan và update `fileReference` (và các property khác) trước/sau khi move.
- Với RTE HTML, Content Fragment, external link… phải xử lý riêng.

#### API reference của AEM có đủ không?

Có các API:

```text
com.day.cq.dam.api.AssetReferenceResolver#getReferences
com.day.cq.dam.api.AssetReferenceHandler#lookupReferences
```

Nhưng trong test, cả hai trả về rỗng dù có một node `fileReference` trỏ tới asset. Chúng chỉ phản ánh reference do AEM quản lý, không thay thế scan nội dung. Dùng chúng như nguồn phụ, đừng dùng làm nguồn duy nhất.

### 3.6. Direct traversal cho folder nhỏ

Với folder ít asset, có thể duyệt trực tiếp thay vì query:

```groovy
def root = resourceResolver.getResource("/content/dam/myproject/hero")
def maxDepth = 3

def walk
walk = { res, depth ->
    if (res == null || depth > maxDepth) return
    def asset = res.adaptTo(com.day.cq.dam.api.Asset)
    if (asset != null && !asset.subAsset) {
        println "${asset.path} | ${asset.name}"
    }
    res.listChildren().each { child -> walk(child, depth + 1) }
}

walk(root, 0)
```

Ưu điểm là code đơn giản và dễ giới hạn depth. Đổi lại, cách này không tận dụng property/index và có thể bỏ sót khi folder lớn. Với cây lớn, nên dùng query.

### 3.7. Paging, sample và snapshot

- Luôn set `q.limit`; không dựa vào default.
- Nếu cần paging, dùng `q.offset`; nhưng **không vừa paging vừa mutate** cùng một query. Kết quả sẽ thay đổi khi node bị move/rename.
- Nên chạy audit một lần, lưu toàn bộ plan vào list/JSON; apply đọc plan thay vì query lại trong lúc move.
- Với dry run, lấy sample trước (ví dụ 20 dòng) để review nhanh; vẫn giữ full plan để apply.
- Sort plan theo path để kết quả ổn định và dễ so sánh giữa các lần chạy.

### 3.8. Chuẩn hoá tên

Một hàm slugify đã test:

```groovy
import java.text.Normalizer
import java.util.Locale

def slugify = { String value ->
    def s = Normalizer.normalize(value, Normalizer.Form.NFD)
        .replaceAll('\\p{M}+', '')
    s = s.replace('đ', 'd').replace('Đ', 'D')
    s = s.toLowerCase(Locale.ROOT)
    s = s.replaceAll('[^a-z0-9]+', '-')
    s = s.replaceAll('-{2,}', '-')
    s = s.replaceAll('^-+|-+$', '')
    s ?: 'asset'
}
```

Ví dụ:

```text
Ảnh Bìa (1).PNG  -> anh-bia-1.png
Hero_Image 02.JPG -> hero-image-02.jpg
```

Lưu ý:

- `đ` -> `d` là quy ước tiếng Việt; với ngôn ngữ khác, cân nhắc transliteration thủ công.
- Nếu tên chỉ có ký tự CJK/emoji, slugify có thể ra `asset`; khi đó cần bảng mapping thủ công, không để thuật toán tự đoán.
- Giữ extension gốc (lowercase) và validate với MIME; không tự đổi `.png` thành `.jpg`.
- Nếu tên mới quá dài, cắt base nhưng giữ extension.
- Nếu trùng, thêm `-2`, `-3` deterministic; không dùng random.

***

## 4. Dry run trước khi ghi

### 4.1. Dry run đúng nghĩa

Dry run không chỉ là chạy thử rồi bỏ qua `save()`. Trong dry run, script phải:

- Không `setProperty`.
- Không `removeItem`.
- Không `session.move`.
- Không `rename` / `move` DSL.
- Không `save()` / `commit()`.
- Chỉ đọc, tính toán, in plan.

`setProperty` tạo transient change nên phần code chạy sau đó vẫn có thể đọc thấy dữ liệu đã đổi. Nếu gọi `save()` ở cuối, dry run sẽ ghi dữ liệu thật; `rename` và `move` DSL còn tự save ngay.

Kết thúc dry run, kiểm tra:

```groovy
if (session.hasPendingChanges()) {
    session.refresh(false)   // bỏ mọi transient change
    throw new IllegalStateException("Dry run left pending changes")
}
```

### 4.2. Plan format

Plan dùng dạng JSON array. Mỗi item tối thiểu gồm:

```json
[
  {
    "path": "/content/dam/myproject/hero/Ảnh Bìa (1).PNG",
    "proposed": "/content/dam/myproject/hero/anh-bia-1.png",
    "uuid": "f30f20a6-4734-423c-868b-c95dacd1f4de",
    "reasons": ["whitespace", "uppercase", "non-ascii", "invalid-char"],
    "refs": 3
  }
]
```

Nên có thêm:

- `mime`, `size`, `lastModified`, `sha1` để đối chiếu.
- `action`: `rename`, `update-metadata`, `skip`.
- `batchId` / `note` để truy vết.

Cách đưa plan sang bước apply:

1. Chạy script audit.
2. Copy JSON từ output (hoặc file CSV/JSON đã lưu).
3. Mở panel **Data** trong Groovy Console, paste JSON.
4. Chạy script apply; biến `data` sẽ là `List`/`Map`.

Với plan rất lớn, không nên paste vào Data panel (giới hạn request). Chia thành nhiều batch nhỏ, hoặc lưu plan thành `nt:file` dưới `/var` và đọc bằng `session`.

### 4.3. Precondition cho từng item

Trước mỗi lần move hoặc update, kiểm tra:

| Điều kiện                                | Lý do                           |
| ---------------------------------------- | ------------------------------- |
| `session.nodeExists(src)`                | asset còn tồn tại               |
| `!session.nodeExists(dst)`               | tránh ghi đè                    |
| `src.startsWith(SCOPE)`                  | chặn path ngoài phạm vi         |
| `srcNode.isNodeType("dam:Asset")`        | tránh sửa nhầm node             |
| `!asset.subAsset`                        | tránh subasset                  |
| `jcr:uuid` khớp plan (nếu có)            | đảm bảo đúng asset              |
| `jcr:lastModified` không đổi (nếu có)    | tránh ghi đè thay đổi đồng thời |
| `jcr:content/dam:assetState = processed` | asset đã xử lý xong             |
| có rendition `original`                  | asset không hỏng                |
| parent của `dst` tồn tại                 | tránh move vào folder không có  |
| `MAX_CHANGES`                            | chặn batch quá lớn              |

Nếu một điều kiện không đạt:

- Với rename: skip item đó, ghi reason, không move.
- Với property: skip item đó, không set.
- Nếu fail hàng loạt: dừng batch, không cố “chạy cho hết”.

### 4.4. Report cần có gì?

Report dry run nên cho biết:

- Tổng số asset đã scan.
- Bao nhiêu asset bị flag.
- Bao nhiêu sẽ đổi tên.
- Bao nhiêu collision (trùng tên mới, target đã tồn tại).
- Bao nhiêu asset có reference.
- Top folder bị ảnh hưởng.
- Danh sách sample `old -> new`.
- Cảnh báo: asset không có original, size 0, MIME mismatch.
- Thời gian chạy và `pendingChanges`.

Ví dụ output CSV:

```text
scope=/content/dam/myproject scanned=3 flagged=2 truncated=false elapsedMs=709
path,name,proposed,reasons,mime,size,fileReferenceCount
"/content/dam/myproject/hero/Ảnh Bìa (1).PNG","Ảnh Bìa (1).PNG","anh-bia-1.png","whitespace|uppercase|non-ascii|invalid-char","image/png","68","0"
"/content/dam/myproject/hero/Ảnh  Bìa (1).PNG","Ảnh  Bìa (1).PNG","anh-bia-1.png","whitespace|uppercase|non-ascii|invalid-char|duplicate-proposed","image/png","68","0"
pendingChanges=false
```

### 4.5. Review với người sở hữu nội dung

Dry run cũng là dữ liệu để content owner review:

- Tên mới có đúng nghĩa không? `anh-bia-1` có thể mất ngữ nghĩa so với `Ảnh Bìa (1)`.
- Có asset nào là logo, campaign, QR code, external link không?
- Có asset đang dùng trong Content Fragment, Experience Fragment, translation, MSM không?
- Có asset thuộc Dynamic Media / Brand Portal / Desktop sync không?
- Có tên nào trùng với asset sẽ upload sau này không?

Plan nên được xác nhận trong ticket, comment hoặc email trước khi apply.

***

## 5. Apply — code và kiểm soát

### 5.1. Rename asset: nguyên tắc

- Dùng `session.move(src, dst)` + `save()`; không dùng `rename` DSL cho batch.
- `session.move` giữ `jcr:uuid`; `copy` + `remove` tạo UUID mới, mất identity/reference theo UUID.
- Không move asset sang folder khác nếu không có kế hoạch reference/redirect.
- Không đổi extension nếu không thực sự convert format.
- Update `fileReference` (và các reference khác) **trong cùng transaction** với move, trước `save()`, để tránh trạng thái nửa vời.
- Nếu `save()` fail, gọi `session.refresh(false)` để bỏ pending changes; các batch trước đã commit vẫn còn.

### 5.2. Update property: nguyên tắc

- Dùng `ModifiableValueMap` nếu đi qua `ResourceResolver`; dùng `Node.setProperty` nếu đi qua `Session`. Không trộn lẫn một cách khó hiểu.
- `resourceResolver.commit()` cho thay đổi Sling; `save()` cho thay đổi JCR.
- Kiểm tra `mvm == null` (thường do thiếu quyền ghi).
- Với `cq:tags`, dùng `String[]`.
- Với date, dùng `Calendar`, không dùng `String`.
- Với property cần xoá, dùng `.remove()`; không set `null` nếu chưa kiểm tra type.
- Không set `jcr:lastModified`, `jcr:lastModifiedBy`, `dam:sha1` bằng tay.

### 5.3. Batch size và transaction

JCR không có transaction bao phủ nhiều lần `save()`; mỗi lần `save()` là một commit:

| Cách                 | Ưu điểm                          | Nhược điểm                                      |
| -------------------- | -------------------------------- | ----------------------------------------------- |
| Save từng item       | batch nhỏ, dễ biết item nào xong | nhiều commit, chậm, rollback phức tạp           |
| Save mỗi 25–100 item | cân bằng tốc độ và rủi ro        | nếu lỗi, mất cả batch chưa save                 |
| Save tất cả          | nhanh                            | transaction lớn, dễ timeout/OOM, lỗi là mất hết |

Với rename hoặc update property, nên:

- Batch 25–100 item cho rename/property.
- Ghi mapping `old -> new` ngay sau mỗi batch.
- Nếu một item fail, dừng batch, không “cố cho hết”.
- Không chạy song song nhiều script ghi trên cùng cây.

### 5.4. Verify sau apply

Verify tối thiểu:

```text
1. Path cũ không còn (404)
2. Path mới tồn tại (200)
3. jcr:uuid giữ nguyên
4. fileReference cũ = 0
5. fileReference mới > 0 (nếu có reference)
6. metadata/rendition còn nguyên
7. jcr:content/dam:assetState = processed
8. Không có exception trong error.log
```

Lưu ý: query có thể trả kết quả cũ do index async. Kiểm tra trực tiếp bằng `session.nodeExists()` trước, rồi mới tin query.

***

## 6. Rủi ro — danh sách đầy đủ

### 6.1. Rủi ro dữ liệu

- **Tên JCR không hợp lệ:** `/`, `:`, `[`, `]`, `|`, `*` không được dùng trong tên; `.`/`..` bị cấm. Đã test: `rename node to "bad/name"` bị hiểu là path và ném `PathNotFoundException`; `%` được phép nhưng URL sẽ encode.
- **Khoảng trắng/chữ hoa/Unicode:** JCR cho phép, nhưng URL, CDN, SEO, sync tool có thể xử lý khác nhau.
- **Case-insensitive collision:** JCR phân biệt hoa/thường, nhưng Windows/macOS và một số CDN không. `Hero.png` và `hero.png` có thể va nhau khi sync.
- **Tên quá dài:** convention 80 ký tự; JCR có giới hạn riêng, nhưng UI/tool có thể cắt.
- **Trùng tên sau chuẩn hoá:** nhiều tên khác nhau có thể cho ra cùng slug; phải detect trước khi apply.
- **Ghi đè target:** `session.move` vào path đã tồn tại sẽ lỗi; nếu dùng `copy` có thể ghi đè/sinh UUID mới.
- **Mất UUID/identity:** `copy` + `remove` tạo asset mới; reference theo UUID, version/revision có thể mất.
- **Sai type:** set `String` cho `Long`, `String` cho `Calendar`, scalar cho multi-value → `ValueFormatException` hoặc dữ liệu sai.
- **Multi-value:** gọi `.string` trên `jcr:mixinTypes`/`cq:tags` ném lỗi; phải dùng `.values`.
- **`dam:sha1` không ổn định:** có thể đổi khi metadata/asset được xử lý lại; không dùng làm khóa duy nhất.
- **`dam:assetState`:** asset đang `processing`/`unprocessed`; đợi xử lý xong mới audit.
- **Rendition:** không rename `original`, `cq5dam.thumbnail.*`, `cq5dam.web.*`; chỉ rename node `dam:Asset`.
- **Binary:** không sửa `jcr:data` nếu không thật sự convert; có thể làm hỏng asset.
- **Metadata extraction async:** `dam:extracted`/dimensions có thể chưa có ngay sau upload; chờ workflow chạy xong.

### 6.2. Rủi ro reference / hiển thị

- **`fileReference` không tự update:** đã test; move asset xong ref cũ vẫn còn. Ảnh trên page sẽ 404.
- **RTE HTML:** đường dẫn nằm trong `text`; không có property chuẩn để query exact. Phải scan chuỗi, kể cả URL-encoded (`%20`, `%28`).
- **Content Fragment / Experience Fragment:** reference nằm trong JSON/property tùy model; query chung dễ bỏ sót.
- **Translation / MSM / live copy:** language copy hoặc live copy có thể giữ path cũ; rollout có thể ghi đè.
- **Dynamic Media / Scene7:** `dam:scene7File`, `dam:scene7Publish`; rename có thể làm mất liên kết với hệ thống ngoài.
- **Brand Portal / Asset Link / Desktop sync / Creative Cloud:** path/name thay đổi có thể làm sync sai hoặc mất link.
- **External link / QR code / email campaign:** URL cũ nằm ngoài AEM, không thể scan.
- **SEO / backlink / sitemap:** đổi URL làm mất backlink, giảm ranking; cần redirect nếu public.
- **CDN / Dispatcher cache:** URL cũ có thể còn cache; URL mới chưa được warm.
- **`sling:resource` / `dam:originalPath` / `dam:resolvedPath`:** AEM move handler có thể update một phần; không được coi là đủ.
- **`dam:references` / AssetReference API:** chỉ là nguồn phụ; test cho thấy có thể rỗng dù `fileReference` tồn tại.

### 6.3. Rủi ro replication / publish

- Rename trên Author **không** tự rename trên Publish.
- Phải deactivate path cũ và activate path mới; nếu không, Publish vẫn serve asset cũ.
- Reference trên Publish có thể vẫn trỏ path cũ; cần activate cả page chứa reference.
- Dispatcher/CDN cache có thể giữ URL cũ; cần flush/invalidate.
- Tree activation có thể kéo theo asset/page không mong muốn; kiểm tra filter.
- Replication queue có thể có item đang chờ; rename/delete có thể làm item fail.

### 6.4. Rủi ro bảo mật / audit

- Groovy Console chạy code tùy ý; ai có quyền vào console gần như có toàn quyền JVM.
- Không expose `/groovyconsole` hoặc `/bin/groovyconsole/post.json` qua Dispatcher/CDN.
- Script và output được lưu trong `/var/groovyconsole/audit`; không hardcode secret.
- Audit record có thể chứa token, password, internal URL; cần retention/chính sách xoá.
- Scheduled job dùng service user; kiểm tra mapping/ACL trước khi bật.
- JCR-SQL2 build bằng string concat có thể bị injection nếu path/value lấy từ input; escape `'` hoặc dùng QueryBuilder predicate.
- Metadata/alt text có thể chứa HTML/JS; đảm bảo output encoding khi render.
- `data` panel nhận JSON; không tin dữ liệu từ nguồn không kiểm soát.

### 6.5. Rủi ro vận hành

- Script chạy lâu chiếm request thread; console có `TimedInterrupt` nhưng timeout của HTTP/Dispatcher có thể ngắn hơn.
- Query lớn/traversal gây chậm toàn instance; luôn limit và scope.
- Load toàn bộ kết quả vào list có thể OOM; dùng iterator, limit, batch.
- `save()` lớn có thể gây commit chậm; chia nhỏ.
- Edit đồng thời: author khác sửa asset trong lúc script chạy; `jcr:lastModified`/UUID check giảm rủi ro nhưng không loại bỏ hoàn toàn.
- Workflow đang chạy trên asset có payload path cũ; rename có thể làm workflow fail.
- Index async: query trả kết quả cũ; verify bằng `nodeExists` trước.
- Partial failure: các batch trước đã commit; không có rollback tự động.
- `rename`/`move` DSL tự save: không dùng trong batch lớn.
- Encoding: script/output UTF-8; CSV mở bằng Excel có thể lỗi tiếng Việt nếu thiếu BOM.
- Groovy 2.4.15: không dùng cú pháp Groovy 3/4; test compile trước.

### 6.6. Rủi ro nghiệp vụ

- Tên mới mất ngữ nghĩa/SEO; cần người sở hữu nội dung duyệt.
- Asset dùng trong chiến dịch/QR/print; đổi URL làm hỏng kênh ngoài.
- Asset có license/nguồn gốc; rename không làm mất license nhưng có thể làm mất liên kết metadata.
- Localization: bỏ dấu tiếng Việt có thể đổi nghĩa; CJK/emoji có thể thành `asset`.
- Accessibility: alt text/description cần đúng ngôn ngữ, không chỉ copy hàng loạt.
- Legal/brand: không tự đổi tên logo, sản phẩm, trademark.

***

## 7. Rollback

### 7.1. Chuẩn bị trước khi apply

- Package nội dung liên quan:

```text
/content/dam/myproject
/content/myproject
```

- Export plan JSON/CSV và lưu ngoài instance.
- Ghi lại `jcr:uuid`, path cũ, path mới, `fileReference` count.
- Nếu asset quan trọng, tạo revision/version hoặc backup binary.
- Chạy thử toàn bộ quy trình trên bản sao/instance thấp hơn trước.

### 7.2. Inverse plan

Trong lúc apply, sinh mapping:

```text
newPath -> oldPath
```

Nếu fail:

1. Xác định các item đã `OK` (đã save).
2. Chạy inverse `session.move(newPath, oldPath)` cho từng item.
3. Set `fileReference` ngược lại.
4. Verify UUID/path/reference.
5. Nếu metadata đã đổi, restore từ package/revision.
6. Nếu đã activate, deactivate path mới và activate path cũ; flush cache.

### 7.3. Vì sao không dùng `rename` DSL cho batch?

`rename node to "new"` tự save ngay. Nếu item thứ 50 lỗi:

- 49 item trước đã commit.
- Không có transaction để rollback.
- Bạn phải dựa vào mapping/output để hoàn tác.

`session.move` + `save()` theo batch cho phép:

- Kiểm soát thời điểm commit.
- Gộp move + update reference trong cùng một commit.
- Biết chính xác batch nào đã ghi.

### 7.4. Rollback trên Publish

- Deactivate path mới.
- Activate path cũ.
- Activate lại page chứa reference.
- Flush Dispatcher/CDN.
- Kiểm tra replication queue và log.

***

## 8. Checklist trước khi apply

### Trước khi chạy

- [ ] Đã xác định đúng scope `/content/dam/<project>` và `/content/<site>`.
- [ ] Đã viết rule tên rõ ràng, có whitelist extension.
- [ ] Đã chạy audit, có plan JSON/CSV.
- [ ] Đã dry run, `pendingChanges=false`.
- [ ] Đã kiểm tra collision (case-insensitive) và target đã tồn tại.
- [ ] Đã scan `fileReference`, RTE, CF/EF, external link.
- [ ] Đã kiểm tra asset đang dùng Dynamic Media/MSM/translation.
- [ ] Đã package/backup nội dung.
- [ ] Đã test trên bản sao/instance thấp hơn.
- [ ] Đã có người review plan.
- [ ] Đã chọn `MAX_CHANGES` và batch size.
- [ ] Đã có mapping để rollback.

### Trong khi chạy

- [ ] `DRY_RUN = false` chỉ sau khi plan được duyệt.
- [ ] Không chạy song song với người đang sửa asset.
- [ ] Theo dõi `error.log` và output từng batch.
- [ ] Lưu mapping/output sau mỗi batch.
- [ ] Dừng ngay nếu có lỗi bất thường.

### Sau khi chạy

- [ ] Path cũ 404, path mới 200.
- [ ] UUID giữ nguyên.
- [ ] `fileReference` cũ = 0, mới > 0.
- [ ] Metadata/rendition còn nguyên.
- [ ] Không có exception trong log.
- [ ] Đã activate/deactivate và flush cache.
- [ ] Đã thông báo cho content owner/SEO/analytics.

***

## 9. Full scripts

> Đổi `SCOPE`, `RESOURCE_TYPE`, `PROPERTY` ở đầu mỗi script. Chạy audit/dry run trước; chỉ đổi `DRY_RUN = false` khi plan đã được duyệt.

### 9.1. Audit tên asset (read-only)

```groovy
import java.text.Normalizer
import java.util.Locale

def cfg = [
    scope          : "/content/dam/myproject",
    maxAssets      : 500,
    maxNameLength  : 80,
    scanReferences : true,
    allowedExt     : ["jpg", "jpeg", "png", "gif", "webp", "svg", "tif", "tiff"] as Set,
    mimeToExt      : [
        "image/jpeg"   : ["jpg", "jpeg"] as Set,
        "image/png"    : ["png"] as Set,
        "image/gif"    : ["gif"] as Set,
        "image/webp"   : ["webp"] as Set,
        "image/svg+xml": ["svg"] as Set,
        "image/tiff"   : ["tif", "tiff"] as Set
    ]
]

def splitExt = { String name ->
    int i = name.lastIndexOf('.')
    if (i > 0 && i < name.length() - 1) {
        return [base: name.substring(0, i), ext: name.substring(i + 1)]
    }
    return [base: name, ext: ""]
}

def slugify = { String value ->
    def s = Normalizer.normalize(value, Normalizer.Form.NFD).replaceAll('\\p{M}+', '')
    s = s.replace('đ', 'd').replace('Đ', 'D')
    s = s.toLowerCase(Locale.ROOT)
    s = s.replaceAll('[^a-z0-9]+', '-')
    s = s.replaceAll('-{2,}', '-')
    s = s.replaceAll('^-+|-+$', '')
    s ?: 'asset'
}

def csv = { value ->
    '"' + (value == null ? '' : value.toString()).replace('"', '""') + '"'
}

def countFileReferences = { String path ->
    if (!cfg.scanReferences) return -1
    def escaped = path.replace("'", "''")
    def sql = "SELECT * FROM [nt:base] AS r " +
        "WHERE ISDESCENDANTNODE(r, '/content') AND r.[fileReference] = '$escaped'"
    def q = session.workspace.queryManager.createQuery(sql, "JCR-SQL2")
    q.limit = 1000
    return q.execute().rows.size()
}

def started = System.currentTimeMillis()
def sql = "SELECT * FROM [dam:Asset] AS a WHERE ISDESCENDANTNODE(a, '" +
    cfg.scope.replace("'", "''") + "')"
def q = session.workspace.queryManager.createQuery(sql, "JCR-SQL2")
q.limit = cfg.maxAssets
def result = q.execute()

def seenProposed = [:]
def rows = []
def scanned = 0
def truncated = false

result.nodes.each { node ->
    if (rows.size() >= cfg.maxAssets) {
        truncated = true
        return
    }

    def asset = resourceResolver.getResource(node.path)?.adaptTo(com.day.cq.dam.api.Asset)
    if (asset?.subAsset) return

    scanned++
    def name = node.name
    def parentPath = node.parent.path
    def parts = splitExt(name)
    def ext = parts.ext.toLowerCase(Locale.ROOT)
    def base = slugify(parts.base)
    def room = cfg.maxNameLength - (ext ? ext.length() + 1 : 0)
    if (base.length() > room) {
        base = base.substring(0, room).replaceAll('-+$', '')
    }
    def proposed = base + (ext ? '.' + ext : '')
    def reasons = []

    if (name != name.trim()) reasons << 'edge-space'
    if (name =~ /\s/) reasons << 'whitespace'
    if (name =~ /[A-Z]/) reasons << 'uppercase'
    if (name =~ /[^\x00-\x7F]/) reasons << 'non-ascii'
    if (name =~ /[^A-Za-z0-9._-]/) reasons << 'invalid-char'
    if (name.contains('..')) reasons << 'double-dot'
    if (name.startsWith('.') || name.endsWith('.')) reasons << 'edge-dot'
    if (name.startsWith('-') || name.endsWith('-')) reasons << 'edge-hyphen'
    if (parts.ext && parts.ext != ext) reasons << 'extension-case'
    if (parts.ext && !cfg.allowedExt.contains(ext)) reasons << 'extension-not-allowed'
    if (name.length() > cfg.maxNameLength) reasons << 'name-too-long'
    if (name =~ /%[0-9A-Fa-f]{2}/) reasons << 'looks-url-encoded'

    def meta = node.hasNode('jcr:content/metadata')
        ? node.getNode('jcr:content/metadata') : null
    def mime = meta?.hasProperty('dc:format')
        ? meta.getProperty('dc:format').string : null
    def size = meta?.hasProperty('dam:size')
        ? meta.getProperty('dam:size').long : -1L
    def hasOriginal = node.hasNode('jcr:content/renditions/original')

    if (mime && cfg.mimeToExt.containsKey(mime) && ext &&
        !cfg.mimeToExt[mime].contains(ext)) {
        reasons << 'extension-mime-mismatch'
    }
    if (size == 0L) reasons << 'zero-bytes'
    if (!hasOriginal) reasons << 'missing-original'

    def key = parentPath + '/' + proposed.toLowerCase(Locale.ROOT)
    if (seenProposed.containsKey(key) && seenProposed[key] != node.path) {
        reasons << 'duplicate-proposed'
    }
    seenProposed[key] = node.path

    if (proposed != name && session.nodeExists(parentPath + '/' + proposed)) {
        reasons << 'target-exists'
    }

    if (reasons) {
        def refs = countFileReferences(node.path)
        rows << [
            path    : node.path,
            name    : name,
            proposed: proposed,
            reasons : reasons.unique().join('|'),
            mime    : mime ?: '',
            size    : size,
            refs    : refs
        ]
    }
}

def elapsed = System.currentTimeMillis() - started
println "=== ASSET NAME AUDIT (READ ONLY) ==="
println "scope=${cfg.scope} scanned=${scanned} flagged=${rows.size()} " +
    "truncated=${truncated} elapsedMs=${elapsed}"
println "path,name,proposed,reasons,mime,size,fileReferenceCount"
rows.each { r ->
    println([r.path, r.name, r.proposed, r.reasons, r.mime, r.size, r.refs]
        .collect(csv).join(','))
}

if (session.hasPendingChanges()) {
    session.refresh(false)
    throw new IllegalStateException("Dry run left pending changes")
}
println "pendingChanges=${session.hasPendingChanges()}"
return "flagged=${rows.size()}"
```

### 9.2. Apply rename theo plan JSON

```groovy
import groovy.json.JsonSlurper

// Đổi thành false CHỈ sau khi plan đã được review.
def DRY_RUN = true
def MAX_CHANGES = 50
def SCOPE = "/content/dam/myproject/"
def BATCH_ID = new Date().format("yyyyMMdd-HHmmss")

if (data == null) {
    throw new IllegalArgumentException("Data panel is empty: paste the JSON plan")
}
def plan = data instanceof List
    ? data
    : new JsonSlurper().parseText(data.toString())
if (!(plan instanceof List) || plan.isEmpty()) {
    throw new IllegalArgumentException("Plan must be a non-empty JSON array")
}

def rows = []
def changed = 0

plan.each { item ->
    if (changed >= MAX_CHANGES) return

    def src = item.path?.toString()
    def dst = item.proposed?.toString()
    if (!src || !dst) {
        rows << [status: "SKIP", src: src, dst: dst, detail: "missing-path"]
        return
    }
    if (!src.startsWith(SCOPE) || !dst.startsWith(SCOPE)) {
        throw new IllegalArgumentException("Outside allowed scope: $src -> $dst")
    }
    if (!session.nodeExists(src)) {
        rows << [status: "SKIP", src: src, dst: dst, detail: "source-missing"]
        return
    }
    if (session.nodeExists(dst)) {
        rows << [status: "SKIP", src: src, dst: dst, detail: "target-exists"]
        return
    }

    def srcNode = session.getNode(src)
    if (!srcNode.isNodeType("dam:Asset")) {
        rows << [status: "SKIP", src: src, dst: dst, detail: "not-dam-asset"]
        return
    }
    def asset = resourceResolver.getResource(src)?.adaptTo(com.day.cq.dam.api.Asset)
    if (asset?.subAsset) {
        rows << [status: "SKIP", src: src, dst: dst, detail: "sub-asset"]
        return
    }

    def parentPath = dst.substring(0, dst.lastIndexOf('/'))
    if (!session.nodeExists(parentPath)) {
        rows << [status: "SKIP", src: src, dst: dst, detail: "target-parent-missing"]
        return
    }

    def uuid = srcNode.hasProperty("jcr:uuid")
        ? srcNode.getProperty("jcr:uuid").string : ""
    def meta = srcNode.hasNode("jcr:content/metadata")
        ? srcNode.getNode("jcr:content/metadata") : null
    def sha1 = meta?.hasProperty("dam:sha1")
        ? meta.getProperty("dam:sha1").string : ""

    if (DRY_RUN) {
        rows << [status: "DRY", src: src, dst: dst,
                 detail: "uuid=$uuid sha1=$sha1"]
        return
    }

    try {
        session.move(src, dst)

        def escaped = src.replace("'", "''")
        def sql = "SELECT * FROM [nt:base] AS r " +
            "WHERE ISDESCENDANTNODE(r, '/content') " +
            "AND r.[fileReference] = '$escaped'"
        def q = session.workspace.queryManager.createQuery(sql, "JCR-SQL2")
        q.limit = 1000
        def refs = []
        q.execute().nodes.each { refNode ->
            refNode.setProperty("fileReference", dst)
            refs << refNode.path
        }

        save()
        changed++
        rows << [status: "OK", src: src, dst: dst,
                 detail: "uuid=$uuid refs=${refs.size()}"]
    } catch (Throwable t) {
        session.refresh(false)
        rows << [status: "FAIL", src: src, dst: dst, detail: t.message]
        throw t
    }
}

println "=== APPLY RENAME ==="
println "batch=$BATCH_ID dryRun=$DRY_RUN changed=$changed " +
    "skipped=${rows.findAll { it.status == 'SKIP' }.size()} " +
    "pending=${session.hasPendingChanges()}"
rows.each { r ->
    println([r.status, r.src, r.dst, r.detail].join("\t"))
}
return "changed=$changed"
```

### 9.3. Batch update property

```groovy
def DRY_RUN = true
def SCOPE = "/content/myproject"
def RESOURCE_TYPE = "myproject/components/image"
def PROPERTY = "altText"
def NEW_VALUE = "Mô tả ảnh đã chuẩn hoá"

def escapedScope = SCOPE.replace("'", "''")
def escapedType = RESOURCE_TYPE.replace("'", "''")
def sql = "SELECT * FROM [nt:base] AS n " +
    "WHERE ISDESCENDANTNODE(n, '$escapedScope') " +
    "AND n.[sling:resourceType] = '$escapedType'"

def q = session.workspace.queryManager.createQuery(sql, "JCR-SQL2")
q.limit = 500
def nodes = []
q.execute().nodes.each { nodes << it }

println "=== BATCH PROPERTY ${DRY_RUN ? 'DRY RUN' : 'APPLY'} ==="
println "scope=$SCOPE type=$RESOURCE_TYPE property=$PROPERTY candidates=${nodes.size()}"

def changed = 0
nodes.each { n ->
    def before = n.hasProperty(PROPERTY)
        ? n.getProperty(PROPERTY).string : ""
    println "${n.path}\tbefore='${before}'\tafter='${NEW_VALUE}'"
    if (!DRY_RUN) {
        n.setProperty(PROPERTY, NEW_VALUE)
        changed++
    }
}

if (!DRY_RUN) save()
println "changed=$changed pending=${session.hasPendingChanges()}"
return "candidates=${nodes.size()} changed=$changed"
```

> Nếu property là multi-value, thay `NEW_VALUE` bằng `["tag-a", "tag-b"] as String[]`. Nếu property cần xoá, dùng `n.getProperty(PROPERTY).remove()` thay vì `setProperty`.

### 9.4. Verify theo plan

```groovy
import groovy.json.JsonSlurper

def plan = data instanceof List
    ? data
    : new JsonSlurper().parseText(data.toString())
def rows = []

plan.each { item ->
    def src = item.path
    def dst = item.proposed
    def expectedUuid = item.uuid
    def srcExists = session.nodeExists(src)
    def dstExists = session.nodeExists(dst)
    def dstUuid = dstExists && session.getNode(dst).hasProperty("jcr:uuid")
        ? session.getNode(dst).getProperty("jcr:uuid").string : ""

    def status = (!srcExists && dstExists) ? "OK" : "FAIL"
    if (expectedUuid && dstUuid && expectedUuid != dstUuid) {
        status = "FAIL"
    }

    def escapedSrc = src.replace("'", "''")
    def refSql = "SELECT * FROM [nt:base] AS r " +
        "WHERE ISDESCENDANTNODE(r, '/content') " +
        "AND r.[fileReference] = '$escapedSrc'"
    def rq = session.workspace.queryManager.createQuery(refSql, "JCR-SQL2")
    rq.limit = 100
    def oldRefs = rq.execute().rows.size()

    rows << [status: status, src: src, dst: dst,
             srcExists: srcExists, dstExists: dstExists,
             oldRefs: oldRefs, uuid: dstUuid]
}

println "=== VERIFY RENAME ==="
rows.each { r ->
    println "${r.status}\t${r.src}\t->\t${r.dst}" +
        "\tsrcExists=${r.srcExists}\tdstExists=${r.dstExists}" +
        "\toldRefs=${r.oldRefs}\tuuid=${r.uuid}"
}
return "failures=${rows.findAll { it.status == 'FAIL' }.size()}"
```

***

## 10. Gọi console từ curl (tùy chọn)

Khi cần chạy audit tự động từ máy local, có thể POST trực tiếp. UI dùng endpoint:

```text
POST /bin/groovyconsole/post.json
```

Ví dụ:

```powershell
curl.exe -sS -u admin:admin `
  --data-urlencode "script@C:\scripts\audit-assets.groovy" `
  --data-urlencode "data=" `
  http://localhost:4502/bin/groovyconsole/post.json
```

Response JSON có:

```text
output               output của println
result               giá trị return
exceptionStackTrace  stack trace nếu lỗi
runningTime          thời gian chạy
```

Lưu ý:

- Chỉ dùng trên máy local/instance được kiểm soát; không expose endpoint.
- Không đưa credential vào script; dùng basic auth/secret bên ngoài.
- Script gửi qua `--data-urlencode` phải là UTF-8; nếu tên file/asset có tiếng Việt, kiểm tra encoding của file script.
- Với plan lớn, dùng `--data-urlencode "data@plan.json"`.

***

## 11. Kết quả test thực tế

Môi trường: **AEM 6.5.24 Author** local, **AEM Groovy Console 15.1.0**, Groovy 2.4.15.

Các test đã chạy:

| Test                                               | Kết quả                                        |
| -------------------------------------------------- | ---------------------------------------------- |
| `session.userID` khi chạy UI                       | `admin`                                        |
| Tạo node không `save()`                            | request sau `404`                              |
| Gọi `save()`                                       | node tồn tại, `pending=false`                  |
| `rename node to "new"`                             | thành công, `pending=false` (tự save)          |
| `move "src" to "dst"`                              | thành công, `pending=false` (tự save)          |
| Audit 3 asset                                      | phát hiện 2 tên lỗi, 1 duplicate proposed      |
| Dry run apply                                      | không tạo target, `pending=false`              |
| Apply rename 1 asset                               | path cũ `404`, path mới `200`, UUID giữ nguyên |
| `fileReference` sau move                           | vẫn trỏ path cũ; phải update tay               |
| Update `fileReference`                             | ref mới đúng, old refs = 0                     |
| `dam:sha1` sau khi update metadata                 | thay đổi; UUID vẫn ổn định                     |
| `AssetReferenceResolver` / `AssetReferenceHandler` | trả rỗng dù có `fileReference`                 |
| Batch update property `altText`                    | dry run 0 thay đổi; apply 1 thay đổi           |
| `jcr:mixinTypes` đọc bằng `.string`                | `ValueFormatException`; phải dùng `.values`    |

Sau test, toàn bộ content/asset test đã được xoá; Groovy Console 15.1.0 vẫn được cài trên instance local để dùng tiếp.

***

## 12. Tài liệu tham khảo

- AEM Groovy Console (ICF Next): `https://github.com/icfnext/aem-groovy-console`
- JCR 2.0 Specification: `https://docs.adobe.com/docs/en/spec/javax.jcr/javadocs/jcr-2.0/`
- Oak Query: `https://jackrabbit.apache.org/oak/docs/query/query.html`
- AEM QueryBuilder Debug: `/libs/cq/search/content/querydebug.html`
- AEM Assets API: `com.day.cq.dam.api.Asset`, `AssetReferenceResolver`, `AssetReferenceHandler`
- AEM 6.5 Assets documentation: metadata, renditions, reference

***

## Điểm cần nhớ

- **Search** dùng query rộng theo path + `dam:Asset`, sau đó filter bằng Groovy; JCR-SQL2 không xử lý regex.
- **Dry run** phải hoàn toàn read-only; `rename`/`move` DSL tự save nên không được dùng trong dry run.
- **Apply** dùng `session.move` + `save()` theo batch, update `fileReference` trong cùng commit; `rename` DSL chỉ dùng cho một node.
- **Reference** không tự update; AEM chỉ xử lý một phần (`sling:resource`, `dam:originalPath`, `dam:resolvedPath`), không xử lý `fileReference`, RTE HTML, CF/EF.
- **Rollback** phải chuẩn bị trước; JCR không có transaction xuyên nhiều `save()`.
- Rủi ro lớn nhất là script chạy đúng trên một tập node sai. Trình tự nên giữ nguyên: audit → dry run → review → apply nhỏ → verify.
