Compare commits

...

283 Commits

Author SHA1 Message Date
alfresco-build
5d9dca1872 [maven-release-plugin][skip ci] prepare release 23.1.0.111 2023-05-18 07:47:34 +00:00
Sara
bf7f64add4 ACS-5918 Bump t-core to 3.2.0-A1 and release ATS 2.2.0-A1 (#1933) 2023-05-18 08:00:51 +01:00
alfresco-build
7d15862b69 [maven-release-plugin][skip ci] prepare for next development iteration 2023-05-17 15:54:13 +00:00
alfresco-build
2e8ec4c226 [maven-release-plugin][skip ci] prepare release 23.1.0.110 2023-05-17 15:54:09 +00:00
dependabot[bot]
24752d0409 Bump commons-compress from 1.22 to 1.23.0 (#1824)
Bumps commons-compress from 1.22 to 1.23.0.

---
updated-dependencies:
- dependency-name: org.apache.commons:commons-compress
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 17:01:50 +02:00
dependabot[bot]
ff8804e7db Bump maven-javadoc-plugin from 3.4.1 to 3.5.0 (#1753)
Bumps [maven-javadoc-plugin](https://github.com/apache/maven-javadoc-plugin) from 3.4.1 to 3.5.0.
- [Release notes](https://github.com/apache/maven-javadoc-plugin/releases)
- [Commits](https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.4.1...maven-javadoc-plugin-3.5.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-javadoc-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 16:44:47 +02:00
dependabot[bot]
02a62cb5f7 Bump jetty-server from 10.0.11 to 10.0.14 in /remote-api (#1887)
Bumps [jetty-server](https://github.com/eclipse/jetty.project) from 10.0.11 to 10.0.14.
- [Release notes](https://github.com/eclipse/jetty.project/releases)
- [Commits](https://github.com/eclipse/jetty.project/compare/jetty-10.0.11...jetty-10.0.14)

---
updated-dependencies:
- dependency-name: org.eclipse.jetty:jetty-server
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 16:34:31 +02:00
dependabot[bot]
e1afe15055 Bump alfresco-greenmail from 6.5 to 6.8 (#1774)
Bumps [alfresco-greenmail](https://github.com/Alfresco/alfresco-greenmail) from 6.5 to 6.8.
- [Release notes](https://github.com/Alfresco/alfresco-greenmail/releases)
- [Commits](https://github.com/Alfresco/alfresco-greenmail/compare/alfresco-greenmail-6.5...alfresco-greenmail-6.8)

---
updated-dependencies:
- dependency-name: org.alfresco:alfresco-greenmail
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 16:02:46 +02:00
dependabot[bot]
0fcdf3b00b Bump maven-dependency-plugin from 3.3.0 to 3.5.0 (#1678)
Bumps [maven-dependency-plugin](https://github.com/apache/maven-dependency-plugin) from 3.3.0 to 3.5.0.
- [Release notes](https://github.com/apache/maven-dependency-plugin/releases)
- [Commits](https://github.com/apache/maven-dependency-plugin/compare/maven-dependency-plugin-3.3.0...maven-dependency-plugin-3.5.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-dependency-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 16:02:01 +02:00
dependabot[bot]
fa63cef4f7 Bump alfresco-messaging-repo from 1.2.20 to 1.2.21 (#1751)
Bumps alfresco-messaging-repo from 1.2.20 to 1.2.21.

---
updated-dependencies:
- dependency-name: org.alfresco.services:alfresco-messaging-repo
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 16:01:45 +02:00
dependabot[bot]
27f41e11b3 Bump ftp from 1.7 to 1.15 (#1929)
Bumps [ftp](https://github.com/Alfresco/alfresco-tas-ftp) from 1.7 to 1.15.
- [Changelog](https://github.com/Alfresco/alfresco-tas-ftp/blob/master/docs/CHANGELOG.md)
- [Commits](https://github.com/Alfresco/alfresco-tas-ftp/compare/v1.7...v1.15)

---
updated-dependencies:
- dependency-name: org.alfresco.tas:ftp
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 15:56:58 +02:00
dependabot[bot]
affa20e996 Bump docker-java from 3.2.13 to 3.3.0 (#1754)
Bumps [docker-java](https://github.com/docker-java/docker-java) from 3.2.13 to 3.3.0.
- [Release notes](https://github.com/docker-java/docker-java/releases)
- [Changelog](https://github.com/docker-java/docker-java/blob/main/CHANGELOG.md)
- [Commits](https://github.com/docker-java/docker-java/compare/3.2.13...3.3.0)

---
updated-dependencies:
- dependency-name: com.github.docker-java:docker-java
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 15:55:50 +02:00
dependabot[bot]
0df9f562e6 Bump alfresco-opencmis-extension from 2.1 to 2.2 (#1747)
Bumps [alfresco-opencmis-extension](https://github.com/Alfresco/opencmis-extension) from 2.1 to 2.2.
- [Release notes](https://github.com/Alfresco/opencmis-extension/releases)
- [Commits](https://github.com/Alfresco/opencmis-extension/compare/2.1...2.2)

---
updated-dependencies:
- dependency-name: org.alfresco.cmis.client:alfresco-opencmis-extension
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 15:55:12 +02:00
dependabot[bot]
9a3ec69b27 Bump lombok from 1.18.24 to 1.18.26 (#1725)
Bumps [lombok](https://github.com/projectlombok/lombok) from 1.18.24 to 1.18.26.
- [Release notes](https://github.com/projectlombok/lombok/releases)
- [Changelog](https://github.com/projectlombok/lombok/blob/master/doc/changelog.markdown)
- [Commits](https://github.com/projectlombok/lombok/compare/v1.18.24...v1.18.26)

---
updated-dependencies:
- dependency-name: org.projectlombok:lombok
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 15:54:17 +02:00
alfresco-build
7126406bf3 [maven-release-plugin][skip ci] prepare for next development iteration 2023-05-17 12:53:18 +00:00
alfresco-build
edc43ed5b9 [maven-release-plugin][skip ci] prepare release 23.1.0.109 2023-05-17 12:53:14 +00:00
dependabot[bot]
907aed826a Bump xmlsec from 3.0.0 to 3.0.2 (#1845)
Bumps xmlsec from 3.0.0 to 3.0.2.

---
updated-dependencies:
- dependency-name: org.apache.santuario:xmlsec
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 14:10:29 +02:00
dependabot[bot]
eaa96607b9 Bump groovy-json from 3.0.16 to 3.0.17 (#1850)
Bumps [groovy-json](https://github.com/apache/groovy) from 3.0.16 to 3.0.17.
- [Release notes](https://github.com/apache/groovy/releases)
- [Commits](https://github.com/apache/groovy/commits)

---
updated-dependencies:
- dependency-name: org.codehaus.groovy:groovy-json
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 14:00:54 +02:00
dependabot[bot]
0d5d9ff0b4 Bump slf4j-api from 2.0.3 to 2.0.7 (#1811)
Bumps [slf4j-api](https://github.com/qos-ch/slf4j) from 2.0.3 to 2.0.7.
- [Release notes](https://github.com/qos-ch/slf4j/releases)
- [Commits](https://github.com/qos-ch/slf4j/commits)

---
updated-dependencies:
- dependency-name: org.slf4j:slf4j-api
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 13:54:55 +02:00
dependabot[bot]
5266304805 Bump groovy from 3.0.16 to 3.0.17 (#1852)
Bumps [groovy](https://github.com/apache/groovy) from 3.0.16 to 3.0.17.
- [Release notes](https://github.com/apache/groovy/releases)
- [Commits](https://github.com/apache/groovy/commits)

---
updated-dependencies:
- dependency-name: org.codehaus.groovy:groovy
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 13:54:21 +02:00
dependabot[bot]
63e77b6f86 Bump joda-time from 2.12.1 to 2.12.5 (#1844)
Bumps [joda-time](https://github.com/JodaOrg/joda-time) from 2.12.1 to 2.12.5.
- [Release notes](https://github.com/JodaOrg/joda-time/releases)
- [Changelog](https://github.com/JodaOrg/joda-time/blob/main/RELEASE-NOTES.txt)
- [Commits](https://github.com/JodaOrg/joda-time/compare/v2.12.1...v2.12.5)

---
updated-dependencies:
- dependency-name: joda-time:joda-time
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 13:53:20 +02:00
dependabot[bot]
9cf74e4dc4 Bump aspectjrt from 1.9.9.1 to 1.9.19 (#1642)
Bumps [aspectjrt](https://github.com/eclipse/org.aspectj) from 1.9.9.1 to 1.9.19.
- [Release notes](https://github.com/eclipse/org.aspectj/releases)
- [Commits](https://github.com/eclipse/org.aspectj/commits)

---
updated-dependencies:
- dependency-name: org.aspectj:aspectjrt
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 13:41:55 +02:00
dependabot[bot]
4107a0fd0e Bump maven-resources-plugin from 3.3.0 to 3.3.1 (#1832)
Bumps [maven-resources-plugin](https://github.com/apache/maven-resources-plugin) from 3.3.0 to 3.3.1.
- [Release notes](https://github.com/apache/maven-resources-plugin/releases)
- [Commits](https://github.com/apache/maven-resources-plugin/compare/maven-resources-plugin-3.3.0...maven-resources-plugin-3.3.1)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-resources-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 13:24:10 +02:00
alfresco-build
8554fe0d74 [maven-release-plugin][skip ci] prepare for next development iteration 2023-05-17 10:51:01 +00:00
alfresco-build
2ed88cd1be [maven-release-plugin][skip ci] prepare release 23.1.0.108 2023-05-17 10:50:59 +00:00
dependabot[bot]
8f4f4e938c Bump webdav from 1.7 to 1.14 (#1925)
Bumps [webdav](https://github.com/Alfresco/alfresco-tas-webdav) from 1.7 to 1.14.
- [Changelog](https://github.com/Alfresco/alfresco-tas-webdav/blob/master/docs/CHANGELOG.md)
- [Commits](https://github.com/Alfresco/alfresco-tas-webdav/compare/v1.7...v1.14)

---
updated-dependencies:
- dependency-name: org.alfresco.tas:webdav
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 12:08:27 +02:00
dependabot[bot]
dc76b15aa6 Bump dependency.log4j.version from 2.19.0 to 2.20.0 (#1762)
Bumps `dependency.log4j.version` from 2.19.0 to 2.20.0.

Updates `log4j-slf4j2-impl` from 2.19.0 to 2.20.0
- [Release notes](https://github.com/apache/logging-log4j2/releases)
- [Changelog](https://github.com/apache/logging-log4j2/blob/release-2.x/CHANGELOG.adoc)
- [Commits](https://github.com/apache/logging-log4j2/compare/rel/2.19.0...rel/2.20.0)

Updates `log4j-api` from 2.19.0 to 2.20.0
- [Release notes](https://github.com/apache/logging-log4j2/releases)
- [Changelog](https://github.com/apache/logging-log4j2/blob/release-2.x/CHANGELOG.adoc)
- [Commits](https://github.com/apache/logging-log4j2/compare/rel/2.19.0...rel/2.20.0)

Updates `log4j-core` from 2.19.0 to 2.20.0
- [Release notes](https://github.com/apache/logging-log4j2/releases)
- [Changelog](https://github.com/apache/logging-log4j2/blob/release-2.x/CHANGELOG.adoc)
- [Commits](https://github.com/apache/logging-log4j2/compare/rel/2.19.0...rel/2.20.0)

---
updated-dependencies:
- dependency-name: org.apache.logging.log4j:log4j-slf4j2-impl
  dependency-type: direct:development
  update-type: version-update:semver-minor
- dependency-name: org.apache.logging.log4j:log4j-api
  dependency-type: direct:production
  update-type: version-update:semver-minor
- dependency-name: org.apache.logging.log4j:log4j-core
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 10:59:03 +02:00
dependabot[bot]
0109db978f Bump icu4j from 72.1 to 73.1 (#1878)
Bumps [icu4j](https://github.com/unicode-org/icu) from 72.1 to 73.1.
- [Release notes](https://github.com/unicode-org/icu/releases)
- [Commits](https://github.com/unicode-org/icu/commits)

---
updated-dependencies:
- dependency-name: com.ibm.icu:icu4j
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 10:48:44 +02:00
dependabot[bot]
6461629024 Bump dependency.jackson.version from 2.15.0-rc1 to 2.15.1 (#1926)
Bumps `dependency.jackson.version` from 2.15.0-rc1 to 2.15.1.

Updates `jackson-core` from 2.15.0-rc1 to 2.15.1
- [Release notes](https://github.com/FasterXML/jackson-core/releases)
- [Changelog](https://github.com/FasterXML/jackson-core/blob/jackson-core-2.15.1/release.properties)
- [Commits](https://github.com/FasterXML/jackson-core/compare/jackson-core-2.15.0-rc1...jackson-core-2.15.1)

Updates `jackson-databind` from 2.15.0-rc1 to 2.15.1
- [Commits](https://github.com/FasterXML/jackson/commits)

Updates `jackson-datatype-joda` from 2.15.0-rc1 to 2.15.1
- [Commits](https://github.com/FasterXML/jackson-datatype-joda/compare/jackson-datatype-joda-2.15.0-rc1...jackson-datatype-joda-2.15.1)

Updates `jackson-dataformat-yaml` from 2.15.0-rc1 to 2.15.1
- [Commits](https://github.com/FasterXML/jackson-dataformats-text/compare/jackson-dataformats-text-2.15.0-rc1...jackson-dataformats-text-2.15.1)

Updates `jackson-annotations` from 2.15.0-rc1 to 2.15.1
- [Commits](https://github.com/FasterXML/jackson/commits)

Updates `jackson-module-jaxb-annotations` from 2.15.0-rc1 to 2.15.1
- [Commits](https://github.com/FasterXML/jackson-modules-base/compare/jackson-modules-base-2.15.0-rc1...jackson-modules-base-2.15.1)

---
updated-dependencies:
- dependency-name: com.fasterxml.jackson.core:jackson-core
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: com.fasterxml.jackson.core:jackson-databind
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: com.fasterxml.jackson.datatype:jackson-datatype-joda
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: com.fasterxml.jackson.dataformat:jackson-dataformat-yaml
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: com.fasterxml.jackson.core:jackson-annotations
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: com.fasterxml.jackson.module:jackson-module-jaxb-annotations
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 10:42:54 +02:00
dependabot[bot]
c35dbb0481 Bump email from 1.11 to 1.17 (#1927)
Bumps [email](https://github.com/Alfresco/alfresco-tas-email) from 1.11 to 1.17.
- [Changelog](https://github.com/Alfresco/alfresco-tas-email/blob/master/docs/CHANGELOG.md)
- [Commits](https://github.com/Alfresco/alfresco-tas-email/compare/v1.11...v1.17)

---
updated-dependencies:
- dependency-name: org.alfresco.tas:email
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 10:26:25 +02:00
dependabot[bot]
637523c2c8 Bump jsoup from 1.15.3 to 1.16.1 (#1910)
Bumps [jsoup](https://github.com/jhy/jsoup) from 1.15.3 to 1.16.1.
- [Release notes](https://github.com/jhy/jsoup/releases)
- [Changelog](https://github.com/jhy/jsoup/blob/master/CHANGES)
- [Commits](https://github.com/jhy/jsoup/compare/jsoup-1.15.3...jsoup-1.16.1)

---
updated-dependencies:
- dependency-name: org.jsoup:jsoup
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-17 10:20:40 +02:00
dependabot[bot]
f1a54895f6 Bump acs-event-model from 0.0.18 to 0.0.21 (#1889)
Bumps [acs-event-model](https://github.com/Alfresco/acs-event-model) from 0.0.18 to 0.0.21.
- [Release notes](https://github.com/Alfresco/acs-event-model/releases)
- [Commits](https://github.com/Alfresco/acs-event-model/commits)

---
updated-dependencies:
- dependency-name: org.alfresco:acs-event-model
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-16 17:06:54 +02:00
alfresco-build
7f6d9443e2 [maven-release-plugin][skip ci] prepare for next development iteration 2023-05-16 14:29:31 +00:00
alfresco-build
297d72c246 [maven-release-plugin][skip ci] prepare release 23.1.0.107 2023-05-16 14:29:28 +00:00
dependabot[bot]
7208ad9b62 Bump woodstox-core from 6.4.0 to 6.5.1 (#1892)
Bumps [woodstox-core](https://github.com/FasterXML/woodstox) from 6.4.0 to 6.5.1.
- [Release notes](https://github.com/FasterXML/woodstox/releases)
- [Commits](https://github.com/FasterXML/woodstox/compare/woodstox-core-6.4.0...woodstox-core-6.5.1)

---
updated-dependencies:
- dependency-name: com.fasterxml.woodstox:woodstox-core
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-16 15:48:25 +02:00
Kacper Magdziarz
31ca2726a8 [ACS-5192] Upgrade Repository Components to Java 17 (#1919) 2023-05-16 15:41:35 +02:00
dependabot[bot]
6f43286441 Bump api-explorer from 7.3.0 to 7.4.0 (#1911)
Bumps [api-explorer](https://github.com/Alfresco/rest-api-explorer) from 7.3.0 to 7.4.0.
- [Release notes](https://github.com/Alfresco/rest-api-explorer/releases)
- [Commits](https://github.com/Alfresco/rest-api-explorer/compare/7.3.0...7.4.0)

---
updated-dependencies:
- dependency-name: org.alfresco:api-explorer
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-16 14:35:30 +02:00
alfresco-build
aec50a991f [maven-release-plugin][skip ci] prepare for next development iteration 2023-05-16 12:14:09 +00:00
alfresco-build
f62b937ded [maven-release-plugin][skip ci] prepare release 23.1.0.106 2023-05-16 12:14:06 +00:00
dependabot[bot]
66d3d72f7c Bump buildnumber-maven-plugin from 3.0.0 to 3.1.0 (#1920)
Bumps [buildnumber-maven-plugin](https://github.com/mojohaus/buildnumber-maven-plugin) from 3.0.0 to 3.1.0.
- [Release notes](https://github.com/mojohaus/buildnumber-maven-plugin/releases)
- [Commits](https://github.com/mojohaus/buildnumber-maven-plugin/compare/buildnumber-maven-plugin-3.0.0...3.1.0)

---
updated-dependencies:
- dependency-name: org.codehaus.mojo:buildnumber-maven-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-16 13:33:35 +02:00
alfresco-build
0b4b9fd47a [maven-release-plugin][skip ci] prepare for next development iteration 2023-05-16 10:39:59 +00:00
alfresco-build
2b955d21f9 [maven-release-plugin][skip ci] prepare release 23.1.0.105 2023-05-16 10:39:56 +00:00
dependabot[bot]
6a853f3b92 Bump swagger-parser from 1.0.63 to 1.0.66 (#1921)
Bumps [swagger-parser](https://github.com/swagger-api/swagger-parser) from 1.0.63 to 1.0.66.
- [Release notes](https://github.com/swagger-api/swagger-parser/releases)
- [Commits](https://github.com/swagger-api/swagger-parser/compare/v1.0.63...v1.0.66)

---
updated-dependencies:
- dependency-name: io.swagger:swagger-parser
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-16 11:56:12 +02:00
alfresco-build
c293ace4e0 [maven-release-plugin][skip ci] prepare for next development iteration 2023-05-16 09:45:10 +00:00
alfresco-build
86dfdd8df4 [maven-release-plugin][skip ci] prepare release 23.1.0.104 2023-05-16 09:45:06 +00:00
dependabot[bot]
abd73e820c Bump maven-assembly-plugin from 3.4.2 to 3.6.0 (#1923)
Bumps [maven-assembly-plugin](https://github.com/apache/maven-assembly-plugin) from 3.4.2 to 3.6.0.
- [Commits](https://github.com/apache/maven-assembly-plugin/compare/maven-assembly-plugin-3.4.2...maven-assembly-plugin-3.6.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-assembly-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-16 10:16:36 +02:00
alfresco-build
09bec28721 [maven-release-plugin][skip ci] prepare for next development iteration 2023-05-15 13:39:32 +00:00
alfresco-build
0d1a6c8a0a [maven-release-plugin][skip ci] prepare release 23.1.0.103 2023-05-15 13:39:29 +00:00
Tom Page
4b9c052f0d Merge pull request #1918 from Alfresco/feature/ACS-5191_LicensePluginUpgrade
ACS-5191 Upgrade to license-maven-plugin 2.0.1.
2023-05-15 13:52:09 +01:00
alfresco-build
6fb0bb3042 [maven-release-plugin][skip ci] prepare for next development iteration 2023-05-14 00:05:55 +00:00
alfresco-build
78f3d58c46 [maven-release-plugin][skip ci] prepare release 23.1.0.102 2023-05-14 00:05:52 +00:00
Alfresco CI User
1913258e84 [force] Force release for 2023-05-14. 2023-05-14 00:02:52 +00:00
Tom Page
d95e6c8e34 ACS-5191 Upgrade to license-maven-plugin 2.0.1. 2023-05-12 16:19:38 +01:00
alfresco-build
958d217339 [maven-release-plugin][skip ci] prepare for next development iteration 2023-05-11 09:43:05 +00:00
alfresco-build
4417e28412 [maven-release-plugin][skip ci] prepare release 23.1.0.101 2023-05-11 09:43:02 +00:00
Damian Ujma
58653cb523 ACS-5087 Add more attempts to create a folder in RenditionIntegrationTests (#1904)
* ACS-5087 Add more attempts to create a folder

* ACS-5087 Use awaitility to add more attempts to create a folder

* ACS-5087 Add ignoreExceptions condition

* ACS-5087 Use a smaller pollInterval
2023-05-11 10:59:38 +02:00
alfresco-build
7af935d43a [maven-release-plugin][skip ci] prepare for next development iteration 2023-05-08 12:41:15 +00:00
alfresco-build
f5d843446a [maven-release-plugin][skip ci] prepare release 23.1.0.100 2023-05-08 12:41:11 +00:00
mstrankowski
817901e74e Update Master branch to 23.1.0, forgotten updates 2023-05-08 13:52:16 +02:00
mstrankowski
c492683113 Update Master branch to 23.1.0 2023-05-08 13:02:01 +02:00
alfresco-build
e2305d053f [maven-release-plugin][skip ci] prepare for next development iteration 2023-05-07 00:07:14 +00:00
alfresco-build
749768457e [maven-release-plugin][skip ci] prepare release 20.163 2023-05-07 00:07:11 +00:00
Alfresco CI User
118f2ecbab [force] Force release for 2023-05-07. 2023-05-07 00:03:02 +00:00
alfresco-build
a4ac93df7a [maven-release-plugin][skip ci] prepare for next development iteration 2023-05-04 07:56:19 +00:00
alfresco-build
1e1fbe8207 [maven-release-plugin][skip ci] prepare release 20.162 2023-05-04 07:56:16 +00:00
Sara
e78f9ced98 ACS-5157_Bump_api-explorer_to_7-4-0 (#1912) 2023-05-04 08:10:00 +01:00
alfresco-build
72221c777d [maven-release-plugin][skip ci] prepare for next development iteration 2023-05-03 20:54:48 +00:00
alfresco-build
25f3f33594 [maven-release-plugin][skip ci] prepare release 20.161 2023-05-03 20:54:45 +00:00
tiagosalvado10
f83328f7b0 [MNT-23550] Always disable behaviours to prevent unexpected modifier changes (#1898) 2023-05-03 20:34:37 +01:00
alfresco-build
a177f391db [maven-release-plugin][skip ci] prepare for next development iteration 2023-05-02 05:22:45 +00:00
alfresco-build
784557afcd [maven-release-plugin][skip ci] prepare release 20.160 2023-05-02 05:22:41 +00:00
MohinishSah
8fb7b0d224 Update G-drive and AOS final version 2023-05-01 12:24:30 +05:30
alfresco-build
011ec9d7e6 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-30 00:06:05 +00:00
alfresco-build
3900f589d9 [maven-release-plugin][skip ci] prepare release 20.159 2023-04-30 00:06:02 +00:00
Alfresco CI User
def7a0d432 [force] Force release for 2023-04-30. 2023-04-30 00:02:53 +00:00
alfresco-build
7371c5d7ff [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-28 16:36:05 +00:00
alfresco-build
90406cef03 [maven-release-plugin][skip ci] prepare release 20.158 2023-04-28 16:36:01 +00:00
Sara
862e6d5596 ACS-5075 and ACS-4832 Bump t-core and t-service to 3.1.0 and 2.1.0 (#1906) 2023-04-28 16:05:00 +01:00
alfresco-build
27be717df5 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-26 12:50:39 +00:00
alfresco-build
28ad071daf [maven-release-plugin][skip ci] prepare release 20.157 2023-04-26 12:50:36 +00:00
dependabot[bot]
06cc5e3499 Bump spring-security-bom from 5.8.2 to 5.8.3 (#1884)
* Bump spring-security-bom from 5.8.2 to 6.0.3

Bumps [spring-security-bom](https://github.com/spring-projects/spring-security) from 5.8.2 to 6.0.3.
- [Release notes](https://github.com/spring-projects/spring-security/releases)
- [Changelog](https://github.com/spring-projects/spring-security/blob/main/RELEASE.adoc)
- [Commits](https://github.com/spring-projects/spring-security/compare/5.8.2...6.0.3)

---
updated-dependencies:
- dependency-name: org.springframework.security:spring-security-bom
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* Bump Spring Security BOM to 5.8.3

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Domenico Sibilio <domenicosibilio@gmail.com>
2023-04-26 14:05:37 +02:00
alfresco-build
df8b36350d [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-23 00:08:06 +00:00
alfresco-build
552abc9bd4 [maven-release-plugin][skip ci] prepare release 20.156 2023-04-23 00:08:03 +00:00
Alfresco CI User
00cab8e6b5 [force] Force release for 2023-04-23. 2023-04-23 00:03:14 +00:00
alfresco-build
6f4069790c [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-21 14:50:56 +00:00
alfresco-build
146b59a4a8 [maven-release-plugin][skip ci] prepare release 20.155 2023-04-21 14:50:52 +00:00
George Evangelopoulos
2c3845bf9d ACS-4025: Throw 400 error when ordering by tag count without including tag count (#1896)
* ACS-4025: change exception to throw 400 and add test
2023-04-21 15:05:21 +01:00
alfresco-build
dd05f3d338 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-21 13:55:35 +00:00
alfresco-build
c2338bdeb2 [maven-release-plugin][skip ci] prepare release 20.154 2023-04-21 13:55:32 +00:00
Piotr Żurek
589e14a0b1 ACS-5100 Include authorization uri in the ClientRegistration (#1897) 2023-04-21 15:12:37 +02:00
alfresco-build
0f753c11c7 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-21 11:50:46 +00:00
alfresco-build
c8fea93298 [maven-release-plugin][skip ci] prepare release 20.153 2023-04-21 11:50:43 +00:00
Marcin Strankowski
d7f881ce0c Update transform-service to 2.1.0-A9, transform-coreto 3.1.0-A12 (#1895)
* Update transform-service to 2.1.0-A9, transform-coreto 3.1.0-A12
2023-04-21 12:41:20 +02:00
alfresco-build
b5fabb1290 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-21 08:05:31 +00:00
alfresco-build
f6d3ff4b15 [maven-release-plugin][skip ci] prepare release 20.152 2023-04-21 08:05:28 +00:00
rrajoria
2eb5bb7b7a Updating google drive and aos alpha version 2023-04-21 10:56:08 +05:30
atkumar14
53909dc086 [APPS-1952] Removed retention management event endpoints from swagger (#1893)
Co-authored-by: suneet-gupta <suneet.gupta@globallogic.com>
2023-04-20 19:18:40 +05:30
alfresco-build
4fedf0bada [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-20 10:30:30 +00:00
alfresco-build
9f6edc648e [maven-release-plugin][skip ci] prepare release 20.151 2023-04-20 10:30:26 +00:00
Tom Page
22298eaa46 Merge pull request #1891 from Alfresco/feature/ACS-5068_SS2.0.7-A5
ACS-5068 Upgrade to SS 2.0.7-A5. [ags]
2023-04-20 10:48:17 +01:00
Tom Page
2e9db406d4 ACS-5068 Upgrade to SS 2.0.7-A5. [ags] 2023-04-20 09:14:55 +01:00
alfresco-build
8565c9413e [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-19 14:07:53 +00:00
alfresco-build
0d411cd759 [maven-release-plugin][skip ci] prepare release 20.150 2023-04-19 14:07:49 +00:00
Domenico Sibilio
ca3bbf5226 ACS-5083 Bump Spring to 5.3.27 (#1888) 2023-04-19 13:43:38 +02:00
alfresco-build
e83cd86c4d [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-19 11:24:36 +00:00
alfresco-build
7da314cd97 [maven-release-plugin][skip ci] prepare release 20.149 2023-04-19 11:24:33 +00:00
George Evangelopoulos
d39401a7ec ACS-4025: Support include count and orderBy count for GET /tags (#1806)
* ACS-4025: Support include count and orderBy count for GET /tags

* ACS-4025: add E2Es
2023-04-19 11:41:33 +01:00
alfresco-build
05df8a7582 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-18 14:05:16 +00:00
alfresco-build
85f22cb6e4 [maven-release-plugin][skip ci] prepare release 20.148 2023-04-18 14:05:13 +00:00
Domenico Sibilio
ce77b1ff42 Bump docker-maven-plugin from 0.42.0 to 0.42.1
This reverts commit 2fcf1bd2d5.
2023-04-18 14:18:40 +02:00
alfresco-build
29a7de55d2 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-18 11:20:22 +00:00
alfresco-build
cb3cb85694 [maven-release-plugin][skip ci] prepare release 20.147 2023-04-18 11:20:18 +00:00
Domenico Sibilio
2fcf1bd2d5 Revert "Bump docker-maven-plugin from 0.42.0 to 0.42.1 (#1866)" (#1885)
This reverts commit 06fdc4302e.
2023-04-18 12:31:40 +02:00
alfresco-build
4c687f670e [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-17 12:10:18 +00:00
alfresco-build
dad0094a46 [maven-release-plugin][skip ci] prepare release 20.146 2023-04-17 12:10:14 +00:00
dependabot[bot]
06fdc4302e Bump docker-maven-plugin from 0.42.0 to 0.42.1 (#1866)
Bumps [docker-maven-plugin](https://github.com/fabric8io/docker-maven-plugin) from 0.42.0 to 0.42.1.
- [Release notes](https://github.com/fabric8io/docker-maven-plugin/releases)
- [Changelog](https://github.com/fabric8io/docker-maven-plugin/blob/master/doc/changelog.md)
- [Commits](https://github.com/fabric8io/docker-maven-plugin/compare/v0.42.0...v0.42.1)

---
updated-dependencies:
- dependency-name: io.fabric8:docker-maven-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-04-17 13:29:34 +02:00
Tom Page
b1466915af ACS-4923 Add support for include=count on GET and PUT tag. (#1880) 2023-04-17 10:12:09 +01:00
alfresco-build
6be773ba18 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-16 00:06:37 +00:00
alfresco-build
fbcfe68c99 [maven-release-plugin][skip ci] prepare release 20.145 2023-04-16 00:06:34 +00:00
Alfresco CI User
e50118115e [force] Force release for 2023-04-16. 2023-04-16 00:03:14 +00:00
alfresco-build
3a2136b886 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-14 15:06:27 +00:00
alfresco-build
86464427a0 [maven-release-plugin][skip ci] prepare release 20.144 2023-04-14 15:06:24 +00:00
Kacper Magdziarz
7e9e0e1ad4 [ACS-5005] Improve keystore/truststore generation for GHA (#1873) 2023-04-14 16:12:33 +02:00
alfresco-build
32c3a5ad90 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-14 11:31:04 +00:00
alfresco-build
e983e4ed22 [maven-release-plugin][skip ci] prepare release 20.143 2023-04-14 11:31:00 +00:00
Marcin Strankowski
ba197fcf70 Set property values of Tranform HttpClient to the ones being set for sharedFileStoreConnector (#1875)
* Set property values to the ones being set for sharedFileStoreConnector, since the only difference is the number of connections, which doesn't work in community-repo due to how the http clients are created per request of transform

* Missing property doesn't allow for providing value from JAVA_OPTS of docker image
2023-04-14 12:50:17 +02:00
MichalKinas
18e6965a61 Merge pull request #1855 from Alfresco/feature/ACS-4966_Add_path_to_categories_api
ACS-4966 Add path to Category API
2023-04-14 12:40:11 +02:00
MichalKinas
c0757f45a2 ACS-4966 Final cleanup 2023-04-14 11:58:18 +02:00
MichalKinas
7bdbc3a91a ACS-4966 Correct creation of categories 2023-04-14 10:58:21 +02:00
MichalKinas
25fa97bdd8 ACS-4966 Correct parent category creation 2023-04-14 10:00:34 +02:00
MichalKinas
7592b637cc ACS-4966 Correct child category creation 2023-04-14 09:57:14 +02:00
MichalKinas
70c490f26c ACS-4966 Parent category not as root 2023-04-14 09:15:07 +02:00
MichalKinas
93f7d06cf0 ACS-4966 Missing imports 2023-04-14 08:37:49 +02:00
MichalKinas
657318c6ae ACS-4966 Create Categories under the right parent 2023-04-14 08:31:54 +02:00
MichalKinas
4f4d8210ef ACS-4966 Explicitly test path equality 2023-04-13 19:37:41 +02:00
MichalKinas
14ba7f5d55 ACS-4966 Explicit test result logging 2023-04-13 19:00:35 +02:00
alfresco-build
c4a4aedad7 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-13 16:10:55 +00:00
alfresco-build
be60d67377 [maven-release-plugin][skip ci] prepare release 20.142 2023-04-13 16:10:52 +00:00
mstrankowski
806131c21c Update Transform-core dependency to 3.1.0-A8
Update Transform-service dependency to 2.1.0-A6
2023-04-13 17:15:26 +02:00
MichalKinas
b0f767c1ae ACS-4966 CR fixes 2023-04-13 12:40:35 +02:00
MichalKinas
baccde2663 ACS-4966 Restore user creation 2023-04-13 10:23:32 +02:00
MichalKinas
e048278a27 ACS-4966 Missing import 2023-04-13 09:38:01 +02:00
MichalKinas
8586d22b95 ACS-4966 Correct categories creation 2023-04-13 09:28:23 +02:00
MichalKinas
3dec621b15 ACS-4966 Correct path in unit tests, cover child category case 2023-04-13 09:19:05 +02:00
alfresco-build
64202ee9d5 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-11 13:56:17 +00:00
alfresco-build
2b92022b5b [maven-release-plugin][skip ci] prepare release 20.141 2023-04-11 13:56:13 +00:00
Damian Ujma
9a56a052e8 ACS-5023 Bump Spring to 5.3.26 (#1868)
* PRODSEC-7146 Bump Spring to 5.3.26 [tas]

* ACS-5023 Bump Spring to 5.3.26 [tas]

---------

Co-authored-by: Domenico Sibilio <domenicosibilio@gmail.com>
2023-04-11 15:09:49 +02:00
alfresco-build
1f38c24bbd [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-10 09:35:45 +00:00
alfresco-build
0bcb96e51e [maven-release-plugin][skip ci] prepare release 20.140 2023-04-10 09:35:42 +00:00
MohinishSah
df522a38b9 Merge pull request #1867 from Alfresco/fix/revert-changes-forgotPassword
Fix/revert changes forgot password
2023-04-10 08:51:44 +00:00
Mohinish Sah
1458ef3311 revert changes 2023-04-10 14:18:17 +05:30
Mohinish Sah
2bdca1a4f5 revert changes 2023-04-10 14:17:13 +05:30
alfresco-build
07cc9aa86e [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-09 00:06:55 +00:00
alfresco-build
7db550cee1 [maven-release-plugin][skip ci] prepare release 20.139 2023-04-09 00:06:52 +00:00
Alfresco CI User
937d80327f [force] Force release for 2023-04-09. 2023-04-09 00:03:20 +00:00
alfresco-build
8abff868cc [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-07 13:02:26 +00:00
alfresco-build
ffae8a62a1 [maven-release-plugin][skip ci] prepare release 20.138 2023-04-07 13:02:23 +00:00
kmagdziarz
0350c966df [ACS-5020] Ignore intermittent tests 2023-04-07 14:14:33 +02:00
kmagdziarz
833a7675bc [ACS-5020] Ignore intermittent test 2023-04-07 11:28:35 +02:00
Kacper Magdziarz
8aa263f377 [ACS-4462] Add connection manager builder for httpClient4Factory (#1864)
Co-authored-by: Marcin Strankowski <74721865+mstrankowski@users.noreply.github.com>
2023-04-06 16:06:03 +02:00
alfresco-build
73f30b7ef2 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-05 15:55:43 +00:00
alfresco-build
4bf58cc99c [maven-release-plugin][skip ci] prepare release 20.137 2023-04-05 15:55:40 +00:00
MohinishSah
d53881d87f Merge pull request #1862 from Alfresco/fix/MNT-22888
MNT-22888: Fix for WikiPages with Link
2023-04-05 15:10:19 +00:00
rrajoria
937601020d MNT-22888: Fix for WikiPages with Link 2023-04-05 18:51:34 +05:30
alfresco-build
429b389b08 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-05 12:28:56 +00:00
alfresco-build
c944f3560c [maven-release-plugin][skip ci] prepare release 20.136 2023-04-05 12:28:53 +00:00
Sara
40ff2558f5 Feature/acs 4718 remove rmi email service (#1843)
* ACS-4718 Remove EmailServiceRemotable.java

* ACS-4718 Remove use of Rmi in SubethaEmailMessage classes

* ACS-4718 Remove Rmi classes called by SubethaEmailMessage classes

* ACS-4718 Remove rmi related classes

* ACS-4718 Cleanup email classes after rmi removal

---------

Co-authored-by: pzurek <Piotr.Zurek@hyland.com>
2023-04-05 12:47:30 +01:00
Tom Page
4f69f28586 ACS-4932 Fix issues around renaming tags. (#1847)
* ACS-4932 Rename tag node without the id changing.

* ACS-4932 Use fake tag to fire events for all nodes.

* ACS-4932 Use event generator to create events for renamed tags.

* ACS-4932 Fix unit test.

* ACS-4932 Fix tag update tests.

* ACS-4932 Tag names are always lower case.

* ACS-4932 Update TAS tag tests to use lowercase tag names.
2023-04-05 11:37:16 +01:00
alfresco-build
aa66dd748f [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-05 07:07:10 +00:00
alfresco-build
bf9c8ab870 [maven-release-plugin][skip ci] prepare release 20.135 2023-04-05 07:07:07 +00:00
Kacper Magdziarz
959cf8f13f Feature/acs 4462 mtls e2e test (#1861)
ACS-4462 add empty response handling
2023-04-05 08:22:25 +02:00
alfresco-build
8b4285afbd [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-05 05:19:09 +00:00
alfresco-build
7143f5975f [maven-release-plugin][skip ci] prepare release 20.134 2023-04-05 05:19:05 +00:00
Piotr Żurek
31944bfc0f ACS-4971 Restore IDS public client configuration (#1860) 2023-04-05 06:30:26 +02:00
alfresco-build
c874fa4e51 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-04 13:19:36 +00:00
alfresco-build
5780871f0c [maven-release-plugin][skip ci] prepare release 20.133 2023-04-04 13:19:33 +00:00
kcichonczyk
85ef347dc3 [ACS-4839] bump ATS versions (#1859) 2023-04-04 14:34:18 +02:00
Domenico Sibilio
0a76858778 ACS-4970 Bump json-path to 2.8.0 and json-smart to 2.4.10 (#1854) 2023-04-04 14:03:18 +02:00
alfresco-build
6db6245e53 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-04 08:13:27 +00:00
alfresco-build
7b572a3e02 [maven-release-plugin][skip ci] prepare release 20.132 2023-04-04 08:13:24 +00:00
Piotr Żurek
b1cbebacc3 ACS-4891 Configurable Public Key Cache (#1858) 2023-04-04 09:25:22 +02:00
alfresco-build
0bbe73aee1 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-03 19:15:09 +00:00
alfresco-build
9135fdae8b [maven-release-plugin][skip ci] prepare release 20.131 2023-04-03 19:15:05 +00:00
MohinishSah
0cb0cfa8f6 Merge pull request #1857 from Alfresco/ACA-4689
added the new email template
2023-04-03 16:46:48 +00:00
alfresco-build
5a96cce5bb [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-03 16:20:26 +00:00
alfresco-build
c999fb25b9 [maven-release-plugin][skip ci] prepare release 20.130 2023-04-03 16:20:23 +00:00
Mohinish Sah
3c2643dbf2 added the new email template 2023-04-03 21:09:46 +05:30
Piotr Żurek
106e398393 ACS-4895 Restore support for providing IDS public key (#1856) 2023-04-03 17:35:14 +02:00
MichalKinas
0612d74c68 ACS-4966 Correct path check 2023-04-03 16:46:22 +02:00
MichalKinas
eb6157ed2a ACS-4966 Move category creation to data preparation step 2023-04-03 15:55:06 +02:00
MichalKinas
72a573c090 ACS-4966 Rest tests expect correct path 2023-04-03 15:45:59 +02:00
MichalKinas
13e3369a7f ACS-4966 Add path to RestCategoryModel, fix path tests 2023-04-03 13:12:51 +02:00
MichalKinas
444de08f91 ACS-4966 Add REST tests 2023-04-03 12:08:12 +02:00
alfresco-build
1c45748f9a [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-03 09:15:11 +00:00
alfresco-build
2b7ff213a9 [maven-release-plugin][skip ci] prepare release 20.129 2023-04-03 09:15:08 +00:00
Piotr Żurek
f693c49e87 ACS-4893 ACS-4890 Restore connection/TLS/mTLS IDS configuration (#1853)
* Unify http client for all IDS related activities
* Restore connection configuration
* Restore TLS/mTLS configuration
2023-04-03 10:30:01 +02:00
MichalKinas
5f5c377532 ACS-4966 Add option to include path for other endpoints, add unit tests covering path param 2023-04-03 10:12:54 +02:00
alfresco-build
0f156ba259 [maven-release-plugin][skip ci] prepare for next development iteration 2023-04-02 00:06:41 +00:00
alfresco-build
31a0a51290 [maven-release-plugin][skip ci] prepare release 20.128 2023-04-02 00:06:38 +00:00
Alfresco CI User
c8fe044993 [force] Force release for 2023-04-02. 2023-04-02 00:03:22 +00:00
alfresco-build
28058864e6 [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-31 14:13:44 +00:00
alfresco-build
23ccb397f4 [maven-release-plugin][skip ci] prepare release 20.127 2023-03-31 14:13:40 +00:00
Piotr Żurek
73ae0d0a6e ACS-4847 Remove Keycloak dependencies (#1848) 2023-03-31 15:28:14 +02:00
alfresco-build
f9b5e5a6fe [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-31 10:27:19 +00:00
alfresco-build
e5bfb0298d [maven-release-plugin][skip ci] prepare release 20.126 2023-03-31 10:27:16 +00:00
Piotr Żurek
34cb9bf76a ACS-4847 Bump AOS module (#1846) 2023-03-31 10:38:09 +02:00
alfresco-build
fcbd406170 [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-30 12:26:47 +00:00
alfresco-build
730ab768e9 [maven-release-plugin][skip ci] prepare release 20.125 2023-03-30 12:26:43 +00:00
Kacper Magdziarz
fab591eb9b [ACS-4459] Investigate and extend/universalize current custom Solr mTLS implementation in Repository (#1735)
* ACS-4459 Add new HttpClient Factory for Mutual TLS and implement it for Transform Service
* ACS-4462 Add e2e for MTLS
2023-03-30 13:43:42 +02:00
MichalKinas
f1561504cd ACS-4966 Add option to include path while fetching Categories 2023-03-29 16:22:48 +02:00
alfresco-build
5bb96729fc [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-29 13:04:41 +00:00
alfresco-build
a80f2c4db7 [maven-release-plugin][skip ci] prepare release 20.124 2023-03-29 13:04:38 +00:00
Piotr Żurek
82df7ce5d4 ACS-4847 Expose authorization code and refresh token grant types for the AOS (#1836) 2023-03-29 14:16:08 +02:00
alfresco-build
73a1de37f6 [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-29 11:22:30 +00:00
alfresco-build
63f9a8e142 [maven-release-plugin][skip ci] prepare release 20.123 2023-03-29 11:22:25 +00:00
rrajoria
f668ed9198 Updating webscript version 2023-03-29 15:33:18 +05:30
alfresco-build
ea15673116 [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-29 08:46:12 +00:00
alfresco-build
6a2a298445 [maven-release-plugin][skip ci] prepare release 20.122 2023-03-29 08:46:08 +00:00
pksingh41
4b0a6d27f9 Merge pull request #1833 from Alfresco/ACS-4636-CreateTagCountParamSupport
[ACS-4636] create tag count param support
2023-03-29 13:26:45 +05:30
Praveen Singh
b432fdc6a3 Addressed review comments 2023-03-29 11:17:00 +05:30
alfresco-build
7d62c89708 [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-28 11:09:25 +00:00
alfresco-build
e79fcf64a5 [maven-release-plugin][skip ci] prepare release 20.121 2023-03-28 11:09:22 +00:00
kcichonczyk
5df4cfff58 [ACS-4929][ACS-4927] transform-service and transform-core version bump (#1837) 2023-03-28 11:42:33 +02:00
alfresco-build
66ab0c4f46 [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-28 07:41:54 +00:00
alfresco-build
1d1252438c [maven-release-plugin][skip ci] prepare release 20.120 2023-03-28 07:41:50 +00:00
MohinishSah
e4ac036f9f Merge pull request #1609 from Alfresco/feature/ACA-4619-Self-service-User-password-reset-ADW
Feature/aca 4619 self service user password reset adw
2023-03-28 06:56:49 +00:00
suneet.gupta
a9ec842358 Merge branch 'master' of github.com:Alfresco/alfresco-community-repo into ACS-4636-CreateTagCountParamSupport 2023-03-28 12:18:42 +05:30
alfresco-build
9590051941 [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-27 17:12:19 +00:00
alfresco-build
37618bd56a [maven-release-plugin][skip ci] prepare release 20.119 2023-03-27 17:12:14 +00:00
Tom Page
8bb30643d4 Merge pull request #1790 from Alfresco/feature/ACS-4779-Count_isssue_for_GET_call
ACS-4779:Count field issue for GET call
2023-03-27 17:23:27 +01:00
Tom Page
f0e0819bc5 ACS-4779 Remove failing integration test.
There is no way that the changes to TagsImpl should have affected shared links and so this
test must be failing due to interactions with other tests (e.g. a change in ordering, or
unexpected data in the system).

Notably a comment above the test suggests it may be duplicated by testSharedLinkCreateGetDelete
(which is another unweildy test that covers a large number of difference scenarios). The two
tests definitely contain a large amount of duplicated code.
2023-03-27 16:32:13 +01:00
suneet.gupta
5999a448d4 Merge branch 'master' of github.com:Alfresco/alfresco-community-repo into ACS-4636-CreateTagCountParamSupport 2023-03-27 13:57:30 +05:30
Mohinish Sah
8f00b44a03 Merge remote-tracking branch 'origin/master' into feature/ACA-4619-Self-service-User-password-reset-ADW 2023-03-27 13:07:01 +05:30
alfresco-build
c0d1b33201 [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-26 00:06:25 +00:00
alfresco-build
4053daaf1a [maven-release-plugin][skip ci] prepare release 20.118 2023-03-26 00:06:23 +00:00
Alfresco CI User
6942294780 [force] Force release for 2023-03-26. 2023-03-26 00:03:13 +00:00
Tom Page
384177a9d9 Merge pull request #1826 from Alfresco/feature/ACS-4863_ValidateNodeWithoutPath
ACS-4863 Add method validateOrLookupNode without path.
2023-03-24 13:53:44 +00:00
alfresco-build
bbdeb5ae97 [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-24 12:17:17 +00:00
alfresco-build
95fb286c14 [maven-release-plugin][skip ci] prepare release 20.117 2023-03-24 12:17:14 +00:00
Tom Page
0652cea296 ACS-4863 Move new validation method to interface as a default implementation. 2023-03-24 11:44:55 +00:00
Tom Page
a86a954771 Merge pull request #1829 from Alfresco/feature/ACS-4863_InvestigateTestFailure
ACS-4863 Restore code to allow aliases in tag and category APIs.
2023-03-24 11:37:15 +00:00
Tom Page
c27a44d711 ACS-4863 Remove test for invalid URL.
This test behaves differently against community and enterprise as the double slash is treated differently.
2023-03-24 10:16:28 +00:00
Krystian Dabrowski
ef089472fb ACS-4915: Editing an orphaned tag results in the tag being deleted (#1823)
* ACS-4915: Editing an orphaned tag results in the tag being deleted
2023-03-24 10:55:12 +01:00
alfresco-build
5769cbe54e [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-24 09:03:52 +00:00
alfresco-build
9899f16d61 [maven-release-plugin][skip ci] prepare release 20.116 2023-03-24 09:03:48 +00:00
Tom Page
219acd6c53 Revert "Revert "ACS-4863 Allow referencing nodes by aliases for tag and category application. (#1822)""
This reverts commit 70b7d5a1f8.
2023-03-24 08:21:11 +00:00
Tom Page
70b7d5a1f8 Revert "ACS-4863 Allow referencing nodes by aliases for tag and category application. (#1822)"
This reverts commit dafa77d0a0.
2023-03-24 08:20:50 +00:00
alfresco-build
279679d78a [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-24 07:03:42 +00:00
alfresco-build
6d1dcf6c7e [maven-release-plugin][skip ci] prepare release 20.115 2023-03-24 07:03:39 +00:00
suneet.gupta
18810de7d0 Merge branch 'master' of github.com:Alfresco/alfresco-community-repo into ACS-4636-CreateTagCountParamSupport 2023-03-24 08:15:46 +05:30
Piotr Żurek
fb119565dc ACS-4888 Use Keycloak free tas-utility (#1827) 2023-03-23 18:29:19 +01:00
Tom Page
10b0d7b5f0 ACS-4863 Ensure we don't accidentally introduce circular reference. 2023-03-23 16:01:07 +00:00
Tom Page
36292d749e ACS-4779 Simplify list creation in test. 2023-03-23 13:58:45 +00:00
Tom Page
c1d424b386 Merge master into ACS-4779-Count_isssue_for_GET_call. 2023-03-23 13:56:54 +00:00
Tom Page
06c6efc6c9 ACS-4779 Remove duplicate @BeforeClass method. 2023-03-23 13:51:47 +00:00
suneet.gupta
626e5b34ef [ACS-4636] Added count support for creation of tags to a node 2023-03-23 18:35:12 +05:30
Tom Page
a549859cbe ACS-4863 Add method validateOrLookupNode without path. 2023-03-23 09:11:48 +00:00
alfresco-build
f2d858f911 [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-22 17:39:49 +00:00
alfresco-build
808a7c67b7 [maven-release-plugin][skip ci] prepare release 20.114 2023-03-22 17:39:45 +00:00
Tom Page
dafa77d0a0 ACS-4863 Allow referencing nodes by aliases for tag and category application. (#1822) 2023-03-22 16:54:01 +00:00
Tom Page
fd96c90c08 ACS-4779 Remove test for unsupported use case. 2023-03-22 16:02:55 +00:00
Tom Page
a41fcdff0f ACS-4779 Ensure we only include the count for tags in the GET response when requested. 2023-03-22 15:18:37 +00:00
Tom Page
ab461e34af ACS-4779 Tidy test class. 2023-03-22 14:48:01 +00:00
Tom Page
c92ef4393c Merge master into feature branch. 2023-03-22 14:46:15 +00:00
alfresco-build
ebdc9e159e [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-22 13:30:35 +00:00
alfresco-build
d885c47df7 [maven-release-plugin][skip ci] prepare release 20.113 2023-03-22 13:30:31 +00:00
Piotr Żurek
a1ccc14a93 ACS- 4752 keycloak migration - resource server role (#1818) 2023-03-22 12:58:13 +01:00
alfresco-build
0023612623 [maven-release-plugin][skip ci] prepare for next development iteration 2023-03-22 10:54:12 +00:00
rrajoria
9ddbda377d Test Case for Client Workspace and changes for Review comments 2023-03-22 12:56:45 +05:30
adam.zakrzewski
267bd98d21 ACS-4779: Adding update for tests after Tome's review 2023-03-08 16:14:21 +01:00
adam.zakrzewski
bcaeedb162 ACS-4779:Count field exists in response for get list of tags even when that field is not included. Other issue is that count field is not present when we do GET call with included count for /tags/{tagId} 2023-03-08 14:39:47 +01:00
adam.zakrzewski
f93bced905 ACS-4779:Count field exists in response for get list of tags even when that field is not included. Other issue is that count field is not present when we do GET call with included count for /tags/{tagId} 2023-03-08 14:27:16 +01:00
Mohinish Sah
91f3edf8e9 incorporated review comments 2023-03-02 22:10:54 +05:30
Mohinish Sah
479724365e incorporated review comments 2023-03-02 22:04:50 +05:30
Mohinish Sah
bb1d5899d9 Merge remote-tracking branch 'origin/master' into feature/ACA-4619-Self-service-User-password-reset-ADW 2023-03-02 21:46:53 +05:30
Mohinish Sah
7ab5e8afd0 Updated the client App name 2023-03-01 18:45:08 +05:30
Mohinish Sah
5107fdfe41 resolved review comments 2023-03-01 12:45:15 +05:30
Mohinish Sah
f59ff23a45 Rebase Branch 2022-12-08 16:26:44 +05:30
rrajoria
5e2f1db714 ACA-4619: Forgot Password Changes 2022-12-08 16:21:29 +05:30
rrajoria
67ee2efc60 ACA-4619: Forgot Password Changes 2022-12-08 16:21:29 +05:30
MohinishSah
1e7dc6ed8d update Gdrive version 2022-11-14 10:54:40 +05:30
rrajoria
e5ea6db30c ACA-4619: Forgot Password Changes 2022-11-09 18:11:16 +05:30
rrajoria
78a613b1de ACA-4619: Forgot Password Changes 2022-11-09 18:10:29 +05:30
131 changed files with 6548 additions and 5508 deletions

View File

@@ -53,24 +53,6 @@ updates:
- dependency-name: org.freemarker:freemarker
versions:
- "> 2.3.20-alfresco-patched-20200421"
- dependency-name: org.keycloak:keycloak-adapter-core
versions:
- "> 12.0.2"
- dependency-name: org.keycloak:keycloak-adapter-spi
versions:
- "> 12.0.2"
- dependency-name: org.keycloak:keycloak-authz-client
versions:
- "> 12.0.2"
- dependency-name: org.keycloak:keycloak-common
versions:
- "> 12.0.2"
- dependency-name: org.keycloak:keycloak-core
versions:
- "> 12.0.2"
- dependency-name: org.keycloak:keycloak-servlet-adapter-spi
versions:
- "> 12.0.2"
- dependency-name: org.eclipse.jetty:jetty-server
versions:
- 9.4.38.v20210224

View File

@@ -23,6 +23,7 @@ env:
MAVEN_USERNAME: ${{ secrets.NEXUS_USERNAME }}
QUAY_PASSWORD: ${{ secrets.QUAY_PASSWORD }}
QUAY_USERNAME: ${{ secrets.QUAY_USERNAME }}
CI_WORKSPACE: ${{ github.workspace }}
TAS_ENVIRONMENT: ./packaging/tests/environment
TAS_SCRIPTS: ../alfresco-community-repo/packaging/tests/scripts
@@ -313,6 +314,11 @@ jobs:
- testSuite: SearchTestSuite
compose-profile: default
mvn-options: '-Dindex.subsystem.name=solr6'
- testSuite: MTLSTestSuite
compose-profile: with-mtls-transform-core-aio
mtls: true
disabledHostnameVerification: false
mvn-options: '-Dencryption.ssl.keystore.location=${CI_WORKSPACE}/keystores/alfresco/alfresco.keystore -Dencryption.ssl.truststore.location=${CI_WORKSPACE}/keystores/alfresco/alfresco.truststore'
steps:
- uses: actions/checkout@v3
- uses: Alfresco/alfresco-build-tools/.github/actions/get-build-info@v1.33.0
@@ -321,6 +327,17 @@ jobs:
run: bash ./scripts/ci/init.sh
- name: "Set transformers tag"
run: echo "TRANSFORMERS_TAG=$(mvn help:evaluate -Dexpression=dependency.alfresco-transform-core.version -q -DforceStdout)" >> $GITHUB_ENV
- name: "Generate Keystores and Truststores for Mutual TLS configuration"
if: ${{ matrix.mtls }}
run: |
git clone -b "master" --depth=1 "https://${{ secrets.BOT_GITHUB_USERNAME }}:${{ secrets.BOT_GITHUB_TOKEN }}@github.com/Alfresco/alfresco-ssl-generator.git"
if ${{ matrix.disabledHostnameVerification }} ; then
bash ${{ env.CI_WORKSPACE }}/alfresco-ssl-generator/scripts/ci/generate_keystores_wrong_hostnames.sh
echo "HOSTNAME_VERIFICATION_DISABLED=true" >> "$GITHUB_ENV"
else
bash ${{ env.CI_WORKSPACE }}/alfresco-ssl-generator/scripts/ci/generate_keystores.sh
echo "HOSTNAME_VERIFICATION_DISABLED=false" >> "$GITHUB_ENV"
fi
- name: "Set up the environment"
run: |
if [ -e ./scripts/ci/tests/${{ matrix.testSuite }}-setup.sh ]; then

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo-amps</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<modules>

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-governance-services-community-parent</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<modules>

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-governance-services-automation-community-repo</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<build>
@@ -82,7 +82,7 @@
<dependency>
<groupId>com.github.docker-java</groupId>
<artifactId>docker-java</artifactId>
<version>3.2.13</version>
<version>3.3.0</version>
</dependency>
</dependencies>
</project>

View File

@@ -50,6 +50,7 @@ import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.junit.Ignore;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.AssertJUnit;
import org.testng.annotations.BeforeClass;
@@ -135,192 +136,195 @@ public class DispositionScheduleLinkedRecordsTest extends BaseRMRestTest {
* <p>
* <p/> TestRail Test C775<p/>
**/
@Test
@AlfrescoTest(jira = "RM-1622")
public void dispositionScheduleLinkedRecords() throws UnsupportedEncodingException {
STEP("Create record category");
Category1 = createRootCategory(categoryRM3077);
// @Ignore("ACS-5020")
// @Test
// @AlfrescoTest(jira = "RM-1622")
// public void dispositionScheduleLinkedRecords() throws UnsupportedEncodingException {
// STEP("Create record category");
// Category1 = createRootCategory(categoryRM3077);
//
// //create retention schedule
// dispositionScheduleService.createCategoryRetentionSchedule(Category1.getName(), false);
//
// // add cut off step
// dispositionScheduleService.addCutOffAfterPeriodStep(Category1.getName(), "day|2", CREATED_DATE);
//
// //create a copy of the category recordsCategory
// String CopyCategoryId = copyCategory(getAdminUser(),Category1.getId(), copyCategoryRM3077);
//
// // create folders in both categories
// CatFolder = createRecordFolder(Category1.getId(), folderRM3077);
// CopyCatFolder = createRecordFolder(CopyCategoryId, copyFolderRM3077);
//
// // create record files
// String electronicRecord = "RM-2801 electronic record";
// Record elRecord = createElectronicRecord(CatFolder.getId(), electronicRecord);
// String elRecordFullName = recordsAPI.getRecordFullName(getDataUser().usingAdmin().getAdminUser().getUsername(),
// getDataUser().usingAdmin().getAdminUser().getPassword(), CatFolder.getName(), electronicRecord);
//
// String nonElectronicRecord = "RM-2801 non-electronic record";
// Record nonElRecord = createNonElectronicRecord(CatFolder.getId(), nonElectronicRecord);
// String nonElRecordFullName = recordsAPI.getRecordFullName(getDataUser().usingAdmin().getAdminUser().getUsername(),
// getDataUser().usingAdmin().getAdminUser().getPassword(), CatFolder.getName(), nonElectronicRecord);
//
// // link the records to copy folder, then complete them
// List<String> recordLists = new ArrayList<>();
// recordLists.add(NODE_REF_WORKSPACE_SPACES_STORE + elRecord.getId());
// recordLists.add(NODE_REF_WORKSPACE_SPACES_STORE + nonElRecord.getId());
//
// linksAPI.linkRecord(getDataUser().getAdminUser().getUsername(),
// getDataUser().getAdminUser().getPassword(), HttpStatus.SC_OK,copyCategoryRM3077 + "/" +
// copyFolderRM3077, recordLists);
// recordsAPI.completeRecord(rmAdmin.getUsername(), rmAdmin.getPassword(), elRecordFullName);
// recordsAPI.completeRecord(rmAdmin.getUsername(), rmAdmin.getPassword(), nonElRecordFullName);
//
// // edit disposition date
// recordFoldersAPI.postFolderAction(getAdminUser().getUsername(),
// getAdminUser().getPassword(),editDispositionDateJson(),CatFolder.getName());
//
// // cut off the Folder
// recordFoldersAPI.postFolderAction(getAdminUser().getUsername(),
// getAdminUser().getPassword(),new JSONObject().put("name","cutoff"),CatFolder.getName());
//
// // Verify the Content
// Node electronicNode = getNode(elRecord.getId());
// assertTrue("The content of " + electronicRecord + " is available",
// StringUtils.isEmpty(electronicNode.getNodeContent().getResponse().getBody().asString()));
//
// // verify the Properties
// AssertJUnit.assertNull("The properties are present even after cutting off the record.", elRecord.getProperties().getTitle());
//
// // delete precondition
// deleteRecordCategory(Category1.getId());
// deleteRecordCategory(CopyCategoryId);
// }
// /**
// * Test covering RM-3060
// * Check the disposition steps for a record can be executed
// * When the record is linked to a folder with the same disposition schedule
// * */
// @Ignore("ACS-5020")
//// @Test
// @AlfrescoTest (jira = "RM-3060")
// public void sameDispositionScheduleLinkedRecords() throws UnsupportedEncodingException {
//
// // create a category with retention applied on records level
// RecordCategory recordCategory = getRestAPIFactory().getFilePlansAPI(rmAdmin)
// .createRootRecordCategory(RecordCategory.builder().name(firstCategoryRM3060).build(),
// RecordCategory.DEFAULT_FILE_PLAN_ALIAS);
// dispositionScheduleService.createCategoryRetentionSchedule(firstCategoryRM3060, true);
// dispositionScheduleService.addCutOffAfterPeriodStep(firstCategoryRM3060, "week|1", DATE_FILED);
// dispositionScheduleService.addTransferAfterEventStep(firstCategoryRM3060, TRANSFER_LOCATION, RMEvents.CASE_CLOSED.getEventName());
// dispositionScheduleService.addDestroyWithoutGhostingAfterPeriodStep(firstCategoryRM3060, "week|1", CUT_OFF_DATE);
//
// // make a copy of the category created
// String categorySecondId = copyCategory(getAdminUser(), recordCategory.getId(), secondCategoryRM3060);
//
// // create a folder on the category firstCategoryRM3060 with a complete electronic record
// RecordCategoryChild firstFolderRecordCategoryChild = createRecordFolder(recordCategory.getId(),firstFolderRM3060);
// Record firstElectronicRecord = createElectronicRecord(firstFolderRecordCategoryChild.getId(),electronicRecordRM3060);
//
// String elRecordFullName = recordsAPI.getRecordFullName(getDataUser().getAdminUser().getUsername(),
// getDataUser().getAdminUser().getPassword(),firstFolderRM3060, electronicRecordRM3060);
// String elRecordNameNodeRef = recordsAPI.getRecordNodeRef(getDataUser().usingAdmin().getAdminUser().getUsername(),
// getDataUser().usingAdmin().getAdminUser().getPassword(), elRecordFullName, "/" + firstCategoryRM3060 + "/" + firstFolderRM3060);
//
// recordsAPI.completeRecord(getDataUser().getAdminUser().getUsername(),
// getDataUser().getAdminUser().getPassword(), elRecordFullName);
//
// // create a folder on the category secondCategoryRM3060 with a non electronic record
// RecordCategoryChild secondFolderRecordCategoryChild = createRecordFolder(categorySecondId,secondFolderRM3060);
// Record secondNonElectronicRecord = createNonElectronicRecord(secondFolderRecordCategoryChild.getId(),nonElectronicRecordRM3060);
//
// // link the nonElectronicRecordRM3060 to firstFolderRM3060
// List<String> recordLists = new ArrayList<>();
// recordLists.add(NODE_REF_WORKSPACE_SPACES_STORE + secondNonElectronicRecord.getId());
//
// linksAPI.linkRecord(getDataUser().getAdminUser().getUsername(),
// getDataUser().getAdminUser().getPassword(), HttpStatus.SC_OK,secondCategoryRM3060 + "/" +
// secondFolderRM3060, recordLists);
// String nonElRecordFullName = recordsAPI.getRecordFullName(getDataUser().usingAdmin().getAdminUser().getUsername(),
// getDataUser().usingAdmin().getAdminUser().getPassword(), secondFolderRM3060, secondNonElectronicRecord.getName());
// String nonElRecordNameNodeRef = recordsAPI.getRecordNodeRef(getDataUser().usingAdmin().getAdminUser().getUsername(),
// getDataUser().usingAdmin().getAdminUser().getPassword(), nonElRecordFullName, "/" + secondCategoryRM3060 + "/" + secondFolderRM3060);
//
// // complete records and cut them off
// recordsAPI.completeRecord(getDataUser().getAdminUser().getUsername(),
// getDataUser().getAdminUser().getPassword(), nonElRecordFullName);
//
// // edit the disposition date
// recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
// getAdminUser().getPassword(),editDispositionDateJson(),nonElRecordNameNodeRef);
//
// // cut off the record
// recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
// getAdminUser().getPassword(),new JSONObject().put("name","cutoff"),nonElRecordNameNodeRef);
//
// //check the record is cut off
// AssertJUnit.assertTrue("The file " + nonElectronicRecordRM3060 + " has not been successfully cut off.", getRestAPIFactory().getRecordsAPI().getRecord(secondNonElectronicRecord.getId()).getAspectNames().contains(CUT_OFF_ASPECT));
//
// // link the electronic record to secondFolderRM3060
// recordLists.clear();
// recordLists.add(NODE_REF_WORKSPACE_SPACES_STORE + secondNonElectronicRecord.getId());
// linksAPI.linkRecord(getDataUser().getAdminUser().getUsername(),
// getDataUser().getAdminUser().getPassword(), HttpStatus.SC_OK,secondCategoryRM3060 + "/" +
// secondFolderRM3060, recordLists);
//
// // edit the disposition date and cut off the record
// recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
// getAdminUser().getPassword(),editDispositionDateJson(),elRecordNameNodeRef);
// recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
// getAdminUser().getPassword(),new JSONObject().put("name","cutoff"),elRecordNameNodeRef);
//
// AssertJUnit.assertTrue("The file " + electronicRecordRM3060 + " has not been successfully cut off.", getRestAPIFactory().getRecordsAPI().getRecord(firstElectronicRecord.getId()).getAspectNames().contains(CUT_OFF_ASPECT));
//
// // open the record and complete the disposition schedule event
// rmRolesAndActionsAPI.completeEvent(getAdminUser().getUsername(),
// getAdminUser().getPassword(), elRecordFullName, RMEvents.CASE_CLOSED, Instant.now());
// rmRolesAndActionsAPI.completeEvent(getAdminUser().getUsername(),
// getAdminUser().getPassword(), nonElRecordFullName, RMEvents.CASE_CLOSED, Instant.now());
//
// // transfer the files & complete transfers
// HttpResponse nonElRecordNameHttpResponse = recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
// getAdminUser().getPassword(),new JSONObject().put("name","transfer"),recordsAPI.getRecordNodeRef(getDataUser().usingAdmin().getAdminUser().getUsername(),
// getDataUser().usingAdmin().getAdminUser().getPassword(), nonElRecordFullName, "/" + secondCategoryRM3060 + "/" + secondFolderRM3060));
//
// String nonElRecordNameTransferId = getTransferId(nonElRecordNameHttpResponse,nonElRecordNameNodeRef);
// recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
// getAdminUser().getPassword(),new JSONObject().put("name","transferComplete"),nonElRecordNameTransferId);
//
// HttpResponse elRecordNameHttpResponse = recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
// getAdminUser().getPassword(),new JSONObject().put("name","transfer"),recordsAPI.getRecordNodeRef(getDataUser().usingAdmin().getAdminUser().getUsername(),
// getDataUser().usingAdmin().getAdminUser().getPassword(), elRecordFullName, "/" + firstCategoryRM3060 + "/" + firstFolderRM3060));
//
// String elRecordNameTransferId = getTransferId(elRecordNameHttpResponse,elRecordNameNodeRef);
// recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
// getAdminUser().getPassword(),new JSONObject().put("name","transferComplete"),elRecordNameTransferId);
//
// AssertJUnit.assertTrue("The file " + electronicRecordRM3060 + " has not been successfully transferred", getRestAPIFactory().getRecordsAPI().getRecord(firstElectronicRecord.getId()).getAspectNames().contains(TRANSFER_TYPE));
// AssertJUnit.assertTrue("The file " + nonElectronicRecordRM3060 + " has not been successfully transferred.", getRestAPIFactory().getRecordsAPI().getRecord(secondNonElectronicRecord.getId()).getAspectNames().contains(TRANSFER_TYPE));
//
// // edit the disposition date for nonElectronicRecordRM3060 & electronicRecordRM3060
// recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
// getAdminUser().getPassword(),editDispositionDateJson(),nonElRecordNameNodeRef);
// recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
// getAdminUser().getPassword(),editDispositionDateJson(),elRecordNameNodeRef);
//
// // destroy nonElectronicRecordRM3060 & electronicRecordRM3060 records
// recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
// getAdminUser().getPassword(),new JSONObject().put("name","destroy"),nonElRecordNameNodeRef);
// recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
// getAdminUser().getPassword(),new JSONObject().put("name","destroy"),elRecordNameNodeRef);
//
// // check the file is not displayed
// assertNull("The file " + nonElectronicRecordRM3060 + " has not been successfully destroyed.", secondNonElectronicRecord.getContent());
// assertNull("The file " + electronicRecordRM3060 + " has not been successfully destroyed.", firstElectronicRecord.getContent());
//
// // delete precondition
// deleteRecordCategory(recordCategory.getId());
// deleteRecordCategory(categorySecondId);
// }
//create retention schedule
dispositionScheduleService.createCategoryRetentionSchedule(Category1.getName(), false);
// add cut off step
dispositionScheduleService.addCutOffAfterPeriodStep(Category1.getName(), "day|2", CREATED_DATE);
//create a copy of the category recordsCategory
String CopyCategoryId = copyCategory(getAdminUser(),Category1.getId(), copyCategoryRM3077);
// create folders in both categories
CatFolder = createRecordFolder(Category1.getId(), folderRM3077);
CopyCatFolder = createRecordFolder(CopyCategoryId, copyFolderRM3077);
// create record files
String electronicRecord = "RM-2801 electronic record";
Record elRecord = createElectronicRecord(CatFolder.getId(), electronicRecord);
String elRecordFullName = recordsAPI.getRecordFullName(getDataUser().usingAdmin().getAdminUser().getUsername(),
getDataUser().usingAdmin().getAdminUser().getPassword(), CatFolder.getName(), electronicRecord);
String nonElectronicRecord = "RM-2801 non-electronic record";
Record nonElRecord = createNonElectronicRecord(CatFolder.getId(), nonElectronicRecord);
String nonElRecordFullName = recordsAPI.getRecordFullName(getDataUser().usingAdmin().getAdminUser().getUsername(),
getDataUser().usingAdmin().getAdminUser().getPassword(), CatFolder.getName(), nonElectronicRecord);
// link the records to copy folder, then complete them
List<String> recordLists = new ArrayList<>();
recordLists.add(NODE_REF_WORKSPACE_SPACES_STORE + elRecord.getId());
recordLists.add(NODE_REF_WORKSPACE_SPACES_STORE + nonElRecord.getId());
linksAPI.linkRecord(getDataUser().getAdminUser().getUsername(),
getDataUser().getAdminUser().getPassword(), HttpStatus.SC_OK,copyCategoryRM3077 + "/" +
copyFolderRM3077, recordLists);
recordsAPI.completeRecord(rmAdmin.getUsername(), rmAdmin.getPassword(), elRecordFullName);
recordsAPI.completeRecord(rmAdmin.getUsername(), rmAdmin.getPassword(), nonElRecordFullName);
// edit disposition date
recordFoldersAPI.postFolderAction(getAdminUser().getUsername(),
getAdminUser().getPassword(),editDispositionDateJson(),CatFolder.getName());
// cut off the Folder
recordFoldersAPI.postFolderAction(getAdminUser().getUsername(),
getAdminUser().getPassword(),new JSONObject().put("name","cutoff"),CatFolder.getName());
// Verify the Content
Node electronicNode = getNode(elRecord.getId());
assertTrue("The content of " + electronicRecord + " is available",
StringUtils.isEmpty(electronicNode.getNodeContent().getResponse().getBody().asString()));
// verify the Properties
AssertJUnit.assertNull("The properties are present even after cutting off the record.", elRecord.getProperties().getTitle());
// delete precondition
deleteRecordCategory(Category1.getId());
deleteRecordCategory(CopyCategoryId);
}
/**
* Test covering RM-3060
* Check the disposition steps for a record can be executed
* When the record is linked to a folder with the same disposition schedule
* */
@Test
@AlfrescoTest (jira = "RM-3060")
public void sameDispositionScheduleLinkedRecords() throws UnsupportedEncodingException {
// create a category with retention applied on records level
RecordCategory recordCategory = getRestAPIFactory().getFilePlansAPI(rmAdmin)
.createRootRecordCategory(RecordCategory.builder().name(firstCategoryRM3060).build(),
RecordCategory.DEFAULT_FILE_PLAN_ALIAS);
dispositionScheduleService.createCategoryRetentionSchedule(firstCategoryRM3060, true);
dispositionScheduleService.addCutOffAfterPeriodStep(firstCategoryRM3060, "week|1", DATE_FILED);
dispositionScheduleService.addTransferAfterEventStep(firstCategoryRM3060, TRANSFER_LOCATION, RMEvents.CASE_CLOSED.getEventName());
dispositionScheduleService.addDestroyWithoutGhostingAfterPeriodStep(firstCategoryRM3060, "week|1", CUT_OFF_DATE);
// make a copy of the category created
String categorySecondId = copyCategory(getAdminUser(), recordCategory.getId(), secondCategoryRM3060);
// create a folder on the category firstCategoryRM3060 with a complete electronic record
RecordCategoryChild firstFolderRecordCategoryChild = createRecordFolder(recordCategory.getId(),firstFolderRM3060);
Record firstElectronicRecord = createElectronicRecord(firstFolderRecordCategoryChild.getId(),electronicRecordRM3060);
String elRecordFullName = recordsAPI.getRecordFullName(getDataUser().getAdminUser().getUsername(),
getDataUser().getAdminUser().getPassword(),firstFolderRM3060, electronicRecordRM3060);
String elRecordNameNodeRef = recordsAPI.getRecordNodeRef(getDataUser().usingAdmin().getAdminUser().getUsername(),
getDataUser().usingAdmin().getAdminUser().getPassword(), elRecordFullName, "/" + firstCategoryRM3060 + "/" + firstFolderRM3060);
recordsAPI.completeRecord(getDataUser().getAdminUser().getUsername(),
getDataUser().getAdminUser().getPassword(), elRecordFullName);
// create a folder on the category secondCategoryRM3060 with a non electronic record
RecordCategoryChild secondFolderRecordCategoryChild = createRecordFolder(categorySecondId,secondFolderRM3060);
Record secondNonElectronicRecord = createNonElectronicRecord(secondFolderRecordCategoryChild.getId(),nonElectronicRecordRM3060);
// link the nonElectronicRecordRM3060 to firstFolderRM3060
List<String> recordLists = new ArrayList<>();
recordLists.add(NODE_REF_WORKSPACE_SPACES_STORE + secondNonElectronicRecord.getId());
linksAPI.linkRecord(getDataUser().getAdminUser().getUsername(),
getDataUser().getAdminUser().getPassword(), HttpStatus.SC_OK,secondCategoryRM3060 + "/" +
secondFolderRM3060, recordLists);
String nonElRecordFullName = recordsAPI.getRecordFullName(getDataUser().usingAdmin().getAdminUser().getUsername(),
getDataUser().usingAdmin().getAdminUser().getPassword(), secondFolderRM3060, secondNonElectronicRecord.getName());
String nonElRecordNameNodeRef = recordsAPI.getRecordNodeRef(getDataUser().usingAdmin().getAdminUser().getUsername(),
getDataUser().usingAdmin().getAdminUser().getPassword(), nonElRecordFullName, "/" + secondCategoryRM3060 + "/" + secondFolderRM3060);
// complete records and cut them off
recordsAPI.completeRecord(getDataUser().getAdminUser().getUsername(),
getDataUser().getAdminUser().getPassword(), nonElRecordFullName);
// edit the disposition date
recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
getAdminUser().getPassword(),editDispositionDateJson(),nonElRecordNameNodeRef);
// cut off the record
recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
getAdminUser().getPassword(),new JSONObject().put("name","cutoff"),nonElRecordNameNodeRef);
//check the record is cut off
AssertJUnit.assertTrue("The file " + nonElectronicRecordRM3060 + " has not been successfully cut off.", getRestAPIFactory().getRecordsAPI().getRecord(secondNonElectronicRecord.getId()).getAspectNames().contains(CUT_OFF_ASPECT));
// link the electronic record to secondFolderRM3060
recordLists.clear();
recordLists.add(NODE_REF_WORKSPACE_SPACES_STORE + secondNonElectronicRecord.getId());
linksAPI.linkRecord(getDataUser().getAdminUser().getUsername(),
getDataUser().getAdminUser().getPassword(), HttpStatus.SC_OK,secondCategoryRM3060 + "/" +
secondFolderRM3060, recordLists);
// edit the disposition date and cut off the record
recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
getAdminUser().getPassword(),editDispositionDateJson(),elRecordNameNodeRef);
recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
getAdminUser().getPassword(),new JSONObject().put("name","cutoff"),elRecordNameNodeRef);
AssertJUnit.assertTrue("The file " + electronicRecordRM3060 + " has not been successfully cut off.", getRestAPIFactory().getRecordsAPI().getRecord(firstElectronicRecord.getId()).getAspectNames().contains(CUT_OFF_ASPECT));
// open the record and complete the disposition schedule event
rmRolesAndActionsAPI.completeEvent(getAdminUser().getUsername(),
getAdminUser().getPassword(), elRecordFullName, RMEvents.CASE_CLOSED, Instant.now());
rmRolesAndActionsAPI.completeEvent(getAdminUser().getUsername(),
getAdminUser().getPassword(), nonElRecordFullName, RMEvents.CASE_CLOSED, Instant.now());
// transfer the files & complete transfers
HttpResponse nonElRecordNameHttpResponse = recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
getAdminUser().getPassword(),new JSONObject().put("name","transfer"),recordsAPI.getRecordNodeRef(getDataUser().usingAdmin().getAdminUser().getUsername(),
getDataUser().usingAdmin().getAdminUser().getPassword(), nonElRecordFullName, "/" + secondCategoryRM3060 + "/" + secondFolderRM3060));
String nonElRecordNameTransferId = getTransferId(nonElRecordNameHttpResponse,nonElRecordNameNodeRef);
recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
getAdminUser().getPassword(),new JSONObject().put("name","transferComplete"),nonElRecordNameTransferId);
HttpResponse elRecordNameHttpResponse = recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
getAdminUser().getPassword(),new JSONObject().put("name","transfer"),recordsAPI.getRecordNodeRef(getDataUser().usingAdmin().getAdminUser().getUsername(),
getDataUser().usingAdmin().getAdminUser().getPassword(), elRecordFullName, "/" + firstCategoryRM3060 + "/" + firstFolderRM3060));
String elRecordNameTransferId = getTransferId(elRecordNameHttpResponse,elRecordNameNodeRef);
recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
getAdminUser().getPassword(),new JSONObject().put("name","transferComplete"),elRecordNameTransferId);
AssertJUnit.assertTrue("The file " + electronicRecordRM3060 + " has not been successfully transferred", getRestAPIFactory().getRecordsAPI().getRecord(firstElectronicRecord.getId()).getAspectNames().contains(TRANSFER_TYPE));
AssertJUnit.assertTrue("The file " + nonElectronicRecordRM3060 + " has not been successfully transferred.", getRestAPIFactory().getRecordsAPI().getRecord(secondNonElectronicRecord.getId()).getAspectNames().contains(TRANSFER_TYPE));
// edit the disposition date for nonElectronicRecordRM3060 & electronicRecordRM3060
recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
getAdminUser().getPassword(),editDispositionDateJson(),nonElRecordNameNodeRef);
recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
getAdminUser().getPassword(),editDispositionDateJson(),elRecordNameNodeRef);
// destroy nonElectronicRecordRM3060 & electronicRecordRM3060 records
recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
getAdminUser().getPassword(),new JSONObject().put("name","destroy"),nonElRecordNameNodeRef);
recordFoldersAPI.postRecordAction(getAdminUser().getUsername(),
getAdminUser().getPassword(),new JSONObject().put("name","destroy"),elRecordNameNodeRef);
// check the file is not displayed
assertNull("The file " + nonElectronicRecordRM3060 + " has not been successfully destroyed.", secondNonElectronicRecord.getContent());
assertNull("The file " + electronicRecordRM3060 + " has not been successfully destroyed.", firstElectronicRecord.getContent());
// delete precondition
deleteRecordCategory(recordCategory.getId());
deleteRecordCategory(categorySecondId);
}
private String copyCategory(UserModel user, String categoryId, String copyName) {
RepoTestModel repoTestModel = new RepoTestModel() {};
repoTestModel.setNodeRef(categoryId);

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-governance-services-community-parent</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<modules>

View File

@@ -1,3 +1,3 @@
SOLR6_TAG=2.0.7-A2
SOLR6_TAG=2.0.7-A5
POSTGRES_TAG=14.4
ACTIVEMQ_TAG=5.17.1-jre11-rockylinux8
ACTIVEMQ_TAG=5.17.4-jre17-rockylinux8

View File

@@ -8,7 +8,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-governance-services-community-repo-parent</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<properties>
@@ -436,7 +436,7 @@
</run>
</image>
<image>
<name>alfresco/alfresco-activemq:${dependency.activemq.version}-jre11-rockylinux8</name>
<name>alfresco/alfresco-activemq:${dependency.activemq.version}-jre17-rockylinux8</name>
<run>
<ports>
<port>${activemq.port1}:${activemq.port1}</port>
@@ -507,7 +507,7 @@
</run>
</image>
<image>
<name>alfresco/alfresco-activemq:${dependency.activemq.version}-jre11-rockylinux8</name>
<name>alfresco/alfresco-activemq:${dependency.activemq.version}-jre17-rockylinux8</name>
<run>
<ports>
<port>${activemq.port1}:${activemq.port1}</port>

View File

@@ -3,8 +3,8 @@
#
# Version label
version.major=7
version.minor=4
version.major=23
version.minor=1
version.revision=0
version.label=

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-governance-services-community-repo-parent</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<build>

View File

@@ -38,9 +38,7 @@ tags:
description: Retrieve and manage unfiled records containers
- name: unfiled-record-folders
description: Retrieve and manage unfiled record folders
- name: events
description: Retrieve and manage retention events
paths:
## GS sites
'/gs-sites':
@@ -2094,172 +2092,8 @@ paths:
description: Unexpected error
schema:
$ref: '#/definitions/Error'
'/events':
get:
tags:
- events
summary: List all available retention events
description: |
Gets the list of events that can be used by retention steps
operationId: getAllEvents
produces:
- application/json
parameters:
- $ref: '#/parameters/skipCountParam'
- $ref: '#/parameters/maxItemsParam'
responses:
'200':
description: Successful response
schema:
$ref: '#/definitions/EventPaging'
'400':
description: |
Invalid parameter: value of **maxItems** or **skipCount** is invalid
'401':
description: Authentication failed
default:
description: Unexpected error
schema:
$ref: '#/definitions/Error'
post:
tags:
- events
summary: Create a new retention event
description: |
Creates a new event that can be used by retention schedules.
operationId: createEvent
parameters:
- in: body
name: eventBodyCreate
description: The new event.
required: true
schema:
$ref: '#/definitions/EventBody'
consumes:
- application/json
produces:
- application/json
responses:
'201':
description: Successful response
schema:
$ref: '#/definitions/EventEntry'
'400':
description: |
Invalid parameter: **name** or **type** is invalid
'401':
description: Authentication failed
'403':
description: Current user does not have permission to create event
'409':
description: Cannot create event. An event with the name **name** already exists
default:
description: Unexpected error
schema:
$ref: '#/definitions/Error'
'/events/{eventId}':
get:
tags:
- events
summary: Return event for given eventId
description: |
Gets information about the retention event with id **eventId**.
operationId: getEvent
produces:
- application/json
parameters:
- $ref: '#/parameters/eventIdParam'
responses:
'200':
description: Successful response
schema:
$ref: '#/definitions/EventEntry'
'400':
description: |
Invalid parameter: **eventId** is invalid
'401':
description: Authentication failed
'404':
description: "**eventId** does not exist"
default:
description: Unexpected error
schema:
$ref: '#/definitions/Error'
put:
tags:
- events
summary: Update event for given eventId
operationId: updateEvent
description: |
Updates retention event with id **eventId**.
produces:
- application/json
parameters:
- $ref: '#/parameters/eventIdParam'
- in: body
name: eventBodyUpdate
description: The event information to update.
required: true
schema:
$ref: '#/definitions/EventBody'
responses:
'200':
description: Successful response
schema:
$ref: '#/definitions/EventEntry'
'400':
description: |
Invalid parameter: The update request is invalid or **eventId** is not a valid format or **eventBodyUpdate** is invalid
'401':
description: Authentication failed
'403':
description: Current user does not have permission to update events
'404':
description: "**eventId** does not exist"
'409':
description: Cannot update event. An event with the name **name** already exists
default:
description: Unexpected error
schema:
$ref: '#/definitions/Error'
'/event-types':
get:
tags:
- events
summary: List all the retention event types
description: |
Gets a list of all the retention event types.
operationId: getAllEventTypes
produces:
- application/json
parameters:
- $ref: '#/parameters/skipCountParam'
- $ref: '#/parameters/maxItemsParam'
responses:
'200':
description: Successful response
schema:
$ref: '#/definitions/EventTypePaging'
'400':
description: |
Invalid parameter: value of **maxItems** or **skipCount** is invalid
'401':
description: Authentication failed
default:
description: Unexpected error
schema:
$ref: '#/definitions/Error'
parameters:
## event
eventIdParam:
name: eventId
in: path
description: The identifier of an event.
required: true
type: string
## File plans
filePlanEntryIncludeParam:
name: include
@@ -3927,92 +3761,4 @@ definitions:
- SiteConsumer
- SiteCollaborator
- SiteContributor
- SiteManager
EventPaging:
type: object
properties:
list:
type: object
properties:
pagination:
$ref: '#/definitions/Pagination'
entries:
type: array
items:
$ref: '#/definitions/EventEntry'
EventEntry:
type: object
required:
- entry
properties:
entry:
$ref: '#/definitions/Event'
Event:
type: object
required:
- id
- name
- type
properties:
id:
type: string
description: this is the id of the event
name:
type: string
description: This is the unique display label of the event
type:
type: string
description: this is event type
EventBody:
type: object
required:
- name
properties:
name:
type: string
description: This is the unique display label of the event
type:
type: string
description: this is event type
default: Simple
EventTypePaging:
type: object
properties:
list:
type: object
properties:
pagination:
$ref: '#/definitions/Pagination'
entries:
type: array
items:
$ref: '#/definitions/EventTypeEntry'
EventTypeEntry:
type: object
required:
- entry
properties:
entry:
$ref: '#/definitions/EventType'
EventType:
type: object
required:
- id
- name
properties:
id:
type: string
description: this is the event type id
name:
type: string
description: this is event type name
isAutomatic:
type: boolean
description: Whether events of this type need completing manually or can be completed automatically
default: true
associationName:
type: string
description: The association used to determine whether automatic events of this type are complete
actionOnAssociatedNode:
type: string
description: If an association name is set for this event type then it is possible to require an action to be completed on the associated node
- SiteManager

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<modules>

View File

@@ -8,7 +8,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo-amps</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<properties>

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<dependencies>
@@ -137,6 +137,10 @@
<artifactId>commons-dbcp2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
</dependencies>
<build>

View File

@@ -0,0 +1,143 @@
/*
* Copyright (C) 2023 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.httpclient;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.alfresco.error.AlfrescoRuntimeException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
public class HttpClient4Factory
{
protected static final String TLS_PROTOCOL = "TLS";
protected static final String HTTPS_PROTOCOL = "https";
protected static final String HTTP_TARGET_HOST = "http.target_host";
protected static final String TLS_V_1_2 = "TLSv1.2";
protected static final String TLS_V_1_3 = "TLSv1.3";
private static SSLContext createSSLContext(HttpClientConfig config)
{
KeyManager[] keyManagers = config.getKeyStore().createKeyManagers();
TrustManager[] trustManagers = config.getTrustStore().createTrustManagers();
try
{
SSLContext sslcontext = SSLContext.getInstance(TLS_PROTOCOL);
sslcontext.init(keyManagers, trustManagers, null);
return sslcontext;
}
catch(Throwable e)
{
throw new AlfrescoRuntimeException("Unable to create SSL context", e);
}
}
public static CloseableHttpClient createHttpClient(HttpClientConfig config)
{
return createHttpClient(config, null);
}
public static CloseableHttpClient createHttpClient(HttpClientConfig config, HttpClientConnectionManager connectionManager)
{
HttpClientBuilder clientBuilder = HttpClients.custom();
if(config.isMTLSEnabled())
{
clientBuilder.addInterceptorFirst((HttpRequestInterceptor) (request, context) -> {
if (!((HttpHost) context.getAttribute(HTTP_TARGET_HOST)).getSchemeName().equals(HTTPS_PROTOCOL))
{
String msg = "mTLS is enabled but provided URL does not use a secured protocol";
throw new HttpClientException(msg);
}
});
clientBuilder.setSSLSocketFactory(getSslConnectionSocketFactory(config));
}
if (connectionManager != null)
{
clientBuilder.setConnectionManager(connectionManager);
}
else
{
//Setting a connectionManager overrides these properties
clientBuilder.setMaxConnTotal(config.getMaxTotalConnections());
clientBuilder.setMaxConnPerRoute(config.getMaxHostConnections());
}
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(config.getConnectionTimeout())
.setSocketTimeout(config.getSocketTimeout())
.setConnectionRequestTimeout(config.getConnectionRequestTimeout())
.build();
clientBuilder.setDefaultRequestConfig(requestConfig);
clientBuilder.setRetryHandler(new StandardHttpRequestRetryHandler(5, false));
return clientBuilder.build();
}
private static SSLConnectionSocketFactory getSslConnectionSocketFactory(HttpClientConfig config)
{
return new SSLConnectionSocketFactory(
createSSLContext(config),
new String[] { TLS_V_1_2, TLS_V_1_3 },
null,
config.isHostnameVerificationDisabled() ? new NoopHostnameVerifier() : SSLConnectionSocketFactory.getDefaultHostnameVerifier());
}
public static PoolingHttpClientConnectionManager createPoolingConnectionManager(HttpClientConfig config)
{
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;
if(config.isMTLSEnabled())
{
poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", getSslConnectionSocketFactory(config))
.build());
}
else
{
poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.build());
}
poolingHttpClientConnectionManager.setMaxTotal(config.getMaxTotalConnections());
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(config.getMaxHostConnections());
return poolingHttpClientConnectionManager;
}
}

View File

@@ -0,0 +1,202 @@
/*
* Copyright (C) 2023 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.httpclient;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.stream.Collectors;
import org.alfresco.encryption.AlfrescoKeyStore;
import org.alfresco.encryption.AlfrescoKeyStoreImpl;
import org.alfresco.encryption.KeyResourceLoader;
import org.alfresco.encryption.ssl.SSLEncryptionParameters;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class HttpClientConfig
{
private static final String HTTPCLIENT_CONFIG = "httpclient.config.";
protected static final Log LOGGER = LogFactory.getLog(HttpClientConfig.class);
private Properties properties;
private String serviceName;
private SSLEncryptionParameters sslEncryptionParameters;
private KeyResourceLoader keyResourceLoader;
private AlfrescoKeyStore keyStore;
private AlfrescoKeyStore trustStore;
private Map<String, String> config;
public void setProperties(Properties properties)
{
this.properties = properties;
}
public void setServiceName(String serviceName)
{
this.serviceName = serviceName;
}
public void setSslEncryptionParameters(SSLEncryptionParameters sslEncryptionParameters)
{
this.sslEncryptionParameters = sslEncryptionParameters;
}
public void setKeyResourceLoader(KeyResourceLoader keyResourceLoader)
{
this.keyResourceLoader = keyResourceLoader;
}
public AlfrescoKeyStore getKeyStore()
{
return keyStore;
}
public AlfrescoKeyStore getTrustStore()
{
return trustStore;
}
public void init()
{
this.keyStore = new AlfrescoKeyStoreImpl(sslEncryptionParameters.getKeyStoreParameters(), keyResourceLoader);
this.trustStore = new AlfrescoKeyStoreImpl(sslEncryptionParameters.getTrustStoreParameters(), keyResourceLoader);
config = retrieveConfig(serviceName);
checkUnsupportedProperties(config);
}
/**
* Method used for retrieving HttpClient config from Global Properties
* @param serviceName name of used service
* @return map of properties
*/
private Map<String, String> retrieveConfig(String serviceName)
{
return properties.keySet().stream()
.filter(key -> key instanceof String)
.map(Object::toString)
.filter(key -> key.startsWith(HTTPCLIENT_CONFIG + serviceName))
.collect(Collectors.toMap(
key -> key.replace(HTTPCLIENT_CONFIG + serviceName + ".", ""),
key -> properties.getProperty(key, null)));
}
private void checkUnsupportedProperties(Map<String, String> config)
{
config.keySet().stream()
.filter(propertyName -> !HttpClientPropertiesEnum.isPropertyNameSupported(propertyName))
.forEach(propertyName -> LOGGER.warn(String.format("For service [%s], an unsupported property [%s] is set", serviceName, propertyName)));
}
private Integer getIntegerProperty(HttpClientPropertiesEnum property)
{
return Integer.parseInt(extractValueFromConfig(property).orElse("0"));
}
private Boolean getBooleanProperty(HttpClientPropertiesEnum property)
{
return Boolean.parseBoolean(extractValueFromConfig(property).orElse("false"));
}
private Optional<String> extractValueFromConfig(HttpClientPropertiesEnum property)
{
Optional<String> optionalProperty = Optional.ofNullable(config.get(property.name));
if(property.isRequired && optionalProperty.isEmpty())
{
String msg = String.format("Required property: '%s' is empty.", property.name);
throw new HttpClientException(msg);
}
return optionalProperty;
}
public Integer getConnectionTimeout()
{
return getIntegerProperty(HttpClientPropertiesEnum.CONNECTION_REQUEST_TIMEOUT);
}
public Integer getSocketTimeout()
{
return getIntegerProperty(HttpClientPropertiesEnum.SOCKET_TIMEOUT);
}
public Integer getConnectionRequestTimeout()
{
return getIntegerProperty(HttpClientPropertiesEnum.CONNECTION_REQUEST_TIMEOUT);
}
public Integer getMaxTotalConnections()
{
return getIntegerProperty(HttpClientPropertiesEnum.MAX_TOTAL_CONNECTIONS);
}
public Integer getMaxHostConnections()
{
return getIntegerProperty(HttpClientPropertiesEnum.MAX_HOST_CONNECTIONS);
}
public Boolean isMTLSEnabled()
{
return getBooleanProperty(HttpClientPropertiesEnum.MTLS_ENABLED);
}
public boolean isHostnameVerificationDisabled()
{
return getBooleanProperty(HttpClientPropertiesEnum.HOSTNAME_VERIFICATION_DISABLED);
}
private enum HttpClientPropertiesEnum
{
CONNECTION_TIMEOUT("connectionTimeout", true),
SOCKET_TIMEOUT("socketTimeout", true),
CONNECTION_REQUEST_TIMEOUT("connectionRequestTimeout", true),
MAX_TOTAL_CONNECTIONS("maxTotalConnections", true),
MAX_HOST_CONNECTIONS("maxHostConnections", true),
HOSTNAME_VERIFICATION_DISABLED("hostnameVerificationDisabled", false),
MTLS_ENABLED("mTLSEnabled", true);
private final String name;
private final Boolean isRequired;
HttpClientPropertiesEnum(String propertyName, Boolean isRequired)
{
this.name = propertyName;
this.isRequired = isRequired;
}
private static final List<String> supportedProperties = new ArrayList<>();
static {
for (HttpClientPropertiesEnum property : HttpClientPropertiesEnum.values()) {
supportedProperties.add(property.name);
}
}
public static boolean isPropertyNameSupported(String propertyName) {
return supportedProperties.contains(propertyName);
}
}
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright (C) 2023 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.httpclient;
import org.alfresco.error.AlfrescoRuntimeException;
public class HttpClientException extends AlfrescoRuntimeException
{
public HttpClientException(String msgId)
{
super(msgId);
}
}

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<properties>
@@ -134,7 +134,7 @@
<dependency>
<groupId>com.fasterxml.woodstox</groupId>
<artifactId>woodstox-core</artifactId>
<version>6.4.0</version>
<version>6.5.1</version>
</dependency>
<!-- the cxf libs were updated, see dependencyManagement section -->

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<dependencies>

View File

@@ -9,6 +9,6 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo-packaging</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
</project>

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo-packaging</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<properties>

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<modules>

View File

@@ -1,3 +1,3 @@
SOLR6_TAG=2.0.7-A2
SOLR6_TAG=2.0.7-A5
POSTGRES_TAG=14.4
ACTIVEMQ_TAG=5.17.1-jre11-rockylinux8
ACTIVEMQ_TAG=5.17.4-jre17-rockylinux8

View File

@@ -6,7 +6,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo-packaging</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<modules>

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo-tests</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<organization>
@@ -16,12 +16,12 @@
</organization>
<properties>
<maven.build.sourceVersion>11</maven.build.sourceVersion>
<maven.build.sourceVersion>17</maven.build.sourceVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<chemistry-opencmis-commons-api>1.1.0</chemistry-opencmis-commons-api>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
<maven-release.version>2.5.3</maven-release.version>
<java.version>11</java.version>
<java.version>17</java.version>
<suiteXmlFile>${project.basedir}/src/test/resources/cmis-suite.xml</suiteXmlFile>
<cmis.binding />
<cmis.basePath />

View File

@@ -4,8 +4,6 @@ import org.alfresco.utility.data.AisToken;
import org.alfresco.utility.data.auth.DataAIS;
import org.alfresco.utility.model.UserModel;
import org.apache.chemistry.opencmis.commons.SessionParameter;
import org.keycloak.authorization.client.util.HttpResponseException;
import org.keycloak.representations.AccessTokenResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -86,9 +84,9 @@ public class AuthParameterProviderFactory
parameters.put(SessionParameter.OAUTH_REFRESH_TOKEN, aisToken.getRefreshToken());
parameters.put(SessionParameter.OAUTH_EXPIRATION_TIMESTAMP, String.valueOf(System.currentTimeMillis()
+ (aisToken.getExpiresIn() * 1000))); // getExpiresIn is in seconds
parameters.put(SessionParameter.OAUTH_TOKEN_ENDPOINT, cmisProperties.aisProperty().getAdapterConfig().getAuthServerUrl()
parameters.put(SessionParameter.OAUTH_TOKEN_ENDPOINT, cmisProperties.aisProperty().getAuthServerUrl()
+ "/realms/alfresco/protocol/openid-connect/token");
parameters.put(SessionParameter.OAUTH_CLIENT_ID, cmisProperties.aisProperty().getAdapterConfig().getResource());
parameters.put(SessionParameter.OAUTH_CLIENT_ID, cmisProperties.aisProperty().getResource());
return parameters;
}
@@ -110,10 +108,10 @@ public class AuthParameterProviderFactory
// Attempt to get an access token for userModel from AIS
aisToken = dataAIS.perform().getAccessToken(userModel);
}
catch (HttpResponseException e)
catch (AssertionError e)
{
// Trying to authenticate with invalid user credentials so return an invalid access token
if (e.getStatusCode() == 401)
if (e.getMessage().contains("invalid_grant"))
{
STEP(String.format("%s Invalid user credentials were provided %s:%s. Using invalid token for reqest.",
STEP_PREFIX, userModel.getUsername(), userModel.getPassword()));

View File

@@ -9,7 +9,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo-tests</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<developers>

View File

@@ -9,7 +9,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo-tests</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<developers>

View File

@@ -8,20 +8,19 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo-tests</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<properties>
<suiteXmlFile>${project.basedir}/src/test/resources/restapi-suite.xml</suiteXmlFile>
<maven.build.sourceVersion>11</maven.build.sourceVersion>
<maven.build.sourceVersion>17</maven.build.sourceVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<rest.api.explorer.branch>master</rest.api.explorer.branch>
<httpclient-osgi-version>4.5.6</httpclient-osgi-version>
<org.glassfish.version>1.1.4</org.glassfish.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
<scribejava-apis.version>8.3.1</scribejava-apis.version>
<license-maven-plugin.version>2.0.1.alfresco-2</license-maven-plugin.version>
<java.version>11</java.version>
<java.version>17</java.version>
</properties>
<profiles>
@@ -85,6 +84,13 @@
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${dependency.awaitility.version}</version>
<scope>test</scope>
</dependency>
<!-- REST ASSURED -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
@@ -165,14 +171,14 @@
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>3.0.16</version>
<version>3.0.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy-json-->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-json</artifactId>
<version>3.0.16</version>
<version>3.0.17</version>
</dependency>
<dependency>

View File

@@ -30,7 +30,6 @@ import static org.alfresco.utility.report.log.Step.STEP;
import org.alfresco.utility.data.AisToken;
import org.alfresco.utility.data.auth.DataAIS;
import org.alfresco.utility.model.UserModel;
import org.keycloak.authorization.client.util.HttpResponseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -86,12 +85,11 @@ public class RestAisAuthentication
// Attempt to get an access token for userModel from AIS
aisToken = dataAIS.perform().getAccessToken(userModel);
}
catch (HttpResponseException e)
catch (AssertionError e)
{
// Trying to authenticate with invalid user credentials or disabled
// user so return an invalid access token
String httpResponse = new String(e.getBytes());
if (e.getStatusCode() == 401 || httpResponse.contains(USER_DISABLED_MSG))
if (e.getMessage().contains("invalid_grant"))
{
STEP(String.format("%s User disabled or invalid user credentials were provided %s:%s. Using invalid token for request.", STEP_PREFIX,
userModel.getUsername(), userModel.getPassword()));

View File

@@ -680,17 +680,22 @@ public class RestWrapper extends DSLWrapper<RestWrapper>
}
else
{
if (returnedResponse.getContentType().contains("image/png"))
{
LOG.info("On {} {}, received the response with an image and headers: \n{}", restRequest.getHttpMethod(), restRequest.getPath(),
returnedResponse.getHeaders().toString());
}
else if (returnedResponse.getContentType().contains("application/json") && !returnedResponse.asString().isEmpty())
if (returnedResponse.asString().isEmpty())
{
LOG.info("On {} {}, received the following response \n{}", restRequest.getHttpMethod(), restRequest.getPath(),
Utility.prettyPrintJsonString(returnedResponse.asString()));
returnedResponse.getStatusCode());
}
else if (returnedResponse.getContentType().contains("application/xml") && !returnedResponse.asString().isEmpty())
else if (returnedResponse.getContentType().contains("image/png"))
{
LOG.info("On {} {}, received the response with an image and headers: \n{}", restRequest.getHttpMethod(), restRequest.getPath(),
returnedResponse.getHeaders().toString());
}
else if (returnedResponse.getContentType().contains("application/json"))
{
LOG.info("On {} {}, received the following response \n{}", restRequest.getHttpMethod(), restRequest.getPath(),
Utility.prettyPrintJsonString(returnedResponse.asString()));
}
else if (returnedResponse.getContentType().contains("application/xml"))
{
String response = parseXML(returnedResponse);
LOG.info("On {} {}, received the following response \n{}", restRequest.getHttpMethod(), restRequest.getPath(), response);
@@ -698,7 +703,7 @@ public class RestWrapper extends DSLWrapper<RestWrapper>
else
{
LOG.info("On {} {}, received the following response \n{}", restRequest.getHttpMethod(), restRequest.getPath(),
ToStringBuilder.reflectionToString(returnedResponse.asString(), ToStringStyle.MULTI_LINE_STYLE));
ToStringBuilder.reflectionToString(returnedResponse.asString(), ToStringStyle.MULTI_LINE_STYLE));
}
}
}

View File

@@ -52,6 +52,11 @@ This must be unique within the parent category.
*/
private long count;
/**
The path to this category.
*/
private String path;
public String getId()
{
return this.id;
@@ -102,6 +107,14 @@ This must be unique within the parent category.
this.count = count;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Override
public boolean equals(Object o)
{
@@ -126,6 +139,7 @@ This must be unique within the parent category.
", parentId='" + parentId + '\'' +
", hasChildren=" + hasChildren +
", count=" + count +
", path=" + path +
'}';
}

View File

@@ -60,7 +60,7 @@ public class RestErrorModel
public static String INVALID_MAXITEMS = "Invalid paging parameter maxItems:%s";
public static String INVALID_SKIPCOUNT = "Invalid paging parameter skipCount:%s";
public static String INVALID_TAG = "Tag name must not contain %s char sequence";
public static String EMPTY_TAG = "New tag cannot be null";
public static String BLANK_TAG = "New tag cannot be blank";
public static String UNKNOWN_ROLE = "Unknown role '%s'";
public static String ALREADY_Site_MEMBER = "%s is already a member of site %s";
public static String ALREADY_INVITED = "%s is already invited to site %s";

View File

@@ -0,0 +1,223 @@
/*
* #%L
* Alfresco Remote API
* %%
* Copyright (C) 2005 - 2023 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.rest.categories;
import static org.alfresco.utility.data.RandomData.getRandomName;
import static org.alfresco.utility.report.log.Step.STEP;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;
import static org.testng.Assert.assertTrue;
import org.alfresco.dataprep.CMISUtil;
import org.alfresco.rest.model.RestCategoryLinkBodyModel;
import org.alfresco.rest.model.RestCategoryModel;
import org.alfresco.rest.model.RestCategoryModelsCollection;
import org.alfresco.utility.Utility;
import org.alfresco.utility.model.FileModel;
import org.alfresco.utility.model.FolderModel;
import org.alfresco.utility.model.SiteModel;
import org.alfresco.utility.model.TestGroup;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class CategoriesPathTests extends CategoriesRestTest
{
private FileModel file;
private RestCategoryModel category;
@BeforeClass(alwaysRun = true)
@Override
public void dataPreparation() throws Exception
{
STEP("Create user and site");
user = dataUser.createRandomTestUser();
SiteModel site = dataSite.usingUser(user).createPublicRandomSite();
STEP("Create a folder, file in it and a category");
FolderModel folder = dataContent.usingUser(user).usingSite(site).createFolder();
file = dataContent.usingUser(user).usingResource(folder).createContent(CMISUtil.DocumentType.TEXT_PLAIN);
category = prepareCategoryUnderRoot();
STEP("Wait for indexing to complete");
Utility.sleep(1000, 60000, () -> restClient.authenticateUser(user)
.withCoreAPI()
.usingCategory(category)
.include(INCLUDE_PATH_PARAM)
.getCategory()
.assertThat()
.field(FIELD_PATH)
.isNotNull());
}
/**
* Verify path for a category got by ID.
*/
@Test(groups = { TestGroup.REST_API })
public void testGetCategoryById_includePath()
{
STEP("Get category and verify if path is a general path for categories");
final RestCategoryModel actualCategory = restClient.authenticateUser(user)
.withCoreAPI()
.usingCategory(category)
.include(INCLUDE_PATH_PARAM)
.getCategory();
restClient.assertStatusCodeIs(OK);
actualCategory.assertThat().field(FIELD_ID).is(category.getId());
actualCategory.assertThat().field(FIELD_PATH).is("/categories/General");
}
/**
* Verify path for category.
*/
@Test(groups = { TestGroup.REST_API })
public void testGetCategories_includePath()
{
STEP("Get few categories and verify its paths");
final RestCategoryModel parentCategory = createCategoryModelWithId(ROOT_CATEGORY_ID);
final RestCategoryModelsCollection actualCategories = restClient.authenticateUser(user)
.withCoreAPI()
.usingCategory(parentCategory)
.include(INCLUDE_PATH_PARAM)
.getCategoryChildren();
restClient.assertStatusCodeIs(OK);
assertTrue(actualCategories.getEntries().stream()
.map(RestCategoryModel::onModel)
.allMatch(cat -> cat.getPath().equals("/categories/General")));
}
/**
* Verify path for child category.
*/
@Test(groups = { TestGroup.REST_API })
public void testGetChildCategory_includePath()
{
STEP("Create parent and child categories");
final RestCategoryModel parentCategory = prepareCategoryUnderRoot();
final RestCategoryModel childCategory = prepareCategoryUnder(parentCategory);
STEP("Verify path for created child categories");
final RestCategoryModelsCollection actualCategories = restClient.authenticateUser(user)
.withCoreAPI()
.usingCategory(parentCategory)
.include(INCLUDE_PATH_PARAM)
.getCategoryChildren();
restClient.assertStatusCodeIs(OK);
actualCategories.getEntries().stream()
.map(RestCategoryModel::onModel)
.forEach(cat -> cat.assertThat().field(FIELD_PATH).is("/categories/General/" + parentCategory.getName()));
}
/**
* Create category and verify that it has a path.
*/
@Test(groups = { TestGroup.REST_API })
public void testCreateCategory_includingPath()
{
STEP("Create a category under root and verify if path is a general path for categories");
final String categoryName = getRandomName("Category");
final RestCategoryModel rootCategory = createCategoryModelWithId(ROOT_CATEGORY_ID);
final RestCategoryModel aCategory = createCategoryModelWithName(categoryName);
final RestCategoryModel createdCategory = restClient.authenticateUser(dataUser.getAdminUser())
.withCoreAPI()
.include(INCLUDE_PATH_PARAM)
.usingCategory(rootCategory)
.createSingleCategory(aCategory);
restClient.assertStatusCodeIs(CREATED);
createdCategory.assertThat().field(FIELD_NAME).is(categoryName);
createdCategory.assertThat().field(FIELD_PATH).is("/categories/General");
}
/**
* Update category and verify that it has a path.
*/
@Test(groups = { TestGroup.REST_API })
public void testUpdateCategory_includePath()
{
STEP("Update linked category and verify if path is a general path for categories");
final String categoryNewName = getRandomName("NewCategoryName");
final RestCategoryModel fixedCategoryModel = createCategoryModelWithName(categoryNewName);
final RestCategoryModel updatedCategory = restClient.authenticateUser(dataUser.getAdminUser())
.withCoreAPI()
.usingCategory(category)
.include(INCLUDE_PATH_PARAM)
.updateCategory(fixedCategoryModel);
restClient.assertStatusCodeIs(OK);
updatedCategory.assertThat().field(FIELD_ID).is(category.getId());
updatedCategory.assertThat().field(FIELD_PATH).is("/categories/General");
}
/**
* Link node to categories and verify that they have path.
*/
@Test(groups = { TestGroup.REST_API })
public void testLinkNodeToCategories_includePath()
{
STEP("Link node to categories and verify if path is a general path");
final RestCategoryLinkBodyModel categoryLinkModel = createCategoryLinkModelWithId(category.getId());
final RestCategoryModel linkedCategory = restClient.authenticateUser(dataUser.getAdminUser())
.withCoreAPI()
.usingNode(file)
.include(INCLUDE_PATH_PARAM)
.linkToCategory(categoryLinkModel);
restClient.assertStatusCodeIs(CREATED);
linkedCategory.assertThat().field(FIELD_ID).is(category.getId());
linkedCategory.assertThat().field(FIELD_PATH).is("/categories/General");
}
/**
* List categories for given node and verify that they have a path.
*/
@Test(groups = { TestGroup.REST_API })
public void testListCategoriesForNode_includePath()
{
STEP("Link file to category");
final RestCategoryLinkBodyModel categoryLink = createCategoryLinkModelWithId(category.getId());
final RestCategoryModel linkedCategory = restClient.authenticateUser(dataUser.getAdminUser())
.withCoreAPI()
.usingNode(file)
.include(INCLUDE_PATH_PARAM)
.linkToCategory(categoryLink);
STEP("Get linked category and verify if path is a general path");
final RestCategoryModelsCollection linkedCategories = restClient.authenticateUser(dataUser.getAdminUser())
.withCoreAPI()
.usingNode(file)
.include(INCLUDE_PATH_PARAM)
.getLinkedCategories();
restClient.assertStatusCodeIs(OK);
linkedCategories.assertThat().entriesListCountIs(1);
linkedCategories.getEntries().get(0).onModel().assertThat().field(FIELD_ID).is(category.getId());
linkedCategories.getEntries().get(0).onModel().assertThat().field(FIELD_PATH).is("/categories/General");
}
}

View File

@@ -46,6 +46,7 @@ import org.testng.annotations.BeforeClass;
abstract class CategoriesRestTest extends RestTest
{
protected static final String INCLUDE_COUNT_PARAM = "count";
protected static final String INCLUDE_PATH_PARAM = "path";
protected static final String ROOT_CATEGORY_ID = "-root-";
protected static final String CATEGORY_NAME_PREFIX = "CategoryName";
protected static final String FIELD_NAME = "name";
@@ -53,6 +54,7 @@ abstract class CategoriesRestTest extends RestTest
protected static final String FIELD_PARENT_ID = "parentId";
protected static final String FIELD_HAS_CHILDREN = "hasChildren";
protected static final String FIELD_COUNT = "count";
protected static final String FIELD_PATH = "path";
protected UserModel user;

View File

@@ -1,5 +1,7 @@
package org.alfresco.rest.renditions;
import java.time.Duration;
import com.google.common.base.Predicates;
import org.alfresco.rest.RestTest;
import org.alfresco.rest.core.RestResponse;
import org.alfresco.rest.model.RestNodeModel;
@@ -8,6 +10,8 @@ import org.alfresco.utility.model.FileModel;
import org.alfresco.utility.model.FolderModel;
import org.alfresco.utility.model.SiteModel;
import org.alfresco.utility.model.UserModel;
import org.awaitility.Awaitility;
import org.awaitility.Durations;
import org.springframework.http.HttpStatus;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
@@ -68,15 +72,23 @@ public abstract class RenditionIntegrationTests extends RestTest
*/
protected RestNodeModel uploadFile(String sourceFile) throws Exception
{
FolderModel folder = FolderModel.getRandomFolderModel();
folder = dataContent.usingUser(user).usingSite(site).createFolder(folder);
FolderModel folder = Awaitility
.await()
.atMost(Duration.ofSeconds(30))
.pollInterval(Durations.ONE_SECOND)
.ignoreExceptions()
.until(() -> {
FolderModel randomFolderModel = FolderModel.getRandomFolderModel();
return dataContent.usingUser(user).usingSite(site).createFolder(randomFolderModel);
}, Predicates.notNull());
restClient.authenticateUser(user).configureRequestSpec()
.addMultiPart("filedata", Utility.getResourceTestDataFile(sourceFile));
.addMultiPart("filedata", Utility.getResourceTestDataFile(sourceFile));
RestNodeModel fileNode = restClient.authenticateUser(user).withCoreAPI().usingNode(folder).createNode();
Assert.assertEquals(Integer.valueOf(restClient.getStatusCode()).intValue(), HttpStatus.CREATED.value(),
"Failed to created a node for rendition tests using file " + sourceFile);
"Failed to created a node for rendition tests using file " + sourceFile);
return fileNode;
}
}

View File

@@ -1,5 +1,10 @@
package org.alfresco.rest.tags;
import static org.alfresco.utility.data.RandomData.getRandomName;
import static org.alfresco.utility.report.log.Step.STEP;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;
import org.alfresco.rest.model.RestErrorModel;
import org.alfresco.rest.model.RestTagModel;
import org.alfresco.utility.constants.UserRole;
@@ -14,9 +19,14 @@ import org.testng.annotations.Test;
public class GetTagTests extends TagsDataPrep
{
private static final String FIELD_ID = "id";
private static final String FIELD_TAG = "tag";
private static final String FIELD_COUNT = "count";
private static final String TAG_NAME_PREFIX = "tag-name";
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION, description = "Verify admin user gets tag using REST API and status code is OK (200)")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void adminIsAbleToGetTag() throws Exception
public void adminIsAbleToGetTag()
{
RestTagModel returnedTag = restClient.authenticateUser(adminUserModel).withCoreAPI().getTag(documentTag);
restClient.assertStatusCodeIs(HttpStatus.OK);
@@ -25,7 +35,7 @@ public class GetTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.SANITY, description = "Verify user with Manager role gets tag using REST API and status code is OK (200)")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.SANITY })
public void userWithManagerRoleIsAbleToGetTag() throws Exception
public void userWithManagerRoleIsAbleToGetTag()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteManager));
@@ -37,7 +47,7 @@ public class GetTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION, description = "Verify user with Collaborator role gets tag using REST API and status code is OK (200)")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void userWithCollaboratorRoleIsAbleToGetTag() throws Exception
public void userWithCollaboratorRoleIsAbleToGetTag()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteCollaborator));
RestTagModel returnedTag = restClient.withCoreAPI().getTag(documentTag);
@@ -47,7 +57,7 @@ public class GetTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION, description = "Verify user with Contributor role gets tag using REST API and status code is OK (200)")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void userWithContributorRoleIsAbleToGetTag() throws Exception
public void userWithContributorRoleIsAbleToGetTag()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteContributor));
RestTagModel returnedTag = restClient.withCoreAPI().getTag(documentTag);
@@ -57,7 +67,7 @@ public class GetTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION, description = "Verify user with Consumer role gets tag using REST API and status code is OK (200)")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void userWithConsumerRoleIsAbleToGetTag() throws Exception
public void userWithConsumerRoleIsAbleToGetTag()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteConsumer));
RestTagModel returnedTag = restClient.withCoreAPI().getTag(documentTag);
@@ -68,7 +78,7 @@ public class GetTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.SANITY, description = "Verify Manager user gets status code 401 if authentication call fails")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.SANITY })
// @Bug(id="MNT-16904", description = "It fails only on environment with tenants")
public void managerIsNotAbleToGetTagIfAuthenticationFails() throws Exception
public void managerIsNotAbleToGetTagIfAuthenticationFails()
{
UserModel managerUser = dataUser.usingAdmin().createRandomTestUser();
String managerPassword = managerUser.getPassword();
@@ -82,7 +92,7 @@ public class GetTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that if tag id is invalid status code returned is 400")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void invalidTagIdTest() throws Exception
public void invalidTagIdTest()
{
String tagId = documentTag.getId();
documentTag.setId("random_tag_value");
@@ -94,7 +104,7 @@ public class GetTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS },
executionType = ExecutionType.REGRESSION, description = "Check that properties filter is applied when getting tag using Manager user.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void checkPropertiesFilterIsApplied() throws Exception
public void checkPropertiesFilterIsApplied()
{
RestTagModel returnedTag = restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteManager))
.withParams("properties=id,tag").withCoreAPI().getTag(documentTag);
@@ -107,7 +117,7 @@ public class GetTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS },
executionType = ExecutionType.REGRESSION, description = "Check that Manager user can get tag of a folder.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void getTagOfAFolder() throws Exception
public void getTagOfAFolder()
{
RestTagModel returnedTag = restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteManager))
.withCoreAPI().getTag(folderTag);
@@ -118,7 +128,7 @@ public class GetTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS },
executionType = ExecutionType.REGRESSION, description = "Check default error model schema. Use invalid skipCount parameter.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void checkDefaultErrorModelSchema() throws Exception
public void checkDefaultErrorModelSchema()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteManager))
.withParams("skipCount=abc").withCoreAPI().getTag(documentTag);
@@ -128,4 +138,44 @@ public class GetTagTests extends TagsDataPrep
.descriptionURLIs(RestErrorModel.RESTAPIEXPLORER)
.stackTraceIs(RestErrorModel.STACKTRACE);
}
}
/**
* Verify that count field is not present for searched tag when not requested.
*/
@Test(groups = {TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION})
public void testGetTag_notIncludingCount()
{
STEP("Create single tag as admin");
String tagName = getRandomName(TAG_NAME_PREFIX).toLowerCase();
final RestTagModel tagModel = createTagModelWithName(tagName);
final RestTagModel createdTag = restClient.authenticateUser(adminUserModel).withCoreAPI().createSingleTag(tagModel);
restClient.assertStatusCodeIs(CREATED);
STEP("Get a single tag, not including count and verify if it is not present in the response");
final RestTagModel searchedTag = restClient.withCoreAPI().getTag(createdTag);
restClient.assertStatusCodeIs(OK);
RestTagModel expected = RestTagModel.builder().id(createdTag.getId()).tag(tagName).create();
searchedTag.assertThat().isEqualTo(expected);
}
/**
* Check that the count field can be included.
*/
@Test (groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void testGetTag_includeCount()
{
STEP("Create unused tag as admin");
String tagName = getRandomName(TAG_NAME_PREFIX).toLowerCase();
RestTagModel tagModel = createTagModelWithName(tagName);
RestTagModel createdTag = restClient.authenticateUser(adminUserModel).withCoreAPI().createSingleTag(tagModel);
STEP("Get a single tag with the count field");
RestTagModel searchedTag = restClient.withCoreAPI().include("count").getTag(createdTag);
restClient.assertStatusCodeIs(OK);
RestTagModel expected = RestTagModel.builder().id(createdTag.getId()).tag(tagName).count(0).create();
searchedTag.assertThat().isEqualTo(expected);
}
}

View File

@@ -1,6 +1,9 @@
package org.alfresco.rest.tags;
import static org.alfresco.utility.data.RandomData.getRandomName;
import static org.alfresco.utility.report.log.Step.STEP;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.OK;
import java.util.Set;
@@ -8,68 +11,209 @@ import org.alfresco.rest.model.RestErrorModel;
import org.alfresco.rest.model.RestTagModel;
import org.alfresco.rest.model.RestTagModelsCollection;
import org.alfresco.utility.constants.UserRole;
import org.alfresco.utility.data.RandomData;
import org.alfresco.utility.model.TestGroup;
import org.alfresco.utility.testrail.ExecutionType;
import org.alfresco.utility.testrail.annotation.TestRail;
import org.springframework.http.HttpStatus;
import org.testng.annotations.Test;
import java.util.Set;
import java.util.stream.IntStream;
import static org.alfresco.utility.report.log.Step.STEP;
@Test(groups = {TestGroup.REQUIRE_SOLR})
public class GetTagsTests extends TagsDataPrep
{
private static final String FIELD_ID = "id";
private static final String FIELD_TAG = "tag";
private static final String FIELD_COUNT = "count";
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.SANITY, description = "Verify user with Manager role gets tags using REST API and status code is OK (200)")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.SANITY })
public void getTagsWithManagerRole() throws Exception
public void getTagsWithManagerRole()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteManager));
returnedCollection = restClient.withParams("maxItems=10000").withCoreAPI().getTags();
restClient.assertStatusCodeIs(HttpStatus.OK);
restClient.assertStatusCodeIs(OK);
returnedCollection.assertThat().entriesListIsNotEmpty()
.and().entriesListContains("tag", documentTagValue.toLowerCase())
.and().entriesListContains("tag", documentTagValue2.toLowerCase());
.and().entriesListContains("tag", documentTagValue)
.and().entriesListContains("tag", documentTagValue2);
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION, description = "Verify user with Collaborator role gets tags using REST API and status code is OK (200)")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void getTagsWithCollaboratorRole() throws Exception
public void getTagsWithCollaboratorRole()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteCollaborator));
returnedCollection = restClient.withParams("maxItems=10000").withCoreAPI().getTags();
restClient.assertStatusCodeIs(HttpStatus.OK);
restClient.assertStatusCodeIs(OK);
returnedCollection.assertThat().entriesListIsNotEmpty()
.and().entriesListContains("tag", documentTagValue.toLowerCase())
.and().entriesListContains("tag", documentTagValue2.toLowerCase());
.and().entriesListContains("tag", documentTagValue)
.and().entriesListContains("tag", documentTagValue2);
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION, description = "Verify user with Contributor role gets tags using REST API and status code is OK (200)")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void getTagsWithContributorRole() throws Exception
public void getTagsWithContributorRole()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteContributor));
returnedCollection = restClient.withParams("maxItems=10000").withCoreAPI().getTags();
restClient.assertStatusCodeIs(HttpStatus.OK);
restClient.assertStatusCodeIs(OK);
returnedCollection.assertThat().entriesListIsNotEmpty()
.and().entriesListContains("tag", documentTagValue.toLowerCase())
.and().entriesListContains("tag", documentTagValue2.toLowerCase());
.and().entriesListContains("tag", documentTagValue)
.and().entriesListContains("tag", documentTagValue2);
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION, description = "Verify user with Consumer role gets tags using REST API and status code is OK (200)")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void getTagsWithConsumerRole() throws Exception
public void getTagsWithConsumerRole()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteConsumer));
returnedCollection = restClient.withParams("maxItems=10000").withCoreAPI().getTags();
restClient.assertStatusCodeIs(HttpStatus.OK);
restClient.assertStatusCodeIs(OK);
returnedCollection.assertThat().entriesListIsNotEmpty()
.and().entriesListContains("tag", documentTagValue.toLowerCase())
.and().entriesListContains("tag", documentTagValue2.toLowerCase());
.and().entriesListContains("tag", documentTagValue)
.and().entriesListContains("tag", documentTagValue2);
}
/**
* Include count in the query parameters and ensure count is as expected for returned tags.
*/
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void testGetTags_withIncludeCount()
{
STEP("Get tags including count filter and ensure count is as expected for returned tags");
returnedCollection = restClient.authenticateUser(adminUserModel)
.withParams("include=count")
.withCoreAPI()
.getTags();
restClient.assertStatusCodeIs(OK);
returnedCollection.getEntries().stream()
.filter(e -> e.onModel().getTag().equals(folderTagValue) || e.onModel().getTag().equals(documentTagValue))
.forEach(e -> e.onModel().assertThat().field("count").is(2));
returnedCollection.getEntries().stream()
.filter(e -> e.onModel().getTag().equals(documentTagValue2))
.forEach(e -> e.onModel().assertThat().field("count").is(1));
}
/**
* Get tags and order results by count. Default sort order should be ascending
*/
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void testGetTags_withOrderByCountDefaultOrderShouldBeAsc()
{
STEP("Get tags and order results by count. Default sort order should be ascending");
returnedCollection = restClient.authenticateUser(adminUserModel)
.withParams("include=count&orderBy=count")
.withCoreAPI()
.getTags();
restClient.assertStatusCodeIs(OK);
returnedCollection.assertThat().entriesListIsSortedAscBy("count");
}
/**
* Get tags and order results by count in ascending order
*/
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void testGetTags_withOrderByCountAsc()
{
STEP("Get tags and order results by count in ascending order");
returnedCollection = restClient.authenticateUser(adminUserModel)
.withParams("include=count&orderBy=count ASC")
.withCoreAPI()
.getTags();
restClient.assertStatusCodeIs(OK);
returnedCollection.assertThat().entriesListIsSortedAscBy("count");
}
/**
* Get tags and order results by count in descending order
*/
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void testGetTags_withOrderByCountDesc()
{
STEP("Get tags and order results by count in descending order");
returnedCollection = restClient.authenticateUser(adminUserModel)
.withParams("include=count&orderBy=count DESC")
.withCoreAPI()
.getTags();
restClient.assertStatusCodeIs(OK);
returnedCollection.assertThat().entriesListIsSortedDescBy("count");
}
/**
* Get tags and order results by tag name. Default sort order should be ascending
*/
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void testGetTags_withOrderByTagDefaultOrderShouldBeAsc()
{
STEP("Get tags and order results by tag name. Default sort order should be ascending");
returnedCollection = restClient.authenticateUser(adminUserModel)
.withParams("orderBy=tag")
.withCoreAPI()
.getTags();
restClient.assertStatusCodeIs(OK);
returnedCollection.assertThat().entriesListIsSortedAscBy("tag");
}
/**
* Get tags and order results by tag name in ascending order
*/
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void testGetTags_withOrderByTagAsc()
{
STEP("Get tags and order results by tag name in ascending order");
returnedCollection = restClient.authenticateUser(adminUserModel)
.withParams("orderBy=tag ASC")
.withCoreAPI()
.getTags();
restClient.assertStatusCodeIs(OK);
returnedCollection.assertThat().entriesListIsSortedAscBy("tag");
}
/**
* Get tags and order results by tag name in descending order
*/
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void testGetTags_withOrderByTagDesc()
{
STEP("Get tags and order results by tag name in descending order");
returnedCollection = restClient.authenticateUser(adminUserModel)
.withParams("orderBy=tag DESC")
.withCoreAPI()
.getTags();
restClient.assertStatusCodeIs(OK);
returnedCollection.assertThat().entriesListIsSortedDescBy("tag");
}
/**
* Ensure that we get a 400 error when we request to order by count without also including the tag count.
*/
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void testGetTags_orderByCountWithoutIncludeCount()
{
restClient.authenticateUser(adminUserModel)
.withParams("orderBy=count")
.withCoreAPI()
.getTags();
restClient.assertStatusCodeIs(BAD_REQUEST);
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.SANITY, description = "Failed authentication get tags call returns status code 401 with Manager role")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.SANITY })
// @Bug(id="MNT-16904", description = "It fails only on environment with tenants")
public void failedAuthenticationReturnsUnauthorizedStatus() throws Exception
public void failedAuthenticationReturnsUnauthorizedStatus()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteManager));
userModel = dataUser.createRandomTestUser();
@@ -83,7 +227,7 @@ public class GetTagsTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that if maxItems is invalid status code returned is 400")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION})
public void maxItemsInvalidValueTest() throws Exception
public void maxItemsInvalidValueTest()
{
restClient.authenticateUser(adminUserModel).withParams("maxItems=abc").withCoreAPI().getTags();
restClient.assertStatusCodeIs(HttpStatus.BAD_REQUEST).assertLastError().containsSummary(String.format(RestErrorModel.INVALID_MAXITEMS, "abc"));
@@ -92,7 +236,7 @@ public class GetTagsTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that if skipCount is invalid status code returned is 400")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION})
public void skipCountInvalidValueTest() throws Exception
public void skipCountInvalidValueTest()
{
restClient.authenticateUser(adminUserModel).withParams("skipCount=abc").withCoreAPI().getTags();
restClient.assertStatusCodeIs(HttpStatus.BAD_REQUEST).assertLastError().containsSummary(String.format(RestErrorModel.INVALID_SKIPCOUNT, "abc"));
@@ -101,55 +245,55 @@ public class GetTagsTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that file tag is retrieved")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION})
public void fileTagIsRetrieved() throws Exception
public void fileTagIsRetrieved()
{
restClient.authenticateUser(adminUserModel);
returnedCollection = restClient.withParams("maxItems=10000").withCoreAPI().getTags();
restClient.assertStatusCodeIs(HttpStatus.OK);
restClient.assertStatusCodeIs(OK);
returnedCollection.assertThat().entriesListIsNotEmpty()
.and().entriesListContains("tag", documentTagValue.toLowerCase())
.and().entriesListContains("tag", documentTagValue2.toLowerCase());
.and().entriesListContains("tag", documentTagValue)
.and().entriesListContains("tag", documentTagValue2);
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that folder tag is retrieved")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION})
public void folderTagIsRetrieved() throws Exception
public void folderTagIsRetrieved()
{
restClient.authenticateUser(adminUserModel);
returnedCollection = restClient.withParams("maxItems=10000").withCoreAPI().getTags();
restClient.assertStatusCodeIs(HttpStatus.OK);
restClient.assertStatusCodeIs(OK);
returnedCollection.assertThat().entriesListIsNotEmpty()
.and().entriesListContains("tag", folderTagValue.toLowerCase());
.and().entriesListContains("tag", folderTagValue);
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify site Manager is able to get tags using properties parameter."
+ "Check that properties filter is applied.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void siteManagerIsAbleToRetrieveTagsWithPropertiesParameter() throws Exception
public void siteManagerIsAbleToRetrieveTagsWithPropertiesParameter()
{
returnedCollection = restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteManager))
.withParams("maxItems=5000&properties=tag").withCoreAPI().getTags();
restClient.assertStatusCodeIs(HttpStatus.OK);
restClient.assertStatusCodeIs(OK);
returnedCollection.assertThat().entriesListIsNotEmpty()
.and().entriesListContains("tag", documentTagValue.toLowerCase())
.and().entriesListContains("tag", documentTagValue2.toLowerCase())
.and().entriesListContains("tag", documentTagValue)
.and().entriesListContains("tag", documentTagValue2)
.and().entriesListDoesNotContain("id");
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "With admin get tags and use skipCount parameter. Check pagination")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void useSkipCountCheckPagination() throws Exception
public void useSkipCountCheckPagination()
{
returnedCollection = restClient.authenticateUser(adminUserModel).withCoreAPI().getTags();
restClient.assertStatusCodeIs(HttpStatus.OK);
restClient.assertStatusCodeIs(OK);
RestTagModel firstTag = returnedCollection.getEntries().get(0).onModel();
RestTagModel secondTag = returnedCollection.getEntries().get(1).onModel();
RestTagModelsCollection tagsWithSkipCount = restClient.withParams("skipCount=2").withCoreAPI().getTags();
restClient.assertStatusCodeIs(HttpStatus.OK);
restClient.assertStatusCodeIs(OK);
tagsWithSkipCount.assertThat().entriesListDoesNotContain("tag", firstTag.getTag())
.assertThat().entriesListDoesNotContain("tag", secondTag.getTag());
@@ -159,15 +303,15 @@ public class GetTagsTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "With admin get tags and use maxItems parameter. Check pagination")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void useMaxItemsParameterCheckPagination() throws Exception
public void useMaxItemsParameterCheckPagination()
{
returnedCollection = restClient.authenticateUser(adminUserModel).withCoreAPI().getTags();
restClient.assertStatusCodeIs(HttpStatus.OK);
restClient.assertStatusCodeIs(OK);
RestTagModel firstTag = returnedCollection.getEntries().get(0).onModel();
RestTagModel secondTag = returnedCollection.getEntries().get(1).onModel();
RestTagModelsCollection tagsWithMaxItems = restClient.withParams("maxItems=2").withCoreAPI().getTags();
restClient.assertStatusCodeIs(HttpStatus.OK);
restClient.assertStatusCodeIs(OK);
tagsWithMaxItems.assertThat().entriesListContains("tag", firstTag.getTag())
.assertThat().entriesListContains("tag", secondTag.getTag())
@@ -178,23 +322,22 @@ public class GetTagsTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "With manager get tags and use high skipCount parameter. Check pagination")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void useHighSkipCountCheckPagination() throws Exception
public void useHighSkipCountCheckPagination()
{
returnedCollection = restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteManager))
.withParams("skipCount=20000").withCoreAPI().getTags();
restClient.assertStatusCodeIs(HttpStatus.OK);
restClient.assertStatusCodeIs(OK);
returnedCollection.assertThat().entriesListIsEmpty()
.getPagination().assertThat().field("maxItems").is(100)
.and().field("hasMoreItems").is("false")
.and().field("count").is("0")
.and().field("skipCount").is(20000)
.and().field("totalItems").is(0);
.and().field("skipCount").is(20000);
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "With Collaborator user get tags and use maxItems with value zero. Check default error model schema")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void useMaxItemsWithValueZeroCheckDefaultErrorModelSchema() throws Exception
public void useMaxItemsWithValueZeroCheckDefaultErrorModelSchema()
{
returnedCollection = restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteCollaborator))
.withParams("maxItems=0").withCoreAPI().getTags();
@@ -208,9 +351,9 @@ public class GetTagsTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "With Manager user delete tag. Check it is not retrieved anymore.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void checkThatDeletedTagIsNotRetrievedAnymore() throws Exception
public void checkThatDeletedTagIsNotRetrievedAnymore()
{
String removedTag = RandomData.getRandomName("tag3");
String removedTag = getRandomName("tag3");
RestTagModel deletedTag = restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteManager))
.withCoreAPI().usingResource(document).addTag(removedTag);
@@ -220,7 +363,7 @@ public class GetTagsTests extends TagsDataPrep
returnedCollection = restClient.withParams("maxItems=10000").withCoreAPI().getTags();
returnedCollection.assertThat().entriesListIsNotEmpty()
.and().entriesListDoesNotContain("tag", removedTag.toLowerCase());
.and().entriesListDoesNotContain("tag", removedTag);
}
/**
@@ -237,7 +380,7 @@ public class GetTagsTests extends TagsDataPrep
restClient.assertStatusCodeIs(HttpStatus.OK);
returnedCollection.assertThat()
.entrySetMatches("tag", Set.of(documentTagValue.toLowerCase()));
.entrySetMatches("tag", Set.of(documentTagValue));
}
/**
@@ -254,7 +397,7 @@ public class GetTagsTests extends TagsDataPrep
restClient.assertStatusCodeIs(HttpStatus.OK);
returnedCollection.assertThat()
.entrySetMatches("tag", Set.of(documentTagValue.toLowerCase(), folderTagValue.toLowerCase()));
.entrySetMatches("tag", Set.of(documentTagValue, folderTagValue));
}
/**
@@ -265,13 +408,13 @@ public class GetTagsTests extends TagsDataPrep
{
STEP("Get tags with names filter using MATCHES and expect one item in result");
returnedCollection = restClient.authenticateUser(adminUserModel)
.withParams("where=(tag MATCHES ('orphan*'))")
.withCoreAPI()
.getTags();
.withParams("where=(tag MATCHES ('orphan*'))", "maxItems=10000")
.withCoreAPI()
.getTags();
restClient.assertStatusCodeIs(HttpStatus.OK);
returnedCollection.assertThat()
.entrySetContains("tag", orphanTag.getTag().toLowerCase());
.entrySetContains("tag", orphanTag.getTag());
}
/**
@@ -282,13 +425,13 @@ public class GetTagsTests extends TagsDataPrep
{
STEP("Get tags with names filter using EQUALS and MATCHES and expect four items in result");
returnedCollection = restClient.authenticateUser(adminUserModel)
.withParams("where=(tag='" + orphanTag.getTag() + "' OR tag MATCHES ('*tag*'))")
.withParams("where=(tag MATCHES ('*tag*'))", "maxItems=10000")
.withCoreAPI()
.getTags();
restClient.assertStatusCodeIs(HttpStatus.OK);
returnedCollection.assertThat()
.entrySetContains("tag", documentTagValue.toLowerCase(), documentTagValue2.toLowerCase(), folderTagValue.toLowerCase(), orphanTag.getTag().toLowerCase());
.entrySetContains("tag", documentTagValue, documentTagValue2, folderTagValue, orphanTag.getTag());
}
/**
@@ -299,17 +442,17 @@ public class GetTagsTests extends TagsDataPrep
{
STEP("Get tags applying names filter using MATCHES twice and expect four items in result");
returnedCollection = restClient.authenticateUser(adminUserModel)
.withParams("where=(tag MATCHES ('orphan*') OR tag MATCHES ('tag*'))")
.withParams("where=(tag MATCHES ('orphan*') OR tag MATCHES ('tag*'))", "maxItems=10000")
.withCoreAPI()
.getTags();
restClient.assertStatusCodeIs(HttpStatus.OK);
returnedCollection.assertThat()
.entrySetContains("tag", documentTagValue.toLowerCase(), documentTagValue2.toLowerCase(), folderTagValue.toLowerCase(), orphanTag.getTag().toLowerCase());
.entrySetContains("tag", documentTagValue, documentTagValue2, folderTagValue, orphanTag.getTag());
}
/**
* Verify that providing incorrect field name in where query will result with 400 (Bad Request).
* Verify that providing incorrect field name in where query will result with 400 (Bad Request).
*/
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void testGetTags_withWrongWherePropertyNameAndExpect400()
@@ -339,4 +482,36 @@ public class GetTagsTests extends TagsDataPrep
restClient.assertStatusCodeIs(HttpStatus.BAD_REQUEST)
.assertLastError().containsSummary("An invalid WHERE query was received. Unsupported Predicate");
}
/**
* Verify if count field is present for searched tags.
*/
@Test(groups = {TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION})
public void testGetTags_includingCount()
{
STEP("Get tags including count and verify if it is present in the response");
final RestTagModelsCollection searchedTags = restClient.withCoreAPI().include(FIELD_COUNT).getTags();
restClient.assertStatusCodeIs(OK);
searchedTags.assertThat().entriesListIsNotEmpty()
.assertThat().entriesListContains(FIELD_COUNT)
.assertThat().entriesListContains(FIELD_TAG)
.assertThat().entriesListContains(FIELD_ID);
}
/**
* Verify if count field is not present for searched tags.
*/
@Test(groups = {TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION})
public void testGetTags_notIncludingCount()
{
STEP("Get tags, not including count and verify if it is not in the response");
final RestTagModelsCollection searchedTags = restClient.withCoreAPI().getTags();
restClient.assertStatusCodeIs(OK);
searchedTags.assertThat().entriesListIsNotEmpty()
.assertThat().entriesListDoesNotContain(FIELD_COUNT)
.assertThat().entriesListContains(FIELD_TAG)
.assertThat().entriesListContains(FIELD_ID);
}
}

View File

@@ -22,7 +22,8 @@ public class TagsDataPrep extends RestTest
protected static ListUserWithRoles usersWithRoles;
protected static SiteModel siteModel;
protected static FileModel document;
protected static FolderModel folder;
protected static FolderModel folder, folder2;
protected static RestTagModelsCollection folder2tags;
protected static String documentTagValue, documentTagValue2, folderTagValue;
protected static RestTagModel documentTag, documentTag2, folderTag, orphanTag, returnedModel;
protected static RestTagModelsCollection returnedCollection;
@@ -38,25 +39,28 @@ public class TagsDataPrep extends RestTest
usersWithRoles = dataUser.usingAdmin().addUsersWithRolesToSite(siteModel, UserRole.SiteManager, UserRole.SiteCollaborator, UserRole.SiteConsumer, UserRole.SiteContributor);
document = dataContent.usingUser(adminUserModel).usingSite(siteModel).createContent(CMISUtil.DocumentType.TEXT_PLAIN);
folder = dataContent.usingUser(adminUserModel).usingSite(siteModel).createFolder();
folder2 = dataContent.usingUser(adminUserModel).usingSite(siteModel).createFolder();
documentTagValue = RandomData.getRandomName("tag");
documentTagValue2 = RandomData.getRandomName("tag");
folderTagValue = RandomData.getRandomName("tag");
documentTagValue = RandomData.getRandomName("tag").toLowerCase();
documentTagValue2 = RandomData.getRandomName("tag").toLowerCase();
folderTagValue = RandomData.getRandomName("tag").toLowerCase();
restClient.authenticateUser(adminUserModel);
documentTag = restClient.withCoreAPI().usingResource(document).addTag(documentTagValue);
documentTag2 = restClient.withCoreAPI().usingResource(document).addTag(documentTagValue2);
folderTag = restClient.withCoreAPI().usingResource(folder).addTag(folderTagValue);
orphanTag = restClient.withCoreAPI().createSingleTag(RestTagModel.builder().tag(RandomData.getRandomName("orphan-tag")).create());
orphanTag = restClient.withCoreAPI().createSingleTag(RestTagModel.builder().tag(RandomData.getRandomName("orphan-tag").toLowerCase()).create());
folder2tags = restClient.withCoreAPI().usingResource(folder2).addTags(folderTagValue, documentTagValue);
// Allow indexing to complete.
Utility.sleep(500, 60000, () ->
{
returnedCollection = restClient.withParams("maxItems=10000", "where=(tag MATCHES ('*tag*'))")
.withCoreAPI().getTags();
returnedCollection.assertThat().entriesListContains("tag", documentTagValue.toLowerCase())
.and().entriesListContains("tag", documentTagValue2.toLowerCase())
.and().entriesListContains("tag", folderTagValue.toLowerCase());
.withCoreAPI().getTags();
returnedCollection.assertThat().entriesListContains("tag", documentTagValue)
.and().entriesListContains("tag", documentTagValue2)
.and().entriesListContains("tag", folderTagValue)
.and().entriesListContains("tag", orphanTag.getTag());
});
}
@@ -78,4 +82,9 @@ public class TagsDataPrep extends RestTest
.tag(tag)
.create();
}
protected RestTagModel createTagModelWithName(final String tagName)
{
return RestTagModel.builder().tag(tagName).create();
}
}

View File

@@ -1,5 +1,8 @@
package org.alfresco.rest.tags;
import static org.alfresco.utility.report.log.Step.STEP;
import static org.testng.Assert.fail;
import org.alfresco.rest.model.RestErrorModel;
import org.alfresco.rest.model.RestTagModel;
import org.alfresco.utility.Utility;
@@ -13,6 +16,7 @@ import org.alfresco.utility.testrail.annotation.TestRail;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.http.HttpStatus;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Ignore;
import org.testng.annotations.Test;
/**
@@ -25,28 +29,29 @@ public class UpdateTagTests extends TagsDataPrep
private String randomTag = "";
@BeforeMethod(alwaysRun=true)
public void addTagToDocument() throws Exception
public void addTagToDocument()
{
restClient.authenticateUser(adminUserModel);
oldTag = restClient.withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("old"));
randomTag = RandomData.getRandomName("tag");
oldTag = restClient.withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("old").toLowerCase());
randomTag = RandomData.getRandomName("tag").toLowerCase();
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.SANITY, description = "Verify Admin user updates tags and status code is 200")
@Bug(id="REPO-1828")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.SANITY })
public void adminIsAbleToUpdateTags() throws Exception
public void adminIsAbleToUpdateTags()
{
restClient.authenticateUser(adminUserModel);
returnedModel = restClient.withCoreAPI().usingTag(oldTag).update(randomTag);
restClient.assertStatusCodeIs(HttpStatus.OK);
returnedModel.assertThat().field("tag").is(randomTag);
returnedModel.assertThat().field("id").isNotNull();
}
@TestRail(section = { TestGroup.REST_API,
TestGroup.TAGS }, executionType = ExecutionType.REGRESSION, description = "Verify Manager user can't update tags with Rest API and status code is 403")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void managerIsNotAbleToUpdateTag() throws Exception
public void managerIsNotAbleToUpdateTag()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteManager));
restClient.withCoreAPI().usingTag(oldTag).update(randomTag);
@@ -56,7 +61,7 @@ public class UpdateTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS },
executionType = ExecutionType.REGRESSION, description = "Verify Collaborator user can't update tags with Rest API and status code is 403")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void collaboratorIsNotAbleToUpdateTagCheckDefaultErrorModelSchema() throws Exception
public void collaboratorIsNotAbleToUpdateTagCheckDefaultErrorModelSchema()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteCollaborator));
restClient.withCoreAPI().usingTag(oldTag).update(randomTag);
@@ -69,7 +74,7 @@ public class UpdateTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS },
executionType = ExecutionType.REGRESSION, description = "Verify Contributor user can't update tags with Rest API and status code is 403")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void contributorIsNotAbleToUpdateTag() throws Exception
public void contributorIsNotAbleToUpdateTag()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteContributor));
restClient.withCoreAPI().usingTag(oldTag).update(randomTag);
@@ -79,7 +84,7 @@ public class UpdateTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS },
executionType = ExecutionType.SANITY, description = "Verify Consumer user can't update tags with Rest API and status code is 403")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void consumerIsNotAbleToUpdateTag() throws Exception
public void consumerIsNotAbleToUpdateTag()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteConsumer));
restClient.withCoreAPI().usingTag(oldTag).update(randomTag);
@@ -90,7 +95,7 @@ public class UpdateTagTests extends TagsDataPrep
executionType = ExecutionType.SANITY, description = "Verify user gets status code 401 if authentication call fails")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.SANITY })
// @Bug(id="MNT-16904", description = "It fails only on environment with tenants")
public void userIsNotAbleToUpdateTagIfAuthenticationFails() throws Exception
public void userIsNotAbleToUpdateTagIfAuthenticationFails()
{
UserModel siteManager = usersWithRoles.getOneUserWithRole(UserRole.SiteManager);
String managerPassword = siteManager.getPassword();
@@ -103,118 +108,140 @@ public class UpdateTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION, description = "Verify admin is not able to update tag with invalid id")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void adminIsNotAbleToUpdateTagWithInvalidId() throws Exception
public void adminIsNotAbleToUpdateTagWithInvalidId()
{
String invalidTagId = "invalid-id";
RestTagModel tag = restClient.authenticateUser(adminUserModel).withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
RestTagModel tag = restClient.authenticateUser(adminUserModel).withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag").toLowerCase());
tag.setId(invalidTagId);
restClient.withCoreAPI().usingTag(tag).update(RandomData.getRandomName("tag"));
restClient.withCoreAPI().usingTag(tag).update(RandomData.getRandomName("tag").toLowerCase());
restClient.assertStatusCodeIs(HttpStatus.NOT_FOUND)
.assertLastError().containsSummary(String.format(RestErrorModel.ENTITY_NOT_FOUND, invalidTagId));
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION, description = "Verify admin is not able to update tag with empty id")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void adminIsNotAbleToUpdateTagWithEmptyId() throws Exception
public void adminIsNotAbleToUpdateTagWithEmptyId()
{
RestTagModel tag = restClient.authenticateUser(adminUserModel).withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
RestTagModel tag = restClient.authenticateUser(adminUserModel).withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag").toLowerCase());
tag.setId("");
restClient.withCoreAPI().usingTag(tag).update(RandomData.getRandomName("tag"));
restClient.withCoreAPI().usingTag(tag).update(RandomData.getRandomName("tag").toLowerCase());
restClient.assertStatusCodeIs(HttpStatus.METHOD_NOT_ALLOWED)
.assertLastError().containsSummary(RestErrorModel.PUT_EMPTY_ARGUMENT);
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION, description = "Verify admin is not able to update tag with invalid body")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void adminIsNotAbleToUpdateTagWithEmptyBody() throws Exception
public void adminIsNotAbleToUpdateTagWithEmptyBody()
{
RestTagModel tag = restClient.authenticateUser(adminUserModel).withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
RestTagModel tag = restClient.authenticateUser(adminUserModel).withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag").toLowerCase());
restClient.withCoreAPI().usingTag(tag).update("");
restClient.assertStatusCodeIs(HttpStatus.BAD_REQUEST)
.assertLastError().containsSummary(RestErrorModel.EMPTY_TAG);
.assertLastError().containsSummary(RestErrorModel.BLANK_TAG);
}
@Bug(id="ACE-5629")
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify admin is not able to update tag with invalid body containing '|' symbol")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void adminIsNotAbleToUpdateTagWithInvalidBodyScenario1() throws Exception
@Ignore
public void adminIsNotAbleToUpdateTagWithInvalidBodyScenario1()
{
String invalidTagBody = "|.\"/<>*";
RestTagModel tag = restClient.authenticateUser(adminUserModel).withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
Utility.sleep(500, 20000, () ->
RestTagModel tag = restClient.authenticateUser(adminUserModel).withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag").toLowerCase());
try
{
restClient.withCoreAPI().usingTag(tag).update(invalidTagBody);
restClient.assertStatusCodeIs(HttpStatus.BAD_REQUEST)
.assertLastError().containsSummary(String.format(RestErrorModel.INVALID_TAG, invalidTagBody));
});
Utility.sleep(500, 20000, () ->
{
restClient.withCoreAPI().usingTag(tag).update(invalidTagBody);
restClient.assertStatusCodeIs(HttpStatus.BAD_REQUEST)
.assertLastError().containsSummary(String.format(RestErrorModel.INVALID_TAG, invalidTagBody));
});
}
catch (InterruptedException e)
{
fail("Test interrupted while waiting for error status code.");
}
}
@Bug(id="ACE-5629")
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify admin is not able to update tag with invalid body without '|' symbol")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void adminIsNotAbleToUpdateTagWithInvalidBodyScenario2() throws Exception
@Ignore
public void adminIsNotAbleToUpdateTagWithInvalidBodyScenario2()
{
String invalidTagBody = ".\"/<>*";
RestTagModel tag = restClient.authenticateUser(adminUserModel).withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
try
{
Utility.sleep(500, 20000, () ->
{
restClient.withCoreAPI().usingTag(tag).update(invalidTagBody);
restClient.assertStatusCodeIs(HttpStatus.BAD_REQUEST)
restClient.withCoreAPI().usingTag(tag).update(invalidTagBody);
restClient.assertStatusCodeIs(HttpStatus.BAD_REQUEST)
.assertLastError().containsSummary(String.format(RestErrorModel.INVALID_TAG, invalidTagBody));
});
});
}
catch (InterruptedException e)
{
fail("Test interrupted while waiting for error status code.");
}
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify admin user can provide large string for new tag value.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
@Bug(id="REPO-1828")
public void adminIsAbleToUpdateTagsProvideLargeStringTag() throws Exception
@Ignore
public void adminIsAbleToUpdateTagsProvideLargeStringTag()
{
String largeStringTag = RandomStringUtils.randomAlphanumeric(10000);
String largeStringTag = RandomStringUtils.randomAlphanumeric(10000).toLowerCase();
restClient.authenticateUser(adminUserModel);
returnedModel = restClient.withCoreAPI().usingTag(oldTag).update(largeStringTag);
restClient.assertStatusCodeIs(HttpStatus.OK);
returnedModel.assertThat().field("tag").is(largeStringTag);
returnedModel.assertThat().field("id").isNotNull();
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify admin user can provide short string for new tag value.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
@Bug(id="REPO-1828")
public void adminIsAbleToUpdateTagsProvideShortStringTag() throws Exception
public void adminIsAbleToUpdateTagsProvideShortStringTag()
{
String shortStringTag = RandomStringUtils.randomAlphanumeric(2);
String shortStringTag = RandomStringUtils.randomAlphanumeric(2).toLowerCase();
restClient.authenticateUser(adminUserModel);
returnedModel = restClient.withCoreAPI().usingTag(oldTag).update(shortStringTag);
restClient.assertStatusCodeIs(HttpStatus.OK);
returnedModel.assertThat().field("tag").is(shortStringTag);
returnedModel.assertThat().field("id").isNotNull();
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify admin user can provide string with special chars for new tag value.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
@Bug(id="REPO-1828")
public void adminIsAbleToUpdateTagsProvideSpecialCharsStringTag() throws Exception
@Ignore
public void adminIsAbleToUpdateTagsProvideSpecialCharsStringTag()
{
String specialCharsString = "!@#$%^&*()'\".,<>-_+=|\\";
String specialCharsString = RandomData.getRandomName("!@#$%^&*()'\".,<>-_+=|\\").toLowerCase();
restClient.authenticateUser(adminUserModel);
returnedModel = restClient.withCoreAPI().usingTag(oldTag).update(specialCharsString);
restClient.assertStatusCodeIs(HttpStatus.OK);
returnedModel.assertThat().field("tag").is(specialCharsString);
returnedModel.assertThat().field("id").isNotNull();
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify Admin user can provide existing tag for new tag value.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
@Bug(id="REPO-1828")
public void adminIsAbleToUpdateTagsProvideExistingTag() throws Exception
@Ignore
public void adminIsAbleToUpdateTagsProvideExistingTag()
{
String existingTag = "oldTag";
String existingTag = RandomData.getRandomName("oldTag").toLowerCase();
RestTagModel oldExistingTag = restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteManager))
.withCoreAPI().usingResource(document).addTag(existingTag);
restClient.assertStatusCodeIs(HttpStatus.CREATED);
@@ -223,38 +250,43 @@ public class UpdateTagTests extends TagsDataPrep
returnedModel = restClient.withCoreAPI().usingTag(oldExistingTag).update(existingTag);
restClient.assertStatusCodeIs(HttpStatus.OK);
returnedModel.assertThat().field("tag").is(existingTag);
returnedModel.assertThat().field("id").isNotNull();
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify Admin user can delete a tag, add tag and update it.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
@Bug(id="REPO-1828")
public void adminDeleteTagAddTagUpdateTag() throws Exception
@Ignore
public void adminDeleteTagAddTagUpdateTag()
{
restClient.authenticateUser(adminUserModel)
.withCoreAPI().usingResource(document).deleteTag(oldTag);
restClient.assertStatusCodeIs(HttpStatus.NO_CONTENT);
String newTag = "addTag";
String newTag = RandomData.getRandomName("addTag").toLowerCase();
RestTagModel newTagModel = restClient.withCoreAPI().usingResource(document).addTag(newTag);
restClient.assertStatusCodeIs(HttpStatus.CREATED);
returnedModel = restClient.withCoreAPI().usingTag(newTagModel).update(newTag);
restClient.assertStatusCodeIs(HttpStatus.OK);
returnedModel.assertThat().field("tag").is(newTag);
returnedModel.assertThat().field("id").isNotNull();
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify Admin user can update a tag, delete tag and add it.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
@Bug(id="REPO-1828")
public void adminUpdateTagDeleteTagAddTag() throws Exception
@Ignore
public void adminUpdateTagDeleteTagAddTag()
{
String newTag = "addTag";
String newTag = RandomData.getRandomName("addTag").toLowerCase();
returnedModel = restClient.authenticateUser(adminUserModel).withCoreAPI().usingTag(oldTag).update(newTag);
restClient.assertStatusCodeIs(HttpStatus.OK);
returnedModel.assertThat().field("tag").is(newTag);
returnedModel.assertThat().field("id").isNotNull();
restClient.withCoreAPI().usingResource(document).deleteTag(returnedModel);
restClient.assertStatusCodeIs(HttpStatus.NO_CONTENT);
@@ -262,4 +294,35 @@ public class UpdateTagTests extends TagsDataPrep
restClient.withCoreAPI().usingResource(document).addTag(newTag);
restClient.assertStatusCodeIs(HttpStatus.CREATED);
}
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.SANITY,
description = "Verify Admin user updates orphan tags and status code is 200")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.SANITY })
public void adminIsAbleToUpdateOrphanTag()
{
STEP("Update orphan tag and expect 200");
final String newTagName = RandomData.getRandomName("new").toLowerCase();
returnedModel = restClient.authenticateUser(adminUserModel).withCoreAPI().usingTag(orphanTag).update(newTagName);
restClient.assertStatusCodeIs(HttpStatus.OK);
RestTagModel expected = RestTagModel.builder().id(orphanTag.getId()).tag(newTagName).create();
returnedModel.assertThat().isEqualTo(expected);
}
@Test (groups = { TestGroup.REST_API, TestGroup.TAGS })
public void canUpdateTagAndGetCount()
{
STEP("Create an orphaned tag");
String tagName = RandomData.getRandomName("tag").toLowerCase();
RestTagModel createdTag = RestTagModel.builder().tag(tagName).create();
RestTagModel tag = restClient.authenticateUser(adminUserModel).withCoreAPI().createSingleTag(createdTag);
STEP("Update tag and request the count field");
String newTagName = RandomData.getRandomName("new").toLowerCase();
returnedModel = restClient.authenticateUser(adminUserModel).withCoreAPI().include("count").usingTag(tag).update(newTagName);
restClient.assertStatusCodeIs(HttpStatus.OK);
RestTagModel expected = RestTagModel.builder().id(tag.getId()).tag(newTagName).count(0).create();
returnedModel.assertThat().isEqualTo(expected);
}
}

View File

@@ -33,13 +33,13 @@ public class AddTagTests extends TagsDataPrep
@BeforeMethod(alwaysRun = true)
public void generateRandomTag()
{
tagValue = RandomData.getRandomName("tag");
tagValue = RandomData.getRandomName("tag").toLowerCase();
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify admin user adds tags with Rest API and status code is 201")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void adminIsAbleToAddTag() throws Exception
public void adminIsAbleToAddTag()
{
restClient.authenticateUser(adminUserModel);
returnedModel = restClient.withCoreAPI().usingResource(document).addTag(tagValue);
@@ -51,7 +51,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.SANITY,
description = "Verify Manager user adds tags with Rest API and status code is 201")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.SANITY })
public void managerIsAbleToTagAFile() throws Exception
public void managerIsAbleToTagAFile()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteManager));
returnedModel = restClient.withCoreAPI().usingResource(document).addTag(tagValue);
@@ -63,7 +63,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify Collaborator user adds tags with Rest API and status code is 201")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void collaboratorIsAbleToTagAFile() throws Exception
public void collaboratorIsAbleToTagAFile()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteCollaborator));
returnedModel = restClient.withCoreAPI().usingResource(document).addTag(tagValue);
@@ -75,7 +75,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify Contributor user doesn't have permission to add tags with Rest API and status code is 403")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void contributorIsNotAbleToAddTagToAnotherContent() throws Exception
public void contributorIsNotAbleToAddTagToAnotherContent()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteContributor));
restClient.withCoreAPI().usingResource(document).addTag(tagValue);
@@ -85,7 +85,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify Contributor user adds tags to his content with Rest API and status code is 201")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void contributorIsAbleToAddTagToHisContent() throws Exception
public void contributorIsAbleToAddTagToHisContent()
{
userModel = usersWithRoles.getOneUserWithRole(UserRole.SiteContributor);
restClient.authenticateUser(userModel);
@@ -99,7 +99,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify Consumer user doesn't have permission to add tags with Rest API and status code is 403")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void consumerIsNotAbleToTagAFile() throws Exception
public void consumerIsNotAbleToTagAFile()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteConsumer));
restClient.withCoreAPI().usingResource(document).addTag(tagValue);
@@ -110,7 +110,7 @@ public class AddTagTests extends TagsDataPrep
description = "Verify user gets status code 401 if authentication call fails")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.SANITY })
// @Bug(id="MNT-16904", description = "It fails only on environment with tenants")
public void userIsNotAbleToAddTagIfAuthenticationFails() throws Exception
public void userIsNotAbleToAddTagIfAuthenticationFails()
{
UserModel siteManager = usersWithRoles.getOneUserWithRole(UserRole.SiteManager);
String managerPassword = siteManager.getPassword();
@@ -124,7 +124,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that adding empty tag returns status code 400")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void emptyTagTest() throws Exception
public void emptyTagTest()
{
restClient.authenticateUser(adminUserModel);
returnedModel = restClient.withCoreAPI().usingResource(document).addTag("");
@@ -134,7 +134,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that adding tag with user that has no permissions returns status code 403")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void addTagWithUserThatDoesNotHavePermissions() throws Exception
public void addTagWithUserThatDoesNotHavePermissions()
{
restClient.authenticateUser(dataUser.createRandomTestUser());
returnedModel = restClient.withCoreAPI().usingResource(document).addTag(tagValue);
@@ -144,7 +144,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that adding tag to a node that does not exist returns status code 404")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void addTagToInexistentNode() throws Exception
public void addTagToInexistentNode()
{
String oldNodeRef = document.getNodeRef();
String nodeRef = RandomStringUtils.randomAlphanumeric(10);
@@ -159,7 +159,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.SANITY,
description = "Verify that manager is able to tag a folder")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.SANITY })
public void managerIsAbleToTagAFolder() throws Exception
public void managerIsAbleToTagAFolder()
{
FolderModel folderModel = dataContent.usingUser(adminUserModel).usingSite(siteModel).createFolder();
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteManager));
@@ -171,7 +171,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that tagged file can be tagged again")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void addTagToATaggedFile() throws Exception
public void addTagToATaggedFile()
{
restClient.authenticateUser(adminUserModel);
@@ -195,7 +195,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that user cannot add invalid tag")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void addInvalidTag() throws Exception
public void addInvalidTag()
{
restClient.authenticateUser(adminUserModel);
returnedModel = restClient.withCoreAPI().usingResource(document).addTag("-1~!|@#$%^&*()_=");
@@ -205,7 +205,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that contributor is able to tag a folder created by self")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void contributorIsAbleToTagAFolderCreatedBySelf() throws Exception
public void contributorIsAbleToTagAFolderCreatedBySelf()
{
FolderModel folderModel = dataContent.usingUser(usersWithRoles.getOneUserWithRole(UserRole.SiteContributor)).usingSite(siteModel).createFolder();
@@ -218,7 +218,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that collaborator is able to tag a folder")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void collaboratorIsAbleToTagAFolder() throws Exception
public void collaboratorIsAbleToTagAFolder()
{
FolderModel folderModel = dataContent.usingUser(adminUserModel).usingSite(siteModel).createFolder();
@@ -231,7 +231,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that consumer is not able to tag a folder. Check default error model schema.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void consumerIsNotAbleToTagAFolder() throws Exception
public void consumerIsNotAbleToTagAFolder()
{
FolderModel folderModel = dataContent.usingUser(adminUserModel).usingSite(siteModel).createFolder();
@@ -246,7 +246,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that tagged folder can be tagged again")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void addTagToATaggedFolder() throws Exception
public void addTagToATaggedFolder()
{
FolderModel folderModel = dataContent.usingUser(adminUserModel).usingSite(siteModel).createFolder();
@@ -269,11 +269,11 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Using collaborator provide more than one tag element")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void provideMoreThanOneTagElement() throws Exception
public void provideMoreThanOneTagElement()
{
FolderModel folderModel = dataContent.usingUser(adminUserModel).usingSite(siteModel).createFolder();
String tagValue1 = RandomData.getRandomName("tag1");
String tagValue2 = RandomData.getRandomName("tag2");
String tagValue1 = RandomData.getRandomName("tag1").toLowerCase();
String tagValue2 = RandomData.getRandomName("tag2").toLowerCase();
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteCollaborator));
@@ -288,7 +288,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that manager cannot add tag with special characters.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void addTagWithSpecialCharacters() throws Exception
public void addTagWithSpecialCharacters()
{
FolderModel folderModel = dataContent.usingUser(adminUserModel).usingSite(siteModel).createFolder();
String specialCharsTag = "!@#$%^&*()'\".,<>-_+=|\\";
@@ -301,7 +301,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that you cannot tag a comment and it returns status code 405")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void addTagToAComment() throws Exception
public void addTagToAComment()
{
FileModel file = dataContent.usingSite(siteModel).usingUser(adminUserModel).createContent(CMISUtil.DocumentType.TEXT_PLAIN);
String comment = "comment for a tag";
@@ -316,7 +316,7 @@ public class AddTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that you cannot tag a tag and it returns status code 405")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void addTagToATag() throws Exception
public void addTagToATag()
{
FileModel file = dataContent.usingSite(siteModel).usingUser(adminUserModel).createContent(CMISUtil.DocumentType.TEXT_PLAIN);
@@ -326,4 +326,17 @@ public class AddTagTests extends TagsDataPrep
restClient.withCoreAPI().usingResource(file).addTag(tagValue);
restClient.assertStatusCodeIs(HttpStatus.METHOD_NOT_ALLOWED).assertLastError().containsSummary(RestErrorModel.CANNOT_TAG);
}
}
@TestRail (section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify the tag name is converted to lower case before being applied")
@Test (groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void tagNameIsConvertedToLowerCase()
{
restClient.authenticateUser(adminUserModel);
String tagName = RandomData.getRandomName("TaG-oNe");
returnedModel = restClient.withCoreAPI().usingResource(document).addTag(tagName);
restClient.assertStatusCodeIs(HttpStatus.CREATED);
returnedModel.assertThat().field("tag").is(tagName.toLowerCase())
.and().field("id").isNotEmpty();
}
}

View File

@@ -30,14 +30,14 @@ public class AddTagsTests extends TagsDataPrep
@BeforeMethod(alwaysRun = true)
public void generateRandomTagsList()
{
tag1 = RandomData.getRandomName("tag");
tag2 = RandomData.getRandomName("tag");
tag1 = RandomData.getRandomName("tag").toLowerCase();
tag2 = RandomData.getRandomName("tag").toLowerCase();
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify admin user adds multiple tags with Rest API and status code is 201")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void adminIsAbleToAddTags() throws Exception
public void adminIsAbleToAddTags()
{
restClient.authenticateUser(adminUserModel);
returnedCollection = restClient.withCoreAPI().usingResource(document).addTags(tag1, tag2);
@@ -49,7 +49,7 @@ public class AddTagsTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.SANITY,
description = "Verify Manager user adds multiple tags with Rest API and status code is 201")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.SANITY })
public void managerIsAbleToAddTags() throws Exception
public void managerIsAbleToAddTags()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteManager));
returnedCollection = restClient.withCoreAPI().usingResource(document).addTags(tag1, tag2);
@@ -61,7 +61,7 @@ public class AddTagsTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS },
executionType = ExecutionType.SANITY, description = "Verify Collaborator user adds multiple tags with Rest API and status code is 201")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void collaboratorIsAbleToAddTags() throws Exception
public void collaboratorIsAbleToAddTags()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteCollaborator));
returnedCollection = restClient.withCoreAPI().usingResource(document).addTags(tag1, tag2);
@@ -73,7 +73,7 @@ public class AddTagsTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify Contributor user doesn't have permission to add multiple tags with Rest API and status code is 403")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void contributorIsNotAbleToAddTagsToAnotherContent() throws Exception
public void contributorIsNotAbleToAddTagsToAnotherContent()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteContributor));
restClient.withCoreAPI().usingResource(document).addTags(tag1, tag2);
@@ -83,7 +83,7 @@ public class AddTagsTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify Contributor user adds multiple tags to his content with Rest API and status code is 201")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void contributorIsAbleToAddTagsToHisContent() throws Exception
public void contributorIsAbleToAddTagsToHisContent()
{
userModel = usersWithRoles.getOneUserWithRole(UserRole.SiteContributor);
restClient.authenticateUser(userModel);
@@ -97,7 +97,7 @@ public class AddTagsTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify Consumer user doesn't have permission to add multiple tags with Rest API and status code is 403")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void consumerIsNotAbleToAddTags() throws Exception
public void consumerIsNotAbleToAddTags()
{
restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteConsumer)).withCoreAPI().usingResource(document).addTags(tag1, tag2);
restClient.assertStatusCodeIs(HttpStatus.FORBIDDEN).assertLastError().containsSummary(RestErrorModel.PERMISSION_WAS_DENIED);
@@ -107,7 +107,7 @@ public class AddTagsTests extends TagsDataPrep
description = "Verify user gets status code 401 if authentication call fails")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.SANITY })
// @Bug(id="MNT-16904", description = "It fails only on environment with tenants")
public void userIsNotAbleToAddTagsIfAuthenticationFails() throws Exception
public void userIsNotAbleToAddTagsIfAuthenticationFails()
{
UserModel siteManager = usersWithRoles.getOneUserWithRole(UserRole.SiteManager);
String managerPassword = siteManager.getPassword();
@@ -120,7 +120,7 @@ public class AddTagsTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API,
TestGroup.TAGS }, executionType = ExecutionType.REGRESSION, description = "Verify include count parameter")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void getTagsUsingCountParam() throws Exception
public void getTagsUsingCountParam()
{
FileModel file = dataContent.usingSite(siteModel).usingUser(adminUserModel).createContent(CMISUtil.DocumentType.TEXT_PLAIN);
String tagName = RandomData.getRandomName("tag");
@@ -139,4 +139,4 @@ public class AddTagsTests extends TagsDataPrep
}
}
}
}

View File

@@ -15,6 +15,7 @@ import org.alfresco.utility.testrail.ExecutionType;
import org.alfresco.utility.testrail.annotation.TestRail;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.http.HttpStatus;
import org.testng.annotations.Ignore;
import org.testng.annotations.Test;
/**
@@ -29,7 +30,7 @@ public class DeleteTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify Admin user deletes tags with Rest API and status code is 204")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void adminIsAbleToDeleteTags() throws Exception
public void adminIsAbleToDeleteTags()
{
restClient.authenticateUser(adminUserModel);
tag = restClient.withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
@@ -43,7 +44,7 @@ public class DeleteTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.SANITY,
description = "Verify Manager user deletes tags created by admin user with Rest API and status code is 204")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.SANITY })
public void managerIsAbleToDeleteTags() throws Exception
public void managerIsAbleToDeleteTags()
{
restClient.authenticateUser(adminUserModel);
tag = restClient.withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
@@ -56,7 +57,7 @@ public class DeleteTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify Collaborator user deletes tags created by admin user with Rest API and status code is 204")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void collaboratorIsAbleToDeleteTags() throws Exception
public void collaboratorIsAbleToDeleteTags()
{
restClient.authenticateUser(adminUserModel);
tag = restClient.withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
@@ -69,7 +70,7 @@ public class DeleteTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify Contributor user can't delete tags created by admin user with Rest API and status code is 403")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void contributorIsNotAbleToDeleteTagsForAnotherUserContent() throws Exception
public void contributorIsNotAbleToDeleteTagsForAnotherUserContent()
{
restClient.authenticateUser(adminUserModel);
tag = restClient.withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
@@ -82,7 +83,7 @@ public class DeleteTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify Contributor user deletes tags created by him with Rest API and status code is 204")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void contributorIsAbleToDeleteTagsForHisContent() throws Exception
public void contributorIsAbleToDeleteTagsForHisContent()
{
userModel = usersWithRoles.getOneUserWithRole(UserRole.SiteContributor);
restClient.authenticateUser(userModel);
@@ -96,7 +97,7 @@ public class DeleteTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify Consumer user can't delete tags created by admin user with Rest API and status code is 403")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void consumerIsNotAbleToDeleteTags() throws Exception
public void consumerIsNotAbleToDeleteTags()
{
restClient.authenticateUser(adminUserModel);
tag = restClient.withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
@@ -110,7 +111,7 @@ public class DeleteTagTests extends TagsDataPrep
description = "Verify user gets status code 401 if authentication call fails")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.SANITY })
// @Bug(id="MNT-16904", description = "It fails only on environment with tenants")
public void userIsNotAbleToDeleteTagIfAuthenticationFails() throws Exception
public void userIsNotAbleToDeleteTagIfAuthenticationFails()
{
restClient.authenticateUser(adminUserModel);
tag = restClient.withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
@@ -127,7 +128,7 @@ public class DeleteTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that if user has no permission to remove tag returned status code is 403. Check default error model schema")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void deleteTagWithUserWithoutPermissionCheckDefaultErrorModelSchema() throws Exception
public void deleteTagWithUserWithoutPermissionCheckDefaultErrorModelSchema()
{
restClient.authenticateUser(adminUserModel);
RestTagModel tag = restClient.withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
@@ -144,7 +145,7 @@ public class DeleteTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that if node does not exist returned status code is 404")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void deleteTagForANonexistentNode() throws Exception
public void deleteTagForANonexistentNode()
{
restClient.authenticateUser(adminUserModel);
RestTagModel tag = restClient.withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
@@ -159,7 +160,7 @@ public class DeleteTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that if tag does not exist returned status code is 404")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void deleteTagThatDoesNotExist() throws Exception
public void deleteTagThatDoesNotExist()
{
restClient.authenticateUser(adminUserModel);
RestTagModel tag = restClient.withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
@@ -172,7 +173,7 @@ public class DeleteTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that if tag id is empty returned status code is 405")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void deleteTagWithEmptyId() throws Exception
public void deleteTagWithEmptyId()
{
restClient.authenticateUser(adminUserModel);
RestTagModel tag = restClient.withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
@@ -185,7 +186,7 @@ public class DeleteTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that folder tag can be deleted")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void deleteFolderTag() throws Exception
public void deleteFolderTag()
{
FolderModel folderModel = dataContent.usingUser(adminUserModel).usingSite(siteModel).createFolder();;
restClient.authenticateUser(adminUserModel);
@@ -200,7 +201,8 @@ public class DeleteTagTests extends TagsDataPrep
executionType = ExecutionType.REGRESSION, description = "Verify Manager user can't delete deleted tag.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
@Bug(id = "ACE-5455")
public void managerCannotDeleteDeletedTag() throws Exception
@Ignore
public void managerCannotDeleteDeletedTag()
{
tag = restClient.authenticateUser(adminUserModel)
.withCoreAPI().usingResource(document).addTag(RandomData.getRandomName("tag"));
@@ -216,7 +218,7 @@ public class DeleteTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS },
executionType = ExecutionType.REGRESSION, description = "Verify Collaborator user can delete long tag.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void userCollaboratorCanDeleteLongTag() throws Exception
public void userCollaboratorCanDeleteLongTag()
{
String longTag = RandomStringUtils.randomAlphanumeric(800);
@@ -231,7 +233,7 @@ public class DeleteTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS },
executionType = ExecutionType.REGRESSION, description = "Verify Manager user can delete short tag.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void managerCanDeleteShortTag() throws Exception
public void managerCanDeleteShortTag()
{
String shortTag = RandomStringUtils.randomAlphanumeric(10);
@@ -246,7 +248,7 @@ public class DeleteTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS },
executionType = ExecutionType.REGRESSION, description = "Verify Admin can delete tag then add it again.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void adminRemovesTagAndAddsItAgain() throws Exception
public void adminRemovesTagAndAddsItAgain()
{
String tagValue = RandomStringUtils.randomAlphanumeric(10);
@@ -267,7 +269,7 @@ public class DeleteTagTests extends TagsDataPrep
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS },
executionType = ExecutionType.REGRESSION, description = "Verify Manager user can delete tag added by another user.")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION })
public void managerCanDeleteTagAddedByAnotherUser() throws Exception
public void managerCanDeleteTagAddedByAnotherUser()
{
tag = restClient.authenticateUser(usersWithRoles.getOneUserWithRole(UserRole.SiteCollaborator))
.withCoreAPI().usingResource(document).addTag(RandomStringUtils.randomAlphanumeric(10));
@@ -276,4 +278,4 @@ public class DeleteTagTests extends TagsDataPrep
.withCoreAPI().usingResource(document).deleteTag(tag);
restClient.assertStatusCodeIs(HttpStatus.NO_CONTENT);
}
}
}

View File

@@ -150,18 +150,6 @@ public class GetNodeTagsTests extends TagsDataPrep
restClient.assertStatusCodeIs(HttpStatus.NOT_FOUND).assertLastError().containsSummary(String.format(RestErrorModel.ENTITY_NOT_FOUND, nodeRef));
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify that if node id is empty returns status code 403")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION})
public void emptyNodeIdTest() throws Exception
{
FileModel badDocument = dataContent.usingSite(siteModel).usingUser(adminUserModel).createContent(CMISUtil.DocumentType.TEXT_PLAIN);
badDocument.setNodeRef("");
restClient.authenticateUser(adminUserModel).withCoreAPI().usingResource(badDocument).getNodeTags();
restClient.assertStatusCodeIs(HttpStatus.NOT_FOUND).assertLastError().containsSummary(String.format(RestErrorModel.ENTITY_NOT_FOUND, ""));
}
@TestRail(section = { TestGroup.REST_API, TestGroup.TAGS }, executionType = ExecutionType.REGRESSION,
description = "Verify folder tags")
@Test(groups = { TestGroup.REST_API, TestGroup.TAGS, TestGroup.REGRESSION})
@@ -303,4 +291,4 @@ public class GetNodeTagsTests extends TagsDataPrep
.and().field("skipCount").is("10000");
returnedCollection.assertThat().entriesListCountIs(0);
}
}
}

View File

@@ -9,7 +9,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo-tests</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<developers>

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo-packaging</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<properties>
@@ -140,7 +140,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>buildnumber-maven-plugin</artifactId>
<version>3.0.0</version>
<version>3.1.0</version>
<executions>
<execution>
<phase>validate</phase>

75
pom.xml
View File

@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>alfresco-community-repo</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
<packaging>pom</packaging>
<name>Alfresco Community Repo Parent</name>
@@ -23,8 +23,8 @@
</modules>
<properties>
<acs.version.major>7</acs.version.major>
<acs.version.minor>4</acs.version.minor>
<acs.version.major>23</acs.version.major>
<acs.version.minor>1</acs.version.minor>
<acs.version.revision>0</acs.version.revision>
<acs.version.label />
<amp.min.version>${acs.version.major}.0.0</amp.min.version>
@@ -38,7 +38,7 @@
<builder.name>entitled-builder</builder.name>
<local.registry>127.0.0.1:5000</local.registry>
<java.version>11</java.version>
<java.version>17</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<maven.build.sourceVersion>${java.version}</maven.build.sourceVersion>
@@ -49,20 +49,20 @@
<dependency.alfresco-trashcan-cleaner.version>2.4.1</dependency.alfresco-trashcan-cleaner.version>
<dependency.alfresco-jlan.version>7.4</dependency.alfresco-jlan.version>
<dependency.alfresco-server-root.version>6.0.1</dependency.alfresco-server-root.version>
<dependency.alfresco-messaging-repo.version>1.2.20</dependency.alfresco-messaging-repo.version>
<dependency.alfresco-messaging-repo.version>1.2.21</dependency.alfresco-messaging-repo.version>
<dependency.activiti-engine.version>5.23.0</dependency.activiti-engine.version>
<dependency.activiti.version>5.23.0</dependency.activiti.version>
<dependency.alfresco-transform-service.version>2.0.0</dependency.alfresco-transform-service.version>
<dependency.alfresco-transform-core.version>3.0.0</dependency.alfresco-transform-core.version>
<dependency.alfresco-greenmail.version>6.5</dependency.alfresco-greenmail.version>
<dependency.acs-event-model.version>0.0.18</dependency.acs-event-model.version>
<dependency.alfresco-transform-service.version>2.2.0-A1</dependency.alfresco-transform-service.version>
<dependency.alfresco-transform-core.version>3.2.0-A1</dependency.alfresco-transform-core.version>
<dependency.alfresco-greenmail.version>6.8</dependency.alfresco-greenmail.version>
<dependency.acs-event-model.version>0.0.21</dependency.acs-event-model.version>
<dependency.spring.version>5.3.25</dependency.spring.version>
<dependency.spring.version>5.3.27</dependency.spring.version>
<dependency.antlr.version>3.5.3</dependency.antlr.version>
<dependency.jackson.version>2.15.0-rc1</dependency.jackson.version>
<dependency.jackson.version>2.15.1</dependency.jackson.version>
<dependency.cxf.version>3.5.5</dependency.cxf.version>
<dependency.opencmis.version>1.0.0</dependency.opencmis.version>
<dependency.webscripts.version>8.38</dependency.webscripts.version>
<dependency.webscripts.version>8.40</dependency.webscripts.version>
<dependency.bouncycastle.version>1.70</dependency.bouncycastle.version>
<dependency.mockito-core.version>4.9.0</dependency.mockito-core.version>
<dependency.assertj.version>3.24.2</dependency.assertj.version>
@@ -74,27 +74,26 @@
<dependency.httpcore.version>4.4.15</dependency.httpcore.version>
<dependency.commons-httpclient.version>3.1-HTTPCLIENT-1265</dependency.commons-httpclient.version>
<dependency.xercesImpl.version>2.12.2</dependency.xercesImpl.version>
<dependency.slf4j.version>2.0.3</dependency.slf4j.version>
<dependency.log4j.version>2.19.0</dependency.log4j.version>
<dependency.slf4j.version>2.0.7</dependency.slf4j.version>
<dependency.log4j.version>2.20.0</dependency.log4j.version>
<dependency.gytheio.version>0.18</dependency.gytheio.version>
<dependency.groovy.version>3.0.16</dependency.groovy.version>
<dependency.groovy.version>3.0.17</dependency.groovy.version>
<dependency.tika.version>2.4.1</dependency.tika.version>
<dependency.spring-security.version>5.8.2</dependency.spring-security.version>
<dependency.spring-security.version>5.8.3</dependency.spring-security.version>
<dependency.truezip.version>7.7.10</dependency.truezip.version>
<dependency.poi.version>5.2.2</dependency.poi.version>
<dependency.poi-ooxml-lite.version>5.2.3</dependency.poi-ooxml-lite.version>
<dependency.keycloak.version>18.0.0</dependency.keycloak.version>
<dependency.jboss.logging.version>3.5.0.Final</dependency.jboss.logging.version>
<dependency.camel.version>3.20.2</dependency.camel.version> <!-- when bumping this version, please keep track/sync with included netty.io dependencies -->
<dependency.netty.version>4.1.87.Final</dependency.netty.version> <!-- must be in sync with camels transitive dependencies, e.g.: netty-common -->
<dependency.netty.qpid.version>4.1.82.Final</dependency.netty.qpid.version> <!-- must be in sync with camels transitive dependencies: native-unix-common/native-epoll/native-kqueue -->
<dependency.netty-tcnative.version>2.0.56.Final</dependency.netty-tcnative.version> <!-- must be in sync with camels transitive dependencies -->
<dependency.activemq.version>5.17.4</dependency.activemq.version>
<dependency.apache-compress.version>1.22</dependency.apache-compress.version>
<dependency.apache-compress.version>1.23.0</dependency.apache-compress.version>
<dependency.apache.taglibs.version>1.2.5</dependency.apache.taglibs.version>
<dependency.awaitility.version>4.2.0</dependency.awaitility.version>
<dependency.swagger-ui.version>3.38.0</dependency.swagger-ui.version>
<dependency.swagger-parser.version>1.0.63</dependency.swagger-parser.version>
<dependency.swagger-parser.version>1.0.66</dependency.swagger-parser.version>
<dependency.maven-filtering.version>3.1.1</dependency.maven-filtering.version>
<dependency.maven-artifact.version>3.8.6</dependency.maven-artifact.version>
<dependency.jdom2.version>2.0.6.1</dependency.jdom2.version>
@@ -108,26 +107,26 @@
<dependency.jakarta-jws-api.version>2.1.0</dependency.jakarta-jws-api.version>
<dependency.jakarta-mail-api.version>1.6.5</dependency.jakarta-mail-api.version>
<dependency.jakarta-json-api.version>1.1.6</dependency.jakarta-json-api.version>
<dependency.jakarta-json-path.version>2.7.0</dependency.jakarta-json-path.version>
<dependency.json-smart.version>2.4.8</dependency.json-smart.version>
<dependency.jakarta-json-path.version>2.8.0</dependency.jakarta-json-path.version>
<dependency.json-smart.version>2.4.10</dependency.json-smart.version>
<dependency.jakarta-rpc-api.version>1.1.4</dependency.jakarta-rpc-api.version>
<alfresco.googledrive.version>3.4.0-M1</alfresco.googledrive.version>
<alfresco.aos-module.version>1.6.0-M1</alfresco.aos-module.version>
<alfresco.api-explorer.version>7.3.0</alfresco.api-explorer.version> <!-- Also in alfresco-enterprise-share -->
<alfresco.googledrive.version>3.4.0</alfresco.googledrive.version>
<alfresco.aos-module.version>1.6.0</alfresco.aos-module.version>
<alfresco.api-explorer.version>7.4.0</alfresco.api-explorer.version> <!-- Also in alfresco-enterprise-share -->
<alfresco.maven-plugin.version>2.2.0</alfresco.maven-plugin.version>
<license-maven-plugin.version>2.0.1.alfresco-2</license-maven-plugin.version>
<license-maven-plugin.version>2.0.1</license-maven-plugin.version>
<dependency.postgresql.version>42.5.2</dependency.postgresql.version>
<dependency.mysql.version>8.0.30</dependency.mysql.version>
<dependency.mysql-image.version>8</dependency.mysql-image.version>
<dependency.mariadb.version>2.7.4</dependency.mariadb.version>
<dependency.tas-utility.version>3.0.61</dependency.tas-utility.version>
<dependency.tas-utility.version>4.0.0</dependency.tas-utility.version>
<dependency.rest-assured.version>5.2.0</dependency.rest-assured.version>
<dependency.tas-email.version>1.11</dependency.tas-email.version>
<dependency.tas-webdav.version>1.7</dependency.tas-webdav.version>
<dependency.tas-ftp.version>1.7</dependency.tas-ftp.version>
<dependency.tas-email.version>1.17</dependency.tas-email.version>
<dependency.tas-webdav.version>1.14</dependency.tas-webdav.version>
<dependency.tas-ftp.version>1.15</dependency.tas-ftp.version>
<dependency.tas-dataprep.version>2.6</dependency.tas-dataprep.version>
<!-- AGS properties shared between community and enterprise -->
@@ -151,7 +150,7 @@
<connection>scm:git:https://github.com/Alfresco/alfresco-community-repo.git</connection>
<developerConnection>scm:git:https://github.com/Alfresco/alfresco-community-repo.git</developerConnection>
<url>https://github.com/Alfresco/alfresco-community-repo</url>
<tag>20.112</tag>
<tag>23.1.0.111</tag>
</scm>
<distributionManagement>
@@ -658,7 +657,7 @@
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.15.3</version>
<version>1.16.1</version>
</dependency>
<!-- upgrade dependency from TIKA -->
<dependency>
@@ -742,7 +741,7 @@
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.12.1</version>
<version>2.12.5</version>
</dependency>
<!-- provided dependencies -->
@@ -899,7 +898,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<version>1.18.26</version>
<scope>provided</scope>
</dependency>
<dependency>
@@ -937,7 +936,7 @@
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.42.0</version>
<version>0.42.1</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
@@ -958,21 +957,21 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.4.1</version>
<version>3.5.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.0</version>
<version>3.3.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.3.0</version>
<version>3.5.0</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.4.2</version>
<version>3.6.0</version>
</plugin>
<plugin>
<groupId>org.alfresco.maven.plugin</groupId>

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<dependencies>
@@ -47,7 +47,7 @@
<dependency>
<groupId>org.apache.santuario</groupId>
<artifactId>xmlsec</artifactId>
<version>3.0.0</version>
<version>3.0.2</version>
</dependency>
<!-- newer version, see REPO-3133 -->
<dependency>
@@ -130,7 +130,7 @@
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>10.0.11</version>
<version>10.0.14</version>
<scope>test</scope>
<exclusions>
<exclusion>
@@ -154,7 +154,7 @@
<dependency>
<groupId>org.alfresco.cmis.client</groupId>
<artifactId>alfresco-opencmis-extension</artifactId>
<version>2.1</version>
<version>2.2</version>
<scope>test</scope>
<exclusions>
<!-- Duplicates classes from jakarta.transaction:jakarta.transaction-api -->

View File

@@ -39,6 +39,8 @@ import org.alfresco.rest.api.model.LockInfo;
import org.alfresco.rest.api.model.Node;
import org.alfresco.rest.api.model.PathInfo;
import org.alfresco.rest.api.model.UserInfo;
import org.alfresco.rest.framework.core.exceptions.EntityNotFoundException;
import org.alfresco.rest.framework.core.exceptions.InvalidArgumentException;
import org.alfresco.rest.framework.resource.content.BasicContentInfo;
import org.alfresco.rest.framework.resource.content.BinaryResource;
import org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo;
@@ -208,6 +210,19 @@ public interface Nodes
NodeRef validateNode(StoreRef storeRef, String nodeId);
NodeRef validateNode(String nodeId);
NodeRef validateNode(NodeRef nodeRef);
/**
* Check that the specified id refers to a valid node.
*
* @param nodeId The node id to look up using SpacesStore or an alias like -root-.
* @return The node ref.
* @throws InvalidArgumentException if the specified node id is not a valid format.
* @throws EntityNotFoundException if the specified node was not found in the database.
*/
default NodeRef validateOrLookupNode(String nodeId)
{
return validateOrLookupNode(nodeId, null);
}
NodeRef validateOrLookupNode(String nodeId, String path);
boolean nodeMatches(NodeRef nodeRef, Set<QName> expectedTypes, Set<QName> excludedTypes);

View File

@@ -37,11 +37,11 @@ import org.alfresco.service.cmr.repository.StoreRef;
public interface Tags
{
List<Tag> addTags(String nodeId, List<Tag> tags);
Tag getTag(StoreRef storeRef, String tagId);
List<Tag> addTags(String nodeId, List<Tag> tags, Parameters parameters);
Tag getTag(StoreRef storeRef, String tagId, Parameters parameters);
void deleteTag(String nodeId, String tagId);
CollectionWithPagingInfo<Tag> getTags(StoreRef storeRef, Parameters params);
Tag changeTag(StoreRef storeRef, String tagId, Tag tag);
Tag changeTag(StoreRef storeRef, String tagId, Tag tag, Parameters parameters);
CollectionWithPagingInfo<Tag> getTags(String nodeId, Parameters params);
@Experimental

View File

@@ -111,6 +111,11 @@ public class CategoriesImpl implements Categories
category.setCount(categoriesCount.getOrDefault(category.getId(), 0));
}
if (parameters.getInclude().contains(Nodes.PARAM_INCLUDE_PATH))
{
category.setPath(getCategoryPath(category));
}
return category;
}
@@ -128,6 +133,10 @@ public class CategoriesImpl implements Categories
{
category.setCount(0);
}
if (parameters.getInclude().contains(Nodes.PARAM_INCLUDE_PATH))
{
category.setPath(getCategoryPath(category));
}
})
.collect(Collectors.toList());
}
@@ -136,11 +145,18 @@ public class CategoriesImpl implements Categories
public List<Category> getCategoryChildren(final StoreRef storeRef, final String parentCategoryId, final Parameters parameters)
{
final NodeRef parentNodeRef = getCategoryNodeRef(storeRef, parentCategoryId);
final List<Category> categories = nodeService.getChildAssocs(parentNodeRef).stream()
.filter(ca -> ContentModel.ASSOC_SUBCATEGORIES.equals(ca.getTypeQName()))
.map(ChildAssociationRef::getChildRef)
.map(this::mapToCategory)
.collect(Collectors.toList());
final List<Category> categories = nodeService.getChildAssocs(parentNodeRef)
.stream()
.filter(ca -> ContentModel.ASSOC_SUBCATEGORIES.equals(ca.getTypeQName()))
.map(ChildAssociationRef::getChildRef)
.map(this::mapToCategory)
.peek(category -> {
if (parameters.getInclude().contains(Nodes.PARAM_INCLUDE_PATH))
{
category.setPath(getCategoryPath(category));
}
})
.collect(Collectors.toList());
if (parameters.getInclude().contains(INCLUDE_COUNT_PARAM))
{
@@ -170,6 +186,11 @@ public class CategoriesImpl implements Categories
category.setCount(categoriesCount.getOrDefault(category.getId(), 0));
}
if (parameters.getInclude().contains(Nodes.PARAM_INCLUDE_PATH))
{
category.setPath(getCategoryPath(category));
}
return category;
}
@@ -189,7 +210,7 @@ public class CategoriesImpl implements Categories
@Override
public List<Category> listCategoriesForNode(final String nodeId, final Parameters parameters)
{
final NodeRef contentNodeRef = nodes.validateNode(nodeId);
final NodeRef contentNodeRef = nodes.validateOrLookupNode(nodeId);
verifyReadPermission(contentNodeRef);
verifyNodeType(contentNodeRef);
@@ -200,7 +221,16 @@ public class CategoriesImpl implements Categories
}
final Collection<NodeRef> actualCategories = DefaultTypeConverter.INSTANCE.getCollection(NodeRef.class, currentCategories);
return actualCategories.stream().map(this::mapToCategory).collect(Collectors.toList());
return actualCategories
.stream()
.map(this::mapToCategory)
.peek(category -> {
if (parameters.getInclude().contains(Nodes.PARAM_INCLUDE_PATH))
{
category.setPath(getCategoryPath(category));
}
})
.collect(Collectors.toList());
}
@Override
@@ -211,7 +241,7 @@ public class CategoriesImpl implements Categories
throw new InvalidArgumentException(NOT_A_VALID_CATEGORY);
}
final NodeRef contentNodeRef = nodes.validateNode(nodeId);
final NodeRef contentNodeRef = nodes.validateOrLookupNode(nodeId);
verifyChangePermission(contentNodeRef);
verifyNodeType(contentNodeRef);
@@ -230,14 +260,23 @@ public class CategoriesImpl implements Categories
linkNodeToCategories(contentNodeRef, categoryNodeRefs);
return categoryNodeRefs.stream().map(this::mapToCategory).collect(Collectors.toList());
return categoryNodeRefs
.stream()
.map(this::mapToCategory)
.peek(category -> {
if (parameters.getInclude().contains(Nodes.PARAM_INCLUDE_PATH))
{
category.setPath(getCategoryPath(category));
}
})
.collect(Collectors.toList());
}
@Override
public void unlinkNodeFromCategory(final StoreRef storeRef, final String nodeId, final String categoryId, final Parameters parameters)
{
final NodeRef categoryNodeRef = getCategoryNodeRef(storeRef, categoryId);
final NodeRef contentNodeRef = nodes.validateNode(nodeId);
final NodeRef contentNodeRef = nodes.validateOrLookupNode(nodeId);
verifyChangePermission(contentNodeRef);
verifyNodeType(contentNodeRef);
@@ -475,4 +514,16 @@ public class CategoriesImpl implements Categories
.stream()
.collect(Collectors.toMap(pair -> pair.getFirst().toString().replace(idPrefix, StringUtils.EMPTY), Pair::getSecond));
}
/**
* Get path for a given category in human-readable form.
*
* @param category Category to provide path for.
* @return Path for a category in human-readable form.
*/
private String getCategoryPath(final Category category)
{
final NodeRef categoryNodeRef = nodes.getNode(category.getId()).getNodeRef();
return nodeService.getPath(categoryNodeRef).toDisplayPath(nodeService, permissionService);
}
}

View File

@@ -1356,7 +1356,7 @@ public class NodesImpl implements Nodes
private void calculateRelativePath(String parentFolderNodeId, Node node)
{
NodeRef rootNodeRef = validateOrLookupNode(parentFolderNodeId, null);
NodeRef rootNodeRef = validateOrLookupNode(parentFolderNodeId);
try
{
// get the path elements
@@ -1741,7 +1741,7 @@ public class NodesImpl implements Nodes
@Override
public void deleteNode(String nodeId, Parameters parameters)
{
NodeRef nodeRef = validateOrLookupNode(nodeId, null);
NodeRef nodeRef = validateOrLookupNode(nodeId);
if (isSpecialNode(nodeRef, getNodeType(nodeRef)))
{
@@ -1785,7 +1785,7 @@ public class NodesImpl implements Nodes
validateProperties(nodeInfo.getProperties(), EXCLUDED_NS, Arrays.asList());
// check that requested parent node exists and it's type is a (sub-)type of folder
NodeRef parentNodeRef = validateOrLookupNode(parentFolderNodeId, null);
NodeRef parentNodeRef = validateOrLookupNode(parentFolderNodeId);
// node name - mandatory
String nodeName = nodeInfo.getName();
@@ -2290,7 +2290,7 @@ public class NodesImpl implements Nodes
validateAspects(nodeInfo.getAspectNames(), EXCLUDED_NS, EXCLUDED_ASPECTS);
validateProperties(nodeInfo.getProperties(), EXCLUDED_NS, Arrays.asList());
final NodeRef nodeRef = validateOrLookupNode(nodeId, null);
final NodeRef nodeRef = validateOrLookupNode(nodeId);
QName nodeTypeQName = getNodeType(nodeRef);
@@ -2523,8 +2523,8 @@ public class NodesImpl implements Nodes
throw new InvalidArgumentException("Missing targetParentId");
}
final NodeRef parentNodeRef = validateOrLookupNode(targetParentId, null);
final NodeRef sourceNodeRef = validateOrLookupNode(sourceNodeId, null);
final NodeRef parentNodeRef = validateOrLookupNode(targetParentId);
final NodeRef sourceNodeRef = validateOrLookupNode(sourceNodeId);
FileInfo fi = moveOrCopyImpl(sourceNodeRef, parentNodeRef, name, isCopy);
return getFolderOrDocument(fi.getNodeRef().getId(), parameters);
@@ -2954,7 +2954,7 @@ public class NodesImpl implements Nodes
throw new InvalidArgumentException("The request content-type is not multipart: "+parentFolderNodeId);
}
NodeRef parentNodeRef = validateOrLookupNode(parentFolderNodeId, null);
NodeRef parentNodeRef = validateOrLookupNode(parentFolderNodeId);
if (!nodeMatches(parentNodeRef, Collections.singleton(ContentModel.TYPE_FOLDER), null, false))
{
throw new InvalidArgumentException("NodeId of folder is expected: " + parentNodeRef.getId());
@@ -3385,7 +3385,7 @@ public class NodesImpl implements Nodes
@Override
public Node lock(String nodeId, LockInfo lockInfo, Parameters parameters)
{
NodeRef nodeRef = validateOrLookupNode(nodeId, null);
NodeRef nodeRef = validateOrLookupNode(nodeId);
if (isSpecialNode(nodeRef, getNodeType(nodeRef)))
{
@@ -3424,7 +3424,7 @@ public class NodesImpl implements Nodes
@Override
public Node unlock(String nodeId, Parameters parameters)
{
NodeRef nodeRef = validateOrLookupNode(nodeId, null);
NodeRef nodeRef = validateOrLookupNode(nodeId);
if (isSpecialNode(nodeRef, getNodeType(nodeRef)))
{

View File

@@ -185,7 +185,7 @@ public class QueriesImpl implements Queries, InitializingBean
String rootNodeId = parameters.getParameter(PARAM_ROOT_NODE_ID);
if (rootNodeId != null)
{
NodeRef nodeRef = nodes.validateOrLookupNode(rootNodeId, null);
NodeRef nodeRef = nodes.validateOrLookupNode(rootNodeId);
query.append("PATH:\"").append(getQNamePath(nodeRef.getId())).append("//*\" AND (");
}
if (term != null)

View File

@@ -695,7 +695,7 @@ public class RenditionsImpl implements Renditions, ResourceLoaderAware
{
if (versionLabelId != null)
{
nodeRef = nodes.validateOrLookupNode(nodeRef.getId(), null);
nodeRef = nodes.validateOrLookupNode(nodeRef.getId());
VersionHistory vh = versionService.getVersionHistory(nodeRef);
if (vh != null)
{

View File

@@ -25,14 +25,18 @@
*/
package org.alfresco.rest.api.impl;
import static java.util.stream.Collectors.toList;
import static org.alfresco.rest.antlr.WhereClauseParser.EQUALS;
import static org.alfresco.rest.antlr.WhereClauseParser.IN;
import static org.alfresco.rest.antlr.WhereClauseParser.MATCHES;
import static org.alfresco.service.cmr.repository.StoreRef.STORE_REF_WORKSPACE_SPACESSTORE;
import static org.alfresco.service.cmr.tagging.TaggingService.TAG_ROOT_NODE_REF;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -41,6 +45,8 @@ import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.alfresco.model.ContentModel;
import org.alfresco.query.ListBackedPagingResults;
import org.alfresco.query.PagingResults;
import org.alfresco.repo.tagging.NonExistentTagException;
import org.alfresco.repo.tagging.TagExistsException;
@@ -57,10 +63,12 @@ import org.alfresco.rest.framework.core.exceptions.UnsupportedResourceOperationE
import org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo;
import org.alfresco.rest.framework.resource.parameters.Paging;
import org.alfresco.rest.framework.resource.parameters.Parameters;
import org.alfresco.rest.framework.resource.parameters.SortColumn;
import org.alfresco.rest.framework.resource.parameters.where.Query;
import org.alfresco.rest.framework.resource.parameters.where.QueryHelper;
import org.alfresco.rest.framework.resource.parameters.where.QueryImpl;
import org.alfresco.service.Experimental;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
@@ -78,269 +86,267 @@ import org.apache.commons.collections.CollectionUtils;
*/
public class TagsImpl implements Tags
{
private static final String PARAM_INCLUDE_COUNT = "count";
private static final String PARAM_WHERE_TAG = "tag";
static final String NOT_A_VALID_TAG = "An invalid parameter has been supplied";
static final String NO_PERMISSION_TO_MANAGE_A_TAG = "Current user does not have permission to manage a tag";
private final NodeRef tagParentNodeRef = new NodeRef("workspace://SpacesStore/tag:tag-root");
public static final String PARAM_INCLUDE_COUNT = "count";
private static final String PARAM_WHERE_TAG = "tag";
static final String NOT_A_VALID_TAG = "An invalid parameter has been supplied";
static final String NO_PERMISSION_TO_MANAGE_A_TAG = "Current user does not have permission to manage a tag";
private Nodes nodes;
private NodeService nodeService;
private TaggingService taggingService;
private TypeConstraint typeConstraint;
private AuthorityService authorityService;
private NodeService nodeService;
private TaggingService taggingService;
private TypeConstraint typeConstraint;
private AuthorityService authorityService;
public void setTypeConstraint(TypeConstraint typeConstraint)
{
this.typeConstraint = typeConstraint;
}
public void setNodes(Nodes nodes)
public void setTypeConstraint(TypeConstraint typeConstraint)
{
this.nodes = nodes;
}
public void setNodeService(NodeService nodeService)
{
this.nodeService = nodeService;
}
this.typeConstraint = typeConstraint;
}
public void setNodes(Nodes nodes)
{
this.nodes = nodes;
}
public void setNodeService(NodeService nodeService)
{
this.nodeService = nodeService;
}
public void setTaggingService(TaggingService taggingService)
{
this.taggingService = taggingService;
}
this.taggingService = taggingService;
}
public void setAuthorityService(AuthorityService authorityService)
{
this.authorityService = authorityService;
}
public void setAuthorityService(AuthorityService authorityService)
{
this.authorityService = authorityService;
}
public List<Tag> addTags(String nodeId, final List<Tag> tags)
{
NodeRef nodeRef = nodes.validateNode(nodeId);
if(!typeConstraint.matches(nodeRef))
{
throw new UnsupportedResourceOperationException("Cannot tag this node");
}
public List<Tag> addTags(String nodeId, final List<Tag> tags, final Parameters parameters)
{
NodeRef nodeRef = nodes.validateOrLookupNode(nodeId);
if (!typeConstraint.matches(nodeRef))
{
throw new UnsupportedResourceOperationException("Cannot tag this node");
}
List<String> tagValues = new AbstractList<String>()
List<String> tagValues = tags.stream().map(Tag::getTag).collect(toList());
try
{
List<Pair<String, NodeRef>> tagNodeRefs = taggingService.addTags(nodeRef, tagValues);
List<Tag> ret = new ArrayList<>(tags.size());
List<Pair<String, Integer>> tagsCountPairList = taggingService.findTaggedNodesAndCountByTagName(nodeRef.getStoreRef());
Map<String, Long> tagsCountMap = tagsCountPairList.stream().collect(Collectors.toMap(Pair::getFirst, pair -> Long.valueOf(pair.getSecond())));
for (Pair<String, NodeRef> pair : tagNodeRefs)
{
@Override
public String get(int arg0)
Tag createdTag = new Tag(pair.getSecond(), pair.getFirst());
if (parameters.getInclude().contains(PARAM_INCLUDE_COUNT))
{
String tag = tags.get(arg0).getTag();
return tag;
createdTag.setCount(Optional.ofNullable(tagsCountMap.get(createdTag.getTag())).orElse(0L) + 1);
}
@Override
public int size()
{
return tags.size();
}
};
try
{
List<Pair<String, NodeRef>> tagNodeRefs = taggingService.addTags(nodeRef, tagValues);
List<Tag> ret = new ArrayList<Tag>(tags.size());
for(Pair<String, NodeRef> pair : tagNodeRefs)
{
ret.add(new Tag(pair.getSecond(), pair.getFirst()));
}
return ret;
ret.add(createdTag);
}
catch(IllegalArgumentException e)
{
throw new InvalidArgumentException(e.getMessage());
}
}
return ret;
}
catch (IllegalArgumentException e)
{
throw new InvalidArgumentException(e.getMessage());
}
}
public void deleteTag(String nodeId, String tagId)
{
NodeRef nodeRef = nodes.validateNode(nodeId);
getTag(tagId);
NodeRef existingTagNodeRef = validateTag(tagId);
String tagValue = taggingService.getTagName(existingTagNodeRef);
taggingService.removeTag(nodeRef, tagValue);
NodeRef nodeRef = nodes.validateNode(nodeId);
getTag(STORE_REF_WORKSPACE_SPACESSTORE, tagId, null);
NodeRef existingTagNodeRef = validateTag(tagId);
String tagValue = taggingService.getTagName(existingTagNodeRef);
taggingService.removeTag(nodeRef, tagValue);
}
@Override
public void deleteTagById(StoreRef storeRef, String tagId) {
verifyAdminAuthority();
public void deleteTagById(StoreRef storeRef, String tagId) {
verifyAdminAuthority();
NodeRef tagNodeRef = validateTag(storeRef, tagId);
String tagValue = taggingService.getTagName(tagNodeRef);
taggingService.deleteTag(storeRef, tagValue);
}
NodeRef tagNodeRef = validateTag(storeRef, tagId);
String tagValue = taggingService.getTagName(tagNodeRef);
taggingService.deleteTag(storeRef, tagValue);
}
@Override
@Override
public CollectionWithPagingInfo<Tag> getTags(StoreRef storeRef, Parameters params)
{
Paging paging = params.getPaging();
Map<Integer, Collection<String>> namesFilters = resolveTagNamesQuery(params.getQuery());
PagingResults<Pair<NodeRef, String>> results = taggingService.getTags(storeRef, Util.getPagingRequest(paging), namesFilters.get(EQUALS), namesFilters.get(MATCHES));
Paging paging = params.getPaging();
Pair<String, Boolean> sorting = !params.getSorting().isEmpty() ? new Pair<>(params.getSorting().get(0).column, params.getSorting().get(0).asc) : null;
Map<Integer, Collection<String>> namesFilters = resolveTagNamesQuery(params.getQuery());
Map<NodeRef, Long> results = taggingService.getTags(storeRef, params.getInclude(), sorting, namesFilters.get(EQUALS), namesFilters.get(MATCHES));
List<Tag> tagsList = results.entrySet().stream().map(entry -> new Tag(entry.getKey(), (String)nodeService.getProperty(entry.getKey(), ContentModel.PROP_NAME))).collect(Collectors.toList());
Integer totalItems = results.getTotalResultCount().getFirst();
List<Pair<NodeRef, String>> page = results.getPage();
List<Tag> tags = new ArrayList<>(page.size());
List<Pair<String, Integer>> tagsByCount;
Map<String, Integer> tagsByCountMap = new HashMap<>();
if (params.getInclude().contains(PARAM_INCLUDE_COUNT))
{
tagsByCount = taggingService.findTaggedNodesAndCountByTagName(storeRef);
if (tagsByCount != null)
{
for (Pair<String, Integer> tagByCountElem : tagsByCount)
{
tagsByCountMap.put(tagByCountElem.getFirst(), tagByCountElem.getSecond());
}
}
}
for (Pair<NodeRef, String> pair : page)
{
Tag selectedTag = new Tag(pair.getFirst(), pair.getSecond());
selectedTag.setCount(Optional.ofNullable(tagsByCountMap.get(selectedTag.getTag())).orElse(0));
tags.add(selectedTag);
tagsList.forEach(tag -> tag.setCount(results.get(tag.getNodeRef())));
}
return CollectionWithPagingInfo.asPaged(paging, tags, results.hasMoreItems(), totalItems);
ListBackedPagingResults listBackedPagingResults = new ListBackedPagingResults(tagsList, Util.getPagingRequest(params.getPaging()));
return CollectionWithPagingInfo.asPaged(paging, listBackedPagingResults.getPage(), listBackedPagingResults.hasMoreItems(), (Integer) listBackedPagingResults.getTotalResultCount().getFirst());
}
public NodeRef validateTag(String tagId)
{
NodeRef tagNodeRef = nodes.validateNode(tagId);
return checkTagRootAsNodePrimaryParent(tagId, tagNodeRef);
NodeRef tagNodeRef = nodes.validateNode(tagId);
return checkTagRootAsNodePrimaryParent(tagId, tagNodeRef);
}
public NodeRef validateTag(StoreRef storeRef, String tagId)
{
NodeRef tagNodeRef = nodes.validateNode(storeRef, tagId);
return checkTagRootAsNodePrimaryParent(tagId, tagNodeRef);
NodeRef tagNodeRef = nodes.validateNode(storeRef, tagId);
return checkTagRootAsNodePrimaryParent(tagId, tagNodeRef);
}
public Tag changeTag(StoreRef storeRef, String tagId, Tag tag)
/**
* Find the number of times the given tag is used (if requested).
*
* @param storeRef The store the tag is in.
* @param tagName The name of the tag.
* @param parameters The request parameters object containing the includes parameter.
* @return The number of times the tag is applied, or null if "count" wasn't in the include parameter.
*/
private Long findCountIfRequested(StoreRef storeRef, String tagName, Parameters parameters)
{
try
{
NodeRef existingTagNodeRef = validateTag(storeRef, tagId);
String existingTagName = taggingService.getTagName(existingTagNodeRef);
String newTagName = tag.getTag();
NodeRef newTagNodeRef = taggingService.changeTag(storeRef, existingTagName, newTagName);
return new Tag(newTagNodeRef, newTagName);
}
catch(NonExistentTagException e)
{
throw new NotFoundException(e.getMessage());
}
catch(TagExistsException e)
{
throw new ConstraintViolatedException(e.getMessage());
}
catch(TaggingException e)
{
throw new InvalidArgumentException(e.getMessage());
}
Long count = null;
if (parameters != null && parameters.getInclude() != null && parameters.getInclude().contains(PARAM_INCLUDE_COUNT))
{
count = taggingService.findCountByTagName(storeRef, tagName);
}
return count;
}
public Tag getTag(String tagId)
@Override
public Tag changeTag(StoreRef storeRef, String tagId, Tag tag, Parameters parameters)
{
return getTag(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, tagId);
try
{
NodeRef existingTagNodeRef = validateTag(storeRef, tagId);
String existingTagName = taggingService.getTagName(existingTagNodeRef);
Long count = findCountIfRequested(storeRef, existingTagName, parameters);
String newTagName = tag.getTag();
NodeRef newTagNodeRef = taggingService.changeTag(storeRef, existingTagName, newTagName);
return Tag.builder().nodeRef(newTagNodeRef).tag(newTagName).count(count).create();
}
catch(NonExistentTagException e)
{
throw new NotFoundException(e.getMessage());
}
catch(TagExistsException e)
{
throw new ConstraintViolatedException(e.getMessage());
}
catch(TaggingException e)
{
throw new InvalidArgumentException(e.getMessage());
}
}
public Tag getTag(StoreRef storeRef, String tagId)
@Override
public Tag getTag(StoreRef storeRef, String tagId, Parameters parameters)
{
NodeRef tagNodeRef = validateTag(storeRef, tagId);
String tagValue = taggingService.getTagName(tagNodeRef);
return new Tag(tagNodeRef, tagValue);
NodeRef tagNodeRef = validateTag(storeRef, tagId);
String tagName = taggingService.getTagName(tagNodeRef);
Long count = findCountIfRequested(storeRef, tagName, parameters);
return Tag.builder().nodeRef(tagNodeRef).tag(tagName).count(count).create();
}
@Override
public CollectionWithPagingInfo<Tag> getTags(String nodeId, Parameters params)
{
NodeRef nodeRef = nodes.validateNode(nodeId);
PagingResults<Pair<NodeRef, String>> results = taggingService.getTags(nodeRef, Util.getPagingRequest(params.getPaging()));
Integer totalItems = results.getTotalResultCount().getFirst();
List<Pair<NodeRef, String>> page = results.getPage();
List<Tag> tags = new ArrayList<Tag>(page.size());
for(Pair<NodeRef, String> pair : page)
{
tags.add(new Tag(pair.getFirst(), pair.getSecond()));
}
NodeRef nodeRef = nodes.validateOrLookupNode(nodeId);
PagingResults<Pair<NodeRef, String>> results = taggingService.getTags(nodeRef, Util.getPagingRequest(params.getPaging()));
Integer totalItems = results.getTotalResultCount().getFirst();
List<Pair<NodeRef, String>> page = results.getPage();
List<Tag> tags = new ArrayList<>(page.size());
for(Pair<NodeRef, String> pair : page)
{
tags.add(new Tag(pair.getFirst(), pair.getSecond()));
}
return CollectionWithPagingInfo.asPaged(params.getPaging(), tags, results.hasMoreItems(), (totalItems == null ? null : totalItems.intValue()));
return CollectionWithPagingInfo.asPaged(params.getPaging(), tags, results.hasMoreItems(), (totalItems == null ? null : totalItems.intValue()));
}
@Experimental
@Override
public List<Tag> createTags(final StoreRef storeRef, final List<Tag> tags, final Parameters parameters)
{
verifyAdminAuthority();
final List<String> tagNames = Optional.ofNullable(tags).orElse(Collections.emptyList()).stream()
.filter(Objects::nonNull)
.map(Tag::getTag)
.distinct()
.collect(Collectors.toList());
@Experimental
@Override
public List<Tag> createTags(final StoreRef storeRef, final List<Tag> tags, final Parameters parameters)
{
verifyAdminAuthority();
final List<String> tagNames = Optional.ofNullable(tags).orElse(Collections.emptyList()).stream()
.filter(Objects::nonNull)
.map(Tag::getTag)
.distinct()
.collect(toList());
if (CollectionUtils.isEmpty(tagNames))
{
throw new InvalidArgumentException(NOT_A_VALID_TAG);
}
if (CollectionUtils.isEmpty(tagNames))
{
throw new InvalidArgumentException(NOT_A_VALID_TAG);
}
return taggingService.createTags(storeRef, tagNames).stream()
.map(pair -> Tag.builder().tag(pair.getFirst()).nodeRef(pair.getSecond()).create())
.peek(tag -> {
if (parameters.getInclude().contains(PARAM_INCLUDE_COUNT))
{
tag.setCount(0);
}
}).collect(Collectors.toList());
}
return taggingService.createTags(storeRef, tagNames).stream()
.map(pair -> Tag.builder().tag(pair.getFirst()).nodeRef(pair.getSecond()).create())
.peek(tag -> {
if (parameters.getInclude().contains(PARAM_INCLUDE_COUNT))
{
tag.setCount(0L);
}
}).collect(toList());
}
private void verifyAdminAuthority()
{
if (!authorityService.hasAdminAuthority())
{
throw new PermissionDeniedException(NO_PERMISSION_TO_MANAGE_A_TAG);
}
}
private void verifyAdminAuthority()
{
if (!authorityService.hasAdminAuthority())
{
throw new PermissionDeniedException(NO_PERMISSION_TO_MANAGE_A_TAG);
}
}
/**
* Method resolves where query looking for clauses: EQUALS, IN or MATCHES.
* Expected values for EQUALS and IN will be merged under EQUALS clause.
* @param namesQuery Where query with expected tag name(s).
* @return Map of expected exact and alike tag names.
*/
private Map<Integer, Collection<String>> resolveTagNamesQuery(final Query namesQuery)
{
if (namesQuery == null || namesQuery == QueryImpl.EMPTY)
{
return Collections.emptyMap();
}
/**
* Method resolves where query looking for clauses: EQUALS, IN or MATCHES.
* Expected values for EQUALS and IN will be merged under EQUALS clause.
* @param namesQuery Where query with expected tag name(s).
* @return Map of expected exact and alike tag names.
*/
private Map<Integer, Collection<String>> resolveTagNamesQuery(final Query namesQuery)
{
if (namesQuery == null || namesQuery == QueryImpl.EMPTY)
{
return Collections.emptyMap();
}
final Map<Integer, Collection<String>> properties = QueryHelper
.resolve(namesQuery)
.usingOrOperator()
.withoutNegations()
.getProperty(PARAM_WHERE_TAG)
.getExpectedValuesForAnyOf(EQUALS, IN, MATCHES)
.skipNegated();
final Map<Integer, Collection<String>> properties = QueryHelper
.resolve(namesQuery)
.usingOrOperator()
.withoutNegations()
.getProperty(PARAM_WHERE_TAG)
.getExpectedValuesForAnyOf(EQUALS, IN, MATCHES)
.skipNegated();
return properties.entrySet().stream()
.collect(Collectors.groupingBy((entry) -> {
if (entry.getKey() == EQUALS || entry.getKey() == IN)
{
return EQUALS;
}
else
{
return MATCHES;
}
}, Collectors.flatMapping((entry) -> entry.getValue().stream().map(String::toLowerCase), Collectors.toCollection(HashSet::new))));
}
return properties.entrySet().stream()
.collect(Collectors.groupingBy((entry) -> {
if (entry.getKey() == EQUALS || entry.getKey() == IN)
{
return EQUALS;
}
else
{
return MATCHES;
}
}, Collectors.flatMapping((entry) -> entry.getValue().stream().map(String::toLowerCase), Collectors.toCollection(HashSet::new))));
}
private NodeRef checkTagRootAsNodePrimaryParent(String tagId, NodeRef tagNodeRef)
{
if ( tagNodeRef == null || !nodeService.getPrimaryParent(tagNodeRef).getParentRef().equals(tagParentNodeRef))
{
throw new EntityNotFoundException(tagId);
}
return tagNodeRef;
}
private NodeRef checkTagRootAsNodePrimaryParent(String tagId, NodeRef tagNodeRef)
{
if ( tagNodeRef == null || !nodeService.getPrimaryParent(tagNodeRef).getParentRef().equals(TAG_ROOT_NODE_REF))
{
throw new EntityNotFoundException(tagId);
}
return tagNodeRef;
}
}

View File

@@ -134,7 +134,7 @@ public class RestRuleModelMapper implements RestModelMapper<Rule, org.alfresco.s
public org.alfresco.service.cmr.rule.Rule toServiceModel(Rule restRuleModel)
{
final org.alfresco.service.cmr.rule.Rule serviceRule = new org.alfresco.service.cmr.rule.Rule();
final NodeRef nodeRef = (restRuleModel.getId() != null) ? nodes.validateOrLookupNode(restRuleModel.getId(), null) : null;
final NodeRef nodeRef = (restRuleModel.getId() != null) ? nodes.validateOrLookupNode(restRuleModel.getId()) : null;
serviceRule.setNodeRef(nodeRef);
serviceRule.setTitle(restRuleModel.getName());
serviceRule.setDescription(restRuleModel.getDescription());

View File

@@ -129,7 +129,7 @@ public class RestRuleSimpleConditionModelMapper implements RestModelMapper<Simpl
parameterValues.put(InCategoryEvaluator.PARAM_CATEGORY_ASPECT, ContentModel.ASPECT_GEN_CLASSIFIABLE);
try
{
parameterValues.put(InCategoryEvaluator.PARAM_CATEGORY_VALUE, nodes.validateOrLookupNode(parameter, null));
parameterValues.put(InCategoryEvaluator.PARAM_CATEGORY_VALUE, nodes.validateOrLookupNode(parameter));
} catch (EntityNotFoundException e) {
throw new InvalidArgumentException(CATEGORY_INVALID_MSG);
}

View File

@@ -173,7 +173,7 @@ public class ActionParameterConverter
}
else if (typeQName.isMatch(DataTypeDefinition.NODE_REF))
{
NodeRef nodeRef = nodes.validateOrLookupNode(stringValue, null);
NodeRef nodeRef = nodes.validateOrLookupNode(stringValue);
if (permissionService.hasReadPermission(nodeRef) != ALLOWED)
{
throw new EntityNotFoundException(stringValue);

View File

@@ -72,7 +72,7 @@ public class NodeValidator
{
try
{
final NodeRef nodeRef = nodes.validateOrLookupNode(folderNodeId, null);
final NodeRef nodeRef = nodes.validateOrLookupNode(folderNodeId);
validatePermission(requireChangePermission, nodeRef);
verifyNodeType(nodeRef, ContentModel.TYPE_FOLDER, null);

View File

@@ -35,6 +35,7 @@ public class Category
private String parentId;
private boolean hasChildren;
private Integer count;
private String path;
public String getId()
{
@@ -91,6 +92,14 @@ public class Category
this.count = count;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Override
public boolean equals(Object o)
{
@@ -100,19 +109,20 @@ public class Category
return false;
Category category = (Category) o;
return hasChildren == category.hasChildren && Objects.equals(id, category.id) && Objects.equals(name, category.name) && Objects.equals(parentId, category.parentId)
&& Objects.equals(count, category.count);
&& Objects.equals(count, category.count) && Objects.equals(path, category.path);
}
@Override
public int hashCode()
{
return Objects.hash(id, name, parentId, hasChildren, count);
return Objects.hash(id, name, parentId, hasChildren, count, path);
}
@Override
public String toString()
{
return "Category{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", parentId='" + parentId + '\'' + ", hasChildren=" + hasChildren + ", count=" + count + '}';
return "Category{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", parentId='" + parentId + '\'' + ", hasChildren=" + hasChildren
+ ", count=" + count + ", path=" + path + '}';
}
public static Builder builder()
@@ -127,6 +137,7 @@ public class Category
private String parentId;
private boolean hasChildren;
private Integer count;
private String path;
public Builder id(String id)
{
@@ -158,6 +169,12 @@ public class Category
return this;
}
public Builder path(String path)
{
this.path = path;
return this;
}
public Category create()
{
final Category category = new Category();
@@ -166,6 +183,7 @@ public class Category
category.setParentId(parentId);
category.setHasChildren(hasChildren);
category.setCount(count);
category.setPath(path);
return category;
}
}

View File

@@ -26,6 +26,7 @@
package org.alfresco.rest.api.model;
import java.util.Objects;
import java.util.Optional;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.alfresco.rest.framework.resource.UniqueId;
@@ -41,7 +42,7 @@ public class Tag implements Comparable<Tag>
{
private NodeRef nodeRef;
private String tag;
private Integer count;
private Long count;
public Tag()
{
@@ -50,7 +51,7 @@ public class Tag implements Comparable<Tag>
public Tag(NodeRef nodeRef, String tag)
{
this.nodeRef = nodeRef;
this.tag = tag;
setTag(tag);
}
@JsonProperty("id")
@@ -72,16 +73,16 @@ public class Tag implements Comparable<Tag>
public void setTag(String tag)
{
this.tag = tag;
this.tag = Optional.ofNullable(tag).map(String::toLowerCase).orElse(null);
}
public Integer getCount()
public Long getCount()
{
return count;
}
public void setCount(Integer count)
public void setCount(Long count)
{
this.count = count;
}
@@ -132,7 +133,7 @@ public class Tag implements Comparable<Tag>
{
private NodeRef nodeRef;
private String tag;
private Integer count;
private Long count;
public Builder nodeRef(NodeRef nodeRef)
{
@@ -146,7 +147,7 @@ public class Tag implements Comparable<Tag>
return this;
}
public Builder count(Integer count)
public Builder count(Long count)
{
this.count = count;
return this;

View File

@@ -31,13 +31,9 @@ import org.alfresco.rest.framework.resource.RelationshipResource;
import org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction;
import org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo;
import org.alfresco.rest.framework.resource.parameters.Parameters;
import org.alfresco.rest.framework.resource.parameters.SortColumn;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.util.ParameterCheck;
import java.util.List;
import java.util.stream.Collectors;
@RelationshipResource(name = "action-definitions", entityResource = NodesEntityResource.class, title = "Node action definitions")
public class NodeActionDefinitionsRelation extends AbstractNodeRelation
implements RelationshipResourceAction.Read<ActionDefinition>
@@ -59,7 +55,7 @@ public class NodeActionDefinitionsRelation extends AbstractNodeRelation
@Override
public CollectionWithPagingInfo<ActionDefinition> readAll(String entityResourceId, Parameters params)
{
NodeRef parentNodeRef = nodes.validateOrLookupNode(entityResourceId, null);
NodeRef parentNodeRef = nodes.validateOrLookupNode(entityResourceId);
return actions.getActionDefinitions(parentNodeRef, params);
}
}

View File

@@ -25,6 +25,11 @@
*/
package org.alfresco.rest.api.nodes;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.alfresco.rest.antlr.WhereClauseParser;
import org.alfresco.rest.api.Nodes;
import org.alfresco.rest.api.model.Node;
@@ -41,11 +46,6 @@ import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QNamePattern;
import org.alfresco.service.namespace.RegexQNamePattern;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Node Parents
*
@@ -67,7 +67,7 @@ public class NodeParentsRelation extends AbstractNodeRelation implements Relatio
@WebApiDescription(title = "Return a list of parent nodes based on child assocs")
public CollectionWithPagingInfo<Node> readAll(String childNodeId, Parameters parameters)
{
NodeRef childNodeRef = nodes.validateOrLookupNode(childNodeId, null);
NodeRef childNodeRef = nodes.validateOrLookupNode(childNodeId);
QNamePattern assocTypeQNameParam = RegexQNamePattern.MATCH_ALL;

View File

@@ -25,6 +25,8 @@
*/
package org.alfresco.rest.api.nodes;
import java.util.List;
import org.alfresco.rest.api.Nodes;
import org.alfresco.rest.api.model.AssocChild;
import org.alfresco.rest.api.model.Node;
@@ -41,8 +43,6 @@ import org.alfresco.service.namespace.QName;
import org.alfresco.service.namespace.QNamePattern;
import org.alfresco.service.namespace.RegexQNamePattern;
import java.util.List;
/**
* Node Secondary Children
*
@@ -71,7 +71,7 @@ public class NodeSecondaryChildrenRelation extends AbstractNodeRelation implemen
@WebApiDescription(title = "Return a paged list of secondary child nodes based on child assocs")
public CollectionWithPagingInfo<Node> readAll(String parentNodeId, Parameters parameters)
{
NodeRef parentNodeRef = nodes.validateOrLookupNode(parentNodeId, null);
NodeRef parentNodeRef = nodes.validateOrLookupNode(parentNodeId);
QNamePattern assocTypeQNameParam = getAssocTypeFromWhereElseAll(parameters);

View File

@@ -25,6 +25,8 @@
*/
package org.alfresco.rest.api.nodes;
import java.util.List;
import org.alfresco.rest.api.model.Node;
import org.alfresco.rest.framework.WebApiDescription;
import org.alfresco.rest.framework.resource.RelationshipResource;
@@ -35,8 +37,6 @@ import org.alfresco.service.cmr.repository.AssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QNamePattern;
import java.util.List;
/**
* Node Sources - list node (peer) associations from target to sources
*
@@ -54,7 +54,7 @@ public class NodeSourcesRelation extends AbstractNodeRelation implements Relatio
@WebApiDescription(title = "Return a paged list of sources nodes based on (peer) assocs")
public CollectionWithPagingInfo<Node> readAll(String targetNodeId, Parameters parameters)
{
NodeRef targetNodeRef = nodes.validateOrLookupNode(targetNodeId, null);
NodeRef targetNodeRef = nodes.validateOrLookupNode(targetNodeId);
QNamePattern assocTypeQNameParam = getAssocTypeFromWhereElseAll(parameters);

View File

@@ -1,28 +1,28 @@
/*
* #%L
* Alfresco Remote API
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/*
* #%L
* Alfresco Remote API
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.rest.api.nodes;
import java.util.List;
@@ -61,7 +61,7 @@ public class NodeTagsRelation implements RelationshipResourceAction.Create<Tag>,
@WebApiDescription(title="Adds one or more tags to the node with id 'nodeId'.")
public List<Tag> create(String nodeId, List<Tag> tagsToCreate, Parameters parameters)
{
return tags.addTags(nodeId, tagsToCreate);
return tags.addTags(nodeId, tagsToCreate, parameters);
}
@Override

View File

@@ -25,6 +25,8 @@
*/
package org.alfresco.rest.api.nodes;
import java.util.List;
import org.alfresco.rest.api.Nodes;
import org.alfresco.rest.api.model.AssocTarget;
import org.alfresco.rest.api.model.Node;
@@ -40,8 +42,6 @@ import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.namespace.QNamePattern;
import org.alfresco.service.namespace.RegexQNamePattern;
import java.util.List;
/**
* Node Targets
*
@@ -64,7 +64,7 @@ public class NodeTargetsRelation extends AbstractNodeRelation implements
@WebApiDescription(title = "Return a paged list of target nodes based on (peer) assocs")
public CollectionWithPagingInfo<Node> readAll(String sourceNodeId, Parameters parameters)
{
NodeRef sourceNodeRef = nodes.validateOrLookupNode(sourceNodeId, null);
NodeRef sourceNodeRef = nodes.validateOrLookupNode(sourceNodeId);
QNamePattern assocTypeQNameParam = getAssocTypeFromWhereElseAll(parameters);

View File

@@ -25,6 +25,13 @@
*/
package org.alfresco.rest.api.nodes;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.directurl.DirectAccessUrlDisabledException;
import org.alfresco.repo.node.integrity.IntegrityException;
@@ -65,13 +72,6 @@ import org.alfresco.util.ParameterCheck;
import org.alfresco.util.PropertyCheck;
import org.springframework.beans.factory.InitializingBean;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Node Versions - version history
*
@@ -117,7 +117,7 @@ public class NodeVersionsRelation extends AbstractNodeRelation implements
@WebApiDescription(title = "Return version history as a paged list of version node infos")
public CollectionWithPagingInfo<Node> readAll(String nodeId, Parameters parameters)
{
NodeRef nodeRef = nodes.validateOrLookupNode(nodeId, null);
NodeRef nodeRef = nodes.validateOrLookupNode(nodeId);
VersionHistory vh = versionService.getVersionHistory(nodeRef);
@@ -293,7 +293,7 @@ public class NodeVersionsRelation extends AbstractNodeRelation implements
public Version findVersion(String nodeId, String versionLabelId)
{
NodeRef nodeRef = nodes.validateOrLookupNode(nodeId, null);
NodeRef nodeRef = nodes.validateOrLookupNode(nodeId);
VersionHistory vh = versionService.getVersionHistory(nodeRef);
if (vh != null)
{

View File

@@ -25,8 +25,8 @@
*/
package org.alfresco.rest.api.tags;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.alfresco.rest.api.Tags;
import org.alfresco.rest.api.model.Tag;
@@ -73,13 +73,13 @@ public class TagsEntityResource implements EntityResourceAction.Read<Tag>,
@WebApiDescription(title="Updates a tag by unique Id")
public Tag update(String id, Tag entity, Parameters parameters)
{
return tags.changeTag(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, id, entity);
return tags.changeTag(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, id, entity, parameters);
}
@Override
public Tag readById(String id, Parameters parameters) throws EntityNotFoundException
{
return tags.getTag(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, id);
return tags.getTag(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, id, parameters);
}
/**

View File

@@ -60,6 +60,7 @@ import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.transfer.PathHelper;
import org.alfresco.rest.api.Nodes;
import org.alfresco.rest.api.model.Category;
import org.alfresco.rest.api.model.Node;
@@ -71,6 +72,7 @@ import org.alfresco.rest.framework.resource.parameters.Parameters;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.Path;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.CategoryService;
import org.alfresco.service.cmr.security.AccessStatus;
@@ -100,6 +102,9 @@ public class CategoriesImplTest
private static final Category CATEGORY = createDefaultCategory();
private static final String CONTENT_NODE_ID = "content-node-id";
private static final NodeRef CONTENT_NODE_REF = createNodeRefWithId(CONTENT_NODE_ID);
private static final String MOCK_ROOT_LEVEL = "/{mockRootLevel}";
private static final String MOCK_CHILD_LEVEL = "/{mockChild}";
private static final String MOCK_CATEGORY_PATH = "//" + MOCK_ROOT_LEVEL + "//" + MOCK_CHILD_LEVEL;
@Mock
private Nodes nodesMock;
@@ -128,7 +133,7 @@ public class CategoriesImplTest
{
given(authorityServiceMock.hasAdminAuthority()).willReturn(true);
given(nodesMock.validateNode(CATEGORY_ID)).willReturn(CATEGORY_NODE_REF);
given(nodesMock.validateNode(CONTENT_NODE_ID)).willReturn(CONTENT_NODE_REF);
given(nodesMock.validateOrLookupNode(CONTENT_NODE_ID)).willReturn(CONTENT_NODE_REF);
given(nodesMock.isSubClass(any(), any(), anyBoolean())).willReturn(true);
given(typeConstraint.matches(any())).willReturn(true);
given(permissionServiceMock.hasReadPermission(any())).willReturn(AccessStatus.ALLOWED);
@@ -252,6 +257,27 @@ public class CategoriesImplTest
.isEqualTo(1);
}
@Test
public void testGetCategoryById_includePath()
{
final QName categoryQName = createCmQNameOf(CATEGORY_NAME);
final NodeRef parentCategoryNodeRef = createNodeRefWithId(PARENT_ID);
final ChildAssociationRef parentAssociation = createAssociationOf(parentCategoryNodeRef, CATEGORY_NODE_REF, categoryQName);
given(nodesMock.getNode(any())).willReturn(createNode());
given(nodeServiceMock.getPrimaryParent(any())).willReturn(parentAssociation);
given(parametersMock.getInclude()).willReturn(List.of(Nodes.PARAM_INCLUDE_PATH));
given(nodeServiceMock.getPath(any())).willReturn(mockCategoryPath());
// when
final Category actualCategory = objectUnderTest.getCategoryById(CATEGORY_ID, parametersMock);
assertThat(actualCategory)
.isNotNull()
.extracting(Category::getPath)
.isNotNull()
.isEqualTo(MOCK_CATEGORY_PATH);
}
@Test
public void testGetCategoryById_notACategory()
{
@@ -479,6 +505,36 @@ public class CategoriesImplTest
.isEqualTo(0);
}
@Test
public void testCreateCategory_includePath()
{
final QName categoryQName = createCmQNameOf(CATEGORY_NAME);
final NodeRef categoryNodeRef = createNodeRefWithId(CATEGORY_ID);
final NodeRef parentCategoryNodeRef = createNodeRefWithId(PARENT_ID);
final ChildAssociationRef parentAssociation = createAssociationOf(parentCategoryNodeRef, CATEGORY_NODE_REF, categoryQName);
given(nodesMock.validateNode(PARENT_ID)).willReturn(parentCategoryNodeRef);
given(categoryServiceMock.createCategory(parentCategoryNodeRef, CATEGORY_NAME)).willReturn(categoryNodeRef);
given(nodesMock.getNode(any())).willReturn(createNode());
given(nodeServiceMock.getPrimaryParent(any())).willReturn(parentAssociation);
given(parametersMock.getInclude()).willReturn(List.of(Nodes.PARAM_INCLUDE_PATH));
given(nodeServiceMock.getPath(any())).willReturn(mockCategoryPath());
final List<Category> categoryModels = new ArrayList<>(prepareCategories());
// when
final List<Category> actualCreatedCategories = objectUnderTest.createSubcategories(PARENT_ID, categoryModels, parametersMock);
then(categoryServiceMock).should().createCategory(any(), any());
then(categoryServiceMock).shouldHaveNoMoreInteractions();
assertThat(actualCreatedCategories)
.isNotNull()
.hasSize(1)
.element(0)
.extracting(Category::getPath)
.isNotNull()
.isEqualTo(MOCK_CATEGORY_PATH);
}
@Test
public void testCreateCategories_noPermissions()
{
@@ -628,6 +684,30 @@ public class CategoriesImplTest
.isEqualTo(List.of(0, 2, 0));
}
@Test
public void testGetCategoryChildren_includePath()
{
final NodeRef parentCategoryNodeRef = createNodeRefWithId(PARENT_ID);
given(nodesMock.validateNode(PARENT_ID)).willReturn(parentCategoryNodeRef);
given(nodesMock.isSubClass(parentCategoryNodeRef, ContentModel.TYPE_CATEGORY, false)).willReturn(true);
final int childrenCount = 3;
final List<ChildAssociationRef> childAssociationRefMocks = prepareChildAssocMocks(childrenCount, parentCategoryNodeRef);
given(nodeServiceMock.getChildAssocs(parentCategoryNodeRef)).willReturn(childAssociationRefMocks);
childAssociationRefMocks.forEach(this::prepareCategoryNodeMocks);
given(parametersMock.getInclude()).willReturn(List.of(Nodes.PARAM_INCLUDE_PATH));
given(nodeServiceMock.getPath(any())).willReturn(mockCategoryPath());
// when
final List<Category> actualCategoryChildren = objectUnderTest.getCategoryChildren(PARENT_ID, parametersMock);
assertThat(actualCategoryChildren)
.isNotNull()
.hasSize(3)
.extracting(Category::getPath)
.isNotNull()
.isEqualTo(List.of(MOCK_CATEGORY_PATH, MOCK_CATEGORY_PATH, MOCK_CATEGORY_PATH));
}
@Test
public void testGetCategoryChildren_noChildren()
{
@@ -751,6 +831,32 @@ public class CategoriesImplTest
.isEqualTo(1);
}
@Test
public void testUpdateCategoryById_includePath()
{
final String categoryNewName = "categoryNewName";
final Category fixedCategory = createCategoryOnlyWithName(categoryNewName);
// simulate path provided by client to check if it will be ignored
fixedCategory.setPath("/test/TestCat");
final QName categoryQName = createCmQNameOf(CATEGORY_NAME);
final NodeRef parentCategoryNodeRef = createNodeRefWithId(PARENT_ID);
final ChildAssociationRef parentAssociation = createAssociationOf(parentCategoryNodeRef, CATEGORY_NODE_REF, categoryQName);
given(nodesMock.getNode(any())).willReturn(createNode(categoryNewName));
given(nodeServiceMock.getPrimaryParent(any())).willReturn(parentAssociation);
given(nodeServiceMock.moveNode(any(), any(), any(), any())).willReturn(createAssociationOf(parentCategoryNodeRef, CATEGORY_NODE_REF, createCmQNameOf(categoryNewName)));
given(parametersMock.getInclude()).willReturn(List.of(Nodes.PARAM_INCLUDE_PATH));
given(nodeServiceMock.getPath(any())).willReturn(mockCategoryPath());
// when
final Category actualCategory = objectUnderTest.updateCategoryById(CATEGORY_ID, fixedCategory, parametersMock);
assertThat(actualCategory)
.isNotNull()
.extracting(Category::getPath)
.isNotNull()
.isEqualTo(MOCK_CATEGORY_PATH);
}
@Test
public void testUpdateCategoryById_noPermission()
{
@@ -900,7 +1006,7 @@ public class CategoriesImplTest
// when
final List<Category> actualLinkedCategories = objectUnderTest.linkNodeToCategories(CONTENT_NODE_ID, categoryLinks, parametersMock);
then(nodesMock).should().validateNode(CONTENT_NODE_ID);
then(nodesMock).should().validateOrLookupNode(CONTENT_NODE_ID);
then(permissionServiceMock).should().hasPermission(CONTENT_NODE_REF, PermissionService.CHANGE_PERMISSIONS);
then(permissionServiceMock).shouldHaveNoMoreInteractions();
then(typeConstraint).should().matches(CONTENT_NODE_REF);
@@ -918,6 +1024,7 @@ public class CategoriesImplTest
then(nodeServiceMock).should().getParentAssocs(categoryParentNodeRef);
then(nodeServiceMock).shouldHaveNoMoreInteractions();
final List<Category> expectedLinkedCategories = List.of(CATEGORY);
expectedLinkedCategories.get(0).setPath(null);
assertThat(actualLinkedCategories)
.isNotNull().usingRecursiveComparison()
.isEqualTo(expectedLinkedCategories);
@@ -984,6 +1091,36 @@ public class CategoriesImplTest
.isEqualTo(expectedLinkedCategories);
}
@Test
public void testLinkNodeToCategories_includePath()
{
final NodeRef categoryParentNodeRef = createNodeRefWithId(PARENT_ID);
final ChildAssociationRef parentAssociation = createAssociationOf(categoryParentNodeRef, CATEGORY_NODE_REF);
given(nodesMock.getNode(any())).willReturn(createNode());
given(nodeServiceMock.getPrimaryParent(any())).willReturn(parentAssociation);
given(nodeServiceMock.hasAspect(any(), any())).willReturn(true);
given(parametersMock.getInclude()).willReturn(List.of(Nodes.PARAM_INCLUDE_PATH));
given(nodeServiceMock.getPath(any())).willReturn(mockCategoryPath());
// when
final List<Category> actualLinkedCategories = objectUnderTest.linkNodeToCategories(CONTENT_NODE_ID, List.of(CATEGORY), parametersMock);
then(nodesMock).should(times(2)).getNode(CATEGORY_ID);
then(nodeServiceMock).should().getChildAssocs(CATEGORY_NODE_REF, RegexQNamePattern.MATCH_ALL, RegexQNamePattern.MATCH_ALL, false);
then(nodeServiceMock).should().getPrimaryParent(CATEGORY_NODE_REF);
then(nodeServiceMock).should().getParentAssocs(CATEGORY_NODE_REF);
then(nodeServiceMock).should().hasAspect(CONTENT_NODE_REF, ContentModel.ASPECT_GEN_CLASSIFIABLE);
then(nodeServiceMock).should().getProperty(CONTENT_NODE_REF, ContentModel.PROP_CATEGORIES);
final Serializable expectedCategories = (Serializable) List.of(CATEGORY_NODE_REF);
then(nodeServiceMock).should().setProperty(CONTENT_NODE_REF, ContentModel.PROP_CATEGORIES, expectedCategories);
then(nodeServiceMock).should().getParentAssocs(categoryParentNodeRef);
final List<Category> expectedLinkedCategories = List.of(CATEGORY);
expectedLinkedCategories.get(0).setPath(MOCK_CATEGORY_PATH);
assertThat(actualLinkedCategories)
.isNotNull().usingRecursiveComparison()
.isEqualTo(expectedLinkedCategories);
}
@Test
public void testLinkNodeToCategories_withPreviouslyLinkedCategories()
{
@@ -1011,12 +1148,12 @@ public class CategoriesImplTest
@Test
public void testLinkNodeToCategories_withInvalidNodeId()
{
given(nodesMock.validateNode(CONTENT_NODE_ID)).willThrow(EntityNotFoundException.class);
given(nodesMock.validateOrLookupNode(CONTENT_NODE_ID)).willThrow(EntityNotFoundException.class);
// when
final Throwable actualException = catchThrowable(() -> objectUnderTest.linkNodeToCategories(CONTENT_NODE_ID, List.of(CATEGORY), parametersMock));
then(nodesMock).should().validateNode(CONTENT_NODE_ID);
then(nodesMock).should().validateOrLookupNode(CONTENT_NODE_ID);
then(permissionServiceMock).shouldHaveNoInteractions();
then(nodeServiceMock).shouldHaveNoInteractions();
assertThat(actualException)
@@ -1031,7 +1168,7 @@ public class CategoriesImplTest
// when
final Throwable actualException = catchThrowable(() -> objectUnderTest.linkNodeToCategories(CONTENT_NODE_ID, List.of(CATEGORY), parametersMock));
then(nodesMock).should().validateNode(CONTENT_NODE_ID);
then(nodesMock).should().validateOrLookupNode(CONTENT_NODE_ID);
then(permissionServiceMock).should().hasPermission(CONTENT_NODE_REF, PermissionService.CHANGE_PERMISSIONS);
then(nodeServiceMock).shouldHaveNoInteractions();
assertThat(actualException)
@@ -1118,7 +1255,7 @@ public class CategoriesImplTest
objectUnderTest.unlinkNodeFromCategory(CONTENT_NODE_ID, CATEGORY_ID, parametersMock);
then(nodesMock).should().validateNode(CATEGORY_ID);
then(nodesMock).should().validateNode(CONTENT_NODE_ID);
then(nodesMock).should().validateOrLookupNode(CONTENT_NODE_ID);
then(permissionServiceMock).should().hasPermission(CONTENT_NODE_REF, PermissionService.CHANGE_PERMISSIONS);
then(permissionServiceMock).shouldHaveNoMoreInteractions();
then(typeConstraint).should().matches(CONTENT_NODE_REF);
@@ -1155,7 +1292,7 @@ public class CategoriesImplTest
// when
final List<Category> actualCategories = objectUnderTest.listCategoriesForNode(CONTENT_NODE_ID, parametersMock);
then(nodesMock).should().validateNode(CONTENT_NODE_ID);
then(nodesMock).should().validateOrLookupNode(CONTENT_NODE_ID);
then(permissionServiceMock).should().hasReadPermission(CONTENT_NODE_REF);
then(permissionServiceMock).shouldHaveNoMoreInteractions();
then(typeConstraint).should().matches(CONTENT_NODE_REF);
@@ -1168,20 +1305,55 @@ public class CategoriesImplTest
then(nodeServiceMock).should().getParentAssocs(categoryParentNodeRef);
then(nodeServiceMock).shouldHaveNoMoreInteractions();
final List<Category> expectedCategories = List.of(CATEGORY);
expectedCategories.get(0).setPath(null);
assertThat(actualCategories)
.isNotNull().usingRecursiveComparison()
.isEqualTo(expectedCategories);
}
@Test
public void testListCategoriesForNode_includePath()
{
final NodeRef categoryParentNodeRef = createNodeRefWithId(PARENT_ID);
final ChildAssociationRef parentAssociation = createAssociationOf(categoryParentNodeRef, CATEGORY_NODE_REF);
given(nodeServiceMock.getProperty(any(), eq(ContentModel.PROP_CATEGORIES))).willReturn((Serializable) List.of(CATEGORY_NODE_REF));
given(nodesMock.getNode(any())).willReturn(createNode());
given(nodeServiceMock.getPrimaryParent(any())).willReturn(parentAssociation);
given(parametersMock.getInclude()).willReturn(List.of(Nodes.PARAM_INCLUDE_PATH));
given(nodeServiceMock.getPath(any())).willReturn(mockCategoryPath());
// when
final List<Category> actualCategories = objectUnderTest.listCategoriesForNode(CONTENT_NODE_ID, parametersMock);
then(nodesMock).should().validateOrLookupNode(CONTENT_NODE_ID);
then(permissionServiceMock).should().hasReadPermission(CONTENT_NODE_REF);
then(permissionServiceMock).shouldHaveNoMoreInteractions();
then(typeConstraint).should().matches(CONTENT_NODE_REF);
then(typeConstraint).shouldHaveNoMoreInteractions();
then(nodesMock).should(times(2)).getNode(CATEGORY_ID);
then(nodesMock).shouldHaveNoMoreInteractions();
then(nodeServiceMock).should().getProperty(CONTENT_NODE_REF, ContentModel.PROP_CATEGORIES);
then(nodeServiceMock).should().getChildAssocs(CATEGORY_NODE_REF, RegexQNamePattern.MATCH_ALL, RegexQNamePattern.MATCH_ALL, false);
then(nodeServiceMock).should().getPrimaryParent(CATEGORY_NODE_REF);
then(nodeServiceMock).should().getParentAssocs(categoryParentNodeRef);
then(nodeServiceMock).should().getPath(any());
then(nodeServiceMock).shouldHaveNoMoreInteractions();
final List<Category> expectedCategories = List.of(CATEGORY);
expectedCategories.get(0).setPath(MOCK_CATEGORY_PATH);
assertThat(actualCategories)
.isNotNull().usingRecursiveComparison()
.isEqualTo(expectedCategories);
}
@Test
public void testListCategoriesForNode_withInvalidNodeId()
{
given(nodesMock.validateNode(CONTENT_NODE_ID)).willThrow(EntityNotFoundException.class);
given(nodesMock.validateOrLookupNode(CONTENT_NODE_ID)).willThrow(EntityNotFoundException.class);
// when
final Throwable actualException = catchThrowable(() -> objectUnderTest.listCategoriesForNode(CONTENT_NODE_ID, parametersMock));
then(nodesMock).should().validateNode(CONTENT_NODE_ID);
then(nodesMock).should().validateOrLookupNode(CONTENT_NODE_ID);
then(nodeServiceMock).shouldHaveNoInteractions();
assertThat(actualException)
.isInstanceOf(EntityNotFoundException.class);
@@ -1195,7 +1367,7 @@ public class CategoriesImplTest
// when
final Throwable actualException = catchThrowable(() -> objectUnderTest.listCategoriesForNode(CONTENT_NODE_ID, parametersMock));
then(nodesMock).should().validateNode(CONTENT_NODE_ID);
then(nodesMock).should().validateOrLookupNode(CONTENT_NODE_ID);
then(permissionServiceMock).should().hasReadPermission(CONTENT_NODE_REF);
then(nodeServiceMock).shouldHaveNoInteractions();
assertThat(actualException)
@@ -1329,4 +1501,13 @@ public class CategoriesImplTest
{
return new ChildAssociationRef(ContentModel.ASSOC_SUBCATEGORIES, parentNode, childNodeName, childNode);
}
private Path mockCategoryPath()
{
final Path mockPath = new Path();
mockPath.append(PathHelper.stringToPath(MOCK_ROOT_LEVEL));
mockPath.append(PathHelper.stringToPath(MOCK_CHILD_LEVEL));
mockPath.append(PathHelper.stringToPath("/"));
return mockPath;
}
}

View File

@@ -25,6 +25,8 @@
*/
package org.alfresco.rest.api.impl;
import static java.util.stream.Collectors.toList;
import static org.alfresco.rest.api.impl.TagsImpl.NOT_A_VALID_TAG;
import static org.alfresco.rest.api.impl.TagsImpl.NO_PERMISSION_TO_MANAGE_A_TAG;
import static org.alfresco.service.cmr.repository.StoreRef.STORE_REF_WORKSPACE_SPACESSTORE;
@@ -38,11 +40,14 @@ import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.alfresco.model.ContentModel;
import org.alfresco.query.PagingRequest;
import org.alfresco.query.PagingResults;
import org.alfresco.rest.api.Nodes;
@@ -50,9 +55,11 @@ import org.alfresco.rest.api.model.Tag;
import org.alfresco.rest.framework.core.exceptions.EntityNotFoundException;
import org.alfresco.rest.framework.core.exceptions.InvalidArgumentException;
import org.alfresco.rest.framework.core.exceptions.PermissionDeniedException;
import org.alfresco.rest.framework.core.exceptions.UnsupportedResourceOperationException;
import org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo;
import org.alfresco.rest.framework.resource.parameters.Paging;
import org.alfresco.rest.framework.resource.parameters.Parameters;
import org.alfresco.rest.framework.resource.parameters.SortColumn;
import org.alfresco.rest.framework.resource.parameters.where.InvalidQueryException;
import org.alfresco.rest.framework.tools.RecognizedParamsExtractor;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
@@ -63,6 +70,7 @@ import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.tagging.TaggingService;
import org.alfresco.util.Pair;
import org.alfresco.util.TypeConstraint;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -77,7 +85,11 @@ public class TagsImplTest
private static final String PARENT_NODE_ID = "tag:tag-root";
private static final String TAG_NAME = "tag-dummy-name";
private static final NodeRef TAG_NODE_REF = new NodeRef(STORE_REF_WORKSPACE_SPACESSTORE, TAG_ID.concat("-").concat(TAG_NAME));
private static final NodeRef TAG_PARENT_NODE_REF = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, PARENT_NODE_ID);
private static final NodeRef TAG_PARENT_NODE_REF = new NodeRef(STORE_REF_WORKSPACE_SPACESSTORE, PARENT_NODE_ID);
private static final String CONTENT_NODE_ID = "content-node-id";
private static final NodeRef CONTENT_NODE_REF = new NodeRef(STORE_REF_WORKSPACE_SPACESSTORE, CONTENT_NODE_ID);
private static final String PARAM_INCLUDE_COUNT = "count";
private final RecognizedParamsExtractor queryExtractor = new RecognizedParamsExtractor() {};
@@ -97,6 +109,8 @@ public class TagsImplTest
private Paging pagingMock;
@Mock
private PagingResults<Pair<NodeRef, String>> pagingResultsMock;
@Mock
private TypeConstraint typeConstraintMock;
@InjectMocks
private TagsImpl objectUnderTest;
@@ -108,21 +122,25 @@ public class TagsImplTest
given(nodesMock.validateNode(STORE_REF_WORKSPACE_SPACESSTORE, TAG_ID)).willReturn(TAG_NODE_REF);
given(taggingServiceMock.getTagName(TAG_NODE_REF)).willReturn(TAG_NAME);
given(nodeServiceMock.getPrimaryParent(TAG_NODE_REF)).willReturn(primaryParentMock);
given(primaryParentMock.getParentRef()).willReturn(TAG_PARENT_NODE_REF);
}
@Test
public void testGetTags()
{
given(parametersMock.getPaging()).willReturn(pagingMock);
given(taggingServiceMock.getTags(any(StoreRef.class), any(PagingRequest.class), any(), any())).willReturn(pagingResultsMock);
given(pagingResultsMock.getTotalResultCount()).willReturn(new Pair<>(Integer.MAX_VALUE, 0));
given(pagingResultsMock.getPage()).willReturn(List.of(new Pair<>(TAG_NODE_REF, TAG_NAME)));
given(parametersMock.getSorting()).willReturn(new ArrayList<>());
given(parametersMock.getInclude()).willReturn(new ArrayList<>());
//given(taggingServiceMock.getTags(eq(STORE_REF_WORKSPACE_SPACESSTORE), any(), any(), isNull(), isNull())).willReturn(List.of(new Pair<>(TAG_NODE_REF, null)));
given(taggingServiceMock.getTags(eq(STORE_REF_WORKSPACE_SPACESSTORE), any(), any(), isNull(), isNull())).willReturn(Map.of(TAG_NODE_REF, 0L));
given(nodeServiceMock.getProperty(any(NodeRef.class), eq(ContentModel.PROP_NAME))).willReturn("tag-dummy-name");
final CollectionWithPagingInfo<Tag> actualTags = objectUnderTest.getTags(STORE_REF_WORKSPACE_SPACESSTORE, parametersMock);
then(taggingServiceMock).should().getTags(eq(STORE_REF_WORKSPACE_SPACESSTORE), any(PagingRequest.class), isNull(), isNull());
then(taggingServiceMock).should().getTags(eq(STORE_REF_WORKSPACE_SPACESSTORE), any(), any(), isNull(), isNull());
then(taggingServiceMock).shouldHaveNoMoreInteractions();
final List<Tag> expectedTags = createTagsWithNodeRefs(List.of(TAG_NAME)).stream().peek(tag -> tag.setCount(0)).collect(Collectors.toList());
final List<Tag> expectedTags = createTagsWithNodeRefs(List.of(TAG_NAME));
assertEquals(expectedTags, actualTags.getCollection());
}
@@ -130,17 +148,163 @@ public class TagsImplTest
public void testGetTags_verifyIfCountIsZero()
{
given(parametersMock.getPaging()).willReturn(pagingMock);
given(taggingServiceMock.getTags(any(StoreRef.class), any(PagingRequest.class), any(), any())).willReturn(pagingResultsMock);
given(pagingResultsMock.getTotalResultCount()).willReturn(new Pair<>(Integer.MAX_VALUE, 0));
given(pagingResultsMock.getPage()).willReturn(List.of(new Pair<>(TAG_NODE_REF, TAG_NAME)));
given(parametersMock.getSorting()).willReturn(new ArrayList<>());
given(parametersMock.getInclude()).willReturn(List.of(PARAM_INCLUDE_COUNT));
given(taggingServiceMock.getTags(any(StoreRef.class), any(), any(), any(), any())).willReturn(Map.of(TAG_NODE_REF, 0L));
given(nodeServiceMock.getProperty(any(NodeRef.class), eq(ContentModel.PROP_NAME))).willReturn("tag-dummy-name");
given(parametersMock.getInclude()).willReturn(List.of("count"));
final CollectionWithPagingInfo<Tag> actualTags = objectUnderTest.getTags(STORE_REF_WORKSPACE_SPACESSTORE, parametersMock);
then(taggingServiceMock).should().findTaggedNodesAndCountByTagName(STORE_REF_WORKSPACE_SPACESSTORE);
final List<Tag> expectedTags = createTagsWithNodeRefs(List.of(TAG_NAME)).stream()
.peek(tag -> tag.setCount(0))
.collect(Collectors.toList());
.peek(tag -> tag.setCount(0L))
.collect(toList());
assertEquals(expectedTags, actualTags.getCollection());
}
/** Check that we can get counts for two tags - one in use and one not applied to any nodes. */
@Test
public void testGetTags_verifyCountPopulatedCorrectly()
{
NodeRef tagNodeA = new NodeRef("tag://A/");
NodeRef tagNodeB = new NodeRef("tag://B/");
given(parametersMock.getSorting()).willReturn(Collections.emptyList());
given(parametersMock.getPaging()).willReturn(pagingMock);
given(parametersMock.getInclude()).willReturn(List.of("count"));
final LinkedHashMap<NodeRef, Long> results = new LinkedHashMap<>();
results.put(tagNodeA, 5L);
results.put(tagNodeB, 0L);
given(taggingServiceMock.getTags(any(StoreRef.class), eq(List.of(PARAM_INCLUDE_COUNT)), isNull(), any(), any())).willReturn(results);
given(nodeServiceMock.getProperty(any(NodeRef.class), eq(ContentModel.PROP_NAME))).willReturn("taga", "tagb");
final CollectionWithPagingInfo<Tag> actualTags = objectUnderTest.getTags(STORE_REF_WORKSPACE_SPACESSTORE, parametersMock);
final List<Tag> expectedTags = List.of(Tag.builder().tag("tagA").nodeRef(tagNodeA).count(5L).create(),
Tag.builder().tag("tagB").nodeRef(tagNodeB).count(0L).create());
assertEquals(expectedTags, actualTags.getCollection());
}
@Test
public void testGetTags_orderByCountAscendingOrder()
{
NodeRef tagNodeA = new NodeRef("tag://A/");
NodeRef tagNodeB = new NodeRef("tag://B/");
NodeRef tagNodeC = new NodeRef("tag://C/");
given(parametersMock.getPaging()).willReturn(pagingMock);
given(parametersMock.getInclude()).willReturn(List.of("count"));
given(parametersMock.getSorting()).willReturn(List.of(new SortColumn("count", true)));
final LinkedHashMap<NodeRef, Long> results = new LinkedHashMap<>();
results.put(tagNodeB, 0L);
results.put(tagNodeC, 2L);
results.put(tagNodeA, 5L);
given(taggingServiceMock.getTags(any(StoreRef.class), eq(List.of(PARAM_INCLUDE_COUNT)), eq(new Pair<>("count", true)), any(), any())).willReturn(results);
given(nodeServiceMock.getProperty(tagNodeA, ContentModel.PROP_NAME)).willReturn("taga");
given(nodeServiceMock.getProperty(tagNodeB, ContentModel.PROP_NAME)).willReturn("tagb");
given(nodeServiceMock.getProperty(tagNodeC, ContentModel.PROP_NAME)).willReturn("tagc");
//when
final CollectionWithPagingInfo<Tag> actualTags = objectUnderTest.getTags(STORE_REF_WORKSPACE_SPACESSTORE, parametersMock);
final List<Tag> expectedTags = List.of(Tag.builder().tag("tagb").nodeRef(tagNodeB).count(0L).create(),
Tag.builder().tag("tagc").nodeRef(tagNodeC).count(2L).create(),
Tag.builder().tag("taga").nodeRef(tagNodeA).count(5L).create());
assertEquals(expectedTags, actualTags.getCollection());
}
@Test
public void testGetTags_orderByCountDescendingOrder()
{
NodeRef tagNodeA = new NodeRef("tag://A/");
NodeRef tagNodeB = new NodeRef("tag://B/");
NodeRef tagNodeC = new NodeRef("tag://C/");
given(parametersMock.getPaging()).willReturn(pagingMock);
given(parametersMock.getInclude()).willReturn(List.of("count"));
given(parametersMock.getSorting()).willReturn(List.of(new SortColumn("count", false)));
final LinkedHashMap<NodeRef, Long> results = new LinkedHashMap<>();
results.put(tagNodeA, 5L);
results.put(tagNodeC, 2L);
results.put(tagNodeB, 0L);
given(taggingServiceMock.getTags(any(StoreRef.class), eq(List.of(PARAM_INCLUDE_COUNT)), eq(new Pair<>("count", false)), any(), any())).willReturn(results);
given(nodeServiceMock.getProperty(tagNodeA, ContentModel.PROP_NAME)).willReturn("taga");
given(nodeServiceMock.getProperty(tagNodeB, ContentModel.PROP_NAME)).willReturn("tagb");
given(nodeServiceMock.getProperty(tagNodeC, ContentModel.PROP_NAME)).willReturn("tagc");
//when
final CollectionWithPagingInfo<Tag> actualTags = objectUnderTest.getTags(STORE_REF_WORKSPACE_SPACESSTORE, parametersMock);
final List<Tag> expectedTags = List.of(Tag.builder().tag("taga").nodeRef(tagNodeA).count(5L).create(),
Tag.builder().tag("tagc").nodeRef(tagNodeC).count(2L).create(),
Tag.builder().tag("tagb").nodeRef(tagNodeB).count(0L).create());
assertEquals(expectedTags, actualTags.getCollection());
}
@Test
public void testGetTags_orderByTagAscendingOrder()
{
NodeRef tagApple = new NodeRef("tag://apple/");
NodeRef tagBanana = new NodeRef("tag://banana/");
NodeRef tagCoconut = new NodeRef("tag://coconut/");
given(parametersMock.getPaging()).willReturn(pagingMock);
given(parametersMock.getInclude()).willReturn(Collections.emptyList());
given(parametersMock.getSorting()).willReturn(List.of(new SortColumn("tag", true)));
final LinkedHashMap<NodeRef, Long> results = new LinkedHashMap<>();
results.put(tagApple, 0L);
results.put(tagBanana, 0L);
results.put(tagCoconut, 0L);
given(taggingServiceMock.getTags(any(StoreRef.class), any(), eq(new Pair<>("tag", true)), any(), any())).willReturn(results);
given(nodeServiceMock.getProperty(tagApple, ContentModel.PROP_NAME)).willReturn("apple");
given(nodeServiceMock.getProperty(tagBanana, ContentModel.PROP_NAME)).willReturn("banana");
given(nodeServiceMock.getProperty(tagCoconut, ContentModel.PROP_NAME)).willReturn("coconut");
//when
final CollectionWithPagingInfo<Tag> actualTags = objectUnderTest.getTags(STORE_REF_WORKSPACE_SPACESSTORE, parametersMock);
final List<Tag> expectedTags = List.of(Tag.builder().tag("apple").nodeRef(tagApple).create(),
Tag.builder().tag("banana").nodeRef(tagBanana).create(),
Tag.builder().tag("coconut").nodeRef(tagCoconut).create());
assertEquals(expectedTags, actualTags.getCollection());
}
@Test
public void testGetTags_orderByTagDescendingOrder()
{
NodeRef tagApple = new NodeRef("tag://apple/");
NodeRef tagBanana = new NodeRef("tag://banana/");
NodeRef tagCoconut = new NodeRef("tag://coconut/");
given(parametersMock.getPaging()).willReturn(pagingMock);
given(parametersMock.getInclude()).willReturn(Collections.emptyList());
given(parametersMock.getSorting()).willReturn(List.of(new SortColumn("tag", false)));
final LinkedHashMap<NodeRef, Long> results = new LinkedHashMap<>();
results.put(tagCoconut, 0L);
results.put(tagBanana, 0L);
results.put(tagApple, 0L);
given(taggingServiceMock.getTags(any(StoreRef.class), any(), eq(new Pair<>("tag", false)), any(), any())).willReturn(results);
given(nodeServiceMock.getProperty(tagApple, ContentModel.PROP_NAME)).willReturn("apple");
given(nodeServiceMock.getProperty(tagBanana, ContentModel.PROP_NAME)).willReturn("banana");
given(nodeServiceMock.getProperty(tagCoconut, ContentModel.PROP_NAME)).willReturn("coconut");
//when
final CollectionWithPagingInfo<Tag> actualTags = objectUnderTest.getTags(STORE_REF_WORKSPACE_SPACESSTORE, parametersMock);
final List<Tag> expectedTags = List.of(Tag.builder().tag("coconut").nodeRef(tagCoconut).create(),
Tag.builder().tag("banana").nodeRef(tagBanana).create(),
Tag.builder().tag("apple").nodeRef(tagApple).create());
assertEquals(expectedTags, actualTags.getCollection());
}
@@ -149,13 +313,13 @@ public class TagsImplTest
{
given(parametersMock.getPaging()).willReturn(pagingMock);
given(parametersMock.getQuery()).willReturn(queryExtractor.getWhereClause("(tag=expectedName)"));
given(taggingServiceMock.getTags(any(StoreRef.class), any(PagingRequest.class), any(), any())).willReturn(pagingResultsMock);
given(pagingResultsMock.getTotalResultCount()).willReturn(new Pair<>(Integer.MAX_VALUE, 0));
given(parametersMock.getSorting()).willReturn(new ArrayList<>());
given(parametersMock.getInclude()).willReturn(new ArrayList<>());
//when
final CollectionWithPagingInfo<Tag> actualTags = objectUnderTest.getTags(STORE_REF_WORKSPACE_SPACESSTORE, parametersMock);
then(taggingServiceMock).should().getTags(eq(STORE_REF_WORKSPACE_SPACESSTORE), any(PagingRequest.class), eq(Set.of("expectedname")), isNull());
then(taggingServiceMock).should().getTags(eq(STORE_REF_WORKSPACE_SPACESSTORE), eq(new ArrayList<>()), any(), eq(Set.of("expectedname")), isNull());
then(taggingServiceMock).shouldHaveNoMoreInteractions();
assertThat(actualTags).isNotNull();
}
@@ -165,13 +329,13 @@ public class TagsImplTest
{
given(parametersMock.getPaging()).willReturn(pagingMock);
given(parametersMock.getQuery()).willReturn(queryExtractor.getWhereClause("(tag IN (expectedName1, expectedName2))"));
given(taggingServiceMock.getTags(any(StoreRef.class), any(PagingRequest.class), any(), any())).willReturn(pagingResultsMock);
given(pagingResultsMock.getTotalResultCount()).willReturn(new Pair<>(Integer.MAX_VALUE, 0));
given(parametersMock.getSorting()).willReturn(new ArrayList<>());
given(parametersMock.getInclude()).willReturn(new ArrayList<>());
//when
final CollectionWithPagingInfo<Tag> actualTags = objectUnderTest.getTags(STORE_REF_WORKSPACE_SPACESSTORE, parametersMock);
then(taggingServiceMock).should().getTags(eq(STORE_REF_WORKSPACE_SPACESSTORE), any(PagingRequest.class), eq(Set.of("expectedname1", "expectedname2")), isNull());
then(taggingServiceMock).should().getTags(eq(STORE_REF_WORKSPACE_SPACESSTORE),any(), any(), eq(Set.of("expectedname1", "expectedname2")), isNull());
then(taggingServiceMock).shouldHaveNoMoreInteractions();
assertThat(actualTags).isNotNull();
}
@@ -181,13 +345,13 @@ public class TagsImplTest
{
given(parametersMock.getPaging()).willReturn(pagingMock);
given(parametersMock.getQuery()).willReturn(queryExtractor.getWhereClause("(tag MATCHES ('expectedName*'))"));
given(taggingServiceMock.getTags(any(StoreRef.class), any(PagingRequest.class), any(), any())).willReturn(pagingResultsMock);
given(pagingResultsMock.getTotalResultCount()).willReturn(new Pair<>(Integer.MAX_VALUE, 0));
given(parametersMock.getSorting()).willReturn(new ArrayList<>());
given(parametersMock.getInclude()).willReturn(new ArrayList<>());
//when
final CollectionWithPagingInfo<Tag> actualTags = objectUnderTest.getTags(STORE_REF_WORKSPACE_SPACESSTORE, parametersMock);
then(taggingServiceMock).should().getTags(eq(STORE_REF_WORKSPACE_SPACESSTORE), any(PagingRequest.class), isNull(), eq(Set.of("expectedname*")));
then(taggingServiceMock).should().getTags(eq(STORE_REF_WORKSPACE_SPACESSTORE), any(), any(), isNull(), eq(Set.of("expectedname*")));
then(taggingServiceMock).shouldHaveNoMoreInteractions();
assertThat(actualTags).isNotNull();
}
@@ -197,6 +361,7 @@ public class TagsImplTest
{
given(parametersMock.getPaging()).willReturn(pagingMock);
given(parametersMock.getQuery()).willReturn(queryExtractor.getWhereClause("(tag=expectedName AND tag IN (expectedName1, expectedName2))"));
given(parametersMock.getSorting()).willReturn(new ArrayList<>());
//when
final Throwable actualException = catchThrowable(() -> objectUnderTest.getTags(STORE_REF_WORKSPACE_SPACESSTORE, parametersMock));
@@ -210,6 +375,7 @@ public class TagsImplTest
{
given(parametersMock.getPaging()).willReturn(pagingMock);
given(parametersMock.getQuery()).willReturn(queryExtractor.getWhereClause("(tag BETWEEN ('expectedName', 'expectedName2'))"));
given(parametersMock.getSorting()).willReturn(new ArrayList<>());
//when
final Throwable actualException = catchThrowable(() -> objectUnderTest.getTags(STORE_REF_WORKSPACE_SPACESSTORE, parametersMock));
@@ -223,6 +389,7 @@ public class TagsImplTest
{
given(parametersMock.getPaging()).willReturn(pagingMock);
given(parametersMock.getQuery()).willReturn(queryExtractor.getWhereClause("(NOT tag=expectedName)"));
given(parametersMock.getSorting()).willReturn(new ArrayList<>());
//when
final Throwable actualException = catchThrowable(() -> objectUnderTest.getTags(STORE_REF_WORKSPACE_SPACESSTORE, parametersMock));
@@ -235,7 +402,6 @@ public class TagsImplTest
public void testDeleteTagById()
{
//when
given(primaryParentMock.getParentRef()).willReturn(TAG_PARENT_NODE_REF);
objectUnderTest.deleteTagById(STORE_REF_WORKSPACE_SPACESSTORE, TAG_ID);
then(authorityServiceMock).should().hasAdminAuthority();
@@ -394,8 +560,8 @@ public class TagsImplTest
final List<Tag> actualCreatedTags = objectUnderTest.createTags(tagsToCreate, parametersMock);
final List<Tag> expectedTags = createTagsWithNodeRefs(tagNames).stream()
.peek(tag -> tag.setCount(0))
.collect(Collectors.toList());
.peek(tag -> tag.setCount(0L))
.collect(toList());
assertThat(actualCreatedTags)
.isNotNull()
.isEqualTo(expectedTags);
@@ -404,19 +570,131 @@ public class TagsImplTest
@Test(expected = EntityNotFoundException.class)
public void testGetTagByIdNotFoundValidation()
{
given(primaryParentMock.getParentRef()).willReturn(TAG_NODE_REF);
objectUnderTest.getTag(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,TAG_ID);
given(nodesMock.validateNode(STORE_REF_WORKSPACE_SPACESSTORE, TAG_ID)).willThrow(EntityNotFoundException.class);
objectUnderTest.getTag(STORE_REF_WORKSPACE_SPACESSTORE, TAG_ID, null);
then(nodeServiceMock).shouldHaveNoInteractions();
then(nodesMock).should().validateNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, TAG_ID);
then(nodesMock).should().validateNode(STORE_REF_WORKSPACE_SPACESSTORE, TAG_ID);
then(nodesMock).shouldHaveNoMoreInteractions();
then(taggingServiceMock).shouldHaveNoInteractions();
}
@Test
public void testAddTags()
{
NodeRef tagNodeA = new NodeRef("tag://A/");
NodeRef tagNodeB = new NodeRef("tag://B/");
given(nodesMock.validateOrLookupNode(CONTENT_NODE_ID)).willReturn(CONTENT_NODE_REF);
given(typeConstraintMock.matches(CONTENT_NODE_REF)).willReturn(true);
List<Pair<String, NodeRef>> pairs = List.of(new Pair<>("taga", new NodeRef("tag://A/")), new Pair<>("tagb", new NodeRef("tag://B/")));
List<String> tagNames = pairs.stream().map(Pair::getFirst).collect(toList());
List<Tag> tags = tagNames.stream().map(name -> Tag.builder().tag(name).create()).collect(toList());
given(taggingServiceMock.addTags(CONTENT_NODE_REF, tagNames)).willReturn(pairs);
given(taggingServiceMock.findTaggedNodesAndCountByTagName(STORE_REF_WORKSPACE_SPACESSTORE)).willReturn(List.of(new Pair<>("taga", 4)));
given(parametersMock.getInclude()).willReturn(List.of("count"));
List<Tag> actual = objectUnderTest.addTags(CONTENT_NODE_ID, tags, parametersMock);
final List<Tag> expected = List.of(Tag.builder().tag("taga").nodeRef(tagNodeA).count(5L).create(),
Tag.builder().tag("tagb").nodeRef(tagNodeB).count(1L).create());
assertEquals("Unexpected tags returned.", expected, actual);
}
@Test(expected = InvalidArgumentException.class)
public void testAddTagsToInvalidNode()
{
given(nodesMock.validateOrLookupNode(CONTENT_NODE_ID)).willThrow(new InvalidArgumentException());
List<Tag> tags = List.of(Tag.builder().tag("tag1").create());
objectUnderTest.addTags(CONTENT_NODE_ID, tags, parametersMock);
}
@Test(expected = UnsupportedResourceOperationException.class)
public void testAddTagsToWrongTypeOfNode()
{
given(nodesMock.validateOrLookupNode(CONTENT_NODE_ID)).willReturn(CONTENT_NODE_REF);
given(typeConstraintMock.matches(CONTENT_NODE_REF)).willReturn(false);
List<Tag> tags = List.of(Tag.builder().tag("tag1").create());
objectUnderTest.addTags(CONTENT_NODE_ID, tags, parametersMock);
}
@Test
public void testGetTagsForNode()
{
given(nodesMock.validateOrLookupNode(CONTENT_NODE_ID)).willReturn(CONTENT_NODE_REF);
given(parametersMock.getPaging()).willReturn(pagingMock);
List<Pair<NodeRef, String>> pairs = List.of(new Pair<>(new NodeRef("tag://A/"), "taga"), new Pair<>(new NodeRef("tag://B/"), "tagb"));
given(taggingServiceMock.getTags(eq(CONTENT_NODE_REF), any(PagingRequest.class))).willReturn(pagingResultsMock);
given(pagingResultsMock.getTotalResultCount()).willReturn(new Pair<>(null, null));
given(pagingResultsMock.getPage()).willReturn(pairs);
CollectionWithPagingInfo<Tag> actual = objectUnderTest.getTags(CONTENT_NODE_ID, parametersMock);
List<Tag> tags = pairs.stream().map(pair -> Tag.builder().tag(pair.getSecond()).nodeRef(pair.getFirst()).create()).collect(toList());
assertEquals(actual.getCollection(), tags);
}
@Test (expected = InvalidArgumentException.class)
public void testGetTagsFromInvalidNode()
{
given(nodesMock.validateOrLookupNode(CONTENT_NODE_ID)).willThrow(new InvalidArgumentException());
objectUnderTest.getTags(CONTENT_NODE_ID, parametersMock);
}
@Test
public void testChangeTag()
{
Tag suppliedTag = Tag.builder().tag("new-name").create();
given(taggingServiceMock.changeTag(STORE_REF_WORKSPACE_SPACESSTORE, TAG_NAME, "new-name")).willReturn(TAG_NODE_REF);
Tag tag = objectUnderTest.changeTag(STORE_REF_WORKSPACE_SPACESSTORE, TAG_ID, suppliedTag, parametersMock);
Tag expected = Tag.builder().nodeRef(TAG_NODE_REF).tag("new-name").create();
assertEquals("Unexpected return value", expected, tag);
}
@Test
public void testChangeTagAndGetCount()
{
Tag suppliedTag = Tag.builder().tag("new-name").create();
given(taggingServiceMock.changeTag(STORE_REF_WORKSPACE_SPACESSTORE, TAG_NAME, "new-name")).willReturn(TAG_NODE_REF);
given(parametersMock.getInclude()).willReturn(List.of(PARAM_INCLUDE_COUNT));
given(taggingServiceMock.findCountByTagName(STORE_REF_WORKSPACE_SPACESSTORE, TAG_NAME)).willReturn(3L);
Tag tag = objectUnderTest.changeTag(STORE_REF_WORKSPACE_SPACESSTORE, TAG_ID, suppliedTag, parametersMock);
Tag expected = Tag.builder().nodeRef(TAG_NODE_REF).tag("new-name").count(3L).create();
assertEquals("Unexpected return value", expected, tag);
}
@Test
public void testGetTag()
{
Tag tag = objectUnderTest.getTag(STORE_REF_WORKSPACE_SPACESSTORE, TAG_ID, parametersMock);
Tag expected = Tag.builder().nodeRef(TAG_NODE_REF).tag(TAG_NAME).create();
assertEquals("Unexpected tag returned", expected, tag);
}
@Test
public void testGetTagWithCount()
{
given(parametersMock.getInclude()).willReturn(List.of(PARAM_INCLUDE_COUNT));
given(taggingServiceMock.findCountByTagName(STORE_REF_WORKSPACE_SPACESSTORE, TAG_NAME)).willReturn(0L);
Tag tag = objectUnderTest.getTag(STORE_REF_WORKSPACE_SPACESSTORE, TAG_ID, parametersMock);
Tag expected = Tag.builder().nodeRef(TAG_NODE_REF).tag(TAG_NAME).count(0L).create();
assertEquals("Unexpected tag returned", expected, tag);
}
private static List<Pair<String, NodeRef>> createTagAndNodeRefPairs(final List<String> tagNames)
{
return tagNames.stream()
.map(tagName -> createPair(tagName, new NodeRef(STORE_REF_WORKSPACE_SPACESSTORE, TAG_ID.concat("-").concat(tagName))))
.collect(Collectors.toList());
.collect(toList());
}
private static Pair<String, NodeRef> createPair(final String tagName, final NodeRef nodeRef)
@@ -426,12 +704,12 @@ public class TagsImplTest
private static List<Tag> createTags(final List<String> tagNames)
{
return tagNames.stream().map(TagsImplTest::createTag).collect(Collectors.toList());
return tagNames.stream().map(TagsImplTest::createTag).collect(toList());
}
private static List<Tag> createTagsWithNodeRefs(final List<String> tagNames)
{
return tagNames.stream().map(TagsImplTest::createTagWithNodeRef).collect(Collectors.toList());
return tagNames.stream().map(TagsImplTest::createTagWithNodeRef).collect(toList());
}
private static Tag createTag(final String tagName)

View File

@@ -134,7 +134,7 @@ public class RestRuleModelMapperTest
// when
final org.alfresco.service.cmr.rule.Rule actualRuleModel = objectUnderTest.toServiceModel(rule);
then(nodesMock).should().validateOrLookupNode(RULE_ID, null);
then(nodesMock).should().validateOrLookupNode(RULE_ID);
then(nodesMock).shouldHaveNoMoreInteractions();
then(actionMapperMock).should().toServiceModel(List.of(action));
then(actionMapperMock).shouldHaveNoMoreInteractions();

View File

@@ -275,7 +275,7 @@ public class RestRuleSimpleConditionModelMapperTest
{
final SimpleCondition simpleCondition = createSimpleCondition(PARAM_CATEGORY);
final NodeRef defaultNodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, PARAMETER_DEFAULT);
given(nodesMock.validateOrLookupNode(PARAMETER_DEFAULT, null)).willReturn(defaultNodeRef);
given(nodesMock.validateOrLookupNode(PARAMETER_DEFAULT)).willReturn(defaultNodeRef);
// when
final ActionCondition actualActionCondition = objectUnderTest.toServiceModel(simpleCondition);

View File

@@ -44,7 +44,6 @@ import java.io.Serializable;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.alfresco.repo.action.executer.AddFeaturesActionExecuter;
import org.alfresco.repo.action.executer.CheckInActionExecuter;
import org.alfresco.repo.action.executer.CheckOutActionExecuter;
@@ -129,8 +128,8 @@ public class ActionParameterConverterTest
@Before
public void setUp()
{
given(nodes.validateOrLookupNode(DUMMY_FOLDER_NODE_ID, null)).willReturn(DUMMY_FOLDER_NODE);
given(nodes.validateOrLookupNode(DUMMY_SCRIPT_NODE_ID, null)).willReturn(DUMMY_SCRIPT_NODE);
given(nodes.validateOrLookupNode(DUMMY_FOLDER_NODE_ID)).willReturn(DUMMY_FOLDER_NODE);
given(nodes.validateOrLookupNode(DUMMY_SCRIPT_NODE_ID)).willReturn(DUMMY_SCRIPT_NODE);
given(permissionService.hasReadPermission(DUMMY_FOLDER_NODE)).willReturn(ALLOWED);
given(permissionService.hasReadPermission(DUMMY_SCRIPT_NODE)).willReturn(ALLOWED);
}
@@ -598,7 +597,7 @@ public class ActionParameterConverterTest
String permissionDeniedNodeId = "permission://denied/node";
final Map<String, Serializable> params = Map.of(PARAM_DESTINATION_FOLDER, permissionDeniedNodeId);
NodeRef permissionDeniedNode = new NodeRef(permissionDeniedNodeId);
given(nodes.validateOrLookupNode(permissionDeniedNodeId, null)).willReturn(permissionDeniedNode);
given(nodes.validateOrLookupNode(permissionDeniedNodeId)).willReturn(permissionDeniedNode);
given(permissionService.hasReadPermission(permissionDeniedNode)).willReturn(DENIED);
given(actionService.getActionDefinition(name)).willReturn(actionDefinition);

View File

@@ -101,7 +101,7 @@ public class NodeValidatorTest
public void setUp() throws Exception
{
MockitoAnnotations.openMocks(this);
given(nodesMock.validateOrLookupNode(eq(FOLDER_NODE_ID), any())).willReturn(folderNodeRef);
given(nodesMock.validateOrLookupNode(FOLDER_NODE_ID)).willReturn(folderNodeRef);
given(nodesMock.validateNode(RULE_SET_ID)).willReturn(ruleSetNodeRef);
given(nodesMock.validateNode(RULE_ID)).willReturn(ruleNodeRef);
given(nodesMock.nodeMatches(any(), any(), any())).willReturn(true);
@@ -115,7 +115,7 @@ public class NodeValidatorTest
// when
final NodeRef nodeRef = nodeValidator.validateFolderNode(FOLDER_NODE_ID, false);
then(nodesMock).should().validateOrLookupNode(FOLDER_NODE_ID, null);
then(nodesMock).should().validateOrLookupNode(FOLDER_NODE_ID);
then(nodesMock).should().nodeMatches(folderNodeRef, Set.of(TYPE_FOLDER), null);
then(nodesMock).shouldHaveNoMoreInteractions();
then(permissionServiceMock).should().hasReadPermission(folderNodeRef);
@@ -128,13 +128,13 @@ public class NodeValidatorTest
@Test
public void testValidateFolderNode_notExistingFolder()
{
given(nodesMock.validateOrLookupNode(any(), any())).willThrow(new EntityNotFoundException(FOLDER_NODE_ID));
given(nodesMock.validateOrLookupNode(FOLDER_NODE_ID)).willThrow(new EntityNotFoundException(FOLDER_NODE_ID));
//when
assertThatExceptionOfType(EntityNotFoundException.class).isThrownBy(
() -> nodeValidator.validateFolderNode(FOLDER_NODE_ID, false));
then(nodesMock).should().validateOrLookupNode(FOLDER_NODE_ID, null);
then(nodesMock).should().validateOrLookupNode(FOLDER_NODE_ID);
then(nodesMock).shouldHaveNoMoreInteractions();
then(ruleServiceMock).shouldHaveNoInteractions();
}
@@ -148,7 +148,7 @@ public class NodeValidatorTest
assertThatExceptionOfType(InvalidArgumentException.class).isThrownBy(
() -> nodeValidator.validateFolderNode(FOLDER_NODE_ID, false));
then(nodesMock).should().validateOrLookupNode(FOLDER_NODE_ID, null);
then(nodesMock).should().validateOrLookupNode(FOLDER_NODE_ID);
then(nodesMock).should().nodeMatches(folderNodeRef, Set.of(TYPE_FOLDER), null);
then(nodesMock).shouldHaveNoMoreInteractions();
then(ruleServiceMock).shouldHaveNoInteractions();
@@ -431,11 +431,12 @@ public class NodeValidatorTest
then(ruleServiceMock).shouldHaveNoMoreInteractions();
}
private void resetNodesMock() {
private void resetNodesMock()
{
reset(nodesMock);
given(nodesMock.validateOrLookupNode(eq(FOLDER_NODE_ID), any())).willReturn(folderNodeRef);
given(nodesMock.validateOrLookupNode(FOLDER_NODE_ID)).willReturn(folderNodeRef);
given(nodesMock.validateNode(RULE_SET_ID)).willReturn(ruleSetNodeRef);
given(nodesMock.validateNode(RULE_ID)).willReturn(ruleNodeRef);
given(nodesMock.nodeMatches(ruleSetNodeRef, Set.of(ContentModel.TYPE_SYSTEM_FOLDER), null)).willReturn(true);
}
}
}

View File

@@ -37,10 +37,8 @@ import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.notNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.notNull;
import static org.mockito.Mockito.when;
import java.io.Serializable;
@@ -186,7 +184,7 @@ public class ResultMapperTests
when(sr.getVersionService()).thenReturn(versionService);
when(sr.getNodeService()).thenReturn(nodeService);
when(nodes.validateOrLookupNode(nullable(String.class), nullable(String.class))).thenAnswer(invocation ->
when(nodes.validateOrLookupNode(nullable(String.class))).thenAnswer(invocation ->
{
Object[] args = invocation.getArguments();
String aNode = (String)args[0];

View File

@@ -529,7 +529,7 @@ public class AuthenticationsTest extends AbstractSingleNetworkSiteTest
InterceptingIdentityRemoteUserMapper interceptingRemoteUserMapper = new InterceptingIdentityRemoteUserMapper();
interceptingRemoteUserMapper.setActive(true);
interceptingRemoteUserMapper.setPersonService(personServiceLocal);
interceptingRemoteUserMapper.setIdentityServiceDeployment(null);
interceptingRemoteUserMapper.setIdentityServiceFacade(null);
interceptingRemoteUserMapper.setUserIdToReturn(user2);
remoteUserMapper = interceptingRemoteUserMapper;
}

View File

@@ -734,195 +734,6 @@ public class SharedLinkApiTest extends AbstractBaseApiTest
}
}
/**
* Tests shared links to file (content) in a multi-tenant system.
*
* <p>POST:</p>
* {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/shared-links}
*
* <p>DELETE:</p>
* {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/shared-links/<sharedId>}
*
* <p>GET:</p>
* The following do not require authentication
* {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/shared-links/<sharedId>}
* {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/shared-links/<sharedId>/content}
* {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/shared-links/<sharedId>/renditions}
* {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/shared-links/<sharedId>/renditions/<renditionId>}
* {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/shared-links/<sharedId>/renditions/<renditionId>/content}
*
*/
// TODO now covered by testSharedLinkCreateGetDelete ? (since base class now uses tenant context by default)
@Test
public void testSharedLinkCreateGetDelete_MultiTenant() throws Exception
{
// As user1
setRequestContext(user1);
String docLibNodeId = getSiteContainerNodeId(tSiteId, "documentLibrary");
String folderName = "folder" + System.currentTimeMillis() + "_1";
String folderId = createFolder(docLibNodeId, folderName, null).getId();
// create doc d1 - pdf
String fileName1 = "quick" + RUNID + "_1.pdf";
File file1 = getResourceFile("quick.pdf");
byte[] file1_originalBytes = Files.readAllBytes(Paths.get(file1.getAbsolutePath()));
String file1_MimeType = MimetypeMap.MIMETYPE_PDF;
MultiPartBuilder.MultiPartRequest reqBody = MultiPartBuilder.create()
.setFileData(new MultiPartBuilder.FileData(fileName1, file1, file1_MimeType))
.build();
HttpResponse response = post(getNodeChildrenUrl(folderId), reqBody.getBody(), null, reqBody.getContentType(), 201);
Document doc1 = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
String d1Id = doc1.getId();
assertNotNull(d1Id);
// create shared link to document 1
Map<String, String> body = new HashMap<>();
body.put("nodeId", d1Id);
response = post(URL_SHARED_LINKS, toJsonAsStringNonNull(body), 201);
QuickShareLink resp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), QuickShareLink.class);
String shared1Id = resp.getId();
assertNotNull(shared1Id);
assertEquals(d1Id, resp.getNodeId());
assertEquals(fileName1, resp.getName());
assertEquals(file1_MimeType, resp.getContent().getMimeType());
assertEquals(user1, resp.getSharedByUser().getId());
// allowable operations not included - no params
response = getSingle(QuickShareLinkEntityResource.class, shared1Id, null, 200);
resp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), QuickShareLink.class);
assertNull(resp.getAllowableOperations());
setRequestContext(null);
// unauth access to get shared link info
Map<String, String> params = Collections.singletonMap("include", "allowableOperations"); // note: this will be ignore for unauth access
response = getSingle(QuickShareLinkEntityResource.class, shared1Id, params, 200);
resp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), QuickShareLink.class);
assertEquals(shared1Id, resp.getId());
assertEquals(fileName1, resp.getName());
assertEquals(d1Id, resp.getNodeId());
assertNull(resp.getAllowableOperations()); // include is ignored
assertNull(resp.getAllowableOperationsOnTarget()); // include is ignored
// unauth access to file 1 content (via shared link)
response = getSingle(QuickShareLinkEntityResource.class, shared1Id + "/content", null, 200);
assertArrayEquals(file1_originalBytes, response.getResponseAsBytes());
Map<String, String> responseHeaders = response.getHeaders();
assertNotNull(responseHeaders);
assertEquals(file1_MimeType + ";charset=utf-8", responseHeaders.get("Content-Type"));
assertNotNull(responseHeaders.get("Expires"));
assertEquals("attachment; filename=\"" + fileName1 + "\"; filename*=UTF-8''" + fileName1 + "", responseHeaders.get("Content-Disposition"));
String lastModifiedHeader = responseHeaders.get(LAST_MODIFIED_HEADER);
assertNotNull(lastModifiedHeader);
// Test 304 response
Map<String, String> headers = Collections.singletonMap(IF_MODIFIED_SINCE_HEADER, lastModifiedHeader);
getSingle(URL_SHARED_LINKS, shared1Id + "/content", null, headers, 304);
// unauth access to file 1 content (via shared link) - without Content-Disposition header (attachment=false)
params = new HashMap<>();
params.put("attachment", "false");
response = getSingle(QuickShareLinkEntityResource.class, shared1Id + "/content", params, 200);
assertArrayEquals(file1_originalBytes, response.getResponseAsBytes());
responseHeaders = response.getHeaders();
assertNotNull(responseHeaders);
assertEquals(file1_MimeType + ";charset=utf-8", responseHeaders.get("Content-Type"));
assertNotNull(responseHeaders.get(LAST_MODIFIED_HEADER));
assertNotNull(responseHeaders.get("Expires"));
assertNull(responseHeaders.get("Content-Disposition"));
// -ve shared link rendition tests
{
// -ve test - try to get non-existent rendition content
getSingle(QuickShareLinkEntityResource.class, shared1Id + "/renditions/doclib/content", null, 404);
// -ve test - try to get unregistered rendition content
getSingle(QuickShareLinkEntityResource.class, shared1Id + "/renditions/dummy/content", null, 404);
}
// unauth access to get rendition info for a shared link (available => CREATED rendition only)
// -ve shared link rendition tests
{
// -ve test - try to get not created rendition for the given shared link
getSingle(QuickShareLinkEntityResource.class, shared1Id + "/renditions/doclib", null, 404);
// -ve test - try to get unregistered rendition
getSingle(QuickShareLinkEntityResource.class, shared1Id + "/renditions/dummy", null, 404);
}
// unauth access to get shared link renditions info (available => CREATED renditions only)
response = getAll(URL_SHARED_LINKS + "/" + shared1Id + "/renditions", null, 200);
List<Rendition> renditions = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), Rendition.class);
assertEquals(0, renditions.size());
// create rendition of pdf doc - note: for some reason create rendition of txt doc fail on build m/c (TBC) ?
setRequestContext(user1);
Rendition rendition = createAndGetRendition(d1Id, "doclib");
assertNotNull(rendition);
assertEquals(Rendition.RenditionStatus.CREATED, rendition.getStatus());
setRequestContext(null);
// unauth access to get shared link renditions info (available => CREATED renditions only)
response = getAll(URL_SHARED_LINKS + "/" + shared1Id + "/renditions", null, 200);
renditions = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), Rendition.class);
assertEquals(1, renditions.size());
assertEquals(Rendition.RenditionStatus.CREATED, renditions.get(0).getStatus());
assertEquals("doclib", renditions.get(0).getId());
// unauth access to get rendition info for a shared link (available => CREATED rendition only)
{
// get a created rendition for the given shared link
getSingle(QuickShareLinkEntityResource.class, shared1Id + "/renditions/doclib", null, 200);
}
// unauth access to get shared link file rendition content
response = getSingle(QuickShareLinkEntityResource.class, shared1Id + "/renditions/doclib/content", null, 200);
assertTrue(response.getResponseAsBytes().length > 0);
responseHeaders = response.getHeaders();
assertNotNull(responseHeaders);
assertEquals(MimetypeMap.MIMETYPE_IMAGE_PNG + ";charset=utf-8", responseHeaders.get("Content-Type"));
assertNotNull(responseHeaders.get(LAST_MODIFIED_HEADER));
assertNotNull(responseHeaders.get("Expires"));
String docName = "doclib";
assertEquals("attachment; filename=\"" + docName + "\"; filename*=UTF-8''" + docName + "", responseHeaders.get("Content-Disposition"));
// unauth access to get shared link file rendition content - without Content-Disposition header (attachment=false)
params = new HashMap<>();
params.put("attachment", "false");
response = getSingle(QuickShareLinkEntityResource.class, shared1Id + "/renditions/doclib/content", params, 200);
assertTrue(response.getResponseAsBytes().length > 0);
responseHeaders = response.getHeaders();
assertNotNull(responseHeaders);
assertEquals(MimetypeMap.MIMETYPE_IMAGE_PNG + ";charset=utf-8", responseHeaders.get("Content-Type"));
assertNotNull(responseHeaders.get("Expires"));
assertNull(responseHeaders.get("Content-Disposition"));
lastModifiedHeader = responseHeaders.get(LAST_MODIFIED_HEADER);
assertNotNull(lastModifiedHeader);
// Test 304 response
headers = Collections.singletonMap(IF_MODIFIED_SINCE_HEADER, lastModifiedHeader);
getSingle(URL_SHARED_LINKS, shared1Id + "/renditions/doclib/content", null, headers, 304);
// -ve test - userTwoN1 cannot delete shared link
setRequestContext(user2);
deleteSharedLink(shared1Id, 403);
// -ve test - unauthenticated
setRequestContext(null);
deleteSharedLink(shared1Id, 401);
// delete shared link
setRequestContext(user1);
deleteSharedLink(shared1Id);
}
/**
* Tests shared links to file with expiry date.
* <p>POST:</p>

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-community-repo</artifactId>
<version>20.112</version>
<version>23.1.0.111</version>
</parent>
<dependencies>
@@ -126,7 +126,7 @@
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>72.1</version>
<version>73.1</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
@@ -375,7 +375,7 @@
<dependency>
<groupId>com.fasterxml.woodstox</groupId>
<artifactId>woodstox-core</artifactId>
<version>6.4.0</version>
<version>6.5.1</version>
</dependency>
<!-- GData -->
@@ -397,6 +397,14 @@
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
@@ -557,69 +565,6 @@
</exclusions>
</dependency>
<!-- Keycloak dependencies -->
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-core</artifactId>
<version>${dependency.keycloak.version}</version>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-common</artifactId>
<version>${dependency.keycloak.version}</version>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-adapter-core</artifactId>
<version>${dependency.keycloak.version}</version>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-adapter-spi</artifactId>
<version>${dependency.keycloak.version}</version>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-servlet-adapter-spi</artifactId>
<version>${dependency.keycloak.version}</version>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- required by keycloak -->
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>${dependency.jboss.logging.version}</version>
</dependency>
<!-- Events dependencies -->
<dependency>
<groupId>org.alfresco</groupId>
@@ -802,7 +747,7 @@
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.9.1</version>
<version>1.9.19</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
@@ -864,6 +809,10 @@
<artifactId>reflections</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
</dependencies>
<build>

View File

@@ -1,28 +1,28 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2023 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.email.server;
import java.util.HashSet;
@@ -37,10 +37,7 @@ import org.alfresco.service.cmr.email.EmailMessageException;
import org.alfresco.service.cmr.email.EmailService;
import org.springframework.extensions.surf.util.AbstractLifecycleBean;
import org.alfresco.util.PropertyCheck;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Base implementation of an email server.
@@ -62,13 +59,13 @@ public abstract class EmailServer extends AbstractLifecycleBean
private boolean requireTLS = false;
private boolean authenticate = false;
private EmailService emailService;
private AuthenticationComponent authenticationComponent;
private EmailService emailService;
private AuthenticationComponent authenticationComponent;
private String unknownUser;
protected EmailServer()
{
this.enabled = false;
protected EmailServer()
{
this.enabled = false;
this.port = 25;
this.domain = null;
this.maxConnections = 3;
@@ -301,60 +298,6 @@ public abstract class EmailServer extends AbstractLifecycleBean
}
}
private static volatile Boolean stop = false;
public static void main(String[] args)
{
if (args.length == 0)
{
usage();
return;
}
try (AbstractApplicationContext context = new ClassPathXmlApplicationContext(args))
{
if (!context.containsBean("emailServer"))
{
usage();
return;
}
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run()
{
stop = true;
synchronized (stop)
{
stop.notifyAll();
}
}
});
System.out.println("Use Ctrl-C to shutdown EmailServer");
while (!stop)
{
synchronized (stop)
{
stop.wait();
}
}
}
catch (BeansException e)
{
System.err.println("Error creating context: " + e);
usage();
}
catch (InterruptedException e)
{
}
}
private static void usage()
{
System.err.println("Use: EmailServer configLocation1, configLocation2, ...");
System.err.println("\t configLocation - spring xml configs with EmailServer related beans (emailServer, emailServerConfiguration, emailService)");
}
/**
* authenticate with a user/password
* @param userName

View File

@@ -1,101 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.email.server;
import org.alfresco.email.server.impl.subetha.SubethaEmailMessage;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.service.cmr.email.EmailDelivery;
import org.alfresco.service.cmr.email.EmailMessage;
import org.alfresco.service.cmr.email.EmailService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.springframework.extensions.surf.util.AbstractLifecycleBean;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.remoting.rmi.RmiClientInterceptor;
/**
* @author Michael Shavnev
* @since 2.2
*/
public class EmailServiceRemotable extends AbstractLifecycleBean implements EmailService
{
private String rmiRegistryHost;
private int rmiRegistryPort;
private EmailService emailServiceProxy;
public void setRmiRegistryHost(String rmiRegistryHost)
{
this.rmiRegistryHost = rmiRegistryHost;
}
public void setRmiRegistryPort(int rmiRegistryPort)
{
this.rmiRegistryPort = rmiRegistryPort;
}
public void importMessage(EmailDelivery delivery, EmailMessage message)
{
if (message instanceof SubethaEmailMessage)
{
((SubethaEmailMessage) message).setRmiRegistry(rmiRegistryHost, rmiRegistryPort);
}
emailServiceProxy.importMessage(delivery, message);
}
public void importMessage(EmailDelivery delivery, NodeRef nodeRef, EmailMessage message)
{
if (message instanceof SubethaEmailMessage)
{
((SubethaEmailMessage) message).setRmiRegistry(rmiRegistryHost, rmiRegistryPort);
}
emailServiceProxy.importMessage(delivery, nodeRef, message);
}
@Override
protected void onBootstrap(ApplicationEvent event)
{
if (rmiRegistryHost == null)
{
throw new AlfrescoRuntimeException("Property 'rmiRegistryHost' not set");
}
if (rmiRegistryPort == 0)
{
throw new AlfrescoRuntimeException("Property 'rmiRegistryPort' not set");
}
RmiClientInterceptor rmiClientInterceptor = new RmiClientInterceptor();
rmiClientInterceptor.setRefreshStubOnConnectFailure(true);
rmiClientInterceptor.setServiceUrl("rmi://" + rmiRegistryHost + ":" + rmiRegistryPort + "/emailService");
emailServiceProxy = (EmailService) ProxyFactory.getProxy(EmailService.class, rmiClientInterceptor);
}
@Override
protected void onShutdown(ApplicationEvent event)
{
}
}

View File

@@ -1,35 +1,34 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2023 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.email.server.impl.subetha;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
@@ -417,29 +416,12 @@ public class SubethaEmailMessage implements EmailMessage
}
return fileName;
}
public void setRmiRegistry(String rmiRegistryHost, int rmiRegistryPort)
{
if (body instanceof SubethaEmailMessagePart)
{
((SubethaEmailMessagePart) body).setRmiRegistry(rmiRegistryHost, rmiRegistryPort);
}
for (EmailMessagePart attachment : attachments)
{
if (attachment instanceof SubethaEmailMessagePart)
{
((SubethaEmailMessagePart) attachment).setRmiRegistry(rmiRegistryHost, rmiRegistryPort);
}
}
}
public List<String> getCC()
{
return cc;
}
public String getFrom()
{
return from;

View File

@@ -1,34 +1,31 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2023 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.email.server.impl.subetha;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -39,7 +36,6 @@ import javax.mail.Part;
import org.alfresco.service.cmr.email.EmailMessageException;
import org.alfresco.service.cmr.email.EmailMessagePart;
import org.springframework.extensions.surf.util.ParameterCheck;
import org.alfresco.util.remote.RemotableInputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -64,9 +60,6 @@ public class SubethaEmailMessagePart implements EmailMessagePart
private String contentType;
private InputStream contentInputStream;
private String rmiRegistryHost;
private int rmiRegistryPort;
protected SubethaEmailMessagePart()
{
super();
@@ -145,20 +138,4 @@ public class SubethaEmailMessagePart implements EmailMessagePart
}
public void setRmiRegistry(String rmiRegistryHost, int rmiRegistryPort)
{
this.rmiRegistryHost = rmiRegistryHost;
this.rmiRegistryPort = rmiRegistryPort;
}
private void writeObject(ObjectOutputStream out) throws IOException
{
contentInputStream = new RemotableInputStream(rmiRegistryHost, rmiRegistryPort, contentInputStream);
out.defaultWriteObject();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
in.defaultReadObject();
}
}

View File

@@ -25,6 +25,7 @@
*/
package org.alfresco.repo.content.transform;
import org.alfresco.httpclient.HttpClientConfig;
import org.alfresco.repo.content.metadata.AsynchronousExtractor;
import org.alfresco.repo.rendition2.RenditionDefinition2;
import org.alfresco.service.cmr.repository.ContentReader;
@@ -60,11 +61,12 @@ public class LocalTransformImpl extends AbstractLocalTransform
boolean retryTransformOnDifferentMimeType,
Set<TransformOption> transformsTransformOptions,
LocalTransformServiceRegistry localTransformServiceRegistry, String baseUrl,
HttpClientConfig httpClientConfig,
int startupRetryPeriodSeconds)
{
super(name, transformerDebug, mimetypeService, strictMimeTypeCheck, strictMimetypeExceptions,
retryTransformOnDifferentMimeType, transformsTransformOptions, localTransformServiceRegistry);
remoteTransformerClient = new RemoteTransformerClient(name, baseUrl);
remoteTransformerClient = new RemoteTransformerClient(name, baseUrl, httpClientConfig);
remoteTransformerClient.setStartupRetryPeriodSeconds(startupRetryPeriodSeconds);
checkAvailability();

View File

@@ -2,7 +2,7 @@
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2019 - 2022 Alfresco Software Limited
* Copyright (C) 2019 - 2023 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
@@ -35,6 +35,8 @@ import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.alfresco.httpclient.HttpClient4Factory;
import org.alfresco.httpclient.HttpClientConfig;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.transform.config.CoreFunction;
import org.alfresco.transform.config.TransformOptionGroup;
@@ -77,6 +79,17 @@ public class LocalTransformServiceRegistry extends TransformServiceRegistryImpl
private boolean strictMimeTypeCheck;
private Map<String, Set<String>> strictMimetypeExceptions;
private boolean retryTransformOnDifferentMimeType;
private HttpClientConfig httpClientConfig;
public HttpClientConfig getHttpClientConfig()
{
return httpClientConfig;
}
public void setHttpClientConfig(HttpClientConfig httpClientConfig)
{
this.httpClientConfig = httpClientConfig;
}
public void setPipelineConfigDir(String pipelineConfigDir)
{
@@ -134,7 +147,7 @@ public class LocalTransformServiceRegistry extends TransformServiceRegistryImpl
@Override
public boolean readConfig() throws IOException
{
CombinedConfig combinedConfig = new CombinedConfig(getLog(), this);
CombinedConfig combinedConfig = new CombinedConfig(getLog(), this, httpClientConfig);
List<String> urls = getTEngineUrlsSortedByName();
boolean successReadingConfig = combinedConfig.addRemoteConfig(urls, "T-Engine");
successReadingConfig &= combinedConfig.addLocalConfig("alfresco/transforms");
@@ -188,7 +201,8 @@ public class LocalTransformServiceRegistry extends TransformServiceRegistryImpl
int startupRetryPeriodSeconds = getStartupRetryPeriodSeconds(name);
localTransform = new LocalTransformImpl(name, transformerDebug, mimetypeService,
strictMimeTypeCheck, strictMimetypeExceptions, retryTransformOnDifferentMimeType,
transformsTransformOptions, this, baseUrl, startupRetryPeriodSeconds);
transformsTransformOptions, this, baseUrl, httpClientConfig,
startupRetryPeriodSeconds);
}
else if (isPipeline)
{

View File

@@ -30,6 +30,8 @@ import java.io.InputStream;
import java.util.StringJoiner;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.httpclient.HttpClient4Factory;
import org.alfresco.httpclient.HttpClientConfig;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.util.Pair;
@@ -45,7 +47,6 @@ import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
@@ -57,6 +58,8 @@ import org.apache.http.util.EntityUtils;
*/
public class RemoteTransformerClient
{
private final HttpClientConfig httpClientConfig;
private final String name;
private final String baseUrl;
@@ -70,10 +73,11 @@ public class RemoteTransformerClient
// Only changed once on success. This is stored so it can always be returned.
private Pair<Boolean, String> checkResult = new Pair<>(null, null);
public RemoteTransformerClient(String name, String baseUrl)
public RemoteTransformerClient(String name, String baseUrl, HttpClientConfig httpClientConfig)
{
this.name = name;
this.baseUrl = baseUrl == null || baseUrl.trim().isEmpty() ? null : baseUrl.trim();
this.httpClientConfig = httpClientConfig;
}
public void setStartupRetryPeriodSeconds(int startupRetryPeriodSeconds)
@@ -129,7 +133,7 @@ public class RemoteTransformerClient
try
{
try (CloseableHttpClient httpclient = HttpClients.createDefault())
try (CloseableHttpClient httpclient = HttpClient4Factory.createHttpClient(httpClientConfig))
{
try (CloseableHttpResponse response = execute(httpclient, httppost))
{
@@ -232,7 +236,7 @@ public class RemoteTransformerClient
try
{
try (CloseableHttpClient httpclient = HttpClients.createDefault())
try (CloseableHttpClient httpclient = HttpClient4Factory.createHttpClient(httpClientConfig))
{
try (CloseableHttpResponse response = execute(httpclient, httpGet))
{

View File

@@ -23,225 +23,225 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.jscript;
import java.util.Collection;
import java.util.List;
import org.alfresco.model.ContentModel;
import org.alfresco.query.PagingRequest;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.CategoryService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.Pair;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
/**
* Support class for finding categories, finding root nodes for categories and creating root categories.
*
* @author Andy Hind
*/
public final class Classification extends BaseScopableProcessorExtension
{
private ServiceRegistry services;
private StoreRef storeRef;
/**
* Set the default store reference
*
* @param storeRef the default store reference
*/
public void setStoreUrl(String storeRef)
{
this.storeRef = new StoreRef(storeRef);
}
/**
* Set the service registry
*
* @param services the service registry
*/
public void setServiceRegistry(ServiceRegistry services)
{
this.services = services;
}
/**
* Find all the category nodes in a given classification.
*
* @param aspect String
* @return Scriptable
*/
public Scriptable getAllCategoryNodes(String aspect)
{
Object[] cats = buildCategoryNodes(services.getCategoryService().getCategories(
storeRef, createQName(aspect), CategoryService.Depth.ANY));
return Context.getCurrentContext().newArray(getScope(), cats);
}
/**
* Get all the aspects that define a classification.
*
* @return String[]
*/
public String[] getAllClassificationAspects()
{
Collection<QName> aspects = services.getCategoryService().getClassificationAspects();
String[] answer = new String[aspects.size()];
int i = 0;
for (QName qname : aspects)
{
answer[i++] = qname.toPrefixString(this.services.getNamespaceService());
}
return answer;
}
/**
* Create a root category in a classification.
*
* @param aspect String
* @param name String
*/
public CategoryNode createRootCategory(String aspect, String name)
{
NodeRef categoryNodeRef = services.getCategoryService().createRootCategory(storeRef, createQName(aspect), name);
CategoryNode categoryNode = new CategoryNode(categoryNodeRef, this.services, getScope());
return categoryNode;
}
/**
* Get the category node from the category node reference.
*
* @param categoryRef category node reference
* @return {@link CategoryNode} category node
*/
public CategoryNode getCategory(String categoryRef)
{
CategoryNode result = null;
NodeRef categoryNodeRef = new NodeRef(categoryRef);
if (services.getNodeService().exists(categoryNodeRef) == true &&
services.getDictionaryService().isSubClass(ContentModel.TYPE_CATEGORY, services.getNodeService().getType(categoryNodeRef)) == true)
{
result = new CategoryNode(categoryNodeRef, this.services, getScope());
}
return result;
}
/**
* Get the root categories in a classification.
*
* @param aspect String
* @return Scriptable
*/
public Scriptable getRootCategories(String aspect)
{
Object[] cats = buildCategoryNodes(services.getCategoryService().getRootCategories(
storeRef, createQName(aspect)));
return Context.getCurrentContext().newArray(getScope(), cats);
}
/**
* Get ordered, filtered and paged root categories in a classification.
*
* @param aspect
* @param filter
* @param maxItems
* @param skipCount (offset)
* @return
*/
public Scriptable getRootCategories(String aspect, String filter, int maxItems, int skipCount)
{
PagingRequest pagingRequest = new PagingRequest(skipCount, maxItems);
List<ChildAssociationRef> rootCategories = services.getCategoryService().getRootCategories(storeRef, createQName(aspect), pagingRequest, true, filter).getPage();
Object[] cats = buildCategoryNodes(rootCategories);
return Context.getCurrentContext().newArray(getScope(), cats);
}
/**
* Get the category usage count.
*
* @param aspect String
* @param maxCount int
* @return Scriptable
*/
public Scriptable getCategoryUsage(String aspect, int maxCount)
{
List<Pair<NodeRef, Integer>> topCats = services.getCategoryService().getTopCategories(storeRef, createQName(aspect), maxCount);
Object[] tags = new Object[topCats.size()];
int i = 0;
for (Pair<NodeRef, Integer> topCat : topCats)
{
tags[i++] = new Tag(new CategoryNode(topCat.getFirst(), this.services, getScope()), topCat.getSecond());
}
return Context.getCurrentContext().newArray(getScope(), tags);
}
/**
* Build category nodes.
*
* @param cars list of associations to category nodes
* @return {@link Object}[] array of category nodes
*/
private Object[] buildCategoryNodes(Collection<ChildAssociationRef> cars)
{
Object[] categoryNodes = new Object[cars.size()];
int i = 0;
for (ChildAssociationRef car : cars)
{
categoryNodes[i++] = new CategoryNode(car.getChildRef(), this.services, getScope());
}
return categoryNodes;
}
/**
* Create QName from string
*
* @param s QName string value
* @return {@link QName} qualified name object
*/
private QName createQName(String s)
{
QName qname;
if (s.indexOf(QName.NAMESPACE_BEGIN) != -1)
{
qname = QName.createQName(s);
}
else
{
qname = QName.createQName(s, this.services.getNamespaceService());
}
return qname;
}
/**
* Tag class returned from getCategoryUsage().
*/
public final class Tag
{
private CategoryNode categoryNode;
private int frequency = 0;
public Tag(CategoryNode categoryNode, int frequency)
{
this.categoryNode = categoryNode;
this.frequency = frequency;
}
public CategoryNode getCategory()
{
return categoryNode;
}
public int getFrequency()
{
return frequency;
}
}
}
package org.alfresco.repo.jscript;
import java.util.Collection;
import java.util.List;
import org.alfresco.model.ContentModel;
import org.alfresco.query.PagingRequest;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.CategoryService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.Pair;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
/**
* Support class for finding categories, finding root nodes for categories and creating root categories.
*
* @author Andy Hind
*/
public final class Classification extends BaseScopableProcessorExtension
{
private ServiceRegistry services;
private StoreRef storeRef;
/**
* Set the default store reference
*
* @param storeRef the default store reference
*/
public void setStoreUrl(String storeRef)
{
this.storeRef = new StoreRef(storeRef);
}
/**
* Set the service registry
*
* @param services the service registry
*/
public void setServiceRegistry(ServiceRegistry services)
{
this.services = services;
}
/**
* Find all the category nodes in a given classification.
*
* @param aspect String
* @return Scriptable
*/
public Scriptable getAllCategoryNodes(String aspect)
{
Object[] cats = buildCategoryNodes(services.getCategoryService().getCategories(
storeRef, createQName(aspect), CategoryService.Depth.ANY));
return Context.getCurrentContext().newArray(getScope(), cats);
}
/**
* Get all the aspects that define a classification.
*
* @return String[]
*/
public String[] getAllClassificationAspects()
{
Collection<QName> aspects = services.getCategoryService().getClassificationAspects();
String[] answer = new String[aspects.size()];
int i = 0;
for (QName qname : aspects)
{
answer[i++] = qname.toPrefixString(this.services.getNamespaceService());
}
return answer;
}
/**
* Create a root category in a classification.
*
* @param aspect String
* @param name String
*/
public CategoryNode createRootCategory(String aspect, String name)
{
NodeRef categoryNodeRef = services.getCategoryService().createRootCategory(storeRef, createQName(aspect), name);
CategoryNode categoryNode = new CategoryNode(categoryNodeRef, this.services, getScope());
return categoryNode;
}
/**
* Get the category node from the category node reference.
*
* @param categoryRef category node reference
* @return {@link CategoryNode} category node
*/
public CategoryNode getCategory(String categoryRef)
{
CategoryNode result = null;
NodeRef categoryNodeRef = new NodeRef(categoryRef);
if (services.getNodeService().exists(categoryNodeRef) == true &&
services.getDictionaryService().isSubClass(ContentModel.TYPE_CATEGORY, services.getNodeService().getType(categoryNodeRef)) == true)
{
result = new CategoryNode(categoryNodeRef, this.services, getScope());
}
return result;
}
/**
* Get the root categories in a classification.
*
* @param aspect String
* @return Scriptable
*/
public Scriptable getRootCategories(String aspect)
{
Object[] cats = buildCategoryNodes(services.getCategoryService().getRootCategories(
storeRef, createQName(aspect)));
return Context.getCurrentContext().newArray(getScope(), cats);
}
/**
* Get ordered, filtered and paged root categories in a classification.
*
* @param aspect
* @param filter
* @param maxItems
* @param skipCount (offset)
* @return
*/
public Scriptable getRootCategories(String aspect, String filter, int maxItems, int skipCount)
{
PagingRequest pagingRequest = new PagingRequest(skipCount, maxItems);
List<ChildAssociationRef> rootCategories = services.getCategoryService().getRootCategories(storeRef, createQName(aspect), pagingRequest, true, filter).getPage();
Object[] cats = buildCategoryNodes(rootCategories);
return Context.getCurrentContext().newArray(getScope(), cats);
}
/**
* Get the category usage count.
*
* @param aspect String
* @param maxCount int
* @return Scriptable
*/
public Scriptable getCategoryUsage(String aspect, int maxCount)
{
List<Pair<NodeRef, Integer>> topCats = services.getCategoryService().getTopCategories(storeRef, createQName(aspect), maxCount);
Object[] tags = new Object[topCats.size()];
int i = 0;
for (Pair<NodeRef, Integer> topCat : topCats)
{
tags[i++] = new Tag(new CategoryNode(topCat.getFirst(), this.services, getScope()), topCat.getSecond());
}
return Context.getCurrentContext().newArray(getScope(), tags);
}
/**
* Build category nodes.
*
* @param cars list of associations to category nodes
* @return {@link Object}[] array of category nodes
*/
private Object[] buildCategoryNodes(Collection<ChildAssociationRef> cars)
{
Object[] categoryNodes = new Object[cars.size()];
int i = 0;
for (ChildAssociationRef car : cars)
{
categoryNodes[i++] = new CategoryNode(car.getChildRef(), this.services, getScope());
}
return categoryNodes;
}
/**
* Create QName from string
*
* @param s QName string value
* @return {@link QName} qualified name object
*/
private QName createQName(String s)
{
QName qname;
if (s.indexOf(QName.NAMESPACE_BEGIN) != -1)
{
qname = QName.createQName(s);
}
else
{
qname = QName.createQName(s, this.services.getNamespaceService());
}
return qname;
}
/**
* Tag class returned from getCategoryUsage().
*/
public final class Tag
{
private CategoryNode categoryNode;
private int frequency = 0;
public Tag(CategoryNode categoryNode, int frequency)
{
this.categoryNode = categoryNode;
this.frequency = frequency;
}
public CategoryNode getCategory()
{
return categoryNode;
}
public int getFrequency()
{
return frequency;
}
}
}

View File

@@ -514,15 +514,11 @@ public class RenditionService2Impl implements RenditionService2, InitializingBea
NodeRef renditionNode = getRenditionNode(sourceNodeRef, renditionName);
boolean createRenditionNode = renditionNode == null;
boolean sourceHasAspectRenditioned = nodeService.hasAspect(sourceNodeRef, RenditionModel.ASPECT_RENDITIONED);
boolean sourceChanges = !sourceHasAspectRenditioned || createRenditionNode || transformInputStream == null;
try
{
if (sourceChanges)
{
ruleService.disableRuleType(RuleType.UPDATE);
behaviourFilter.disableBehaviour(sourceNodeRef, ContentModel.ASPECT_AUDITABLE);
behaviourFilter.disableBehaviour(sourceNodeRef, ContentModel.ASPECT_VERSIONABLE);
}
ruleService.disableRuleType(RuleType.UPDATE);
behaviourFilter.disableBehaviour(sourceNodeRef, ContentModel.ASPECT_AUDITABLE);
behaviourFilter.disableBehaviour(sourceNodeRef, ContentModel.ASPECT_VERSIONABLE);
// If they do not exist create the rendition association and the rendition node.
if (createRenditionNode)
@@ -592,12 +588,9 @@ public class RenditionService2Impl implements RenditionService2, InitializingBea
}
finally
{
if (sourceChanges)
{
behaviourFilter.enableBehaviour(sourceNodeRef, ContentModel.ASPECT_AUDITABLE);
behaviourFilter.enableBehaviour(sourceNodeRef, ContentModel.ASPECT_VERSIONABLE);
ruleService.enableRuleType(RuleType.UPDATE);
}
behaviourFilter.enableBehaviour(sourceNodeRef, ContentModel.ASPECT_AUDITABLE);
behaviourFilter.enableBehaviour(sourceNodeRef, ContentModel.ASPECT_VERSIONABLE);
ruleService.enableRuleType(RuleType.UPDATE);
}
return null;
}, false, true));

View File

@@ -414,34 +414,7 @@ public abstract class AbstractCategoryServiceImpl implements CategoryService
int count = 0;
boolean moreItems = false;
final Function<NodeRef, Collection<ChildAssociationRef>> childNodesSupplier = (nodeRef) -> {
final Set<ChildAssociationRef> childNodes = new HashSet<>();
if (CollectionUtils.isEmpty(exactNamesFilter) && CollectionUtils.isEmpty(alikeNamesFilter))
{
// lookup in DB without filtering
childNodes.addAll(nodeService.getChildAssocs(nodeRef, ContentModel.ASSOC_SUBCATEGORIES, RegexQNamePattern.MATCH_ALL));
}
else
{
if (CollectionUtils.isNotEmpty(exactNamesFilter))
{
// lookup in DB filtering by name
childNodes.addAll(nodeService.getChildrenByName(nodeRef, ContentModel.ASSOC_SUBCATEGORIES, exactNamesFilter));
}
if (CollectionUtils.isNotEmpty(alikeNamesFilter))
{
// lookup using search engin filtering by name
childNodes.addAll(getChildren(nodeRef, Mode.SUB_CATEGORIES, Depth.IMMEDIATE, sortByName, alikeNamesFilter, skipCount + maxItems + 1));
}
}
Stream<ChildAssociationRef> childNodesStream = childNodes.stream();
if (sortByName)
{
childNodesStream = childNodesStream.sorted(Comparator.comparing(tag -> tag.getQName().getLocalName()));
}
return childNodesStream.collect(Collectors.toList());
};
final Function<NodeRef, Collection<ChildAssociationRef>> childNodesSupplier = getNodeRefCollectionFunction(sortByName, exactNamesFilter, alikeNamesFilter, skipCount, maxItems);
OUTER_LOOP: for(NodeRef nodeRef : nodeRefs)
{
@@ -468,6 +441,55 @@ public abstract class AbstractCategoryServiceImpl implements CategoryService
return new ListBackedPagingResults<>(associations, moreItems);
}
public Collection<ChildAssociationRef> getRootCategories(StoreRef storeRef, QName aspectName, Collection<String> exactNamesFilter, Collection<String> alikeNamesFilter)
{
final Set<NodeRef> nodeRefs = getClassificationNodes(storeRef, aspectName);
final List<ChildAssociationRef> associations = new LinkedList<>();
final Function<NodeRef, Collection<ChildAssociationRef>> childNodesSupplier = getNodeRefCollectionFunction(false, exactNamesFilter, alikeNamesFilter, 0, 10000);
for (NodeRef nodeRef : nodeRefs)
{
Collection<ChildAssociationRef> children = childNodesSupplier.apply(nodeRef);
associations.addAll(children);
}
return associations;
}
private Function<NodeRef, Collection<ChildAssociationRef>> getNodeRefCollectionFunction(boolean sortByName, Collection<String> exactNamesFilter, Collection<String> alikeNamesFilter, int skipCount, int maxItems)
{
final Function<NodeRef, Collection<ChildAssociationRef>> childNodesSupplier = (nodeRef) -> {
final Set<ChildAssociationRef> childNodes = new HashSet<>();
if (CollectionUtils.isEmpty(exactNamesFilter) && CollectionUtils.isEmpty(alikeNamesFilter))
{
// lookup in DB without filtering
childNodes.addAll(nodeService.getChildAssocs(nodeRef, ContentModel.ASSOC_SUBCATEGORIES, RegexQNamePattern.MATCH_ALL));
}
else
{
if (CollectionUtils.isNotEmpty(exactNamesFilter))
{
// lookup in DB filtering by name
childNodes.addAll(nodeService.getChildrenByName(nodeRef, ContentModel.ASSOC_SUBCATEGORIES, exactNamesFilter));
}
if (CollectionUtils.isNotEmpty(alikeNamesFilter))
{
// lookup using search engine filtering by name
childNodes.addAll(getChildren(nodeRef, Mode.SUB_CATEGORIES, Depth.IMMEDIATE, sortByName, alikeNamesFilter, skipCount + maxItems + 1));
}
}
Stream<ChildAssociationRef> childNodesStream = childNodes.stream();
if (sortByName)
{
childNodesStream = childNodesStream.sorted(Comparator.comparing(tag -> tag.getQName().getLocalName()));
}
return childNodesStream.collect(Collectors.toList());
};
return childNodesSupplier;
}
public Collection<ChildAssociationRef> getRootCategories(StoreRef storeRef, QName aspectName)
{
return getRootCategories(storeRef, aspectName, null);

View File

@@ -1,61 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.security.authentication.identityservice;
import org.keycloak.adapters.BearerTokenRequestAuthenticator;
import org.keycloak.adapters.KeycloakDeployment;
import org.keycloak.adapters.OIDCAuthenticationError.Reason;
import org.keycloak.adapters.spi.AuthChallenge;
import org.keycloak.adapters.spi.HttpFacade;
/**
* Extends the Keycloak BearerTokenRequestAuthenticator class to capture the error description
* when token valiation fails.
*
* @author Gavin Cornwell
*/
public class AlfrescoBearerTokenRequestAuthenticator extends BearerTokenRequestAuthenticator
{
private String validationFailureDescription;
public AlfrescoBearerTokenRequestAuthenticator(KeycloakDeployment deployment)
{
super(deployment);
}
public String getValidationFailureDescription()
{
return this.validationFailureDescription;
}
@Override
protected AuthChallenge challengeResponse(HttpFacade facade, Reason reason, String error, String description)
{
this.validationFailureDescription = description;
return super.challengeResponse(facade, reason, error, description);
}
}

View File

@@ -28,32 +28,33 @@ package org.alfresco.repo.security.authentication.identityservice;
import org.alfresco.repo.management.subsystems.ActivateableBean;
import org.alfresco.repo.security.authentication.AbstractAuthenticationComponent;
import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceAuthenticationComponent.OAuth2Client.CredentialsVerificationException;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationGrant;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.IdentityServiceFacadeException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* Authenticates a user against Identity Service (Keycloak).
* {@link OAuth2Client} is used to verify provided user credentials. User is set as the current user if the user
* credentials are valid.
* Authenticates a user against Identity Service (Keycloak/Authorization Server).
* {@link IdentityServiceFacade} is used to verify provided user credentials. User is set as the current user if the
* user credentials are valid.
* <br>
* The {@link IdentityServiceAuthenticationComponent#oAuth2Client} can be null in which case this authenticator will
* just fall through to the next one in the chain.
* The {@link IdentityServiceAuthenticationComponent#identityServiceFacade} can be null in which case this authenticator
* will just fall through to the next one in the chain.
*
*/
public class IdentityServiceAuthenticationComponent extends AbstractAuthenticationComponent implements ActivateableBean
{
private final Log LOGGER = LogFactory.getLog(IdentityServiceAuthenticationComponent.class);
/** client used to authenticate user credentials against Authorization Server **/
private OAuth2Client oAuth2Client;
private IdentityServiceFacade identityServiceFacade;
/** enabled flag for the identity service subsystem**/
private boolean active;
private boolean allowGuestLogin;
public void setOAuth2Client(OAuth2Client oAuth2Client)
public void setIdentityServiceFacade(IdentityServiceFacade identityServiceFacade)
{
this.oAuth2Client = oAuth2Client;
this.identityServiceFacade = identityServiceFacade;
}
public void setAllowGuestLogin(boolean allowGuestLogin)
@@ -63,26 +64,25 @@ public class IdentityServiceAuthenticationComponent extends AbstractAuthenticati
public void authenticateImpl(String userName, char[] password) throws AuthenticationException
{
if (oAuth2Client == null)
if (identityServiceFacade == null)
{
if (LOGGER.isDebugEnabled())
{
LOGGER.debug("OAuth2Client was not set, possibly due to the 'identity-service.authentication.enable-username-password-authentication=false' property.");
LOGGER.debug("IdentityServiceFacade was not set, possibly due to the 'identity-service.authentication.enable-username-password-authentication=false' property.");
}
throw new AuthenticationException("User not authenticated because OAuth2Client was not set.");
throw new AuthenticationException("User not authenticated because IdentityServiceFacade was not set.");
}
try
{
// Attempt to verify user credentials
oAuth2Client.verifyCredentials(userName, new String(password));
identityServiceFacade.authorize(AuthorizationGrant.password(userName, new String(password)));
// Verification was successful so treat as authenticated user
setCurrentUser(userName);
}
catch (CredentialsVerificationException e)
catch (IdentityServiceFacadeException e)
{
throw new AuthenticationException("Failed to verify user credentials against the OAuth2 Authorization Server.", e);
}
@@ -108,32 +108,4 @@ public class IdentityServiceAuthenticationComponent extends AbstractAuthenticati
{
return allowGuestLogin;
}
/**
* An abstraction for acting as an OAuth2 Client
*/
interface OAuth2Client
{
/**
* The OAuth2's Client role is only used to verify the user credentials (Resource Owner Password
* Credentials Flow) this is why there is an explicit method for verifying these.
* @param userName user's name
* @param password user's password
* @throws CredentialsVerificationException when the verification failed or couldn't be performed
*/
void verifyCredentials(String userName, String password);
class CredentialsVerificationException extends RuntimeException
{
CredentialsVerificationException(String message)
{
super(message);
}
CredentialsVerificationException(String message, Throwable cause)
{
super(message, cause);
}
}
}
}

View File

@@ -25,15 +25,8 @@
*/
package org.alfresco.repo.security.authentication.identityservice;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.keycloak.representations.adapters.config.AdapterConfig;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.util.UriComponentsBuilder;
/**
@@ -41,23 +34,28 @@ import org.springframework.web.util.UriComponentsBuilder;
*
* @author Gavin Cornwell
*/
public class IdentityServiceConfig extends AdapterConfig implements InitializingBean
public class IdentityServiceConfig
{
private static final Log LOGGER = LogFactory.getLog(IdentityServiceConfig.class);
private static final String REALMS = "realms";
private static final String SECRET = "secret";
private static final String CREDENTIALS_SECRET = "identity-service.credentials.secret";
private static final String CREDENTIALS_PROVIDER = "identity-service.credentials.provider";
private Properties globalProperties;
private int clientConnectionTimeout;
private int clientSocketTimeout;
public void setGlobalProperties(Properties globalProperties)
{
this.globalProperties = globalProperties;
}
// client id
private String resource;
private String clientSecret;
private String authServerUrl;
private String realm;
private int connectionPoolSize;
private boolean allowAnyHostname;
private boolean disableTrustManager;
private String truststore;
private String truststorePassword;
private String clientKeystore;
private String clientKeystorePassword;
private String clientKeyPassword;
private String realmKey;
private int publicKeyCacheTtl;
private boolean publicClient;
/**
*
@@ -94,52 +92,163 @@ public class IdentityServiceConfig extends AdapterConfig implements Initializing
{
this.clientSocketTimeout = clientSocketTimeout;
}
@Override
public void afterPropertiesSet() throws Exception
public void setConnectionPoolSize(int connectionPoolSize)
{
// programmatically build the more complex objects i.e. credentials
Map<String, Object> credentials = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
String secret = this.globalProperties.getProperty(CREDENTIALS_SECRET);
if (secret != null && !secret.isEmpty())
{
credentials.put(SECRET, secret);
}
String provider = this.globalProperties.getProperty(CREDENTIALS_PROVIDER);
if (provider != null && !provider.isEmpty())
{
credentials.put("provider", provider);
}
// TODO: add support for redirect-rewrite-rules and policy-enforcer if and when we need to support it
if (!credentials.isEmpty())
{
this.setCredentials(credentials);
if (LOGGER.isDebugEnabled())
{
LOGGER.debug("Created credentials map from config: " + credentials);
}
}
this.connectionPoolSize = connectionPoolSize;
}
String getIssuerUrl()
public int getConnectionPoolSize()
{
return UriComponentsBuilder.fromUriString(getAuthServerUrl())
.pathSegment(REALMS, getRealm())
.build()
.toString();
return connectionPoolSize;
}
public String getAuthServerUrl()
{
return authServerUrl;
}
public void setAuthServerUrl(String authServerUrl)
{
this.authServerUrl = authServerUrl;
}
public String getRealm()
{
return realm;
}
public void setRealm(String realm)
{
this.realm = realm;
}
public String getResource()
{
return resource;
}
public void setResource(String resource)
{
this.resource = resource;
}
public void setClientSecret(String clientSecret)
{
this.clientSecret = clientSecret;
}
public String getClientSecret()
{
return Optional.ofNullable(getCredentials())
.map(c -> c.get(SECRET))
.filter(String.class::isInstance)
.map(String.class::cast)
.orElse("");
return Optional.ofNullable(clientSecret)
.orElse("");
}
public String getIssuerUrl()
{
return UriComponentsBuilder.fromUriString(getAuthServerUrl())
.pathSegment(REALMS, getRealm())
.build()
.toString();
}
public void setAllowAnyHostname(boolean allowAnyHostname)
{
this.allowAnyHostname = allowAnyHostname;
}
public boolean isAllowAnyHostname()
{
return allowAnyHostname;
}
public void setDisableTrustManager(boolean disableTrustManager)
{
this.disableTrustManager = disableTrustManager;
}
public boolean isDisableTrustManager()
{
return disableTrustManager;
}
public void setTruststore(String truststore)
{
this.truststore = truststore;
}
public String getTruststore()
{
return truststore;
}
public void setTruststorePassword(String truststorePassword)
{
this.truststorePassword = truststorePassword;
}
public String getTruststorePassword()
{
return truststorePassword;
}
public void setClientKeystore(String clientKeystore)
{
this.clientKeystore = clientKeystore;
}
public String getClientKeystore()
{
return clientKeystore;
}
public void setClientKeystorePassword(String clientKeystorePassword)
{
this.clientKeystorePassword = clientKeystorePassword;
}
public String getClientKeystorePassword()
{
return clientKeystorePassword;
}
public void setClientKeyPassword(String clientKeyPassword)
{
this.clientKeyPassword = clientKeyPassword;
}
public String getClientKeyPassword()
{
return clientKeyPassword;
}
public void setRealmKey(String realmKey)
{
this.realmKey = realmKey;
}
public String getRealmKey()
{
return realmKey;
}
public void setPublicKeyCacheTtl(int publicKeyCacheTtl)
{
this.publicKeyCacheTtl = publicKeyCacheTtl;
}
public int getPublicKeyCacheTtl()
{
return publicKeyCacheTtl;
}
public void setPublicClient(boolean publicClient)
{
this.publicClient = publicClient;
}
public boolean isPublicClient()
{
return publicClient;
}
}

View File

@@ -1,105 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.security.authentication.identityservice;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.HttpClient;
import org.keycloak.adapters.HttpClientBuilder;
import org.keycloak.adapters.KeycloakDeployment;
import org.keycloak.adapters.KeycloakDeploymentBuilder;
import org.springframework.beans.factory.FactoryBean;
import java.util.concurrent.TimeUnit;
/**
* Creates an instance of a KeycloakDeployment object for communicating with the Identity Service.
*
* @author Gavin Cornwell
*/
public class IdentityServiceDeploymentFactoryBean implements FactoryBean<KeycloakDeployment>
{
private static Log logger = LogFactory.getLog(IdentityServiceDeploymentFactoryBean.class);
private IdentityServiceConfig identityServiceConfig;
public void setIdentityServiceConfig(IdentityServiceConfig config)
{
this.identityServiceConfig = config;
}
@Override
public KeycloakDeployment getObject() throws Exception
{
KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(this.identityServiceConfig);
// Set client with custom timeout values if client was created by the KeycloakDeploymentBuilder.
// This can be removed if the future versions of Keycloak accept timeout values through the config.
if (deployment.getClient() != null)
{
int connectionTimeout = identityServiceConfig.getClientConnectionTimeout();
int socketTimeout = identityServiceConfig.getClientSocketTimeout();
HttpClient client = new HttpClientBuilder()
.establishConnectionTimeout(connectionTimeout, TimeUnit.MILLISECONDS)
.socketTimeout(socketTimeout, TimeUnit.MILLISECONDS)
.build(this.identityServiceConfig);
deployment.setClient(client);
if (logger.isDebugEnabled())
{
logger.debug("Created HttpClient for Keycloak deployment with connection timeout: "+ connectionTimeout + " ms, socket timeout: "+ socketTimeout+" ms.");
}
}
else
{
if (logger.isDebugEnabled())
{
logger.debug("HttpClient for Keycloak deployment was not set.");
}
}
if (logger.isInfoEnabled())
{
logger.info("Keycloak JWKS URL: " + deployment.getJwksUrl());
logger.info("Keycloak Realm: " + deployment.getRealm());
logger.info("Keycloak Client ID: " + deployment.getResourceName());
}
return deployment;
}
@Override
public Class<KeycloakDeployment> getObjectType()
{
return KeycloakDeployment.class;
}
@Override
public boolean isSingleton()
{
return true;
}
}

View File

@@ -0,0 +1,212 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2023 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.security.authentication.identityservice;
import static java.util.Objects.nonNull;
import static java.util.Objects.requireNonNull;
import java.time.Instant;
import java.util.Objects;
/**
* Allows to interact with the Identity Service
*/
public interface IdentityServiceFacade
{
/**
* Returns {@link AccessToken} based authorization for provided {@link AuthorizationGrant}.
* @param grant the OAuth2 grant provided by the Resource Owner.
* @return {@link AccessTokenAuthorization} containing access token and optional refresh token.
* @throws {@link AuthorizationException} when provided grant cannot be exchanged for the access token.
*/
AccessTokenAuthorization authorize(AuthorizationGrant grant) throws AuthorizationException;
/**
* Decodes the access token into the {@link DecodedAccessToken} which contains claims connected with a given token.
* @param token {@link String} with encoded access token value.
* @return {@link DecodedAccessToken} containing decoded claims.
* @throws {@link TokenDecodingException} when token decoding failed.
*/
DecodedAccessToken decodeToken(String token) throws TokenDecodingException;
class IdentityServiceFacadeException extends RuntimeException
{
public IdentityServiceFacadeException(String message)
{
super(message);
}
IdentityServiceFacadeException(String message, Throwable cause)
{
super(message, cause);
}
}
class AuthorizationException extends IdentityServiceFacadeException
{
AuthorizationException(String message)
{
super(message);
}
AuthorizationException(String message, Throwable cause)
{
super(message, cause);
}
}
class TokenDecodingException extends IdentityServiceFacadeException
{
TokenDecodingException(String message)
{
super(message);
}
TokenDecodingException(String message, Throwable cause)
{
super(message, cause);
}
}
/**
* Represents access token authorization with optional refresh token.
*/
interface AccessTokenAuthorization
{
/**
* Required {@link AccessToken}
* @return {@link AccessToken}
*/
AccessToken getAccessToken();
/**
* Optional refresh token.
* @return Refresh token or {@code null}
*/
String getRefreshTokenValue();
}
interface AccessToken {
String getTokenValue();
Instant getExpiresAt();
}
interface DecodedAccessToken extends AccessToken
{
Object getClaim(String claim);
}
class AuthorizationGrant {
private final String username;
private final String password;
private final String refreshToken;
private final String authorizationCode;
private final String redirectUri;
private AuthorizationGrant(String username, String password, String refreshToken, String authorizationCode, String redirectUri)
{
this.username = username;
this.password = password;
this.refreshToken = refreshToken;
this.authorizationCode = authorizationCode;
this.redirectUri = redirectUri;
}
public static AuthorizationGrant password(String username, String password)
{
return new AuthorizationGrant(requireNonNull(username), requireNonNull(password), null, null, null);
}
public static AuthorizationGrant refreshToken(String refreshToken)
{
return new AuthorizationGrant(null, null, requireNonNull(refreshToken), null, null);
}
public static AuthorizationGrant authorizationCode(String authorizationCode, String redirectUri)
{
return new AuthorizationGrant(null, null, null, requireNonNull(authorizationCode), requireNonNull(redirectUri));
}
boolean isPassword()
{
return nonNull(username);
}
boolean isRefreshToken()
{
return nonNull(refreshToken);
}
boolean isAuthorizationCode()
{
return nonNull(authorizationCode);
}
String getUsername()
{
return username;
}
String getPassword()
{
return password;
}
String getRefreshToken()
{
return refreshToken;
}
String getAuthorizationCode()
{
return authorizationCode;
}
String getRedirectUri()
{
return redirectUri;
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AuthorizationGrant that = (AuthorizationGrant) o;
return Objects.equals(username, that.username) &&
Objects.equals(password, that.password) &&
Objects.equals(refreshToken, that.refreshToken) &&
Objects.equals(authorizationCode, that.authorizationCode) &&
Objects.equals(redirectUri, that.redirectUri);
}
@Override
public int hashCode()
{
return Objects.hash(username, password, refreshToken, authorizationCode, redirectUri);
}
}
}

View File

@@ -0,0 +1,558 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2023 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.security.authentication.identityservice;
import static java.util.Objects.requireNonNull;
import static java.util.Optional.ofNullable;
import static java.util.function.Predicate.not;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.interfaces.RSAPublicKey;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.source.DefaultJWKSetCache;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.jwk.source.RemoteJWKSet;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jose.util.ResourceRetriever;
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.IdentityServiceFacadeException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustAllStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.security.converter.RsaKeyConverters;
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
import org.springframework.security.oauth2.client.oidc.authentication.OidcIdTokenDecoderFactory;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistration.Builder;
import org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.converter.ClaimTypeConverter;
import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimNames;
import org.springframework.security.oauth2.jwt.JwtClaimValidator;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtIssuerValidator;
import org.springframework.security.oauth2.jwt.JwtTimestampValidator;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
/**
*
* Creates an instance of {@link IdentityServiceFacade}. <br>
* This factory can return a null if it is disabled.
*
*/
public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentityServiceFacade>
{
private static final Log LOGGER = LogFactory.getLog(IdentityServiceFacadeFactoryBean.class);
private boolean enabled;
private SpringBasedIdentityServiceFacadeFactory factory;
public void setEnabled(boolean enabled)
{
this.enabled = enabled;
}
public void setIdentityServiceConfig(IdentityServiceConfig identityServiceConfig)
{
factory = new SpringBasedIdentityServiceFacadeFactory(
new HttpClientProvider(identityServiceConfig)::createHttpClient,
new ClientRegistrationProvider(identityServiceConfig)::createClientRegistration,
new JwtDecoderProvider(identityServiceConfig)::createJwtDecoder
);
}
@Override
public IdentityServiceFacade getObject() throws Exception
{
// The creation of the client can be disabled for testing or when the username/password authentication is not required,
// for instance when Identity Service is configured for 'bearer only' authentication or Direct Access Grants are disabled.
if (!enabled)
{
return null;
}
return new LazyInstantiatingIdentityServiceFacade(factory::createIdentityServiceFacade);
}
@Override
public Class<?> getObjectType()
{
return IdentityServiceFacade.class;
}
@Override
public boolean isSingleton()
{
return true;
}
private static IdentityServiceFacadeException authorizationServerCantBeUsedException(RuntimeException cause)
{
return new IdentityServiceFacadeException("Unable to use the Authorization Server.", cause);
}
// The target facade is created lazily to improve resiliency on Identity Service
// (Keycloak/Authorization Server) failures when Spring Context is starting up.
static class LazyInstantiatingIdentityServiceFacade implements IdentityServiceFacade
{
private final AtomicReference<IdentityServiceFacade> targetFacade = new AtomicReference<>();
private final Supplier<IdentityServiceFacade> targetFacadeCreator;
LazyInstantiatingIdentityServiceFacade(Supplier<IdentityServiceFacade> targetFacadeCreator)
{
this.targetFacadeCreator = requireNonNull(targetFacadeCreator);
}
@Override
public AccessTokenAuthorization authorize(AuthorizationGrant grant) throws AuthorizationException
{
return getTargetFacade().authorize(grant);
}
@Override
public DecodedAccessToken decodeToken(String token) throws TokenDecodingException
{
return getTargetFacade().decodeToken(token);
}
private IdentityServiceFacade getTargetFacade()
{
return ofNullable(targetFacade.get())
.orElseGet(() -> targetFacade.updateAndGet(prev ->
ofNullable(prev).orElseGet(this::createTargetFacade)));
}
private IdentityServiceFacade createTargetFacade()
{
try
{
return targetFacadeCreator.get();
}
catch (IdentityServiceFacadeException e)
{
throw e;
}
catch (RuntimeException e)
{
LOGGER.warn("Failed to instantiate IdentityServiceFacade.", e);
throw authorizationServerCantBeUsedException(e);
}
}
}
private static class SpringBasedIdentityServiceFacadeFactory
{
private final Supplier<HttpClient> httpClientProvider;
private final Function<RestOperations, ClientRegistration> clientRegistrationProvider;
private final BiFunction<RestOperations, ProviderDetails, JwtDecoder> jwtDecoderProvider;
SpringBasedIdentityServiceFacadeFactory(
Supplier<HttpClient> httpClientProvider,
Function<RestOperations, ClientRegistration> clientRegistrationProvider,
BiFunction<RestOperations, ProviderDetails, JwtDecoder> jwtDecoderProvider)
{
this.httpClientProvider = Objects.requireNonNull(httpClientProvider);
this.clientRegistrationProvider = Objects.requireNonNull(clientRegistrationProvider);
this.jwtDecoderProvider = Objects.requireNonNull(jwtDecoderProvider);
}
private IdentityServiceFacade createIdentityServiceFacade()
{
//Here we preserve the behaviour of previously used Keycloak Adapter
// * Client is authenticating itself using basic auth
// * Resource Owner Password Credentials Flow is used to authenticate Resource Owner
final ClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClientProvider.get());
final RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
final ClientRegistration clientRegistration = clientRegistrationProvider.apply(restTemplate);
final JwtDecoder jwtDecoder = jwtDecoderProvider.apply(restTemplate, clientRegistration.getProviderDetails());
return new SpringBasedIdentityServiceFacade(createOAuth2RestTemplate(httpRequestFactory), clientRegistration, jwtDecoder);
}
private RestTemplate createOAuth2RestTemplate(ClientHttpRequestFactory requestFactory)
{
final RestTemplate restTemplate = new RestTemplate(Arrays.asList(new FormHttpMessageConverter(), new OAuth2AccessTokenResponseHttpMessageConverter()));
restTemplate.setRequestFactory(requestFactory);
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
return restTemplate;
}
}
private static class HttpClientProvider
{
private final IdentityServiceConfig config;
private HttpClientProvider(IdentityServiceConfig config)
{
this.config = Objects.requireNonNull(config);
}
private HttpClient createHttpClient()
{
try
{
HttpClientBuilder clientBuilder = HttpClients.custom();
applyConnectionConfiguration(clientBuilder);
applySSLConfiguration(clientBuilder);
return clientBuilder.build();
}
catch (Exception e)
{
throw new IllegalStateException("Failed to create ClientHttpRequestFactory. " + e.getMessage(), e);
}
}
private void applyConnectionConfiguration(HttpClientBuilder builder)
{
final RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(config.getClientConnectionTimeout())
.setSocketTimeout(config.getClientSocketTimeout())
.build();
builder.setDefaultRequestConfig(requestConfig)
.setMaxConnTotal(config.getConnectionPoolSize());
}
private void applySSLConfiguration(HttpClientBuilder builder) throws Exception
{
SSLContextBuilder sslContextBuilder = null;
if (config.isDisableTrustManager())
{
sslContextBuilder = SSLContexts.custom()
.loadTrustMaterial(TrustAllStrategy.INSTANCE);
}
else if (isDefined(config.getTruststore()))
{
final char[] truststorePassword = asCharArray(config.getTruststorePassword(), null);
sslContextBuilder = SSLContexts.custom()
.loadTrustMaterial(new File(config.getTruststore()), truststorePassword);
}
if (isDefined(config.getClientKeystore()))
{
if (sslContextBuilder == null)
{
sslContextBuilder = SSLContexts.custom();
}
final char[] keystorePassword = asCharArray(config.getClientKeystorePassword(), null);
final char[] keyPassword = asCharArray(config.getClientKeyPassword(), keystorePassword);
sslContextBuilder.loadKeyMaterial(new File(config.getClientKeystore()), keystorePassword, keyPassword);
}
if (sslContextBuilder != null)
{
builder.setSSLContext(sslContextBuilder.build());
}
if (config.isDisableTrustManager() || config.isAllowAnyHostname())
{
builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
}
}
private char[] asCharArray(String value, char[] nullValue)
{
return Optional.ofNullable(value)
.filter(not(String::isBlank))
.map(String::toCharArray)
.orElse(nullValue);
}
}
private static class ClientRegistrationProvider
{
private final IdentityServiceConfig config;
private ClientRegistrationProvider(IdentityServiceConfig config)
{
this.config = Objects.requireNonNull(config);
}
public ClientRegistration createClientRegistration(final RestOperations rest)
{
return possibleMetadataURIs()
.stream()
.map(u -> extractMetadata(rest, u))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst()
.map(this::createBuilder)
.map(this::configureClientAuthentication)
.map(Builder::build)
.orElseThrow(() -> new IllegalStateException("Failed to create ClientRegistration."));
}
private ClientRegistration.Builder createBuilder(OIDCProviderMetadata metadata)
{
final String authUri = Optional.of(metadata)
.map(OIDCProviderMetadata::getAuthorizationEndpointURI)
.map(URI::toASCIIString)
.orElse(null);
return ClientRegistration
.withRegistrationId("ids")
.authorizationUri(authUri)
.tokenUri(metadata.getTokenEndpointURI().toASCIIString())
.jwkSetUri(metadata.getJWKSetURI().toASCIIString())
.issuerUri(config.getIssuerUrl())
.authorizationGrantType(AuthorizationGrantType.PASSWORD);
}
private Builder configureClientAuthentication(Builder builder)
{
builder.clientId(config.getResource());
if (config.isPublicClient())
{
return builder.clientSecret(null)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST);
}
return builder.clientSecret(config.getClientSecret())
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
}
private Optional<OIDCProviderMetadata> extractMetadata(RestOperations rest, URI metadataUri)
{
final String response;
try
{
final ResponseEntity<String> r = rest.exchange(RequestEntity.get(metadataUri).build(), String.class);
if (r.getStatusCode() != HttpStatus.OK || !r.hasBody())
{
LOGGER.warn("Unexpected response from " + metadataUri + ". Status code: " + r.getStatusCode() + ", has body: " + r.hasBody() + ".");
return Optional.empty();
}
response = r.getBody();
}
catch (Exception e)
{
LOGGER.warn("Failed to get response from " + metadataUri + ". " + e.getMessage(), e);
return Optional.empty();
}
try
{
return Optional.of(OIDCProviderMetadata.parse(response));
}
catch (Exception e)
{
LOGGER.warn("Failed to parse metadata. " + e.getMessage(), e);
return Optional.empty();
}
}
private Collection<URI> possibleMetadataURIs()
{
return List.of(UriComponentsBuilder.fromUriString(config.getIssuerUrl())
.pathSegment(".well-known", "openid-configuration")
.build().toUri());
}
}
static class JwtDecoderProvider
{
private static final SignatureAlgorithm SIGNATURE_ALGORITHM = SignatureAlgorithm.RS256;
private final IdentityServiceConfig config;
JwtDecoderProvider(IdentityServiceConfig config)
{
this.config = Objects.requireNonNull(config);
}
public JwtDecoder createJwtDecoder(RestOperations rest, ProviderDetails providerDetails)
{
try
{
final NimbusJwtDecoder decoder = buildJwtDecoder(rest, providerDetails);
decoder.setJwtValidator(createJwtTokenValidator(providerDetails));
decoder.setClaimSetConverter(new ClaimTypeConverter(OidcIdTokenDecoderFactory.createDefaultClaimTypeConverters()));
return decoder;
} catch (RuntimeException e)
{
LOGGER.warn("Failed to create JwtDecoder.", e);
throw authorizationServerCantBeUsedException(e);
}
}
private NimbusJwtDecoder buildJwtDecoder(RestOperations rest, ProviderDetails providerDetails)
{
if (isDefined(config.getRealmKey()))
{
final RSAPublicKey publicKey = parsePublicKey(config.getRealmKey());
return NimbusJwtDecoder.withPublicKey(publicKey)
.signatureAlgorithm(SIGNATURE_ALGORITHM)
.build();
}
final String jwkSetUri = requireValidJwkSetUri(providerDetails);
return NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
.jwsAlgorithm(SIGNATURE_ALGORITHM)
.restOperations(rest)
.jwtProcessorCustomizer(this::reconfigureJWKSCache)
.build();
}
private void reconfigureJWKSCache(ConfigurableJWTProcessor<SecurityContext> jwtProcessor)
{
final Optional<RemoteJWKSet<SecurityContext>> jwkSource = ofNullable(jwtProcessor)
.map(ConfigurableJWTProcessor::getJWSKeySelector)
.filter(JWSVerificationKeySelector.class::isInstance).map(o -> (JWSVerificationKeySelector<SecurityContext>)o)
.map(JWSVerificationKeySelector::getJWKSource)
.filter(RemoteJWKSet.class::isInstance).map(o -> (RemoteJWKSet<SecurityContext>)o);
if (jwkSource.isEmpty())
{
LOGGER.warn("Not able to reconfigure the JWK Cache. Unexpected JWKSource.");
return;
}
final Optional<URL> jwkSetUrl = jwkSource.map(RemoteJWKSet::getJWKSetURL);
if (jwkSetUrl.isEmpty())
{
LOGGER.warn("Not able to reconfigure the JWK Cache. Unknown JWKSetURL.");
return;
}
final Optional<ResourceRetriever> resourceRetriever = jwkSource.map(RemoteJWKSet::getResourceRetriever);
if (resourceRetriever.isEmpty())
{
LOGGER.warn("Not able to reconfigure the JWK Cache. Unknown ResourceRetriever.");
return;
}
final DefaultJWKSetCache cache = new DefaultJWKSetCache(config.getPublicKeyCacheTtl(), -1, TimeUnit.SECONDS);
final JWKSource<SecurityContext> cachingJWKSource = new RemoteJWKSet<>(jwkSetUrl.get(), resourceRetriever.get(), cache);
jwtProcessor.setJWSKeySelector(new JWSVerificationKeySelector<>(
JWSAlgorithm.parse(SIGNATURE_ALGORITHM.getName()),
cachingJWKSource));
}
private OAuth2TokenValidator<Jwt> createJwtTokenValidator(ProviderDetails providerDetails)
{
return new DelegatingOAuth2TokenValidator<>(
new JwtTimestampValidator(Duration.of(0, ChronoUnit.MILLIS)),
new JwtIssuerValidator(providerDetails.getIssuerUri()),
new JwtClaimValidator<String>("typ", "Bearer"::equals),
new JwtClaimValidator<String>(JwtClaimNames.SUB, Objects::nonNull));
}
private RSAPublicKey parsePublicKey(String pem)
{
try
{
return tryToParsePublicKey(pem);
}
catch (Exception e)
{
if (isPemFormatException(e))
{
//For backward compatibility with Keycloak adapter
return tryToParsePublicKey("-----BEGIN PUBLIC KEY-----\n" + pem + "\n-----END PUBLIC KEY-----");
}
throw e;
}
}
private RSAPublicKey tryToParsePublicKey(String pem)
{
final InputStream pemStream = new ByteArrayInputStream(pem.getBytes(StandardCharsets.UTF_8));
return RsaKeyConverters.x509().convert(pemStream);
}
private boolean isPemFormatException(Exception e)
{
return e.getMessage() != null && e.getMessage().contains("-----BEGIN PUBLIC KEY-----");
}
private String requireValidJwkSetUri(ProviderDetails providerDetails)
{
final String uri = providerDetails.getJwkSetUri();
if (!isDefined(uri)) {
OAuth2Error oauth2Error = new OAuth2Error("missing_signature_verifier",
"Failed to find a Signature Verifier for: '"
+ providerDetails.getIssuerUri()
+ "'. Check to ensure you have configured the JwkSet URI.",
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
return uri;
}
}
private static boolean isDefined(String value)
{
return value != null && !value.isBlank();
}
}

View File

@@ -1,107 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.security.authentication.identityservice;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import org.keycloak.adapters.servlet.ServletHttpFacade;
/**
* HttpFacade wrapper so we can re-use Keycloak authenticator classes.
*
* @author Gavin Cornwell
*/
public class IdentityServiceHttpFacade extends ServletHttpFacade
{
public IdentityServiceHttpFacade(HttpServletRequest request)
{
super(request, null);
}
@Override
public Response getResponse()
{
// return our dummy NoOp implementation so we don't effect the ACS response
return new NoOpResponseFacade();
}
/**
* NoOp implementation of Keycloak Response interface.
*/
private class NoOpResponseFacade implements Response
{
@Override
public void setStatus(int status)
{
}
@Override
public void addHeader(String name, String value)
{
}
@Override
public void setHeader(String name, String value)
{
}
@Override
public void resetCookie(String name, String path)
{
}
@Override
public void setCookie(String name, String value, String path, String domain, int maxAge,
boolean secure, boolean httpOnly)
{
}
@Override
public OutputStream getOutputStream()
{
return new ByteArrayOutputStream();
}
@Override
public void sendError(int code)
{
}
@Override
public void sendError(int code, String message)
{
}
@Override
public void end()
{
}
}
}

View File

@@ -2,7 +2,7 @@
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* Copyright (C) 2005 - 2023 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
@@ -27,17 +27,19 @@ package org.alfresco.repo.security.authentication.identityservice;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
import org.alfresco.repo.management.subsystems.ActivateableBean;
import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.repo.security.authentication.external.RemoteUserMapper;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.IdentityServiceFacadeException;
import org.alfresco.service.cmr.security.PersonService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.keycloak.adapters.KeycloakDeployment;
import org.keycloak.adapters.spi.AuthOutcome;
import org.keycloak.representations.AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
/**
* A {@link RemoteUserMapper} implementation that detects and validates JWTs
@@ -47,7 +49,8 @@ import org.keycloak.representations.AccessToken;
*/
public class IdentityServiceRemoteUserMapper implements RemoteUserMapper, ActivateableBean
{
private static Log logger = LogFactory.getLog(IdentityServiceRemoteUserMapper.class);
private static final Log LOGGER = LogFactory.getLog(IdentityServiceRemoteUserMapper.class);
static final String USERNAME_CLAIM = "preferred_username";
/** Is the mapper enabled */
private boolean isEnabled;
@@ -57,9 +60,9 @@ public class IdentityServiceRemoteUserMapper implements RemoteUserMapper, Activa
/** The person service. */
private PersonService personService;
/** The Keycloak deployment object */
private KeycloakDeployment keycloakDeployment;
private BearerTokenResolver bearerTokenResolver;
private IdentityServiceFacade identityServiceFacade;
/**
* Sets the active flag
@@ -91,58 +94,57 @@ public class IdentityServiceRemoteUserMapper implements RemoteUserMapper, Activa
{
this.personService = personService;
}
public void setIdentityServiceDeployment(KeycloakDeployment deployment)
public void setBearerTokenResolver(BearerTokenResolver bearerTokenResolver)
{
this.keycloakDeployment = deployment;
this.bearerTokenResolver = bearerTokenResolver;
}
public void setIdentityServiceFacade(IdentityServiceFacade identityServiceFacade)
{
this.identityServiceFacade = identityServiceFacade;
}
/*
* (non-Javadoc)
* @see org.alfresco.web.app.servlet.RemoteUserMapper#getRemoteUser(javax.servlet.http.HttpServletRequest)
*/
@Override
public String getRemoteUser(HttpServletRequest request)
{
LOGGER.trace("Retrieving username from http request...");
if (!this.isEnabled)
{
LOGGER.debug("IdentityServiceRemoteUserMapper is disabled, returning null.");
return null;
}
try
{
if (logger.isTraceEnabled())
{
logger.trace("Retrieving username from http request...");
}
if (!this.isEnabled)
{
if (logger.isDebugEnabled())
{
logger.debug("IdentityServiceRemoteUserMapper is disabled, returning null.");
}
return null;
}
String headerUserId = extractUserFromHeader(request);
if (headerUserId != null)
{
// Normalize the user ID taking into account case sensitivity settings
String normalizedUserId = normalizeUserId(headerUserId);
if (logger.isTraceEnabled())
{
logger.trace("Returning userId: " + AuthenticationUtil.maskUsername(normalizedUserId));
}
LOGGER.trace("Returning userId: " + AuthenticationUtil.maskUsername(normalizedUserId));
return normalizedUserId;
}
}
catch (Exception e)
catch (IdentityServiceFacadeException e)
{
logger.error("Failed to authenticate user using IdentityServiceRemoteUserMapper: " + e.getMessage(), e);
if (!isValidationFailureSilent)
{
throw new AuthenticationException("Failed to extract username from token: " + e.getMessage(), e);
}
LOGGER.error("Failed to authenticate user using IdentityServiceRemoteUserMapper: " + e.getMessage(), e);
}
if (logger.isTraceEnabled())
catch (RuntimeException e)
{
logger.trace("Could not identify a userId. Returning null.");
LOGGER.error("Failed to authenticate user using IdentityServiceRemoteUserMapper: " + e.getMessage(), e);
}
LOGGER.trace("Could not identify a userId. Returning null.");
return null;
}
@@ -159,61 +161,40 @@ public class IdentityServiceRemoteUserMapper implements RemoteUserMapper, Activa
* Extracts the user name from the JWT in the given request.
*
* @param request The request containing the JWT
* @return The user name or null if it can not be determined
* @return The username or null if it can not be determined
*/
private String extractUserFromHeader(HttpServletRequest request)
{
String userName = null;
IdentityServiceHttpFacade facade = new IdentityServiceHttpFacade(request);
// try authenticating with bearer token first
if (logger.isDebugEnabled())
LOGGER.debug("Trying bearer token...");
final String bearerToken;
try
{
logger.debug("Trying bearer token...");
bearerToken = bearerTokenResolver.resolve(request);
}
AlfrescoBearerTokenRequestAuthenticator tokenAuthenticator =
new AlfrescoBearerTokenRequestAuthenticator(this.keycloakDeployment);
AuthOutcome tokenOutcome = tokenAuthenticator.authenticate(facade);
if (logger.isDebugEnabled())
catch (OAuth2AuthenticationException e)
{
logger.debug("Bearer token outcome: " + tokenOutcome);
LOGGER.debug("Failed to resolve Bearer token.", e);
return null;
}
if (tokenOutcome == AuthOutcome.FAILED && !isValidationFailureSilent)
final Optional<String> possibleUsername = Optional.ofNullable(bearerToken)
.map(identityServiceFacade::decodeToken)
.map(t -> t.getClaim(USERNAME_CLAIM))
.filter(String.class::isInstance)
.map(String.class::cast);
if (possibleUsername.isEmpty())
{
throw new AuthenticationException("Token validation failed: " +
tokenAuthenticator.getValidationFailureDescription());
LOGGER.debug("User could not be authenticated by IdentityServiceRemoteUserMapper.");
return null;
}
if (tokenOutcome == AuthOutcome.AUTHENTICATED)
{
userName = extractUserFromToken(tokenAuthenticator.getToken());
}
else
{
if (logger.isDebugEnabled())
{
logger.debug("User could not be authenticated by IdentityServiceRemoteUserMapper.");
}
}
return userName;
}
private String extractUserFromToken(AccessToken jwt)
{
// retrieve the preferred_username claim
String userName = jwt.getPreferredUsername();
if (logger.isTraceEnabled())
{
logger.trace("Extracted username: " + AuthenticationUtil.maskUsername(userName));
}
return userName;
String username = possibleUsername.get();
LOGGER.trace("Extracted username: " + AuthenticationUtil.maskUsername(username));
return username;
}
/**
@@ -238,9 +219,9 @@ public class IdentityServiceRemoteUserMapper implements RemoteUserMapper, Activa
}
}, AuthenticationUtil.getSystemUserName());
if (logger.isDebugEnabled())
if (LOGGER.isDebugEnabled())
{
logger.debug("Normalized user name for '" + AuthenticationUtil.maskUsername(userId) + "': " + AuthenticationUtil.maskUsername(normalized));
LOGGER.debug("Normalized user name for '" + AuthenticationUtil.maskUsername(userId) + "': " + AuthenticationUtil.maskUsername(normalized));
}
return normalized == null ? userId : normalized;

View File

@@ -1,270 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2023 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.security.authentication.identityservice;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceAuthenticationComponent.OAuth2Client;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizationContext;
import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder.PasswordGrantBuilder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.endpoint.DefaultPasswordTokenResponseClient;
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.ClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
/**
*
* Creates an instance of {@link OAuth2Client}. <br>
* The creation of {@link OAuth2Client} requires connection to the Identity Service (Keycloak), disable this factory if
* the server cannot be reached. <br>
* This factory can return a null if it is disabled.
*
*/
public class OAuth2ClientFactoryBean implements FactoryBean<OAuth2Client>
{
private static final Log LOGGER = LogFactory.getLog(OAuth2ClientFactoryBean.class);
private IdentityServiceConfig identityServiceConfig;
private boolean enabled;
public void setEnabled(boolean enabled)
{
this.enabled = enabled;
}
public void setIdentityServiceConfig(IdentityServiceConfig identityServiceConfig)
{
this.identityServiceConfig = identityServiceConfig;
}
@Override
public OAuth2Client getObject() throws Exception
{
// The creation of the client can be disabled for testing or when the username/password authentication is not required,
// for instance when Keycloak is configured for 'bearer only' authentication or Direct Access Grants are disabled.
if (!enabled)
{
return null;
}
// The OAuth2AuthorizedClientManager isn't created upfront to make the code resilient to Identity Service being down.
// If it's down the Application Context will start and when it's back online it can be used.
return new SpringOAuth2Client(this::createOAuth2AuthorizedClientManager);
}
private OAuth2AuthorizedClientManager createOAuth2AuthorizedClientManager()
{
//Here we preserve the behaviour of previously used Keycloak Adapter
// * Client is authenticating itself using basic auth
// * Resource Owner Password Credentials Flow is used to authenticate Resource Owner
// * There is no caching of authenticated clients (NoStoredAuthorizedClient)
// * There is only one Authorization Server/Client pair (SingleClientRegistration)
final ClientRegistration clientRegistration = ClientRegistrations
.fromIssuerLocation(identityServiceConfig.getIssuerUrl())
.clientId(identityServiceConfig.getResource())
.clientSecret(identityServiceConfig.getClientSecret())
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.registrationId(SpringOAuth2Client.CLIENT_REGISTRATION_ID)
.build();
final AuthorizedClientServiceOAuth2AuthorizedClientManager oauth2 =
new AuthorizedClientServiceOAuth2AuthorizedClientManager(
new SingleClientRegistration(clientRegistration),
new NoStoredAuthorizedClient());
oauth2.setContextAttributesMapper(OAuth2AuthorizeRequest::getAttributes);
oauth2.setAuthorizedClientProvider(OAuth2AuthorizedClientProviderBuilder.builder()
.password(this::configureTimeouts)
.build());
if (LOGGER.isDebugEnabled())
{
LOGGER.debug(" Created OAuth2 Client");
LOGGER.debug(" OAuth2 Issuer URL: " + clientRegistration.getProviderDetails().getIssuerUri());
LOGGER.debug(" OAuth2 ClientId: " + clientRegistration.getClientId());
}
return oauth2;
}
private void configureTimeouts(PasswordGrantBuilder builder)
{
final SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(identityServiceConfig.getClientConnectionTimeout());
requestFactory.setReadTimeout(identityServiceConfig.getClientSocketTimeout());
final RestTemplate restTemplate = new RestTemplate(Arrays.asList(new FormHttpMessageConverter(), new OAuth2AccessTokenResponseHttpMessageConverter()));
restTemplate.setRequestFactory(requestFactory);
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
final DefaultPasswordTokenResponseClient client = new DefaultPasswordTokenResponseClient();
client.setRestOperations(restTemplate);
builder.accessTokenResponseClient(client);
}
@Override
public Class<?> getObjectType()
{
return OAuth2Client.class;
}
@Override
public boolean isSingleton()
{
return true;
}
static class SpringOAuth2Client implements OAuth2Client
{
private static final String CLIENT_REGISTRATION_ID = "ids";
private final Supplier<OAuth2AuthorizedClientManager> authorizedClientManagerSupplier;
private final AtomicReference<OAuth2AuthorizedClientManager> authorizedClientManager = new AtomicReference<>();
public SpringOAuth2Client(Supplier<OAuth2AuthorizedClientManager> authorizedClientManagerSupplier)
{
this.authorizedClientManagerSupplier = Objects.requireNonNull(authorizedClientManagerSupplier);
}
@Override
public void verifyCredentials(String userName, String password)
{
final OAuth2AuthorizedClientManager clientManager;
try
{
clientManager = getAuthorizedClientManager();
}
catch (RuntimeException e)
{
LOGGER.warn("Failed to instantiate OAuth2AuthorizedClientManager.", e);
throw new CredentialsVerificationException("Unable to use the Authorization Server.", e);
}
final OAuth2AuthorizedClient authorizedClient;
try
{
final OAuth2AuthorizeRequest authRequest = createPasswordCredentialsRequest(userName, password);
authorizedClient = clientManager.authorize(authRequest);
}
catch (OAuth2AuthorizationException e)
{
LOGGER.debug("Failed to authorize against Authorization Server. Reason: " + e.getError() + ".");
throw new CredentialsVerificationException("Authorization against the Authorization Server failed with " + e.getError() + ".", e);
}
catch (RuntimeException e)
{
LOGGER.warn("Failed to authorize against Authorization Server. Reason: " + e.getMessage());
throw new CredentialsVerificationException("Failed to authorize against Authorization Server.", e);
}
if (authorizedClient == null || authorizedClient.getAccessToken() == null)
{
throw new CredentialsVerificationException("Resource Owner Password Credentials is not supported by the Authorization Server.");
}
}
private OAuth2AuthorizedClientManager getAuthorizedClientManager()
{
final OAuth2AuthorizedClientManager current = authorizedClientManager.get();
if (current != null)
{
return current;
}
return authorizedClientManager
.updateAndGet(prev -> prev != null ? prev : authorizedClientManagerSupplier.get());
}
private OAuth2AuthorizeRequest createPasswordCredentialsRequest(String userName, String password)
{
return OAuth2AuthorizeRequest
.withClientRegistrationId(CLIENT_REGISTRATION_ID)
.principal(userName)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, userName)
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password)
.build();
}
}
private static class NoStoredAuthorizedClient implements OAuth2AuthorizedClientService
{
@Override
public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId, String principalName)
{
return null;
}
@Override
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal)
{
//do nothing
}
@Override
public void removeAuthorizedClient(String clientRegistrationId, String principalName)
{
//do nothing
}
}
private static class SingleClientRegistration implements ClientRegistrationRepository
{
private final ClientRegistration clientRegistration;
private SingleClientRegistration(ClientRegistration clientRegistration)
{
this.clientRegistration = Objects.requireNonNull(clientRegistration);
}
@Override
public ClientRegistration findByRegistrationId(String registrationId)
{
return Objects.equals(registrationId, clientRegistration.getRegistrationId()) ? clientRegistration : null;
}
}
}

View File

@@ -0,0 +1,255 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2023 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.security.authentication.identityservice;
import static java.util.Objects.requireNonNull;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.oauth2.client.endpoint.AbstractOAuth2AuthorizationGrantRequest;
import org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.DefaultPasswordTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.DefaultRefreshTokenTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AbstractOAuth2Token;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AccessToken.TokenType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.web.client.RestOperations;
class SpringBasedIdentityServiceFacade implements IdentityServiceFacade
{
private static final Log LOGGER = LogFactory.getLog(SpringBasedIdentityServiceFacade.class);
private static final Instant SOME_INSIGNIFICANT_DATE_IN_THE_PAST = Instant.MIN.plusSeconds(12345);
private final Map<AuthorizationGrantType, OAuth2AccessTokenResponseClient> clients;
private final ClientRegistration clientRegistration;
private final JwtDecoder jwtDecoder;
SpringBasedIdentityServiceFacade(RestOperations restOperations, ClientRegistration clientRegistration, JwtDecoder jwtDecoder)
{
requireNonNull(restOperations);
this.clientRegistration = requireNonNull(clientRegistration);
this.jwtDecoder = requireNonNull(jwtDecoder);
this.clients = Map.of(
AuthorizationGrantType.AUTHORIZATION_CODE, createAuthorizationCodeClient(restOperations),
AuthorizationGrantType.REFRESH_TOKEN, createRefreshTokenClient(restOperations),
AuthorizationGrantType.PASSWORD, createPasswordClient(restOperations));
}
@Override
public AccessTokenAuthorization authorize(AuthorizationGrant authorizationGrant)
{
final AbstractOAuth2AuthorizationGrantRequest request = createRequest(authorizationGrant);
final OAuth2AccessTokenResponseClient client = getClient(request);
final OAuth2AccessTokenResponse response;
try
{
response = client.getTokenResponse(request);
}
catch (OAuth2AuthorizationException e)
{
LOGGER.debug("Failed to authorize against Authorization Server. Reason: " + e.getError() + ".");
throw new AuthorizationException("Failed to obtain access token. " + e.getError(), e);
}
catch (RuntimeException e)
{
LOGGER.warn("Failed to authorize against Authorization Server. Reason: " + e.getMessage());
throw new AuthorizationException("Failed to obtain access token.", e);
}
return new SpringAccessTokenAuthorization(response);
}
@Override
public DecodedAccessToken decodeToken(String token)
{
final Jwt validToken;
try
{
validToken = jwtDecoder.decode(token);
}
catch (RuntimeException e)
{
throw new TokenDecodingException("Failed to decode token. " + e.getMessage(), e);
}
if (LOGGER.isDebugEnabled())
{
LOGGER.debug("Bearer token outcome: " + validToken.getClaims());
}
return new SpringDecodedAccessToken(validToken);
}
private AbstractOAuth2AuthorizationGrantRequest createRequest(AuthorizationGrant grant)
{
if (grant.isPassword())
{
return new OAuth2PasswordGrantRequest(clientRegistration, grant.getUsername(), grant.getPassword());
}
if (grant.isRefreshToken())
{
final OAuth2AccessToken expiredAccessToken = new OAuth2AccessToken(
TokenType.BEARER,
"JUST_FOR_FULFILLING_THE_SPRING_API",
SOME_INSIGNIFICANT_DATE_IN_THE_PAST,
SOME_INSIGNIFICANT_DATE_IN_THE_PAST.plusSeconds(1));
final OAuth2RefreshToken refreshToken = new OAuth2RefreshToken(grant.getRefreshToken(), null);
return new OAuth2RefreshTokenGrantRequest(clientRegistration, expiredAccessToken, refreshToken, clientRegistration.getScopes());
}
if (grant.isAuthorizationCode())
{
final OAuth2AuthorizationExchange authzExchange = new OAuth2AuthorizationExchange(
OAuth2AuthorizationRequest.authorizationCode()
.clientId(clientRegistration.getClientId())
.authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri())
.redirectUri(grant.getRedirectUri())
.scopes(clientRegistration.getScopes())
.build(),
OAuth2AuthorizationResponse.success(grant.getAuthorizationCode())
.redirectUri(grant.getRedirectUri())
.build()
);
return new OAuth2AuthorizationCodeGrantRequest(clientRegistration, authzExchange);
}
throw new UnsupportedOperationException("Unsupported grant type.");
}
private OAuth2AccessTokenResponseClient getClient(AbstractOAuth2AuthorizationGrantRequest request)
{
final AuthorizationGrantType grantType = request.getGrantType();
final OAuth2AccessTokenResponseClient client = clients.get(grantType);
if (client == null)
{
throw new UnsupportedOperationException("Unsupported grant type `" + grantType + "`.");
}
return client;
}
private static OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> createAuthorizationCodeClient(RestOperations rest)
{
final DefaultAuthorizationCodeTokenResponseClient client = new DefaultAuthorizationCodeTokenResponseClient();
client.setRestOperations(rest);
return client;
}
private static OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> createRefreshTokenClient(RestOperations rest)
{
final DefaultRefreshTokenTokenResponseClient client = new DefaultRefreshTokenTokenResponseClient();
client.setRestOperations(rest);
return client;
}
private static OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> createPasswordClient(RestOperations rest)
{
final DefaultPasswordTokenResponseClient client = new DefaultPasswordTokenResponseClient();
client.setRestOperations(rest);
return client;
}
private static class SpringAccessTokenAuthorization implements AccessTokenAuthorization
{
private final OAuth2AccessTokenResponse tokenResponse;
private SpringAccessTokenAuthorization(OAuth2AccessTokenResponse tokenResponse)
{
this.tokenResponse = requireNonNull(tokenResponse);
}
@Override
public AccessToken getAccessToken()
{
return new SpringAccessToken(tokenResponse.getAccessToken());
}
@Override
public String getRefreshTokenValue()
{
return Optional.of(tokenResponse)
.map(OAuth2AccessTokenResponse::getRefreshToken)
.map(AbstractOAuth2Token::getTokenValue)
.orElse(null);
}
}
private static class SpringAccessToken implements AccessToken
{
private final AbstractOAuth2Token token;
private SpringAccessToken(AbstractOAuth2Token token)
{
this.token = requireNonNull(token);
}
@Override
public String getTokenValue()
{
return token.getTokenValue();
}
@Override
public Instant getExpiresAt()
{
return token.getExpiresAt();
}
}
private static class SpringDecodedAccessToken extends SpringAccessToken implements DecodedAccessToken
{
private final Jwt jwt;
private SpringDecodedAccessToken(Jwt jwt)
{
super(jwt);
this.jwt = jwt;
}
@Override
public Object getClaim(String claim)
{
return jwt.getClaim(claim);
}
}
}

Some files were not shown because too many files have changed in this diff Show More